def CPU_thread(window: sg.Window): while True: cpu_percent = psutil.cpu_percent(interval=g_interval) procs = psutil.process_iter() window.write_event_value('-CPU UPDATE FROM THREAD-', (cpu_percent, procs))
def the_thread(window: sg.Window): """ The thread that communicates with the application through the window's events. Because the figure creation time is greater than the GUI drawing time, it's safe to send a non-regulated stream of events without fear of overrunning the communication queue """ while True: fig = your_matplotlib_code() buf = draw_figure(fig) window.write_event_value( '-THREAD-', buf) # Data sent is a tuple of thread name and counter
def show_result(window: sg.Window, result: bool) -> None: """ Show the result as a file. """ if result: window.write_event_value( "-COMPARE RESULT-", [True, "text_face_compare_status", "SUCCESS", "green"], ) else: window.write_event_value( "-COMPARE RESULT-", [False, "text_face_compare_status", "FAILED", "red"], )
def the_thread(window:sg.Window, seconds): """ The thread that communicates with the application through the window's events. Wakes every X seconds that are provided by user in the main GUI: Sends an event to the main thread Goes back to sleep """ i = 0 while True: time.sleep(seconds) # send a message to the main GUI. It will be read using window.read() # the "Value" send is a tuple that contains all the things to show in the popup window.write_event_value('-POPUP-', ('Hello this is the thread...', f'My counter is {i}', f'Will send another message in {seconds} seconds')) i += 1
def the_thread(window: sg.Window): """ The thread that communicates with the application through the window's events. Once a second wakes and sends a new event and associated value to the window """ max_value = random.randint(50, 100) window.write_event_value( DL_START_KEY, max_value) # Data sent is a tuple of thread name and counter for i in range(max_value): time.sleep(.1) window.write_event_value( DL_COUNT_KEY, i) # Data sent is a tuple of thread name and counter window.write_event_value( DL_END_KEY, max_value) # Data sent is a tuple of thread name and counter
def check_validity(window: sg.Window, doc_num: str) -> None: """ For Estonian documents, check the validity on "https://www2.politsei.ee/qr/?qr=" website """ window.write_event_value( "-ONLINE CHECK FOR EST-", [True, "text_valid", "Performing online document validity check...", "white"], ) page = request.urlopen("https://www2.politsei.ee/qr/?qr=" + doc_num).read().decode("utf8") if f"The document {doc_num} is valid." in page: print(f"[+] The document {doc_num} is valid.") window.write_event_value( "-ONLINE CHECK FOR EST-", [True, "text_valid_status", "OK", "green"], ) elif f"The document {doc_num} is invalid." in page: print(f"[-] The document {doc_num} is invalid.") window.write_event_value( "-ONLINE CHECK FOR EST-", [False, "text_valid_status", "INVALID", "red"], ) elif f"The document {doc_num} has not been issued." in page: print(f"[-] The document {doc_num} has not been issued.") window.write_event_value( "-ONLINE CHECK FOR EST-", [False, "text_valid_status", "NOT ISSUED", "red"], ) elif f"The document {doc_num} is a specimen." in page: print(f"[-] The document {doc_num} is a specimen.") window.write_event_value( "-ONLINE CHECK FOR EST-", [False, "text_valid_status", "SPECIMEN", "red"], ) else: print("[-] politsei.ee can't be reached!") window.write_event_value( "-ONLINE CHECK FOR EST-", [False, "text_valid_status", "ERROR", "red"], )
def program_logic(window: sg.Window): camera_id = -1 mrz, _ = capture_mrz(window, camera_id) mrz_print = "\n".join(mrz) print(f"[i] MRZ Read:\n{mrz_print}") document_number, birthdate, expiry_date, issuing_country, name, surname = parse_mrz_text( mrz) mrz_information = other_mrz(document_number, birthdate, expiry_date) sm_object = SMObject(wait_for_card()) atr = sm_object.channel.getATR() print("[+] Card ATR: " + toHexString(atr)) # Select MF try: send(sm_object, APDU(b"\x00", b"\xA4", b"\x00", b"\x0C")) except CardCommunicationError: pass except CardConnectionException as ex: print(ex) pass else: print("[+] MF selected.") # Read EF.CardAccess ef_cardaccess = None try: ef_cardaccess = read_data_from_ef(window, sm_object, b"\x01\x1C", "EF.CardAccess") except EFReadError as ex: print(ex) print("[-] Error while reading file EF.CardAccess.") pass except CardCommunicationError: pass except CardConnectionException as ex: print(ex) pass else: # print(f"[i] EF.CardAccess Read: {toHexString(list(ef_cardaccess))}") security_infos_efca = parse_security_infos(ef_cardaccess) # pace(security_infos_efca, sm_object) # Read EF.DIR try: ef_dir = read_data_from_ef(window, sm_object, b"\x2F\x00", "EF.DIR") except EFReadError as ex: print(ex) print("[-] Error while reading file EF.DIR.") except CardCommunicationError: pass except CardConnectionException as ex: print(ex) pass else: print(f"[i] EF.DIR Read: {toHexString(list(ef_cardaccess))}") # Select eMRTD Applet print("[+] Selecting LDS DF AID: A0000002471001...") aid = bytes.fromhex("A0000002471001") try: send( sm_object, APDU(b"\x00", b"\xA4", b"\x04", b"\x0C", Lc=nb(len(aid)), cdata=aid)) except CardCommunicationError: window.write_event_value("-RAISED EXCEPTION-", "") return except CardConnectionException as ex: print(ex) window.write_event_value("-RAISED EXCEPTION-", "") return ## SECURE MESSAGING ## try: establish_bac_session_keys(sm_object, mrz_information.encode("utf-8")) except SessionKeyEstablishmentError as ex: print(ex) print("[-] Error while establishing BAC session keys") window.write_event_value("-RAISED EXCEPTION-", "") return except CardCommunicationError: window.write_event_value("-RAISED EXCEPTION-", "") return except CardConnectionException as ex: print(ex) window.write_event_value("-RAISED EXCEPTION-", "") return # Read EF.COM try: efcom = read_data_from_ef(window, sm_object, b"\x01\x1E", "EF.COM") except EFReadError as ex: print(ex) print("[-] Error while reading file EF.COM.") window.write_event_value("-RAISED EXCEPTION-", "") return except CardCommunicationError: window.write_event_value("-RAISED EXCEPTION-", "") return except CardConnectionException as ex: print(ex) window.write_event_value("-RAISED EXCEPTION-", "") return else: # print(f"[i] EF.COM Read: {toHexString(list(efcom))}") ef_com_dg_list = parse_efcom(efcom) print(f"[i] DGs specified in EF.COM: {list(ef_com_dg_list.values())}") # Read EF.DG14 try: dg14 = read_data_from_ef(window, sm_object, b"\x01\x0E", "EF.DG14") except EFReadError as ex: print(ex) print("[-] Error while reading file EF.DG14.") window.write_event_value("-RAISED EXCEPTION-", "") return except CardCommunicationError: window.write_event_value("-RAISED EXCEPTION-", "") return except CardConnectionException as ex: print(ex) window.write_event_value("-RAISED EXCEPTION-", "") return else: # print(f"[i] EF.DG14 Read: {toHexString(list(dg14))}") security_infos_dg14 = parse_security_infos(dg14) for si in security_infos_efca: assert si in security_infos_dg14 # print(dump_asn1(si)) window.write_event_value("-RESTART-", "") return
def main( window: sg.Window, args: argparse.Namespace, db: TinyDB, q: Queue, q2: Queue, lock: threading.Lock, lock2: threading.Lock, first_run: bool, ) -> None: """main function""" # Get dir arguments else fallback to EE certs CSCA_certs_dir = args.certs or Path("certs/csca_certs") crls_dir = args.certs or Path("certs/crls") output_dir = args.output output_files = not args.output is None camera_id = -1 outfile: Union[TextIO, BinaryIO] if (args.online and first_run) or ( not os.path.isdir(CSCA_certs_dir) or not os.path.isdir(crls_dir) ): window.write_event_value( "-DOWNLOAD CSCA CERT AND CRL-", [True, "text_download_csca_crl", "Downloading CSCA certificates and CRLs...", "white"], ) download_certs(CSCA_certs_dir, crls_dir) window.write_event_value( "-DOWNLOAD CSCA CERT AND CRL-", [True, "text_download_csca_crl_status", "OK", "green"], ) if first_run: dsccrl_dir = Path(os.path.join(os.path.dirname(CSCA_certs_dir), Path("icao_pkd_dsccrl"))) ml_dir = Path(os.path.join(os.path.dirname(CSCA_certs_dir), Path("icao_pkd_ml"))) window.write_event_value( "-BUILD CERT STORE-", [True, "build_cert_store", "Building certificate store...", "white"], ) build_store(CSCA_certs_dir, crls_dir, ml_dir, dsccrl_dir) window.write_event_value( "-BUILD CERT STORE-", [True, "build_cert_store_status", "OK", "green"], ) # create face detector network if args.biometric: from emrtd_face_access.face_compare import opencv_dnn_detector opencv_dnn_detector() if args.mrz: window.write_event_value( "-SHOW DOCUMENT TO CAMERA-", [ True, "text_instruction", "Please show the Machine Readable Zone (MRZ) of your document to the camera.", "white", ], ) window.write_event_value( "-READ MRZ-", [True, "read_mrz", "Trying to capture MRZ information...", "white"], ) mrz, mrz_image = capture_mrz(window, camera_id) document_number, birthdate, expiry_date, issuing_country, name, surname = parse_mrz_text( mrz ) mrz_information = other_mrz(document_number, birthdate, expiry_date) window.write_event_value( "-WRITE NAME-", [True, "text_name_surname", f"NAME: {name} {surname}", "white"], ) window.write_event_value( "-WRITE DOC NUM-", [True, "text_doc_num", f"DOCUMENT NUMBER: {document_number}", "white"], ) window.write_event_value( "-READ MRZ-", [True, "read_mrz_status", "OK", "green"], ) print("[?] Please place your document onto the card reader.") window.write_event_value( "-PLACE DOCUMENT-", [ True, "text_instruction", "Please place your document onto the card reader.", "white", ], ) window.write_event_value( "-WAIT FOR DOCUMENT-", [True, "text_card_insert", "Waiting for a document...", "white"], ) sm_object = SMObject(wait_for_card()) window.write_event_value("-PLACE DOCUMENT-", [True, "text_instruction", "", "white"]) window.write_event_value( "-WAIT FOR DOCUMENT-", [True, "text_card_insert_status", "OK", "green"], ) atr = sm_object.channel.getATR() print("[+] Card ATR: " + toHexString(atr)) ## DERIVATION OF DOCUMENT BASIC ACCESS KEYS (KENC AND KMAC) ## if args.ee: try: ( mrz_information, document_number, personal_id_code, name, surname, ) = estonia_read_mrz(sm_object) except CardCommunicationError: window.write_event_value("-RAISED EXCEPTION-", "") return except CardConnectionException as ex: print(ex) window.write_event_value("-RAISED EXCEPTION-", "") return else: issuing_country = "EST" window.write_event_value( "-WRITE NAME-", [True, "text_name_surname", f"NAME: {name} {surname}", "white"], ) window.write_event_value( "-WRITE DOC NUM-", [True, "text_doc_num", f"DOCUMENT NUMBER: {document_number}", "white"], ) window.write_event_value( "-WRITE ID CODE-", [True, "text_personal_code", f"PERSONAL ID CODE: {personal_id_code}", "white"], ) if output_files: folder_name = create_output_folder(output_dir, document_number) if args.mrz and output_files: with open(os.path.join(folder_name, "mrz_text.txt"), "wt") as outfile: outfile.write("\n".join(mrz)) mrz_image.save(os.path.join(folder_name, "mrz_photo.jpeg")) # Select eMRTD application print("[+] Selecting eMRTD Application ‘International AID’: A0000002471001...") aid = bytes.fromhex("A0000002471001") try: send(sm_object, APDU(b"\x00", b"\xA4", b"\x04", b"\x0C", Lc=nb(len(aid)), cdata=aid)) except CardCommunicationError: window.write_event_value("-RAISED EXCEPTION-", "") return except CardConnectionException as ex: print(ex) window.write_event_value("-RAISED EXCEPTION-", "") return ## SECURE MESSAGING ## try: establish_bac_session_keys(sm_object, mrz_information.encode("utf-8")) except SessionKeyEstablishmentError as ex: print(ex) print("[-] Error while establishing BAC session keys") window.write_event_value("-RAISED EXCEPTION-", "") return except CardCommunicationError: window.write_event_value("-RAISED EXCEPTION-", "") return except CardConnectionException as ex: print(ex) window.write_event_value("-RAISED EXCEPTION-", "") return # Read EF.COM try: efcom = read_data_from_ef(window, sm_object, b"\x01\x1E", "EF.COM") except EFReadError as ex: print(ex) print("[-] Error while reading file EF.COM.") window.write_event_value("-RAISED EXCEPTION-", "") return except CardCommunicationError: window.write_event_value("-RAISED EXCEPTION-", "") return except CardConnectionException as ex: print(ex) window.write_event_value("-RAISED EXCEPTION-", "") return else: if output_files: with open(os.path.join(folder_name, "EF_COM.BIN"), "wb") as outfile: outfile.write(efcom) ef_com_dg_list = parse_efcom(efcom) # Read EF.SOD try: efsod = read_data_from_ef(window, sm_object, b"\x01\x1D", "EF.SOD") except EFReadError as ex: print(ex) print("[-] Error while reading file EF.SOD.") window.write_event_value("-RAISED EXCEPTION-", "") return except CardCommunicationError: window.write_event_value("-RAISED EXCEPTION-", "") return except CardConnectionException as ex: print(ex) window.write_event_value("-RAISED EXCEPTION-", "") return else: if output_files: with open(os.path.join(folder_name, "EF_SOD.BIN"), "wb") as outfile: outfile.write(efsod) window.write_event_value( "-PASSIVE AUTHENTICATION-", [True, "text_authentic", "Passive Authentication...", "white"], ) pa_error = False ee_deviant_doc = False if issuing_country == "EST": try: with open(Path("certs/erpdeviationlist.bin"), "rb") as infile: deviation_docs = infile.read() except FileNotFoundError: pass else: if deviation_docs.find(document_number.encode("utf-8")) != -1: ee_deviant_doc = True try: passive_auth_return = passive_auth(efsod, ee_deviant_doc=ee_deviant_doc, dump=False) except PassiveAuthenticationCriticalError as ex: print(ex) window.write_event_value( "-PASSIVE AUTHENTICATION-", [False, "text_authentic_status", "ERROR", "red"], ) else: if output_files: with open(os.path.join(folder_name, "CDS.der"), "wb") as outfile: outfile.write(passive_auth_return[2]) if passive_auth_return[3] is None: pa_error = False hash_alg, data_group_hash_values, _, _ = passive_auth_return else: pa_error = True hash_alg, data_group_hash_values, _, exception = passive_auth_return print(exception) window.write_event_value( "-PASSIVE AUTHENTICATION-", [False, "text_authentic_status", "ERROR", "red"], ) if atr in atr_exceptions and hash_alg == "sha256": hash_alg = "sha1" ef_sod_dg_list = get_dg_numbers(data_group_hash_values) if ef_com_dg_list != ef_sod_dg_list: print( "[-] EF.COM might have been changed, there are " "differences between EF_COM DGs and EF_SOD DGs!" ) window.write_event_value( "-PASSIVE AUTHENTICATION-", [False, "text_authentic_status", "ERROR", "red"], ) pa_error = True window.write_event_value( "-FILE VERIFICATION-", [True, "text_read_file", "Reading and verifying document files...", "white"], ) file_read_error = False security_infos = [] if b"\x0e" in ef_sod_dg_list: window.write_event_value( "-FILE VERIFICATION-", [True, "text_read_file_status", "EF.DG14", "yellow"], ) try: DG = read_data_from_ef(window, sm_object, b"\x01" + b"\x0e", "EF.DG14") except EFReadError as ex: print(ex) print("[-] Error while reading file EF.DG14.") window.write_event_value("-RAISED EXCEPTION-", "") return except CardCommunicationError: window.write_event_value("-RAISED EXCEPTION-", "") return except CardConnectionException as ex: print(ex) window.write_event_value("-RAISED EXCEPTION-", "") return if not assert_dg_hash(DG, data_group_hash_values, hash_alg, b"\x0e"): pa_error = True window.write_event_value( "-PASSIVE AUTHENTICATION-", [False, "text_authentic_status", "ERROR", "red"], ) window.write_event_value( "-FILE VERIFICATION-", [False, "text_read_file_status", "EF.DG14", "red"], ) file_read_error = True else: window.write_event_value( "-FILE VERIFICATION-", [True, "text_read_file_status", "EF.DG14", "green"], ) security_infos = parse_security_infos(DG) window.write_event_value( "-CHIP AUTHENTICATION-", [True, "text_copied_2", "Chip Authentication...", "white"], ) try: chip_auth(security_infos, sm_object) except ChipAuthenticationError as ex: print(ex) window.write_event_value( "-CHIP AUTHENTICATION-", [False, "text_copied_2_status", "ERROR", "red"], ) except CardCommunicationError: window.write_event_value("-RAISED EXCEPTION-", "") return except CardConnectionException as ex: print(ex) window.write_event_value("-RAISED EXCEPTION-", "") return else: window.write_event_value( "-CHIP AUTHENTICATION-", [True, "text_copied_2_status", "OK", "green"], ) if b"\x0f" in ef_sod_dg_list: window.write_event_value( "-FILE VERIFICATION-", [True, "text_read_file_status", "EF.DG15", "yellow"], ) try: DG = read_data_from_ef(window, sm_object, b"\x01" + b"\x0f", "EF.DG15") except EFReadError as ex: print(ex) print("[-] Error while reading file EF.DG15.") window.write_event_value("-RAISED EXCEPTION-", "") return except CardCommunicationError: window.write_event_value("-RAISED EXCEPTION-", "") return except CardConnectionException as ex: print(ex) window.write_event_value("-RAISED EXCEPTION-", "") return if output_files: with open(os.path.join(folder_name, "EF.DG15.BIN"), "wb") as outfile: outfile.write(DG) if not assert_dg_hash(DG, data_group_hash_values, hash_alg, b"\x0f"): pa_error = True window.write_event_value( "-PASSIVE AUTHENTICATION-", [False, "text_authentic_status", "ERROR", "red"], ) window.write_event_value( "-FILE VERIFICATION-", [False, "text_read_file_status", "EF.DG15", "red"], ) file_read_error = True else: window.write_event_value( "-FILE VERIFICATION-", [True, "text_read_file_status", "EF.DG15", "green"], ) window.write_event_value( "-ACTIVE AUTHENTICATION-", [True, "text_copied_1", "Active Authentication...", "white"], ) try: active_auth(DG, sm_object, security_infos) except ActiveAuthenticationError as ex: print(ex) window.write_event_value( "-ACTIVE AUTHENTICATION-", [False, "text_copied_1_status", "ERROR", "red"], ) except CardCommunicationError: window.write_event_value("-RAISED EXCEPTION-", "") return except CardConnectionException as ex: print(ex) window.write_event_value("-RAISED EXCEPTION-", "") return else: window.write_event_value( "-ACTIVE AUTHENTICATION-", [True, "text_copied_1_status", "OK", "green"], ) for dg, dgname in ef_sod_dg_list.items(): if dg == b"\x0f" or dg == b"\x0e": # Active Authentication and Chip Authentication assumed completed continue if dg == b"\x03" or dg == b"\x04": # Sensitive Data: Finger and iris image data stored in the LDS # Data Groups 3 and 4, respectively. These data are considered # to be more privacy sensitive than data stored in the other # Data Groups. continue window.write_event_value( "-FILE VERIFICATION-", [True, "text_read_file_status", dgname, "yellow"], ) try: DG = read_data_from_ef(window, sm_object, b"\x01" + dg, dgname) except EFReadError as ex: print(ex) print(f"[-] Error while reading file {dgname}.") if dg in [b"\x01", b"\x02"]: window.write_event_value("-RAISED EXCEPTION-", "") return continue except CardCommunicationError: window.write_event_value("-RAISED EXCEPTION-", "") return except CardConnectionException as ex: print(ex) window.write_event_value("-RAISED EXCEPTION-", "") return if output_files: with open(os.path.join(folder_name, dgname + ".BIN"), "wb") as outfile: outfile.write(DG) dg1_okay = True if not assert_dg_hash(DG, data_group_hash_values, hash_alg, dg): if dg == b"\x01": dg1_okay = False pa_error = True window.write_event_value( "-PASSIVE AUTHENTICATION-", [False, "text_authentic_status", "ERROR", "red"], ) window.write_event_value( "-FILE VERIFICATION-", [False, "text_read_file_status", dgname, "red"], ) file_read_error = True else: window.write_event_value( "-FILE VERIFICATION-", [True, "text_read_file_status", dgname, "green"], ) if dg == b"\x02": id_image = get_jpeg_im(DG) window.write_event_value("-SHOW ID IMAGE-", [jpeg_to_png(id_image)]) if dg == b"\x01": window.write_event_value( "-DOCUMENT EXPIRY CHECK-", [True, "document_expired", "Checking expiration status...", "white"], ) mrz_read = get_dg1_content(DG) if dg1_okay: mrz_expiration_date = b"" if len(mrz_read) == 90: mrz_expiration_date = mrz_read[38:44] elif len(mrz_read) == 72: mrz_expiration_date = mrz_read[57:63] elif len(mrz_read) == 88: mrz_expiration_date = mrz_read[65:71] else: print("[-] Error in MRZ that was read from DG1") window.write_event_value( "-DOCUMENT EXPIRY CHECK-", [False, "document_expired_status", "ERROR", "red"], ) if mrz_expiration_date != b"": valid = check_expiration(mrz_expiration_date) if valid: window.write_event_value( "-DOCUMENT EXPIRY CHECK-", [True, "document_expired_status", "OK", "green"], ) else: window.write_event_value( "-DOCUMENT EXPIRY CHECK-", [False, "document_expired_status", "EXPIRED", "red"], ) else: # Assume the document expired window.write_event_value( "-DOCUMENT EXPIRY CHECK-", [False, "document_expired_status", "ERROR", "red"], ) if args.mrz: window.write_event_value( "-MRZ COMPARE-", [ True, "text_mrz_compare", "Comparing Machine Readable Zone with the DG1 inside the card...", "white", ], ) mrz_scanned = str.encode("".join(mrz)) if mrz_read != mrz_scanned: print( "[-] MRZ in DG1 doesn't match the MRZ read from the card!" f"\nMRZ SCANNED:\n{mrz_scanned!s}\n\nMRZ READ:\n{mrz_read!s}" ) window.write_event_value( "-MRZ COMPARE-", [ False, "text_mrz_compare_status", "ERROR", "red", ], ) else: window.write_event_value( "-MRZ COMPARE-", [ True, "text_mrz_compare_status", "OK", "green", ], ) if db is not None: # Search MRZ in the db window.write_event_value( "-CHECK DATABASE-", [True, "check_database", "Checking database...", "white"], ) database_obj = Query() if db.search(database_obj.mrz == "".join(mrz)) == []: window.write_event_value( "-CHECK DATABASE-", [False, "check_database_status", "NOT FOUND", "red"], ) else: window.write_event_value( "-CHECK DATABASE-", [True, "check_database_status", "OK", "green"], ) issuing_country = mrz_read[2:5] if issuing_country == b"EST": check_validity(window, document_number) if file_read_error: window.write_event_value( "-FILE VERIFICATION-", [False, "text_read_file_status", "ERROR", "red"], ) else: window.write_event_value( "-FILE VERIFICATION-", [True, "text_read_file_status", "ALL OK", "green"], ) if pa_error: window.write_event_value( "-PASSIVE AUTHENTICATION-", [False, "text_authentic_status", "ERROR", "red"], ) else: window.write_event_value( "-PASSIVE AUTHENTICATION-", [True, "text_authentic_status", "OK", "green"], ) if args.biometric: from emrtd_face_access.camera import capture_image from emrtd_face_access.face_compare import compare_faces from emrtd_face_access.image_operations import show_result print("[?] Please take a picture.") camera_image, face_location = capture_image(window, q, q2, lock2, camera_id) with lock: window.write_event_value( "-COMPARE RESULT-", [True, "text_face_compare", "Performing face comparison...", "white"], ) comparison_result = compare_faces( id_image, camera_image, face_location, None if not output_files else folder_name ) show_result(window, comparison_result) # termios.tcflush(sys.stdin, termios.TCIOFLUSH) # input("[?] Please take your ID card out and press [Enter] to run again.") window.write_event_value( "-TAKE ID OUT-", [ True, "text_instruction", "Please take your document out and press [Enter] to run again.", "white", ], ) window.write_event_value("-RUN COMPLETE-", "") return
def capture_mrz(window: sg.Window, camera_id: int) -> Tuple[List[str], Image.Image]: """ Capture the MRZ by using OCR and the camera footage. :returns: MRZ lines in a list """ cap = cv2.VideoCapture(camera_id) tess_api = PyTessBaseAPI(init=False, psm=PSM.SINGLE_BLOCK_VERT_TEXT) tess_api.InitFull( # https://github.com/DoubangoTelecom/ultimateMRZ-SDK/tree/master/assets/models path="text_detection", lang="mrz", variables={ "load_system_dawg": "false", "load_freq_dawg": "false", "tessedit_char_whitelist": "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ<", }, ) # mrz_list: List[List[str]] = [] pool = ThreadPool(processes=1) ocr_running = False while True: _, frame = cap.read() mrz = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) mrz = cv2.adaptiveThreshold(mrz, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 21, 10) # mrz = cv2.adaptiveThreshold(mrz, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,3,2) # mrz = cv2.GaussianBlur(mrz, (5,5), 0) # _, mrz = cv2.threshold(mrz, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) # mrz = cv2.GaussianBlur(mrz, (5,5), 0) # mrz = cv2.medianBlur(mrz, 3) frame_shown = copy.deepcopy(mrz) width = 320 height = int(frame_shown.shape[0] * (320 / frame_shown.shape[1])) frame_shown = cv2.resize(frame_shown, (width, height)) alpha = 0.8 frame_overlay = add_mrz_overlay(copy.deepcopy(frame_shown), "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<", 3, 0.9, False) frame_overlay = add_mrz_overlay( frame_overlay, "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<", 2, 0.9, True) cv2.addWeighted(frame_shown, alpha, frame_overlay, 1 - alpha, 0, frame_shown) imgbytes = cv2.imencode(".png", frame_shown)[1].tobytes() window.write_event_value("-SHOW MRZ-", [imgbytes]) mrz = Image.fromarray(mrz) if not ocr_running: checked_frame = Image.fromarray(frame[:, :, ::-1]) tess_api.SetImage(mrz) async_result = pool.apply_async(tess_api.GetUTF8Text) ocr_running = True if async_result.ready(): ocr_running = False mrz_text = async_result.get() result = parse_mrz_ocr(mrz_text) if result is not None: break # if result and len(mrz_list) < 3: # mrz_list.append(result) # elif not result: # mrz_list = [] # else: # if all(x == mrz_list[0] for x in mrz_list): # break # When everything done, release the capture cap.release() # cv2.destroyAllWindows() tess_api.End() # return mrz_list[0] window.write_event_value("-HIDE MRZ-", "") return (result, checked_frame)
def the_thread(window: sg.Window, sp: subprocess.Popen): """ The thread that's used to run the subprocess so that the GUI can continue and the stdout/stderror is collected :param window: :param sp: :return: """ window.write_event_value('-THREAD-', (sp, '===THEAD STARTING===')) window.write_event_value('-THREAD-', (sp, '----- STDOUT Follows ----')) for line in sp.stdout: oline = line.decode().rstrip() window.write_event_value('-THREAD-', (sp, oline)) window.write_event_value('-THREAD-', (sp, '----- STDERR ----')) for line in sp.stderr: oline = line.decode().rstrip() window.write_event_value('-THREAD-', (sp, oline)) window.write_event_value('-THREAD-', (sp, '===THEAD DONE==='))
def read_data_from_ef(window: sg.Window, sm_object: SMObject, fid: bytes, fname: str) -> bytes: """ Read the data from file id fid and return sm_object -- Necessary secure messaging object (Encryption session key etc.) fid -- File id fname -- Printed file name :returns: data from the file """ # Select File print("[+] Selecting file: " + fname) # exception caught in main program loop send(sm_object, APDU(b"\x00", b"\xA4", b"\x02", b"\x0C", Lc=b"\x02", cdata=fid)) # Read Binary of first four bytes print("[+] Read first 4 bytes of selected file...") # exception caught in main program loop data = send(sm_object, APDU(b"\x00", b"\xB0", b"\x00", b"\x00", Le=b"\x04")) if data == b"": raise EFReadError("[-] No reply from card") elif len(data) != 4: raise EFReadError("[-] Broken reply from card") data_len = len2int(data) offset = 4 # Read the rest of the bytes print("[+] Read the rest of the bytes of selected file...") # IAS_ECC_v1 page 121 "Particular issue for the READ BINARY command" while offset < data_len: if ( data_len - offset < 0xFA ): # 0xFA because all the cards I have access to only send 250 bytes in BAC SM 242 in AES SM le = bytes([data_len - offset]) else: le = b"\x00" window.write_event_value( "-PROGRESS BAR-", [offset, data_len], ) # exception caught in main program loop decrypted_data = send( sm_object, APDU(b"\x00", b"\xB0", bytes([offset >> 8]), bytes([offset & 0xFF]), Le=le), ) if decrypted_data == b"": raise EFReadError("[-] No reply from card") data += decrypted_data offset += len(decrypted_data) window.write_event_value( "-PROGRESS BAR-", [offset, data_len], ) if offset != data_len: raise EFReadError("[-] Error while processing a file.") window.write_event_value( "-PROGRESS BAR-", [0, 100], ) return data
def capture_image(window: sg.Window, q: Queue, q2: Queue, lock2: threading.Lock, camera_id: int) -> Tuple[np.ndarray, List[Tuple[int, ...]]]: """ Capture user image when pressed Enter :returns: opencv image """ cap = cv2.VideoCapture(camera_id) window.write_event_value( "-CAMERA ON-", [ True, "text_instruction", "Press [Enter] to capture image...", "white" ], ) pause = False while True: _, frame = cap.read() frame_shown = copy.deepcopy(frame) scale = 320 / frame_shown.shape[1] width = int(frame_shown.shape[1] * scale) height = int(frame_shown.shape[0] * scale) frame_shown = cv2.resize(frame_shown, (width, height)) face_locations = get_bounding_boxes(frame, scale_size=(height, width)) for (top, right, bottom, left) in face_locations: cv2.rectangle(frame_shown, (left, top), (right, bottom), (0, 255, 0), 2) imgbytes = cv2.imencode(".png", frame_shown)[1].tobytes() with lock2: if not q.empty(): queue_element = q.get() if queue_element == "Done": q2.put("Done") break if queue_element == "Pause": pause = True if queue_element == "Continue": pause = False elif pause: continue else: window.write_event_value( "-SHOW CAMERA-", [imgbytes, len(face_locations)]) if len(face_locations) == 1: frame_to_return = copy.deepcopy(frame) face_locations_to_return = [ tuple(int(x / scale) for x in face_locations[0]) ] # cv2.putText( # frame_text, # "Press [Enter] to capture image", # (50, 50), # cv2.FONT_HERSHEY_SIMPLEX, # 0.5, # (0, 255, 255), # 1, # cv2.LINE_4, # ) # Display the resulting frame # cv2.imshow("frame", frame_text) # if cv2.waitKey(1) & 0xFF == ord("\r"): # frame_question = frame.copy() # cv2.putText( # frame_question, # "Press [Enter] to accept image, anything else to cancel", # (50, 50), # cv2.FONT_HERSHEY_SIMPLEX, # 0.5, # (0, 255, 255), # 1, # cv2.LINE_4, # ) # cv2.imshow("frame", frame_question) # if cv2.waitKey(0) & 0xFF == ord("\r"): # break # When everything done, release the capture cap.release() # cv2.destroyAllWindows() return frame_to_return, face_locations_to_return
def database_builder_loop(window: sg.Window): camera_id = -1 mrz, _ = capture_mrz(window, camera_id) mrz_scan = "".join(mrz) print(f"[i] MRZ Read:\n{mrz_scan}") document_number, birthdate, expiry_date, _, _, _ = parse_mrz_text(mrz) mrz_information = other_mrz(document_number, birthdate, expiry_date) sm_object = SMObject(wait_for_card()) atr = sm_object.channel.getATR() print("[+] Card ATR: " + toHexString(atr)) # Select eMRTD Applet print("[+] Selecting LDS DF AID: A0000002471001...") aid = bytes.fromhex("A0000002471001") try: send(sm_object, APDU(b"\x00", b"\xA4", b"\x04", b"\x0C", Lc=nb(len(aid)), cdata=aid)) except CardCommunicationError: window.write_event_value("-RAISED EXCEPTION-", "") return except CardConnectionException as ex: print(ex) window.write_event_value("-RAISED EXCEPTION-", "") return ## SECURE MESSAGING ## try: establish_bac_session_keys(sm_object, mrz_information.encode("utf-8")) except SessionKeyEstablishmentError as ex: print(ex) print("[-] Error while establishing BAC session keys") window.write_event_value("-RAISED EXCEPTION-", "") return except CardCommunicationError: window.write_event_value("-RAISED EXCEPTION-", "") return except CardConnectionException as ex: print(ex) window.write_event_value("-RAISED EXCEPTION-", "") return # Read EF.DG1 try: dg1 = read_data_from_ef(window, sm_object, b"\x01\x01", "EF.DG1") except EFReadError as ex: print(ex) print("[-] Error while reading file EF.DG1.") window.write_event_value("-RAISED EXCEPTION-", "") return except CardCommunicationError: window.write_event_value("-RAISED EXCEPTION-", "") return except CardConnectionException as ex: print(ex) window.write_event_value("-RAISED EXCEPTION-", "") return else: mrz_read = get_dg1_content(dg1).decode("utf-8") print(mrz_read) if mrz_read == mrz_scan: window.write_event_value("-SHOW WARNING-", mrz_read) else: window.write_event_value("-PROBLEM IN EITHER READ OR DOCUMENT-", "")