Skip to content

Commit 3345cd6

Browse files
committed
Update facerec.py
Fixe most important security issues
1 parent 28aa8ce commit 3345cd6

File tree

1 file changed

+35
-17
lines changed

1 file changed

+35
-17
lines changed

facerec.py

Lines changed: 35 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,16 @@
22
import sys
33
import cv2
44
import numpy as np
5-
from openvino import Core, convert_model
5+
66
import os
77
import subprocess
88
import pickle
99
import time
1010
import shutil
11-
from skimage.feature import local_binary_pattern
1211

12+
import getpass
13+
import base64
14+
from openvino import Core, convert_model
1315

1416

1517
DIR = os.path.dirname(__file__)
@@ -63,6 +65,20 @@
6365
anti_spoof_model = core.read_model(anti_spoof_model_path)
6466
compiled_anti_spoof = core.compile_model(anti_spoof_model, "AUTO")
6567

68+
def save_as_root(content, filepath):
69+
subprocess.run(["sudo","true"]) # make sure sudo is active in current session
70+
data = pickle.dumps(content)
71+
proc = subprocess.run(
72+
["sudo", "tee", filepath],
73+
input=data,
74+
stdout=subprocess.DEVNULL,
75+
check=True
76+
)
77+
78+
def load_file(filepath):
79+
return pickle.load(filepath)
80+
81+
6682
def display_bgr_term(frame):
6783
def unicode_color_fg(b, g, r): return f"\x1b[38;2;{int(r)};{int(g)};{int(b)}m"
6884
def unicode_color_bg(b, g, r): return f"\x1b[48;2;{r};{g};{b}m"
@@ -398,9 +414,6 @@ def align_face_with_landmarks(face_bgr, orig_frame, bbox, output_size=(128, 128)
398414
ref_embeddings={os.environ["USER"]:{0:ref_embeddings}}
399415
else:
400416
ref_embeddings = {os.environ["USER"]:{}}
401-
for user, faces in enumerate(ref_embeddings): # turn in dictionnary for easier embedding
402-
if type(faces)==list:
403-
ref_embeddings[user]={str(i): content for i, content in enumerate(faces)}
404417
#----End data loader-----------------------
405418

406419
# --- Helper: Process detection results ---
@@ -471,6 +484,8 @@ def score(rec_embedding):
471484
if command == 1:
472485
must_exit = True
473486
reason = "Got stop command"
487+
if must_exit:
488+
break
474489
if spoof_attempts>2:
475490
reason = "spoof detected"
476491
break
@@ -518,7 +533,7 @@ def score(rec_embedding):
518533
label = np.argmax(anti_spoof_result)
519534
value = anti_spoof_result[0][label]
520535

521-
if label != 1:
536+
if label != 1 or value < C+K: # use same treshold for legitimate face as for similarity
522537
spoof_attempts+=1
523538
break
524539

@@ -573,7 +588,7 @@ def add_face(cap_path=...,face_name=...,complete=False):
573588
total_progress=0
574589
if cap_path==... or not os.path.exists(cap_path):
575590
cap_path=CAP_PATHS[0]
576-
username = os.environ["USER"]
591+
username = getpass.getuser()
577592
new_face=[]
578593
if not username in ref_embeddings:
579594
ref_embeddings[username]={}
@@ -665,32 +680,35 @@ def add_face(cap_path=...,face_name=...,complete=False):
665680
cap.release()
666681
# save faces as vertex data (safer than images and faster to load)
667682
tmp_path="/tmp/facerec.tmp"
668-
print("Please enter your password in order to save your new face:")
669-
with open(tmp_path, "wb") as f:
670-
pickle.dump(ref_embeddings, f)
683+
print("Please enter your password if asked to in order to save your new face:")
671684
try:
672-
subprocess.check_output(["sudo","bash", "-c", f"mv {tmp_path} '{os.path.join(DIR,"preload_embeddings.pkl")}' && systemctl restart org.FaceRecognition"])
685+
save_as_root(ref_embeddings, os.path.join(DIR,"preload_embeddings.pkl"))
686+
subprocess.check_output(["sudo", "systemctl", "restart", "org.FaceRecognition"])
673687
print(f"Saved your face as {face_name} successfully. The daemon has been restarted and will be opperating in a few seconds.")
674688
except subprocess.CalledProcessError:
675689
print("Failed to save face!!! Maybe you don't have root permissions !")
676690

677691
def remove_face(*selection):
678-
username=os.environ["USER"]
692+
username = getpass.getuser()
679693
if len(selection)==0 or "all" in selection:
680-
input("Are you sure to delete all your saved faces ? They can't be restored. Type your root password to continue.")
694+
r = input("Are you sure to delete all your saved faces ? They can't be restored. Type YES to continue: ")
695+
if r != "YES":
696+
quit(11)
681697
del ref_embeddings[username]
682698
else:
699+
r = input(f"Are you sure to delete these faces: {", ".join(selection)} ? They can't be restored. Type YES to continue: ")
700+
if r != "YES":
701+
quit(11)
683702
for face_name in set(selection):
684703
try:
685704
del ref_embeddings[username][face_name]
686705
except IndexError:
687706
print(f"Unable to delete {face_name}, because it doesn't exists...")
688-
tmp_path="/tmp/facerec.tmp"
689707
print("Please enter your password in order to save your new face:")
690-
with open(tmp_path, "wb") as f:
691-
pickle.dump(ref_embeddings, f)
708+
692709
try:
693-
subprocess.check_output(["sudo","bash", "-c", f"mv {tmp_path} '{os.path.join(DIR,"preload_embeddings.pkl")}' && systemctl restart org.FaceRecognition"])
710+
save_as_root(ref_embeddings, os.path.join(DIR,"preload_embeddings.pkl"))
711+
subprocess.check_output(["sudo", "systemctl", "restart", "org.FaceRecognition"])
694712
print(f"Deleted face{"s" if len(set(selection))>1 else ""} successfully. The daemon has been restarted and will be opperating in a few seconds.")
695713
except subprocess.CalledProcessError:
696714
print(f"Failed to delete face{"s" if len(set(selection))>1 else ""}!!! Maybe you don't have root permissions !")

0 commit comments

Comments
 (0)