#!/usr/bin/python2
#  mrpkey.py - calculate 3DES key for Machine Readable Passport
#
#  Adam Laurie <adam@algroup.co.uk>
#  http://rfidiot.org/
#
#  This code is copyright (c) Adam Laurie, 2006, 2007, All rights reserved.
#  For non-commercial use only, the following terms apply - for all other
#  uses, please contact the author:
#
#    This code is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This code is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#

# pylint: disable=global-statement,global-variable-not-assigned,too-many-nested-blocks,too-many-branches,too-many-statements,too-many-lines

import sys
import os
import shutil
# import subprocess
# import io
from tkinter import (
    Frame, Canvas, Checkbutton, Radiobutton, Button, Label,
    Tk, StringVar, W, NW, NE, E
)
from operator import xor, and_
from Crypto.Hash import SHA, CMAC
from Crypto.Cipher import DES3, DES, AES
# import string
import rfidiot
from rfidiot import pace


STRIP_INDEX = True
DEBUG = False
Filetype = ""
DocumentType = "?"
Fields = ()
FieldNames = ()
FieldLengths = ()
FieldKeys = ()

# this needs fixing - MAX should be able to go up to size supported by device
MAXCHUNK = 118


DOCUMENT_TYPE = {}

# TEST data
TEST_MRZ = "L898902C<3UTO6908061F9406236ZE184226B<<<<<14"
TEST_rnd_ifd = "781723860C06C226"
TEST_rnd_icc = "4608F91988702212"
TEST_Kifd = "0B795240CB7049B01C19B33E32804F0B"
TEST_respdata = "46B9342A41396CD7386BF5803104D7CEDC122B9132139BAF2EEDC94EE178534F2F2D235D074D7449"
MRZ_WEIGHT = [7, 3, 1]
APDU_OK = "9000"
APDU_BAC = "6982"

# Data Groups and Elements
EF_COM = "60"
EF_DG1 = "61"
EF_DG2 = "75"
EF_DG3 = "63"
EF_DG4 = "76"
EF_DG5 = "65"
EF_DG6 = "66"
EF_DG7 = "67"
EF_DG8 = "68"
EF_DG9 = "69"
EF_DG10 = "6a"
EF_DG11 = "6b"
EF_DG12 = "6c"
EF_DG13 = "6d"
EF_DG14 = "6e"
EF_DG15 = "6f"
EF_DG16 = "70"
EF_SOD = "77"
EF_TAGS = "5c"
EF_CardAccess = "EF_CardAccess"

# Data Group Names
TAG_NAME = {
    EF_COM: "EF.COM Data Group Presence Map",
    EF_DG1: "EF.DG1 Data Recorded in MRZ",
    EF_DG2: "EF.DG2 Encoded Identification Features - FACE",
    EF_DG3: "EF.DG3 Encoded Identification Features - FINGER(s)",
    EF_DG4: "EF.DG4 Encoded Identification Features - IRIS(s)",
    EF_DG5: "EF.DG5 Displayed Identification Feature(s) - PORTRAIT",
    EF_DG6: "EF.DG6 Reserved for future use",
    EF_DG7: "EF.DG7 Displayed Identification Features - SIGNATURE or USUAL MARK",
    EF_DG8: "EF.DG8 Encoded Security Features - DATA FEATURE(s)",
    EF_DG9: "EF.DG9 Encoded Security Features - STRUCTURE FEATURE(s)",
    EF_DG10: "EF.DG10 Encoded Security Features - SUBSTANCE FEATURE(s)",
    EF_DG11: "EF.DG11 Additional Personal Detail(s)",
    EF_DG12: "EF.DG12 Additional Document Detail(s)",
    EF_DG13: "EF.DG13 Optional Detail(s)",
    EF_DG14: "EF.DG14 EAC Chip Authentication Public Key Info",
    EF_DG15: "EF.DG15 Active Authentication Public Key Info",
    EF_DG16: "EF.DG16 Person(s) to Notify",
    EF_CardAccess: "EF.CardAccess Supplemental Access Control",
    EF_SOD: "EF.SOD Document Security Object",
    EF_TAGS: "Tag List",
}

# Data Group Passport Application Long FID
TAG_FID = {
    EF_COM: "011E",
    EF_DG1: "0101",
    EF_DG2: "0102",
    EF_DG3: "0103",
    EF_DG4: "0104",
    EF_DG5: "0105",
    EF_DG6: "0106",
    EF_DG7: "0107",
    EF_DG8: "0108",
    EF_DG9: "0109",
    EF_DG10: "010A",
    EF_DG11: "010B",
    EF_DG12: "010C",
    EF_DG13: "010D",
    EF_DG14: "010E",
    EF_DG15: "010F",
    EF_DG16: "0110",
    EF_CardAccess: "011C",
    EF_SOD: "011D",
}

# Filesystem paths
tempfiles = "/tmp/"
filespath = ""

# Data Group filenames for local storage
TAG_FILE = {
    EF_COM: "EF_COM.BIN",
    EF_DG1: "EF_DG1.BIN",
    EF_DG2: "EF_DG2.BIN",
    EF_DG3: "EF_DG3.BIN",
    EF_DG4: "EF_DG4.BIN",
    EF_DG5: "EF_DG5.BIN",
    EF_DG6: "EF_DG6.BIN",
    EF_DG7: "EF_DG7.BIN",
    EF_DG8: "EF_DG8.BIN",
    EF_DG9: "EF_DG9.BIN",
    EF_DG10: "EF_DG10.BIN",
    EF_DG11: "EF_DG11.BIN",
    EF_DG12: "EF_DG12.BIN",
    EF_DG13: "EF_DG13.BIN",
    EF_DG14: "EF_DG14.BIN",
    EF_DG15: "EF_DG15.BIN",
    EF_DG16: "EF_DG16.BIN",
    EF_CardAccess: "EF_CardAccess.BIN",
    EF_SOD: "EF_SOD.BIN",
}

# Flags filenames for local storage
NOBAC_FILE = "NOBAC"

# Data Group 1 Elements
DG1_ELEMENTS = {
    EF_DG1: "EF.DG1",
    "5f01": "LDS Version number with format aabb, where aa defines the version of the LDS and bb defines the update level",
    "5f36": "Unicode Version number with format aabbcc, where aa defines the Major version, bb defines the Minor version and cc defines the release level",
    "5c": "Tag list. List of all Data Groups present.",
}
# Data Group 2 Elements
BDB = "5f2e"
BDB1 = "7f2e"
FAC = "46414300"
DG2_ELEMENTS = {
    EF_DG2: "EF.DG2",
    "7f61": "Biometric Information Group Template",
    "02": "Integer - Number of instances of this type of biometric",
    "7f60": "1st Biometric Information Template",
    "a1": "Biometric Header Template (BHT)",
    "80": "ICAO header version [01 00] (Optional) - Version of the CBEFF patron header format",
    "81": "Biometric type (Optional)",
    "82": "Biometric feature (Optional for DG2, mandatory for DG3, DG4.)",
    "83": "Creation date and time (Optional)",
    "84": "Validity period (from through) (Optional)",
    "86": "Creator of the biometric reference data (PID) (Optional)",
    "87": "Format owner (Mandatory)",
    "88": "Format type (Mandatory)",
    BDB: "Biometric data (encoded according to Format Owner) also called the biometric data block (BDB).",
    BDB1: "Biometric data (encoded according to Format Owner) also called the biometric data block (BDB).",
    # DUP "7f60": "2nd Biometric Information Template",
    FAC: "Format Identifier ASCII FAC\0",
}
# Data Group 2 field types
TEMPLATE = 0
SUB = 1
DG2_TYPE = {
    EF_DG2: TEMPLATE,
    "7f61": TEMPLATE,
    "02": SUB,
    "7f60": TEMPLATE,
    "a1": TEMPLATE,
    "80": SUB,
    "81": SUB,
    "82": SUB,
    "83": SUB,
    "84": SUB,
    "86": SUB,
    "87": SUB,
    "88": SUB,
    "5f2e": TEMPLATE,
    "7f2e": TEMPLATE,
    # DUP    "7f60": TEMPLATE,
}

# ISO 19794_5 (Biometric identifiers)
ISO19794_5_GENDER = {
    "00": "Unpecified",
    "01": "Male",
    "02": "Female",
    "03": "Unknown",
    "ff": "Other",
}

ISO19794_5_EYECOLOUR = {
    "00": "Unspecified",
    "01": "Black",
    "02": "Blue",
    "03": "Brown",
    "04": "Grey",
    "05": "Green",
    "06": "Multi",
    "07": "Pink",
    "08": "Other",
}

ISO19794_5_HAIRCOLOUR = {
    "00": "Unspecified",
    "01": "Bald",
    "02": "Black",
    "03": "Blonde",
    "04": "Brown",
    "05": "Grey",
    "06": "White",
    "07": "Red",
    "08": "Green",
    "09": "Blue",
    "ff": "Other",
}

ISO19794_5_FEATURE = {
    0x01: "Specified",
    0x02: "Glasses",
    0x04: "Moustache",
    0x08: "Beard",
    0x10: "Teeth Visible",
    0x20: "Blink",
    0x40: "Mouth Open",
    0x80: "Left Eyepatch",
    0x100: "Right Eyepatch",
    0x200: "Dark Glasses",
    0x400: "Distorted",
}

ISO19794_5_EXPRESSION = {
    "0000": "Unspecified",
    "0001": "Neutral",
    "0002": "Smile Closed",
    "0003": "Smile Open",
    "0004": "Raised Eyebrow",
    "0005": "Looking Away",
    "0006": "Squinting",
    "0007": "Frowning",
}

ISO19794_5_IMG_TYPE = {
    "00": "Unspecified (Front)",
    "01": "Basic",
    "02": "Full Front",
    "03": "Token Front",
    "04": "Other",
}

ISO19794_5_IMG_DTYPE = {"00": "JPEG", "01": "JPEG 2000"}

ISO19794_5_IMG_FTYPE = {"00": "JPG", "01": "JP2"}

ISO19794_5_IMG_CSPACE = {
    "00": "Unspecified",
    "01": "RGB24",
    "02": "YUV422",
    "03": "GREY8BIT",
    "04": "Other",
}

ISO19794_5_IMG_SOURCE = {
    "00": "Unspecified",
    "01": "Static Unspecified",
    "02": "Static Digital",
    "03": "Static Scan",
    "04": "Video Unknown",
    "05": "Video Analogue",
    "06": "Video Digital",
    "07": "Unknown",
}

ISO19794_5_IMG_QUALITY = {"00": "Unspecified"}

DG7_ELEMENTS = {
    EF_DG7: "EF.DG7",
    "5f43": "Displayed signature or mark",
    "02": "Integer - Number of instances of this type of displayed image",
}

# display options
# standard document
MRZ_FIELD_NAMES = (
    "Document code",
    "Issuing State or Organisation",
    "Name",
    "Passport Number",
    "Check Digit",
    "Nationality",
    "Date of Birth",
    "Check Digit",
    "Sex",
    "Date of Expiry",
    "Check Digit",
    "Personal Number or other optional elements",
    "Check Digit",
    "Composite Check Digit",
)
MRZ_FIELD_LENGTHS = (2, 3, 39, 9, 1, 3, 6, 1, 1, 6, 1, 14, 1, 1)
MRZ_FIELD_DISPLAY = (0, 3, 1, 2, 5, 6, 8, 9, 11)
MRZ_FIELD_KEYS = (44, 57, 65)
# id card
MRZ_FIELD_NAMES_ID = (
    "Document code",
    "Issuing State or Organisation",
    "Document Number",
    "Check Digit",
    "Personal Number or other optional elements",
    "Check Digit",
    "Date of Birth",
    "Check Digit",
    "Sex",
    "Date of Expiry",
    "Check Digit",
    "Nationality",
    "Check Digit",
    "Name",
)
MRZ_FIELD_LENGTHS_ID = (2, 3, 9, 1, 14, 1, 6, 1, 1, 6, 1, 14, 1, 30)
MRZ_FIELD_DISPLAY_ID = (0, 2, 1, 13, 11, 6, 8, 9, 4)
MRZ_FIELD_KEYS_ID = (5, 30, 38)

# Global Send Sequence Counter
SSC = ""
# secure messaging cipher: 3DES (BAC, PACE-3DES) unless PACE negotiated AES
SM_AES = False

# Global bruteforce vars
br_num = []
br_map = []
brnum = 0


def mrzspaces(data, fill):
    out = ""
    for x in data:
        if x == "<":
            out += fill
        else:
            out += x
    return out

#    for x in range(len(data)):
#        if data[x] == "<":
#            out += fill
#        else:
#            out += data[x]
#    return out


Displayed = False
Display_DG7 = False


def drawfeatures(face, features):
    global Displayed # global
    global Style # global

    face.delete("feature")
    if Displayed:
        Displayed = False
        return
    for item in features:
        x = int(item[4:8], 16)
        y = int(item[8:12], 16)
        if Style == "Arrow":
            face.create_line(0, 0, x, y, fill="Red", arrow="last", width=2, tags="feature")
        if Style == "Cross":
            face.create_line(x - 6, y - 6, x + 6, y + 6, fill="Red", width=2, tags="feature")
            face.create_line(x - 6, y + 6, x + 6, y - 6, fill="Red", width=2, tags="feature")
        if Style == "Target":
            face.create_line(x, y - 15, x, y + 15, fill="Red", width=3, tags="feature")
            face.create_line(x - 15, y, x + 15, y, fill="Red", width=3, tags="feature")
            face.create_oval(x - 6, y - 6, x + 6, y + 6, fill="Red", tags="feature")
        if Style == "Circle":
            face.create_oval(x - 6, y - 6, x + 6, y + 6, fill="Red", tags="feature")
        Displayed = True


def changestyle(style, face, features):
    global Style
    global Displayed

    Style = style
    if Displayed:
        Displayed = False
        drawfeatures(face, features)


# secure messaging primitives (ICAO 9303-11 9.8): 3DES-CBC (IV 0) + Retail-MAC with
# 8-byte padding, or for PACE-AES: AES-CBC (IV = E(KSenc, SSC)) + AES-CMAC truncated
# to 8 bytes with 16-byte padding. Padding is ISO 9797-1 method 2 in both cases.
def sm_pad(data):
    "pad to the SM cipher's block size (0x80 then zeros)"
    bs = 16 if SM_AES else 8
    data = bytes(data) + b"\x80"
    while len(data) % bs:
        data += b"\x00"
    return data


def sm_ssc_increment(ssc):
    "increment the Send Sequence Counter, keeping its length (8 bytes 3DES, 16 AES)"
    n = len(ssc)
    return bytearray(((int.from_bytes(bytes(ssc), "big") + 1) % (1 << (8 * n))).to_bytes(n, "big"))


def _sm_cipher(keyenc):
    if SM_AES:
        iv = AES.new(bytes(keyenc), AES.MODE_ECB).encrypt(bytes(SSC))
        return AES.new(bytes(keyenc), AES.MODE_CBC, iv)
    return DES3.new(keyenc, DES.MODE_CBC, passport.DES_IV)


def sm_encrypt(keyenc, data):
    "encrypt (already padded) command data with the current SSC"
    return _sm_cipher(keyenc).encrypt(bytes(data))


def sm_decrypt(keyenc, data):
    "decrypt a response cryptogram with the current SSC"
    return _sm_cipher(keyenc).decrypt(bytes(data))


def sm_mac(keymac, data):
    "8-byte cryptographic checksum over data (padded here for AES; DESMAC pads itself)"
    if SM_AES:
        c = CMAC.new(bytes(keymac), ciphermod=AES)
        c.update(sm_pad(data))
        return c.digest()[:8]
    return passport.DESMAC(data, keymac, "")


def _ber_len(n):
    if n < 0x80:
        return bytes([n])
    if n < 0x100:
        return bytes([0x81, n])
    return bytes([0x82, n >> 8, n & 0xFF])


def sm_do87(cryptogram):
    "DO87: padding-content indicator 01 + cryptogram, with a BER length"
    body = b"\x01" + bytes(cryptogram)
    return b"\x87" + _ber_len(len(body)) + body


def sm_tlvs(rapdu):
    "split a protected response (hex) into {tag: raw TLV bytes} for DO87/DO99/DO8E"
    data = passport.ToBinary(rapdu)
    out = {}
    i = 0
    while i + 2 <= len(data):
        tag = data[i]
        ln = data[i + 1]
        hdr = 2
        if ln == 0x81:
            ln, hdr = data[i + 2], 3
        elif ln == 0x82:
            ln, hdr = (data[i + 2] << 8) | data[i + 3], 4
        out[tag] = bytes(data[i : i + hdr + ln])
        i += hdr + ln
    return out


def sm_do87_plain(keyenc, rapdu):
    "decrypt the DO87 of a protected response, returning the padded plaintext"
    do87 = sm_tlvs(rapdu).get(0x87)
    if not do87:
        return b""
    hdr = 3 if do87[1] == 0x81 else (4 if do87[1] == 0x82 else 2)
    # skip the tag/length and the 01 padding-content indicator
    return sm_decrypt(keyenc, do87[hdr + 1 :])


def secure_select_file(keyenc, keymac, file, p1="02", p2="0c"):
    "secure select file (p1=02/p2=0c selects an EF by id; p1=04 selects a DF by name)"
    global SSC

    cla = "0c"
    ins = passport.ISOAPDU["SELECT_FILE"]
    command = sm_pad(passport.ToBinary(cla + ins + p1 + p2))
    data = sm_pad(passport.ToBinary(file))
    # increment first: the AES IV is derived from this command's SSC
    SSC = sm_ssc_increment(SSC)
    encdata = sm_encrypt(keyenc, data)
    if DEBUG:
        print("Encrypted data: ", end="")
        passport.HexPrint(encdata)
    do87 = sm_do87(encdata)
    m = command + do87
    if DEBUG:
        print("DO87: ", end="")
        passport.HexPrint(m)
    n = SSC + m
    cc = sm_mac(keymac, n)
    if DEBUG:
        print("CC: ", end="")
        passport.HexPrint(cc)
    do8e = passport.ToBinary(passport.DO8E) + cc
    if DEBUG:
        print("DO8E: ", end="")
        passport.HexPrint(do8e)
    lc = "%02x" % (len(do87) + len(do8e))
    le = "00"
    data = passport.ToHex(do87 + do8e)
    if DEBUG:
        print()
        print("Protected APDU: ", end="")
        print(cla + ins + p1 + p2 + lc + data + le)
    ins = "SELECT_FILE"
    if passport.send_apdu("", "", "", "", cla, ins, p1, p2, lc, data, le):
        out = passport.data
    if DEBUG:
        print("Secure Select:", end="")
    if passport.errorcode == APDU_OK:
        if DEBUG:
            print("OK")
        check_cc(keymac, out)
        return True, out
    # else:
    return False, passport.errorcode


def secure_read_binary(keymac, d_bytes, offset):
    "secure read binary data"
    global SSC

    cla = "0c"
    ins = passport.ISOAPDU["READ_BINARY"]
    hexoffset = "%04x" % offset
    p1 = hexoffset[0:2]
    p2 = hexoffset[2:4]
    le = "%02x" % d_bytes
    command = sm_pad(passport.ToBinary(cla + ins + p1 + p2))
    do97 = passport.ToBinary(passport.DO97 + le)
    m = command + do97
    SSC = sm_ssc_increment(SSC)
    n = SSC + m
    cc = sm_mac(keymac, n)
    do8e = passport.ToBinary(passport.DO8E) + cc
    lc = "%02x" % (len(do97) + len(do8e))
    le = "00"
    data = passport.ToHex(do97 + do8e)
    if DEBUG:
        print()
        print("Protected APDU: ", end="")
        print(cla + ins + p1 + p2 + lc + data + le)
    ins = "READ_BINARY"
    if passport.send_apdu("", "", "", "", cla, ins, p1, p2, lc, data, le):
        out = passport.data
    if DEBUG:
        print("Secure Read Binary (%02d bytes): " % d_bytes, end="")
    if passport.errorcode == APDU_OK:
        if DEBUG:
            print("OK:", out)
        check_cc(keymac, out)
        return True, out
    # else:
    return False, passport.errorcode


def calculate_check_digit(data):
    "calculate ICAO 9303 check digit"
    cd = n = 0
    for d in data:
        if "A" <= d <= "Z":
            value = ord(d) - 55
        elif d == "<":
            value = 0
        else:
            value = int(d)
        cd += value * MRZ_WEIGHT[n % 3]
        n += 1
    return "%s" % (cd % 10)


def check_cc(key, rapdu):
    "Check Cryptographic Checksum"
    global SSC

    SSC = sm_ssc_increment(SSC)
    # copy: SSC is a mutable bytearray, and k += ... below would otherwise
    # extend the global SSC in place (corrupting it for the next command)
    k = bytes(SSC)
    # MAC input: SSC + DO87 (if present) + DO99 (if present), each as a full TLV
    # (DO87 may use a long BER length, e.g. 87 81 81 for a 128-byte AES chunk)
    tlvs = sm_tlvs(rapdu)
    k += tlvs.get(0x87, b"") + tlvs.get(0x99, b"")

    if DEBUG:
        print("K: ", end="")
        passport.HexPrint(k)
    cc = sm_mac(key, k)
    if DEBUG:
        print("CC: ", end="")
        print(passport.ToHex(cc), end="")
    if cc == passport.ToBinary(rapdu[len(rapdu) - len(cc) * 2 :]):
        if DEBUG:
            print("(verified)")
        return True
    # else:
    print("Cryptographic Checksum failed!")
    print("Expected CC: ", end="")
    passport.HexPrint(cc)
    print("Received CC: ", end="")
    print(rapdu[len(rapdu) - len(cc) * 2 :])
    sys.exit(True)


def decode_ef_com(data):  # inconsistent-return-statements
    "display contents of EF.COM"
    TAG_PAD = "80"

    # set up array for Data Groups to be read
    ef_groups = []

    hexdata = passport.ToHex(data)
    # skip header
    pos = 2
    # EF.COM length
    print("Length: ", asn1datalength(hexdata[pos:]))
    pos += asn1fieldlength(hexdata[pos:])
    while pos < len(hexdata):
        # end of data
        if hexdata[pos : pos + 2] == TAG_PAD:
            return None # fix pylint inconsistent-return-statements
        # LDS & Unicode Versions
        decoded = False
        for length in 2, 4:
            if hexdata[pos : pos + length] in DG1_ELEMENTS:
                decoded = True
                print(
                    "  tag:",
                    hexdata[pos : pos + length],
                    "(" + DG1_ELEMENTS[hexdata[pos : pos + length]] + ")",
                )
                # decode tag list (stored objects)
                if hexdata[pos : pos + length] == EF_TAGS:
                    pos += 2
                    print("    length: ", end="")
                    length = asn1datalength(hexdata[pos:])
                    print(length)
                    pos += asn1fieldlength(hexdata[pos:])
                    for n in range(length): # Unused variable 'n'
                        print("      Data Group: ", end="")
                        print(hexdata[pos : pos + 2] + " (" + TAG_NAME[hexdata[pos : pos + 2]] + ")")
                        ef_groups.append(hexdata[pos : pos + 2])
                        pos += 2
                else:
                    pos += length
                    fieldlength = asn1datalength(hexdata[pos:])
                    print("    length:", fieldlength)
                    pos += asn1fieldlength(hexdata[pos:])
                    print("    data:", hexdata[pos : pos + fieldlength * 2])
                    pos += fieldlength * 2
        if not decoded:
            print("Unrecognised element:", hexdata[pos : pos + 4])
            sys.exit(True)
    return ef_groups


def read_file(file):
    if not passport.iso_7816_select_file(file, passport.ISO_7816_SELECT_BY_EF, "0C"):
        return False, ""
    readlen = 4
    offset = 4
    if not passport.iso_7816_read_binary(readlen, 0):
        return False, ""
    data = passport.data
    # get file length
    tag = data[:2] # pylint tag unused-variable
    datalen = asn1datalength(data[2:])
    print("File Length:", datalen)
    # deduct length field and header from what we've already read
    readlen = datalen - (3 - asn1fieldlength(data[2:]) // 2)
    print("Remaining data length:", readlen)
    # read remaining bytes
    while readlen > 0:
        if readlen > MAXCHUNK:
            toread = MAXCHUNK
        else:
            toread = readlen
        if not passport.iso_7816_read_binary(toread, offset):
            return False, ""
        data += passport.data
        offset += toread
        readlen -= toread
        print("Reading: %05d\r" % readlen, end="")
        sys.stdout.flush()
    print()
    return True, passport.ToBinary(data)


def asn1fieldlength(data):
    # return length of number field according to asn.1 rules (doubled as we normally care about the hex version)
    if int(data[:2], 16) <= 0x7F:
        return 2
    if int(data[:2], 16) == 0x81:
        return 4
    if int(data[:2], 16) == 0x82:
        return 6
    if int(data[:2], 16) == 0x83:
        return 8
    return None # to fix inconsistent-return-statements


def asn1datalength(data):   # inconsistent-return-statements
    # return actual length represented by asn.1 field
    if int(data[:2], 16) <= 0x7F:
        return int(data[:2], 16)
    if int(data[:2], 16) == 0x81:
        return int(data[2:4], 16)
    if int(data[:2], 16) == 0x82:
        return int(data[2:6], 16)
    if int(data[:2], 16) == 0x83:
        return int(data[2:8], 16)
    return 0 # should not happen


def secure_read_file(keyenc, keymac, file):
    #       MAXCHUNK= int(passport.ISO_FRAMESIZE[passport.framesize])

    status, rapdu = secure_select_file(keyenc, keymac, file)
    if not status:
        return False, rapdu
    # secure read file header (header byte plus up to 3 bytes of field length)
    readlen = 4
    offset = 4
    status, rapdu = secure_read_binary(keymac, readlen, 0)
    if not status:
        return False, rapdu
    if DEBUG:
        print("Decrypted DO87: ", end="")
    decdo87 = sm_do87_plain(keyenc, rapdu)[:readlen]
    if DEBUG:
        passport.HexPrint(decdo87)

    # get file length
    do87hex = passport.ToHex(decdo87)
    # tag = do87hex[:2]  # unused-variable
    datalen = asn1datalength(do87hex[2:])
    print("File Length:", datalen)
    # deduct length field and header from what we've already read
    readlen = datalen - (3 - asn1fieldlength(do87hex[2:]) // 2)
    print("Remaining data length:", readlen)
    # secure read remaining bytes
    while readlen > 0:
        if readlen > MAXCHUNK:
            toread = MAXCHUNK
        else:
            toread = readlen
        status, rapdu = secure_read_binary(keymac, toread, offset)
        if not status:
            return False, rapdu
        decdo87 += sm_do87_plain(keyenc, rapdu)[:toread]
        offset += toread
        readlen -= toread
        print("Reading: %05d\r" % readlen, end="")
        sys.stdout.flush()
    print()
    return True, decdo87


def decode_ef_dg1(data):
    global DocumentType
    global DOCUMENT_TYPE
    global Fields
    global FieldNames
    global FieldLengths
    global FieldKeys

    length = data[4]
    print("Data Length: ", end="")
    print(length)
    pointer = 5
    out = ""
    while pointer < len(data):
        if data[pointer] == 0x80:
            break
        out += chr(data[pointer])
        pointer += 1
    print("  Decoded Data: " + out)
    DocumentType = out[0:2]
    if DocumentType == "IP":
        print("    Document type: Passport Card")
        DOCUMENT_TYPE = "Passport Card"
        Fields = MRZ_FIELD_DISPLAY_ID
        FieldNames = MRZ_FIELD_NAMES_ID
        FieldLengths = MRZ_FIELD_LENGTHS_ID
        FieldKeys = MRZ_FIELD_KEYS_ID
    elif DocumentType[0] == "I":
        print("    Document type: ID Card")
        DOCUMENT_TYPE = "ID Card"
        Fields = MRZ_FIELD_DISPLAY_ID
        FieldNames = MRZ_FIELD_NAMES_ID
        FieldLengths = MRZ_FIELD_LENGTHS_ID
        FieldKeys = MRZ_FIELD_KEYS_ID
    elif DocumentType == "AC":
        print("    Document type: Aircrew card, which we do not know how to decode. Attempting ID card settings.")
        DOCUMENT_TYPE = "Aircrew Card"
        Fields = MRZ_FIELD_DISPLAY_ID
        FieldNames = MRZ_FIELD_NAMES_ID
        FieldLengths = MRZ_FIELD_LENGTHS_ID
        FieldKeys = MRZ_FIELD_KEYS_ID
    else:
        print("    Document type: Passport")
        DOCUMENT_TYPE = "Passport"
        Fields = MRZ_FIELD_DISPLAY
        FieldNames = MRZ_FIELD_NAMES
        FieldLengths = MRZ_FIELD_LENGTHS
        FieldKeys = MRZ_FIELD_KEYS
    pointer = 0
    for n in range(len(FieldNames)):
        print("    " + FieldNames[n] + ": ", end="")
        print(out[pointer : pointer + FieldLengths[n]])
        pointer += FieldLengths[n]
    return out


def decode_ef_dg2(data):
    global Filetype
    img_features = []

    datahex = passport.ToHex(data)
    position = 0
    end = len(datahex)
    instance = 1
    instances = 1
    while position < end:
        decoded = False
        # check for presence of tags
        for length in 4, 2:
            if datahex[position : position + length] in DG2_ELEMENTS:
                decoded = True
                tag = datahex[position : position + length]
                print(
                    "  Tag:",
                    tag,
                    "(" + DG2_ELEMENTS[tag] + ")",
                    "@",
                    position // 2,
                    end="",
                )
                # don't skip TEMPLATE fields as they contain sub-fields
                # except BDB which is a special case (CBEFF formatted) so for now
                # just try and extract the image which is 65 bytes in
                if DG2_TYPE[tag] == TEMPLATE:
                    position += length
                    fieldlength = asn1datalength(datahex[position:])
                    print("     length:", fieldlength)
                    if tag in (BDB, BDB1):
                        # process CBEFF block
                        position += asn1fieldlength(datahex[position:])
                        startposition = position // 2
                        # FACE header
                        length = len(FAC)
                        tag = datahex[position : position + length]
                        if tag != FAC:
                            print("Missing FAC in CBEFF block: %s" % tag)
                            sys.exit(True)
                        position += length
                        # FACE version
                        print("    FACE version: %s" % passport.ToBinary(datahex[position : position + 6]))
                        position += 8
                        # Image length
                        print("      Record Length: %d" % int(datahex[position : position + 8], 16))
                        # imagelength = int(datahex[position : position + 8], 16) @ unused
                        position += 8
                        # Number of Images
                        images = int(datahex[position : position + 4], 16)
                        print("      Number of Images: %d" % images)
                        position += 4
                        # Facial Image block
                        print("      Block Length: %d" % int(datahex[position : position + 8], 16))
                        position += 8
                        features = int(datahex[position : position + 4], 16)
                        print("      Number of Features: %d" % features)
                        position += 4
                        print("      Gender: %s" % ISO19794_5_GENDER[datahex[position : position + 2]])
                        position += 2
                        print("      Eye Colour: %s" % ISO19794_5_EYECOLOUR[datahex[position : position + 2]])
                        position += 2
                        print("      Hair Colour: %s" % ISO19794_5_HAIRCOLOUR[datahex[position : position + 2]])
                        position += 2
                        mask = int(datahex[position : position + 6], 16)
                        print("      Feature Mask: %s" % datahex[position : position + 6])
                        position += 6
                        if features:
                            print("      Features:")
                            for m, d in list(ISO19794_5_FEATURE.items()):
                                if and_(mask, m):
                                    print("        : %s" % d)
                        print("      Expression: %s" % ISO19794_5_EXPRESSION[datahex[position : position + 4]])
                        position += 4
                        print("      Pose Angle: %s" % datahex[position : position + 6])
                        position += 6
                        print("      Pose Angle Uncertainty: %s" % datahex[position : position + 6])
                        position += 6
                        while features > 0:
                            print("      Feature block: %s" % datahex[position : position + 16])
                            img_features.append(datahex[position : position + 16])
                            features -= 1
                            position += 16
                        print("      Image Type: %s" % ISO19794_5_IMG_TYPE[datahex[position : position + 2]])
                        position += 2
                        print("      Image Data Type: %s" % ISO19794_5_IMG_DTYPE[datahex[position : position + 2]])
                        Filetype = ISO19794_5_IMG_FTYPE[datahex[position : position + 2]]
                        position += 2
                        print("      Image Width: %d" % int(datahex[position : position + 4], 16))
                        position += 4
                        print("      Image Height: %d" % int(datahex[position : position + 4], 16))
                        position += 4
                        print("      Image Colour Space: %s" % ISO19794_5_IMG_CSPACE[datahex[position : position + 2]])
                        position += 2
                        print("      Image Source Type: %s" % ISO19794_5_IMG_SOURCE[datahex[position : position + 2]])
                        position += 2
                        print("      Image Device Type: %s" % datahex[position : position + 6])
                        position += 6
                        print("      Image Quality: %s" % ISO19794_5_IMG_QUALITY[datahex[position : position + 2]])
                        position += 2
                        if instances > 1:
                            filename = "%sEF_DG2_%i.%s" % (
                                tempfiles,
                                instance,
                                Filetype,
                            )
                            instance += 1
                        else:
                            filename = "%sEF_DG2.%s" % (tempfiles, Filetype)
                        with open(filename, "wb+") as img:
                            img.write(data[position // 2 : startposition + fieldlength])
                        print("     JPEG image stored in %s" % filename)
                        position = (startposition + fieldlength) * 2
                    else:
                        position += asn1fieldlength(datahex[position:])
                else:
                    position += length
                    fieldlength = asn1datalength(datahex[position:])
                    print("     length:", fieldlength)
                    position += asn1fieldlength(datahex[position:])
                    print("     data:", datahex[position : position + fieldlength * 2])
                    if tag == "02":
                        instances = int(datahex[position : position + fieldlength * 2], 16)
                    position += fieldlength * 2
        if not decoded:
            print(
                "Unrecognised element @",
                position // 2,
                ":",
                datahex[position : position + 4],
            )
            sys.exit(True)
    return img_features


def decode_ef_dg7(data):
    global Filetype
    global Display_DG7
    datahex = passport.ToHex(data)
    position = 0
    end = len(datahex)
    while position < end:
        decoded = False
        # check for presence of tags
        for length in 4, 2:
            if datahex[position : position + length] in DG7_ELEMENTS:
                decoded = True
                tag = datahex[position : position + length]
                print("  Tag:", tag, "(" + DG7_ELEMENTS[tag] + ")")
                position += length
                fieldlength = asn1datalength(datahex[position:])
                print("     length:", fieldlength)
                if tag == "67":
                    position += asn1fieldlength(datahex[position:])
                elif tag == "02":
                    position += asn1fieldlength(datahex[position:])
                    print("     content: %i instance(s)" % int(datahex[position : position + fieldlength * 2], 16))
                    # note that for now we don't support decoding several instances...
                    position += fieldlength * 2
                elif tag == "5f43":
                    position += asn1fieldlength(datahex[position:])
                    with open(tempfiles + "EF_DG7." + Filetype, "wb+") as img:
                        img.write(data[position // 2 : position + fieldlength])
                    print("     JPEG image stored in %sEF_DG7.%s" % (tempfiles, Filetype))
                    Display_DG7 = True
                    position += fieldlength * 2
        if not decoded:
            print("Unrecognised element:", datahex[position : position + 4])
            sys.exit(True)
    return # pylint  useless-return ?


def jmrtd_create_file(file, length):
    "create JMRTD file"
    ins = "CREATE_FILE"
    p1 = "00"
    p2 = "00"
    le = "06"  # length is always 6
    data = "6304" + "%04x" % length + file
    if passport.send_apdu("", "", "", "", "", ins, p1, p2, le, data, ""):
        return
    if passport.errorcode == "6D00":
        # could be a vonJeek card
        print("create file failed - assuming vonJeek emulator")
        return
    passport.iso_7816_fail(passport.errorcode)


def jmrtd_select_file(file):
    "select JMRTD file"
    ins = "SELECT_FILE"
    p1 = "00"
    p2 = "00"
    data = "02" + file
    if passport.send_apdu("", "", "", "", "", ins, p1, p2, "", data, ""):
        return
    if passport.errorcode == "6982":
        # try vonJeek
        print("selecting vonJeek file")
        ins = "VONJEEK_SELECT_FILE"
        cla = "10"
        if passport.send_apdu("", "", "", "", cla, ins, p1, p2, "", data, ""):
            return
    passport.iso_7816_fail(passport.errorcode)


def jmrtd_write_file(file, data):
    "write data to JMRTD file"
    jmrtd_select_file(file)
    offset = 0
    towrite = len(data)
    while towrite:
        if towrite > MAXCHUNK:
            chunk = MAXCHUNK
        else:
            chunk = towrite
        print("\rwriting %d bytes       " % towrite, end="")
        sys.stdout.flush()
        jmrtd_update_binary(offset, data[offset : offset + chunk])
        offset += chunk
        towrite -= chunk
    print()


def jmrtd_update_binary(offset, data):
    "write a chunk of data to an offset within the currently selected JMRTD file"
    hexoff = "%04x" % offset
    ins = "UPDATE_BINARY"
    p1 = hexoff[0:2]
    p2 = hexoff[2:4]
    lc = "%02x" % len(data)
    data = passport.ToHex(data)
    if passport.send_apdu("", "", "", "", "", ins, p1, p2, lc, data, ""):
        return
    if passport.errorcode == "6D00":
        # vonJeek
        print("(vonJeek)", end="")
        ins = "VONJEEK_UPDATE_BINARY"
        cla = "10"
        if passport.send_apdu("", "", "", "", cla, ins, p1, p2, lc, data, ""):
            return
    passport.iso_7816_fail(passport.errorcode)


def jmrtd_personalise(documentnumber, dob, expiry):
    "set the secret key for JMRTD document"
    ins = "PUT_DATA"
    p1 = "00"
    p2 = "62"
    data = (
        "621B04"
        + "%02x" % len(documentnumber)
        + passport.ToHex(documentnumber)
        + "04"
        + "%02x" % len(dob)
        + passport.ToHex(dob)
        + "04"
        + "%02X" % len(expiry)
        + passport.ToHex(expiry)
    )
    lc = "%02X" % (len(data) // 2)
    if passport.send_apdu("", "", "", "", "", ins, p1, p2, lc, data, ""):
        return
    if passport.errorcode == "6D00":
        # vonJeek
        cla = "10"
        ins = "VONJEEK_SET_MRZ"
        data = (
            passport.ToHex(documentnumber)
            + passport.ToHex(calculate_check_digit(documentnumber))
            + passport.ToHex(dob)
            + passport.ToHex(calculate_check_digit(dob))
            + passport.ToHex(expiry)
            + passport.ToHex(calculate_check_digit(expiry))
        )
        lc = "%02X" % (len(data) // 2)
        if passport.send_apdu("", "", "", "", cla, ins, p1, p2, lc, data, ""):
            # see if we need to set BAC or not, hacky way for now...
            if os.access(filespath + NOBAC_FILE, os.F_OK):
                BAC = False
            else:
                BAC = True
            if BAC:
                vonjeek_setBAC()
            else:
                vonjeek_unsetBAC()
            return
    passport.iso_7816_fail(passport.errorcode)


def vonjeek_setBAC():
    "enable BAC on vonjeek emulator card"
    # Setting BAC works only on recent vonJeek emulators, older have only BAC anyway
    print("Forcing BAC mode to ENABLED")
    if passport.send_apdu("", "", "", "", "10", "VONJEEK_SET_BAC", "00", "01", "00", "", ""):
        return
    # else:
    print("ERROR Could not enable BAC, make sure you are using a recent vonJeek emulator")
    sys.exit(True)


def vonjeek_unsetBAC():
    "disable BAC on vonjeek emulator card"
    print("Forcing BAC mode to DISABLED")
    if passport.send_apdu("", "", "", "", "10", "VONJEEK_SET_BAC", "00", "00", "00", "", ""):
        return
    # else:
    print("ERROR Could not disable BAC, make sure you are using a recent vonJeek emulator")
    sys.exit(True)


def jmrtd_lock():
    "set the JMRTD to Read Only"
    ins = "PUT_DATA"
    p1 = "de"
    p2 = "ad"
    lc = "00"
    if passport.send_apdu("", "", "", "", "", ins, p1, p2, lc, "", ""):
        return
    passport.iso_7816_fail(passport.errorcode)


def bruteno(init):
    global br_num # global
    global br_map # global
    global brnum # global
    global width # global

    if init:
        # set up brute force and return number of iterations required
        width = 0
        # for x in range(len(init)):
        for x, init_dat in enumerate(init):
            if init_dat == "?":
                width += 1
                br_num.append(0)
                br_map.append(True)
            else:
                br_num.append(init_dat)
                br_map.append(False)
        return pow(10, width)
    # else:
    out = ""
    bruted = False
    for x in range(len(br_num)):  # pylint: disable=consider-using-enumerate
        if br_map[x]:
            if bruted:
                continue
            # else:
            bruted = True
            out += "%0*d" % (width, brnum)
            brnum += 1
        else:
            out += br_num[x]
    return out


try:
    passport = rfidiot.card
except:
    sys.exit(True)

args = rfidiot.args
Help = rfidiot.help
Nogui = rfidiot.nogui
DEBUG = rfidiot.rfidiotglobals.Debug

myver = "mrpkey v3.1e"

TEST = False
FILES = False
bruteforce = False
bruteforceno = False
bruteforcereset = False
Jmrtd = False
JmrtdLock = False
MRZ = True
BAC = True
SETBAC = False
UNSETBAC = False
PACE = False
UsePACE = False
pace_authenticated = False


def print_help():
    print()
    print("Usage:")
    print("\t" + sys.argv[0] + " [OPTIONS] <MRZ (Lower)|PLAIN|CHECK|[PATH]> [WRITE|WRITELOCK|SLOWBRUTE|PACE]")
    print()
    print("\tSpecify the Lower MRZ as a quoted string or the word TEST to use sample data.")
    print("\tLower MRZ can be full line or shortened to the essentials: chars 1-9;14-19;22-27")
    print("\tFor Passport Cards, all three lines are required or use card number, DOB and expiry (NNNNNNNNNNYYMMDDYYMMDD)")
    print("\tSpecify the word PLAIN if the passport doesn't have BAC (shorthand for dummy MRZ)")
    print("\tSpecify the word CHECK to check if the device is a passport.")
    print("\tSpecify a PATH to use files that were previously read from a passport.")
    print("\tSpecify the option WRITE after a PATH to initialise a JMRTD or vonJeek emulator 'blank'.")
    print("\tSpecify the option WRITELOCK after a PATH to initialise a JMRTD emulator 'blank' and set to Read Only.")
    print("\tSpecify the option WRITE/WRITELOCK after a MRZ or PLAIN to clone a passport to a JMRTD or vonJeek emulator.")
    print("\tSpecify the option SETBAC   to enable  BAC on a (already configured) vonJeek emulator card.")
    print("\tSpecify the option UNSETBAC to disable BAC on a (already configured) vonJeek emulator card.")
    print("\tSpecify '?' for check digits if not known and they will be calculated.")
    print("\tSpecify '?' in the passport number field for bruteforce of that portion.")
    print("\tNote: only one contiguous portion of the field may be bruteforced.")
    print("\tSpecify the option SLOWBRUTE after MRZ to force reset between attempts (required on some new passports)")
    print("\tSpecify the option PACE after the MRZ to use PACE instead of BAC (if the chip supports it).")
    print("\tPadding character '<' should be used for unknown fields.")
    print()
    print("\tPassive Authentication: set $RFIDIOT_MASTERLIST to a CSCA master list (.ml)")
    print("\t(e.g. the BSI GermanMasterList) to verify the passport and flag it SAFE/UNSAFE,")
    print("\tor place one at ~/.rfidiot/masterlist.ml or /etc/rfidiot/masterlist.ml.")
    print("\tWithout a master list it still checks data-group integrity and any CSCA the")
    print("\tdocument itself carries. Set $RFIDIOT_CSCA_FETCH=1 to also follow the URLs the")
    print("\tdocument names (AIA/CPS) to fetch a CSCA - result stays UNTRUSTED (DUT-chosen).")
    print()
    sys.exit(True)


if len(args) == 0 or Help:
    print_help()

passport.info(myver)

arg0 = args[0].upper()

if (
    not (
        len(arg0) == 44
        or len(arg0) == 21
        or len(arg0) == 90
        or arg0 == "TEST"
        or arg0 == "CHECK"
        or arg0 == "PLAIN"
        or arg0 == "SETBAC"
        or arg0 == "UNSETBAC"
        or os.access(args[0], os.F_OK)
    )
    or len(args) > 2
):
    print_help()

if len(args) == 2:
    arg1 = args[1].upper()
    if arg1 == "PACE":
        UsePACE = True
    elif arg1 in ('WRITE', 'WRITELOCK', 'SLOWBRUTE'):
        help()

print()

# check if we are reading from files
if os.access(args[0], os.F_OK):
    FILES = True
    filespath = args[0]
    if not filespath[len(filespath) - 1] == "/":
        filespath += "/"
    try:
        with open(filespath + "EF_COM.BIN", "rb") as passfile:
            data = passfile.read()
        eflist = decode_ef_com(data)
        raw_efcom = data
    except:
        print("Can't open %s" % (filespath + "EF_COM.BIN"))
        sys.exit(True)

#    try:
#        passfile = open(filespath + "EF_COM.BIN", "rb")
#    except:
#        print("Can't open %s" % (filespath + "EF_COM.BIN"))
#        sys.exit(True)
#    data = passfile.read()
#    eflist = decode_ef_com(data)
#    raw_efcom = data
#    passfile.close()

if arg0 == "PLAIN" or len(arg0) == 44 or len(arg0) == 21 or FILES:
    if len(args) == 2:
        if arg1 == "WRITE":
            Jmrtd = True
        if arg1 == "WRITELOCK":
            Jmrtd = True
            JmrtdLock = True

if len(args) == 2 and arg1 == "SLOWBRUTE":
    bruteforcereset = True

if arg0 == "TEST":
    TEST = True

if arg0 == "SETBAC":
    MRZ = False
    SETBAC = True

if arg0 == "UNSETBAC":
    MRZ = False
    UNSETBAC = True

if arg0 == "CHECK":
    while not passport.hsselect("08", "A") and not passport.hsselect("08", "B"):
        print("Waiting for passport... (%s)" % passport.errorcode)
    if passport.iso_7816_select_file(passport.AID_MRTD, passport.ISO_7816_SELECT_BY_NAME, "0C"):
        print("Device is a Machine Readable Document")
        sys.exit(False)
    else:
        print("Device may NOT be a Machine Readable Document")
        passport.iso_7816_fail(passport.errorcode)
        sys.exit(True)

if arg0 == "PLAIN":
    MRZ = False

if TEST:
    passport.MRPmrzl(TEST_MRZ)
    print("Test MRZ: " + TEST_MRZ)
if not TEST and not FILES and MRZ:
    key = arg0
    # expands short MRZ version if needed. The optional-data field (positions
    # 29-42) must be padded with the MRZ filler '<' (value 0), not 'X' (value 33),
    # or the recomputed optional and composite check digits come out wrong (#11).
    # The check-digit positions themselves are recomputed, so their padding is
    # immaterial; '<' is used throughout for a faithful "Corrected MRZ" display.
    if len(key) == 21:
        key = key[0:9] + "<" * 4 + key[9:15] + "<" * 2 + key[15:21] + "<" * 17
    elif len(key) == 90:
        # Handles full MRZ needed for Passport cards
        key = key[5:15] + "XXX" + key[30:45] + "XXXXXXXXXXXXXXXX"
    passport.MRPmrzl(key)


if not FILES and not TEST:
    # set communication speed
    # 01 = 106 kBaud
    # 02 = 212 kBaud
    # 04 = 414 kBaud
    # 08 = 818 kBaud
    while 42:
        cardtype = "A"
        if passport.hsselect("08", cardtype):
            break
        cardtype = "B"
        if passport.hsselect("08", cardtype):
            break
        print("Waiting for passport... (%s)" % passport.errorcode)
    print("Device set to %s transfers" % passport.ISO_SPEED[passport.speed])
    print("Device supports %s Byte transfers" % passport.ISO_FRAMESIZE[passport.framesize])
    print()
    print("Checking presence of EF_CardAccess (PACE):")
    pace_infos = []
    status, data = read_file(TAG_FID[EF_CardAccess])
    if status:
        print("  Stored in", tempfiles + TAG_FILE[EF_CardAccess])

        with open(tempfiles + TAG_FILE[EF_CardAccess], "wb+") as outfile:
            outfile.write(data)
            outfile.flush()
        PACE = True
        pace_infos = pace.parse_cardaccess(data)
        for pinfo in pace_infos:
            print("  PACEInfo: %s  domain parameter %s%s"
                  % (pinfo[0], pinfo[2], "" if pace.supported(pinfo) else "  (not implemented)"))
        if not UsePACE:
            print("ePP supports PACE (add the PACE keyword after the MRZ to use it)")
    else:
        print("ePP doesn't support PACE")

    if UsePACE:
        if not pace_infos or not pace.supported(pace_infos[0]):
            print("Cannot use PACE: no supported PACEInfo in EF.CardAccess")
            sys.exit(True)
        if not MRZ:
            print("Please provide a MRZ to use PACE!")
            sys.exit(True)
        oid_dotted, oid_hex, param_id = pace_infos[0]
        passport.MRPnumbercd = calculate_check_digit(passport.MRPnumber)
        passport.MRPdobcd = calculate_check_digit(passport.MRPdob)
        passport.MRPexpirycd = calculate_check_digit(passport.MRPexpiry)
        kmrz = (passport.MRPnumber + passport.MRPnumbercd + passport.MRPdob
                + passport.MRPdobcd + passport.MRPexpiry + passport.MRPexpirycd)
        print()
        print("Performing PACE (%s, domain parameter %d):" % (oid_dotted, param_id))
        try:
            KSenc, KSmac, SSC, pace_sm = pace.perform_pace(
                passport, kmrz, oid_dotted, oid_hex, param_id,
                password_ref=1, debug=DEBUG)
        except pace.PACEError as pmsg:
            print("PACE failed:", pmsg)
            sys.exit(True)
        print("PACE established secure messaging (%s)" % pace_sm)
        SM_AES = pace_sm.startswith("AES")
        print("  Session Key ENC: ", end="")
        passport.HexPrint(KSenc)
        print("  Session Key MAC: ", end="")
        passport.HexPrint(KSmac)
        print("Select Passport Application (AID) under SM: ", end="")
        status, _d = secure_select_file(KSenc, KSmac, passport.AID_MRTD, p1="04")
        if not status:
            passport.iso_7816_fail(passport.errorcode)
        print("OK")
        BAC = True
        pace_authenticated = True
    else:
        print("Select Passport Application (AID): ", end="")
        if passport.iso_7816_select_file(passport.AID_MRTD, passport.ISO_7816_SELECT_BY_NAME, "0C"):
            print("OK")
        else:
            passport.iso_7816_fail(passport.errorcode)

        print("Select Master File: ", end="")
        if passport.iso_7816_select_file(TAG_FID[EF_COM], passport.ISO_7816_SELECT_BY_EF, "0C"):

            # try forcing BAC by reading a file
            status, data = read_file(TAG_FID[EF_DG1])
            if not status and passport.errorcode == APDU_BAC:
                BAC = True
            else:
                print("No Basic Access Control!")
                print(passport.errorcode)
                BAC = False
if BAC and not pace_authenticated:
    print("Basic Access Control Enforced!")

if SETBAC:
    vonjeek_setBAC()
    sys.exit(True)

if UNSETBAC:
    vonjeek_unsetBAC()
    sys.exit(True)

if BAC and not MRZ:
    print("Please provide a MRZ!")
    sys.exit(True)

if not FILES and BAC and not pace_authenticated:
    print("Passport number: " + passport.MRPnumber)
    # if passport.MRPnumber.find("?") >= 0:
    if "?" in passport.MRPnumber:
        bruteforce = True
        bruteforceno = True
        # initialise bruteforce for number
        iterations = bruteno(passport.MRPnumber)
        print("Bruteforcing Passport Number (%d iterations)" % iterations)
    else:
        iterations = 1
    print("Nationality: " + passport.MRPnationality)
    print("Date Of Birth: " + passport.MRPdob)
    print("Sex: " + passport.MRPsex)
    print("Expiry: " + passport.MRPexpiry)
    print("Optional: " + passport.MRPoptional)

    # loop until successful login breaks us out or we've tried all possibilities
    while iterations:
        iterations -= 1
        if bruteforceno:
            passport.MRPnumber = bruteno("")
        # always calculate check digits (makes bruteforcing easier)
        passport.MRPnumbercd = calculate_check_digit(passport.MRPnumber)
        passport.MRPdobcd = calculate_check_digit(passport.MRPdob)
        passport.MRPexpirycd = calculate_check_digit(passport.MRPexpiry)
        passport.MRPoptionalcd = calculate_check_digit(passport.MRPoptional)
        passport.MRPcompsoitecd = calculate_check_digit(
            passport.MRPnumber
            + passport.MRPnumbercd
            + passport.MRPdob
            + passport.MRPdobcd
            + passport.MRPexpiry
            + passport.MRPexpirycd
            + passport.MRPoptional
            + passport.MRPoptionalcd
        )

        kmrz = passport.MRPnumber + passport.MRPnumbercd + passport.MRPdob + passport.MRPdobcd + passport.MRPexpiry + passport.MRPexpirycd

        print()
        print("Generate local keys:")
        print()
        if not TEST:
            print("Supplied MRZ:  " + arg0)
            print(
                "Corrected MRZ: "
                + passport.MRPnumber
                + passport.MRPnumbercd
                + passport.MRPnationality
                + passport.MRPdob
                + passport.MRPdobcd
                + passport.MRPsex
                + passport.MRPexpiry
                + passport.MRPexpirycd
                + passport.MRPoptional
                + passport.MRPoptionalcd
                + passport.MRPcompsoitecd
            )
        print("Key MRZ Info (kmrz): " + kmrz)
        print()
        kseedhash = SHA.new(kmrz.encode('utf-8'))
        #kseed = kseedhash.digest()[:16].decode('iso-8859-15')
        kseed = kseedhash.digest()[:16]
        if DEBUG:
            print("Kseed (SHA1 hash digest of kmrz): " + kseedhash.hexdigest()[:32])

        # calculate Kenc & Kmac
        Kenc = passport.DESKey(kseed, passport.KENC, 16)
        if DEBUG:
            print("Kenc: ", end="")
            passport.HexPrint(Kenc)
        Kmac = passport.DESKey(kseed, passport.KMAC, 16)
        if DEBUG:
            print("Kmac: ", end="")
            passport.HexPrint(Kmac)
            print()

        if TEST:
            rnd_ifd = TEST_rnd_ifd
            rnd_icc = TEST_rnd_icc
            Kifd = TEST_Kifd
        else:
            if DEBUG:
                print("Get Challenge from Passport (rnd_icc): ", end="")
            if passport.iso_7816_get_challenge(8):
                rnd_icc = passport.data
            else:
                passport.iso_7816_fail(passport.errorcode)
            if DEBUG:
                passport.HexPrint(rnd_icc)
            rnd_ifd = passport.GetRandom(8)
            Kifd = passport.GetRandom(16)

        if DEBUG or TEST:
            print("Generate local random Challenge (rnd_ifd): " + rnd_ifd)
            print("Generate local random Challenge (Kifd): " + Kifd)
            print()

        S = passport.ToBinary(rnd_ifd + rnd_icc + Kifd)

        if DEBUG or TEST:
            print("S: ", end="")
            passport.HexPrint(S)

        if DEBUG or TEST:
            print("Kenc: ", end="")
            passport.HexPrint(Kenc)

        tdes = DES3.new(Kenc, DES.MODE_CBC, passport.DES_IV)
        Eifd = tdes.encrypt(bytes(S))
        if DEBUG or TEST:
            print("Eifd: ", end="")
            passport.HexPrint(Eifd)
            print("Kmac: ", end="")
            passport.HexPrint(Kmac)
        Mifd = passport.DESMAC(Eifd, Kmac, "")
        if DEBUG or TEST:
            print("Mifd: ", end="")
            passport.HexPrint(Mifd)

        cmd_data = Eifd + Mifd
        if DEBUG or TEST:
            print("cmd_data: ", end="")
            passport.HexPrint(cmd_data)
            print()

        if TEST:
            respdata = TEST_respdata
        else:
            print("Authenticating: ", end="")
            if passport.iso_7816_external_authenticate(passport.ToHex(cmd_data), Kmac):
                respdata = passport.data
            else:
                # failures allowed if we're brute forcing
                if brnum:
                    respdata = ""
                else:
                    passport.iso_7816_fail(passport.errorcode)
        if DEBUG or TEST:
            print("Auth Response: " + respdata)
        resp = respdata[:64]  # pylint respdata possibly-used-before-assignment
        respmac = respdata[64:80]
        if DEBUG or TEST:
            print("Auth message: " + resp)
            print("Auth MAC: " + respmac + " (verified)")
        tdes = DES3.new(Kenc, DES.MODE_CBC, passport.DES_IV)
        decresp = passport.ToHex(tdes.decrypt(passport.ToBinary(resp)))
        if DEBUG or TEST:
            print("Decrypted Auth Response: " + decresp)
            print("Decrypted rnd_icc: " + decresp[:16])
        recifd = decresp[16:32]
        if DEBUG or TEST:
            print("Decrypted rnd_ifd: " + recifd, end="")
        # check returned rnd_ifd matches our challenge
        if passport.ToBinary(recifd) != passport.ToBinary(rnd_ifd):
            print("Challenge failed!")
            print("Expected rnd_ifd: ", rnd_ifd)
            print("Received rnd_ifd: ", recifd)
            if not bruteforce or iterations == 0:
                sys.exit(True)
            if bruteforcereset:
                while not passport.hsselect("08", cardtype):
                    print("Waiting for passport... (%s)" % passport.errorcode)
                passport.iso_7816_select_file(passport.AID_MRTD, passport.ISO_7816_SELECT_BY_NAME, "0C")
        else:
            if DEBUG or TEST:
                print("(verified)")
            # challenge succeeded, so break
            break

    kicc = decresp[32:64]
    if DEBUG or TEST:
        print("Decrypted Kicc: " + kicc)

    # generate session keys
    print()
    print("Generate session keys: ")
    print()
    kseedhex = "%032x" % xor(int(Kifd, 16), int(kicc, 16))
    kseed = passport.ToBinary(kseedhex)
    print("Kifd XOR Kicc (kseed): ", end="")
    passport.HexPrint(kseed)
    KSenc = passport.DESKey(kseed, passport.KENC, 16)
    print("Session Key ENC: ", end="")
    passport.HexPrint(KSenc)
    KSmac = passport.DESKey(kseed, passport.KMAC, 16)
    print("Session Key MAC: ", end="")
    passport.HexPrint(KSmac)

    print()
    # calculate Send Sequence Counter
    print("Calculate Send Sequence Counter: ")
    print()
    SSC = passport.ToBinary(rnd_icc[8:16] + rnd_ifd[8:16])
    print("SSC: ", end="")
    passport.HexPrint(SSC)

    # secure select master file
    if TEST:
        KSmac = passport.ToBinary("F1CB1F1FB5ADF208806B89DC579DC1F8")
        rapdu = "990290008E08FA855A5D4C50A8ED9000"
        # ran out of steam on testing here!
        sys.exit(False)
    else:
        status, data = secure_read_file(KSenc, KSmac, TAG_FID[EF_COM])
        if not status:
            passport.iso_7816_fail(data)

    # secure read file header
    # if TEST:
    #       KSmac= passport.ToBinary('F1CB1F1FB5ADF208806B89DC579DC1F8')
    #       rapdu= '8709019FF0EC34F9922651990290008E08AD55CC17140B2DED9000'
    # else:
    #       readlen= 4
    #       rapdu= secure_read_binary(KSmac,readlen,0)

    print("EF.COM: ", end="")
    if DEBUG:
        passport.HexPrint(data)
    eflist = decode_ef_com(data)
    raw_efcom = data
    with open(tempfiles + TAG_FILE[EF_COM], "wb+") as efcom:
        efcom.write(data)
        # efcom.flush()
    print("EF.COM stored in", tempfiles + TAG_FILE[EF_COM])

if not FILES and pace_authenticated:
    # PACE has already established secure messaging; read EF.COM under SM
    status, data = secure_read_file(KSenc, KSmac, TAG_FID[EF_COM])
    if not status:
        passport.iso_7816_fail(data)
    print("EF.COM: ", end="")
    if DEBUG:
        passport.HexPrint(data)
    eflist = decode_ef_com(data)
    raw_efcom = data
    with open(tempfiles + TAG_FILE[EF_COM], "wb+") as efcom:
        efcom.write(data)
    print("EF.COM stored in", tempfiles + TAG_FILE[EF_COM])

if not FILES and not BAC:
    status, data = read_file(TAG_FID[EF_COM])
    if not status:
        passport.iso_7816_fail(passport.errorcode)

    print("EF.COM: ", end="")
    if DEBUG:
        passport.HexPrint(data)
    eflist = decode_ef_com(data)
    raw_efcom = data

    # ??
    bacfile = open(tempfiles + NOBAC_FILE, "wb+")
    bacfile.close()

    with open(tempfiles + TAG_FILE[EF_COM], "wb+") as efcom:
        efcom.write(data)
        efcom.flush()
    print("EF.COM stored in", tempfiles + TAG_FILE[EF_COM])

# get SOD
# print
# print 'Select EF.SOD: ',
# data= secure_read_file(KSenc,KSmac,TAG_FID[EF_SOD])
# if DEBUG:
#       passport.HexPrint(data)
# sod= open(tempfiles+TAG_FILE[EF_SOD],'w+')
# sod.write(data)
# sod.flush()
# sod.close()
# print 'EF.SOD stored in', tempfiles+TAG_FILE[EF_SOD]

# Add Security Object and Main Directory to list for reading
eflist.insert(0, EF_SOD)
eflist.insert(0, EF_COM)
# now get everything else
for tag in eflist:
    print("Reading:", TAG_NAME[tag])
    if not FILES:
        if tag in [EF_DG3, EF_DG4]:
            # DG3 (fingerprints) / DG4 (iris) are EAC-protected: reading them needs
            # Terminal Authentication with a country-signed inspection-system
            # certificate, which we don't have (and a failed attempt would drop the
            # secure-messaging session and force a new BAC).
            print("skipping (requires EAC Terminal Authentication - country-signed inspection-system certificate)")
            continue
        if BAC:
            status, data = secure_read_file(KSenc, KSmac, TAG_FID[tag])
        else:
            status, data = read_file(TAG_FID[tag])
        if not status:
            print("skipping (%s)" % passport.get_error_str(data))
            continue
    else:
        try:
            with open(filespath + TAG_FILE[tag], "rb") as passfile:
                data = passfile.read()
        except:
            print("*** Warning! Can't open %s" % filespath + TAG_FILE[tag])
            continue


# Orig code never closed file ??
#        try:
#            passfile = open(filespath + TAG_FILE[tag], "rb")
#        except:
#            print("*** Warning! Can't open %s" % filespath + TAG_FILE[tag])
#            continue
#        data = passfile.read()

    if DEBUG:
        passport.HexPrint(data)
    with open(tempfiles + TAG_FILE[tag], "wb+") as outfile:
        outfile.write(data)

    print("  Stored in", tempfiles + TAG_FILE[tag])
    # special cases
    if tag == EF_SOD:
        # extract DER file (should be at offset 3 or 4 - if not, use sod.py to find it in EF_SOD.BIN
        sodhex = passport.ToHex(data)
        tag = sodhex[:2]
        fieldlength = asn1fieldlength(sodhex[2:])

        with open(tempfiles + "EF_SOD.TMP", "wb+") as outfile:
            outfile.write(data[1 + fieldlength // 2 :])

        exitstatus = os.system("openssl pkcs7 -text -print_certs -in %sEF_SOD.TMP -inform DER" % tempfiles)
        if not exitstatus:
            exitstatus = os.system("openssl pkcs7 -in %sEF_SOD.TMP -out %sEF_SOD.PEM -inform DER" % (tempfiles, tempfiles))
            exitstatus = os.system("openssl pkcs7 -text -print_certs -in %sEF_SOD.PEM" % tempfiles)
            print()
            print("Certificate stored in %sEF_SOD.PEM" % tempfiles)
    if tag == EF_DG1:
        mrz = decode_ef_dg1(data)
    if tag == EF_DG2:
        dg2_features = decode_ef_dg2(data)
    if tag == EF_DG7:
        decode_ef_dg7(data)
    if tag == EF_DG14:
        # TODO parse DG14 SecurityInfos
        exitstatus = os.system("openssl asn1parse -i -in %sEF_DG14.BIN -inform DER" % tempfiles)
    if tag == EF_DG15:
        dg15hex = passport.ToHex(data)
        tag = dg15hex[:2]
        fieldlength = asn1fieldlength(dg15hex[2:])
        with open(tempfiles + "EF_DG15.TMP", "wb+") as outfile:
            outfile.write(data[1 + fieldlength // 2 :])
        exitstatus = os.system("openssl rsa -in %sEF_DG15.TMP -inform DER -pubin -text -noout" % tempfiles)
        if not exitstatus:
            os.system("openssl rsa -in %sEF_DG15.TMP -out %sEF_DG15.PEM -inform DER -pubin" % (tempfiles, tempfiles))
            print("Key stored in %sEF_DG15.PEM" % tempfiles)
            continue
        if exitstatus:
            exitstatus = os.system("openssl ec -in %sEF_DG15.TMP -inform DER -pubin -text -noout" % tempfiles)
        if not exitstatus:
            os.system("openssl ec -in %sEF_DG15.TMP -out %sEF_DG15.PEM -inform DER -pubin" % (tempfiles, tempfiles))
            print("Key stored in %sEF_DG15.PEM" % tempfiles)

# initialise app if we are going to WRITE JMRTD
if Jmrtd:
    if not FILES:
        filespath = tempfiles
        print()
        input("Please replace passport with a JMRTD or vonJeek emulator card and press ENTER when ready...")
    if (not passport.hsselect("08", "A") and not passport.hsselect("08", "B")) or not passport.iso_7816_select_file(
        passport.AID_MRTD, passport.ISO_7816_SELECT_BY_NAME, "0C"
    ):
        print("Couldn't select JMRTD!")
        sys.exit(True)
    print("Initialising JMRTD or vonJeek...")
    if STRIP_INDEX:
        print("Stripping AA & EAC files")
        print("old EF.COM: " + passport.ToHex(raw_efcom))
        # DG.COM tag & length
        total_length = raw_efcom[1]
        new_total_length = raw_efcom[1]
        i = 2
        tmp = bytearray()
        while i - 2 < total_length - 1:
            # next tag
            tag = bytearray([raw_efcom[i]])
            tmp.append(raw_efcom[i])
            # not sure how to distinguish 2-byte tags...
            if raw_efcom[i] == 0x5F or raw_efcom[i] == 0x7F:
                i += 1
                tag.append(raw_efcom[i])
                tmp.append(raw_efcom[i])
            i += 1
            length = raw_efcom[i]
            i += 1
            if bytes(tag) == bytes.fromhex("5C"):
                # Keeping only known files in the tag index
                oldindex = raw_efcom[i : i + length]
                clearDGs = [EF_DG1, EF_DG2, EF_DG7, EF_DG11, EF_DG12, EF_DG13]
                newindex = bytes([x for x in oldindex if "%02x" % x in clearDGs])
                newlength = len(newindex)
                tmp.append(newlength)
                tmp += newindex
                i += newlength
                # Fixing total length:
                new_total_length = total_length - (length - newlength)
            else:
                tmp.append(length)
                tmp += raw_efcom[i : i + length]
            i += length
        raw_efcom = bytes([raw_efcom[0], new_total_length]) + bytes(tmp)
        print("new EF.COM: " + passport.ToHex(raw_efcom))
        eflist = decode_ef_com(raw_efcom)
        eflist.insert(0, EF_SOD)
        eflist.insert(0, EF_COM)
    for tag in eflist:
        print("Reading:", TAG_NAME[tag])
        if tag == EF_COM and STRIP_INDEX:
            data = raw_efcom
        else:
            try:
                # passfile = open(filespath + TAG_FILE[tag], "rb")
                with open(filespath + TAG_FILE[tag], "rb") as passfile:
                    data = passfile.read()
            except:
                print("*** Warning! Can't open %s" % filespath + TAG_FILE[tag])
                continue
        print("Creating JMRTD", TAG_NAME[tag], "Length", len(data))
        jmrtd_create_file(TAG_FID[tag], len(data))
        print("Writing JMRTD", TAG_NAME[tag])
        jmrtd_write_file(TAG_FID[tag], data)
    # set private key
    # second line of MRZ is second half of decoded mrz from DG1
    passport.MRPmrzl(mrz[len(mrz) // 2 :])  # pylint mrz possibly-used-before-assignment
    print("Setting 3DES key")
    jmrtd_personalise(
        mrz[FieldKeys[0] : FieldKeys[0] + 9],
        mrz[FieldKeys[1] : FieldKeys[1] + 6],
        mrz[FieldKeys[2] : FieldKeys[2] + 6],
    )
    print(
        "JMRTD/vonJeek 3DES key set to: "
        + mrz[FieldKeys[0] : FieldKeys[0] + 9]
        + mrz[FieldKeys[1] : FieldKeys[1] + 6]
        + mrz[FieldKeys[2] : FieldKeys[2] + 6]
    )
if JmrtdLock:
    jmrtd_lock()

# ----- Passive Authentication hook -----
# If a CSCA master list is available, verify the passport just read and flag it
# SAFE / UNSAFE. Enable by setting $RFIDIOT_MASTERLIST to a CSCA master list .ml
# (e.g. the BSI GermanMasterList.ml), or by placing one at a default path.
_pa_sod = tempfiles + "EF_SOD.BIN"
if os.path.exists(_pa_sod):
    _pa_ml = os.environ.get("RFIDIOT_MASTERLIST", "")
    if not _pa_ml:
        for _p in (
            os.path.expanduser("~/.rfidiot/masterlist.ml"),
            "/etc/rfidiot/masterlist.ml",
            tempfiles + "masterlist.ml",
        ):
            if os.path.exists(_p):
                _pa_ml = _p
                break
    print()
    if _pa_ml:
        print("===== Passive Authentication (%s) =====" % _pa_ml)
    else:
        print("===== Passive Authentication (no master list - content + self-provided CSCA only) =====")
    _pa_fetch = os.environ.get("RFIDIOT_CSCA_FETCH", "").lower() in ("1", "true", "yes", "on")
    try:
        import passiveauth

        _pa_verdict = passiveauth.passive_authenticate(_pa_sod, _pa_ml or None, tempfiles, fetch=_pa_fetch)
    except Exception as _pa_e:
        _pa_verdict = None
        print("Passive Authentication error:", _pa_e)
    print()
    if _pa_verdict == "SAFE":
        print("***** PASSPORT SAFE - signed by a CSCA in the master list, data groups intact *****")
    elif _pa_verdict == "TAMPERED":
        print("##### PASSPORT UNSAFE - TAMPERED: data altered and not validly re-signed #####")
    elif _pa_verdict == "SELFSIGNED":
        print("##### PASSPORT UNSAFE - UNTRUSTED: data groups intact and the DS chains to a CSCA, but that")
        print("      CSCA was supplied by the document itself (circular) - NO proof of authenticity #####")
        if not _pa_ml:
            print("      (set $RFIDIOT_MASTERLIST to a CSCA master list .ml to establish real trust)")
    elif _pa_verdict == "UNTRUSTED":
        print("##### PASSPORT UNSAFE - UNTRUSTED: internally consistent but no trusted CSCA for the signer #####")
        if not _pa_ml:
            print("      (set $RFIDIOT_MASTERLIST to a CSCA master list .ml to establish real trust)")
    else:
        print("----- Passport trust UNVERIFIED - could not run Passive Authentication -----")

# image read is nasty hacky bodge to see if image display without interpreting the headers
# start of image location may change - look for JPEG header bytes 'FF D8 FF E0'
# german is JP2 format, not JPG - look for '00 00 00 0C 6A 50'
# in /tmp/EF_DG2.BIN


def do_command(func, *args, **kw):
    def _wrapper(*wargs):
        return func(*(wargs + args), **kw)

    return _wrapper


# display data and image in gui window
Style = "Arrow"
if not Nogui:
    # PIL is only needed for the GUI, so import it here: the -g (no GUI) and TEST paths
    # then run on a host without Pillow's ImageTk.
    try:
        from PIL import Image, ImageTk
    except ImportError as e:
        print("Could not import Pillow ImageTk (%s) - pip install Pillow, or run with -g for no GUI" % e)
        sys.exit(True)
    root = Tk()

    font = "courier 22"
    fonta = "courier 22"

    frame = Frame(root, colormap="new", visual="truecolor").grid()
    root.title(f"{myver} (RFIDIOt v{passport.VERSION})")
    if Filetype == "JP2":
        # nasty hack to deal with JPEG 2000 until PIL support comes along.
        # ImageMagick 7 renamed 'convert' to 'magick'; prefer it when present.
        _im = "magick" if shutil.which("magick") else "convert"
        exitstatus = os.system("%s %sJP2 %sJPG" % (_im, tempfiles + "EF_DG2.", tempfiles + "EF_DG2."))
        if exitstatus:
            print("Could not convert JPEG 2000 image (%d) - please install ImageMagick" % exitstatus)
            sys.exit(True)
        print("      (converted %sJP2 to %sJPG for display)" % (tempfiles + "EF_DG2.", tempfiles + "EF_DG2."))
        if Display_DG7:
            if not os.system("%s %sJP2 %sJPG" % (_im, tempfiles + "EF_DG7.", tempfiles + "EF_DG7.")):
                print("      (converted %sJP2 to %sJPG for display)" % (tempfiles + "EF_DG7.", tempfiles + "EF_DG7."))
        Filetype = "JPG"
    # TODO need to open EF_DG2_* in case of multiple images??
    imagedata = ImageTk.PhotoImage(file=tempfiles + "EF_DG2." + Filetype)
    canvas = Canvas(frame, height=imagedata.height(), width=imagedata.width())
    canvas.grid(row=3, sticky=NW, rowspan=20)
    canvasimage = canvas.create_image(0, 0, image=imagedata, anchor=NW)
    featurebutton = Checkbutton(
        frame,
        text="Show Features",
        command=do_command(drawfeatures, canvas, dg2_features),
    )
    featurebutton.grid(row=1, column=0, sticky=W, rowspan=1)
    # a single shared control variable makes the four a mutually-exclusive group
    stylevar = StringVar(value=Style)
    featurestyle = Radiobutton(
        frame,
        text="Arrow",
        variable=stylevar,
        value="Arrow",
        command=do_command(changestyle, "Arrow", canvas, dg2_features),
    )
    featurestyle.grid(row=1, column=0, rowspan=1)
    featurestyle2 = Radiobutton(
        frame,
        text="Cross",
        variable=stylevar,
        value="Cross",
        command=do_command(changestyle, "Cross", canvas, dg2_features),
    )
    featurestyle2.grid(row=2, column=0, rowspan=1)
    featurestyle3 = Radiobutton(
        frame,
        text="Circle ",
        variable=stylevar,
        value="Circle",
        command=do_command(changestyle, "Circle", canvas, dg2_features),
    )
    featurestyle3.grid(row=1, column=0, rowspan=1, sticky=E)
    featurestyle4 = Radiobutton(
        frame,
        text="Target",
        variable=stylevar,
        value="Target",
        command=do_command(changestyle, "Target", canvas, dg2_features),
    )
    featurestyle4.grid(row=2, column=0, rowspan=1, sticky=E)
    quitbutton = Button(frame, text="Quit", command=root.quit)
    quitbutton.grid(row=1, column=3, sticky=NE, rowspan=2)
    Label(frame, text="Type").grid(row=1, sticky=W, column=1)
    Label(frame, text=DOCUMENT_TYPE, font=font).grid(row=2, sticky=W, column=1)
    row = 3
    for item in Fields:
        Label(frame, text=FieldNames[item]).grid(row=row, sticky=W, column=1)
        row += 1
        mrzoffset = 0
        for x in range(item):
            mrzoffset += FieldLengths[x]
        if FieldNames[item] == "Issuing State or Organisation" or FieldNames[item] == "Nationality":
            Label(
                frame,
                text=mrzspaces(mrz[mrzoffset : mrzoffset + FieldLengths[item]], " ")
                + "  "
                + passport.ISO3166CountryCodesAlpha[mrzspaces(mrz[mrzoffset : mrzoffset + FieldLengths[item]], "")],
                font=font,
            ).grid(row=row, sticky=W, column=1)
        else:
            Label(
                frame,
                text=mrzspaces(mrz[mrzoffset : mrzoffset + FieldLengths[item]], " "),
                font=font,
            ).grid(row=row, sticky=W, column=1)
        row += 1
    if len(mrz) == 90:
        # Passport cards have a three-line MRZ
        Label(frame, text=mrz[:30], font=fonta, justify="center").grid(row=row, columnspan=4)
        row += 1
        Label(frame, text=mrz[30:60], font=fonta, justify="center").grid(row=row, columnspan=4)
        row += 1
        Label(frame, text=mrz[60:], font=fonta, justify="center").grid(row=row, columnspan=4)
        row += 1
    else:
        Label(frame, text="  " + mrz[: len(mrz) // 2], font=fonta, justify="left").grid(row=row, sticky=W, columnspan=4)
        row += 1
        Label(frame, text="  " + mrz[len(mrz) // 2 :], font=fonta, justify="left").grid(row=row, sticky=W, columnspan=4)
        row += 1
    if Display_DG7:
        im = Image.open(tempfiles + "EF_DG7." + Filetype)
        width, height = im.size
        im = im.resize((300, 300 * height // width))
        pic = ImageTk.PhotoImage(im)
        width, height = im.size
        signcanvas = Canvas(frame, height=height, width=width)
        signcanvas.create_image(0, 0, image=pic, anchor=NW)
        signcanvas.grid(row=row, sticky=NW, columnspan=4)
    row += 1
    Label(frame, text="http://rfidiot.org").grid(row=row, sticky=W, column=1)
    root.mainloop()

passport.shutdown()
sys.exit(False)
