#!/usr/bin/python2
#  relayuid.py - [EXPERIMENTAL / WORK IN PROGRESS] full ISO 14443-4 emulation on a
#  libnfc PN53x with a UID of your choice: answer anticollision with any UID
#  (as emulateuid.py does), then run the ISO 14443-4 (T=CL) block protocol on the
#  target side - answer the RATS with an ATS and handle I-blocks - so a reader
#  both sees our UID AND can exchange APDUs. The APDUs are answered by a responder:
#  a stub (reply 9000 / a GET CHALLENGE) by default, or relayed to a real card on
#  a second reader with -c (the "full relay": real UID + real card behaviour).
#
#  This is the thing a naive merge of emulateuid + pn532mitm would imply, but it
#  is a distinct mode (host owns anticollision AND T=CL) - see TODO section 17a.
#
#  Adam Laurie <adam@algroup.co.uk>
#  http://rfidiot.org/
#
#    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.

import getopt
import os
import socket
import sys
import time

import rfidiot

# NB: rfidiot.card is accessed lazily (it opens the reader on first touch). Agent
# mode (-S) drives its reader via open_relay and never touches rfidiot.card, so it
# needs no -f/-r/-R emulator; emulator mode binds `card` below.
args = rfidiot.args


def crc_a(data):
    "ISO 14443-3 CRC_A of bytes, as 2 bytes LSB first"
    crc = 0x6363
    for b in data:
        b ^= crc & 0xFF
        b = (b ^ (b << 4)) & 0xFF
        crc = (crc >> 8) ^ (b << 8) ^ (b << 3) ^ (b >> 4)
    return bytes([crc & 0xFF, crc >> 8])


def usage():
    print()
    print(sys.argv[0] + " - emulate a full ISO 14443-4 card with a chosen UID (experimental)")
    print()
    print("Usage: %s [options] [<UID>|random|auto]" % sys.argv[0])
    print()
    print("  UID is 4, 7 or 10 bytes of HEX (a 4-byte UID may not start with 88), or:")
    print("    random  - a random 4-byte UID with the 0x08 random-UID marker on the front")
    print("    auto    - clone the UID the -c relay reader reports for the real card")
    print("              (the default when -c is given and no UID is named). NB a Type B")
    print("              card's reported id is a random, per-tap PUPI, not a stable UID -")
    print("              for those use 'random' to present a clean 0x08 UID instead.")
    print()
    print("  Options:")
    print("    -a <ATQA>     ATQA on the wire (default 0400/4400/8400 by UID size)")
    print("    -k <SAK>      final SAK (default 20 = ISO 14443-4; the reader then sends RATS)")
    print("    -c <TARGET>   relay APDUs to a real card on:")
    print("                    <libnfc connstring>   a libnfc PN53x reader (local)")
    print("                    ccid[:bus:dev]        ACR122U, direct CCID / PN532 (local)")
    print("                    eccid[:bus:dev]       standard CCID reader, e.g. TWN4 (local)")
    print("                    tcp:HOST:PORT         a relayuid agent (-S) on another machine")
    print("                  without -c a stub answers (9000 / GET CHALLENGE)")
    print("    -S <PORT>     AGENT mode: serve the local -c reader's card over TCP to a")
    print("                  remote relayuid (its -c tcp:HOST:PORT). No -f needed.")
    print("    -w <SECONDS>  stop after this many seconds (default: run until Ctrl-C)")
    print()
    print("  A 4-byte UID starting with 08 is presented natively by the chip's AutoColl")
    print("  (no priming, survives readers that cycle their field); other UIDs are primed.")
    print()
    print("  Emulator mode needs a libnfc PN53x (-f), e.g. an SCL3711. Split across two")
    print("  machines: run  relayuid.py -S 5000 -c eccid:3:66  on the card's host, and")
    print("  relayuid.py -f pn53x_usb:... -c tcp:<cardhost>:5000 auto  on the emulator's.")
    print()


if rfidiot.help:
    usage()
    sys.exit(False)

try:
    opts, args = getopt.getopt(args, "a:k:c:w:S:")
except getopt.GetoptError as e:
    print("  " + str(e))
    usage()
    sys.exit(True)

atqa = None
sak = 0x20
sak_explicit = False
relay = None
serve_port = None
wait = 0
try:
    for o, a in opts:
        if o == "-a":
            atqa = bytes.fromhex(a)
            assert len(atqa) == 2
        elif o == "-k":
            sak = int(a, 16)
            sak_explicit = True
        elif o == "-c":
            relay = a
        elif o == "-S":
            serve_port = int(a)
        elif o == "-w":
            wait = float(a)
    # UID is optional now: a hex value, the word "random", or omitted
    uid_arg = args[0] if args else None
except (ValueError, AssertionError, IndexError):
    usage()
    sys.exit(True)

def random_uid():
    "a random 4-byte UID with the ISO 14443-3 random-UID marker 0x08 on the front"
    return b"\x08" + os.urandom(3)
# ATS we present after the RATS: TL=05, T0=78 (TA1/TB1/TC1 present, FSCI=8 -> 256),
# TA1=80 (106 kbps both ways), TB1=E0 (FWI=14 -> FWT ~4.9 s, so a slow relayed reply
# never trips the reader's frame-wait timeout; avoids needing S(WTX)), TC1=00 (no
# CID, no NAD). No historical bytes.
ATS = bytes.fromhex("057880E000")
# largest INF we put in one response I-block before chaining - a ceiling (< FSD
# 256 and the PN53x target frame limit). The ACTUAL per-frame limit is the
# victim's FSD, announced in its RATS (FSDI): we clamp to it at RATS time, below.
# Getting this wrong overflows a victim with a small FSD - e.g. a libnfc PN532
# victim RATSes FSDI 5 (FSD 64), so a 74-byte SELECT-AID FCI sent in one frame
# is dropped and the read stalls; an ACR122U victim RATSes FSD 256 and never hit it.
FRAG = 240
# ISO 14443-4 FSD (bytes a reader can receive in one frame) by FSDI 0..12
FSD_TABLE = {0: 16, 1: 24, 2: 32, 3: 40, 4: 48, 5: 64, 6: 96, 7: 128,
             8: 256, 9: 512, 10: 1024, 11: 2048, 12: 4096}
# response fragment size actually used; clamped to the victim's FSD when it RATSes
victim_frag = FRAG

# --- APDU responder: stub, or relay to a real card --------------------------
relay_reader = None


def open_relay(spec):
    """open a relay target for APDUs; returns (handle, send(apdu_hex)->resp_hex,
    card_uid_hex_or_None). The target is a local reader, or - with "tcp:HOST:PORT" -
    a relayuid agent (-S) on another machine driving the real card there."""
    if spec.lower().startswith("tcp:"):
        _, host, port = spec.split(":")
        s = socket.create_connection((host, int(port)), timeout=10)
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        f = s.makefile("rwb", buffering=0)
        line = f.readline().decode("ascii", "replace").strip()   # agent sends the card UID first
        carduid = None if line in ("", "-") else line
        def send(apdu_hex):
            f.write((apdu_hex + "\n").encode("ascii"))
            r = f.readline().decode("ascii", "replace").strip()
            return None if r in ("", "ERR") else r
        return s, send, carduid
    if spec.lower().startswith("eccid"):
        # standard CCID reader (ELATEC TWN4 in PC/SC firmware, etc.) via CCIDDev;
        # spec "eccid[:bus:dev]" -> CCIDDev("ccid[:bus:dev]"). The reader does T=CL.
        from rfidiot.pynfc import CCIDDev
        r = CCIDDev(spec[1:])
        r.connect()                           # IccPowerOn: activate the card, get ATR
        def send(apdu_hex):
            try:
                data, s1, s2 = r.transmit([int(apdu_hex[i:i + 2], 16) for i in range(0, len(apdu_hex), 2)])
            except Exception:
                return None
            return "".join("%02X" % b for b in data) + "%02X%02X" % (s1, s2)
        getuid = send("FFCA000000")           # PC/SC get-UID pseudo-APDU
        carduid = getuid[:-4] if getuid and getuid.endswith("9000") and len(getuid) > 4 else None
        return r, send, carduid
    if spec.lower().startswith("ccid"):
        from rfidiot.pynfc import ACR122CCID
        r = ACR122CCID(spec)
        sel = r.selectISO14443A()
    else:
        from rfidiot.pynfc import NFC
        r = NFC(spec)
        sel = r.selectISO14443A()
    def send(apdu_hex):
        ok, resp = r.sendAPDU(apdu_hex, 3)
        return resp if ok else None
    carduid = getattr(sel, "uid", None)
    return r, send, carduid


def stub(apdu_hex):
    "minimal card: SELECT->9000, GET CHALLENGE->8 random bytes+9000, else 9000"
    a = bytes.fromhex(apdu_hex)
    if len(a) >= 2 and a[1] == 0x84:          # GET CHALLENGE
        return os.urandom(8).hex().upper() + "9000"
    return "9000"


def serve(port, spec):
    "AGENT mode (-S): open the local real-card reader (-c spec) and relay APDUs over TCP"
    reader, send, carduid = open_relay(spec)
    print("  agent: serving %s on 0.0.0.0:%d (card UID %s)" % (spec, port, carduid or "-"))
    srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    srv.bind(("0.0.0.0", port))
    srv.listen(1)
    try:
        while True:
            conn, addr = srv.accept()
            conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
            f = conn.makefile("rwb", buffering=0)
            f.write(((carduid or "-") + "\n").encode("ascii"))   # report the card UID first
            print("  agent: client %s:%d" % addr)
            try:
                while True:
                    line = f.readline()
                    if not line:
                        break
                    apdu = line.decode("ascii", "replace").strip()
                    if not apdu:
                        continue
                    resp = send(apdu)
                    f.write(((resp or "ERR") + "\n").encode("ascii"))
                    print("  agent << %s   >> %s" % (apdu, (resp or "ERR")[:40]))
            except OSError:
                pass
            finally:
                conn.close()
                print("  agent: client gone")
    except KeyboardInterrupt:
        pass
    finally:
        for meth in ("disconnect", "powerOff", "deconfigure"):
            fn = getattr(reader, meth, None)
            if fn:
                try:
                    fn()
                except Exception:
                    pass


if serve_port is not None:
    if not relay:
        print("  agent mode (-S) needs -c <local-reader> (the real card's reader)")
        sys.exit(True)
    print("relayuid v0.1c (EXPERIMENTAL) - agent mode")
    serve(serve_port, relay)
    sys.exit(False)

# --- emulator mode from here (open the libnfc PN53x only now) ---
card = rfidiot.card
card.info("relayuid v0.1c (EXPERIMENTAL)")
if card.readertype != card.READER_LIBNFC or not hasattr(card.nfc, "initAsTarget"):
    print("  The emulator must be a libnfc PN53x reader (-f <connstring>)")
    sys.exit(True)

carduid = None
if relay:
    try:
        relay_reader, responder, carduid = open_relay(relay)
        print("  Relaying APDUs to real card on %s" % relay)
    except Exception as e:
        print("  Could not open relay reader '%s': %s" % (relay, e))
        sys.exit(True)
else:
    responder = stub
    print("  Stub responder (no -c): replying 9000 / GET CHALLENGE")

# --- resolve the UID we present ---------------------------------------------
# a hex UID is presented verbatim; "random" (or any generated fallback) uses the
# ISO 14443-3 random-UID marker 0x08 on the front; "auto" (or no UID, with -c)
# clones the UID the relay reader reports for the real card.
try:
    if uid_arg and uid_arg.lower() not in ("random", "auto"):
        uid = bytes.fromhex(uid_arg)
        assert len(uid) in (4, 7, 10)
        uidsrc = "as given"
    elif uid_arg and uid_arg.lower() == "random":
        uid = random_uid()
        uidsrc = "random (0x08 + 3 random bytes)"
    elif relay and (uid_arg is None or uid_arg.lower() == "auto"):
        if carduid and len(carduid) % 2 == 0 and len(bytes.fromhex(carduid)) in (4, 7, 10):
            uid = bytes.fromhex(carduid)
            uidsrc = "auto: cloned from the real card"
        else:
            uid = random_uid()
            uidsrc = "auto: relay reader reported no UID - random (0x08 front)"
    else:
        uid = random_uid()
        uidsrc = "random (0x08 front; no UID given and no -c)"
except (ValueError, AssertionError):
    print("  UID must be 4, 7 or 10 bytes of hex, or 'random'/'auto'")
    sys.exit(True)
if len(uid) == 4 and uid[0] == 0x88:
    print("  A 4-byte UID can't start with 88 (that is the cascade tag)")
    sys.exit(True)

# --- cascade levels for the chosen UID (as emulateuid.py) -------------------
if atqa is None:
    atqa = {4: b"\x04\x00", 7: b"\x44\x00", 10: b"\x84\x00"}[len(uid)]
if len(uid) == 4:
    parts = [uid]
elif len(uid) == 7:
    parts = [b"\x88" + uid[0:3], uid[3:7]]
else:
    parts = [b"\x88" + uid[0:3], b"\x88" + uid[3:6], uid[6:10]]
levels = []
for n, part in enumerate(parts):
    bcc = part[0] ^ part[1] ^ part[2] ^ part[3]
    final = n == len(parts) - 1
    level_sak = (sak & ~0x04) if final else 0x04
    levels.append((0x93 + 2 * n, part + bytes([bcc]), bytes([level_sak]) + crc_a(bytes([level_sak]))))

shown = {}


def send(tx_bytes, crc=False):
    data = tx_bytes + (crc_a(tx_bytes) if crc else b"")
    card.nfc.targetSend(data.hex())


def handle_tcl(rx, frame):
    """service one ISO 14443-4 (T=CL) frame from the reader - we are the card.
    Shared by both activation paths (host anticollision and native AutoColl):
    answer the RATS with the ATS, relay I-block APDUs (with command/response
    chaining), echo S(WTX). CRC_A is appended by hand (targetHandleCRC off)."""
    global victim_frag
    if rx and rx[0] == 0xE0:                                    # RATS
        # clamp response fragmentation to the victim's FSD (FSDI = high nibble of
        # the RATS param byte) so we never send a frame it can't receive
        fsdi = (rx[1] >> 4) if len(rx) > 1 else 8
        fsd = FSD_TABLE.get(fsdi, 256)
        victim_frag = min(FRAG, fsd - 3)                       # - PCB - CRC(2); no CID/NAD
        print("  %.3f RATS %s (FSDI %d = FSD %d, frag %d) -> ATS %s"
              % (time.time(), frame, fsdi, fsd, victim_frag, ATS.hex().upper()))
        send(ATS, crc=True)
        return
    if rx and (rx[0] & 0xC0) == 0x00:                           # I-block (command APDU)
        pcb = rx[0]
        inf = rx[1:-2]                                          # strip PCB + CRC (no CID)
        # receive-side (command) chaining: the reader splits a long command into
        # chained I-blocks (PCB bit 0x10); R(ACK) each and accumulate the INF
        while pcb & 0x10:
            send(bytes([0xA2 | ((pcb & 0x01) ^ 1)]), crc=True)  # R(ACK), toggled block
            ok, f2 = card.nfc.targetReceive(2000, quiet=True)
            if not ok or not f2:
                break
            n = bytes.fromhex(f2)
            pcb = n[0]
            inf += n[1:-2]
        apdu = inf.hex().upper()
        resp = responder(apdu)
        print("  %.3f << %s   >> %s (%dB)"
              % (time.time(), apdu, (resp[:40] + "..") if resp and len(resp) > 40 else resp,
                 len(resp) // 2 if resp else 0))
        if resp is None:
            return
        rbytes = bytes.fromhex(resp)
        # send-side (response) chaining: split INF > victim_frag into chained
        # I-blocks (clamped to the victim's FSD at RATS), each ACKed by the reader
        # with an R(ACK); block number toggles per block
        block = pcb & 0x01                                     # response echoes the command block number
        off = 0
        while True:
            frag = rbytes[off:off + victim_frag]
            off += victim_frag
            last = off >= len(rbytes)
            send(bytes([0x02 | block | (0x00 if last else 0x10)]) + frag, crc=True)
            if last:
                break
            ok, _ack = card.nfc.targetReceive(2000, quiet=True)  # R(ACK) from reader
            if not ok:
                break
            block ^= 1
        return
    if rx and (rx[0] & 0xE6) == 0xF2:                          # S(WTX) request (fallback)
        send(bytes([0xF2]) + rx[1:2], crc=True)                # echo WTX back
        return
    # unhandled
    key = frame[:6]
    shown[key] = shown.get(key, 0) + 1
    if rx != b"\x26" and shown[key] <= 3:
        print("  %.3f rx %s (unhandled)" % (time.time(), frame))


native = len(uid) == 4 and uid[0] == 0x08
print()
print("  UID %s (%s), ATQA %s, SAK %02X" % (uid.hex().upper(), uidsrc, atqa.hex().upper(), sak))
start = time.time()

if native:
    # --- native: the chip's AutoColl answers anticollision with our real 08 UID
    # itself, then (SAK 20) relays the RATS up to us; no priming, and it survives
    # a reader that cycles its field (the UID is re-sent from hardware each poll).
    # We arm, run T=CL until the reader drops us (NFC_ETGRELEASED), then re-arm.
    from rfidiot.pynfc import NFC_ETGRELEASED
    nt = card.nfc.make_iso14443a_target(atqa.hex(), uid.hex(), "%02X" % sak)
    print("  Native hardware AutoColl (08-prefix UID): no priming, survives field-cycling.")
    print("  Present the UID to a reader (Ctrl-C to stop" + (", or -w to bound the run)" if not wait else ")"))
    print()
    try:
        while not wait or time.time() - start < wait:
            armms = int((wait - (time.time() - start)) * 1000) if wait else 0
            if wait and armms <= 0:
                break
            ok, first = card.nfc.initAsTarget(nt, armms, raw=True, quiet=True)
            if not ok:
                continue                                       # timeout / released -> re-arm
            card.nfc.targetHandleCRC(False)                    # host appends CRC on T=CL
            print("  %.3f selected as %s" % (time.time(), uid.hex().upper()))
            if first:
                handle_tcl(bytes.fromhex(first), first)        # the RATS handed up on activation
            while not wait or time.time() - start < wait:      # service until released
                ok, frame = card.nfc.targetReceive(1000, quiet=True)
                if not ok:
                    if frame == NFC_ETGRELEASED:
                        break                                  # field cycled / gone -> re-arm
                    continue                                   # timeout -> keep servicing
                if frame:
                    handle_tcl(bytes.fromhex(frame), frame)
    except KeyboardInterrupt:
        pass
else:
    # --- priming (as emulateuid.py): SAK 20 provokes a RATS that breaks AutoColl,
    # then the host answers anticollision itself with any UID (4/7/10 bytes) ---
    prime_uid = "08" + os.urandom(3).hex().upper()
    nt = card.nfc.make_iso14443a_target("0400", prime_uid, "20")
    print("  Waiting for the real reader to prime us (its first activation will fail)...")
    ok, first = card.nfc.initAsTarget(nt, int(wait * 1000) if wait else 0)
    if not ok:
        print("  Not activated (%s)" % first)
        sys.exit(True)
    print("  %.3f primed (by %s); now present the UID to a reader (Ctrl-C to stop)" % (time.time(), prime_uid))
    print()
    # host now owns every layer: anticollision frames carry no CRC, and we append
    # CRC_A to the ATS / I-blocks by hand
    card.nfc.targetHandleCRC(False)
    halted = False
    level = 0
    activated = False
    try:
        while not wait or time.time() - start < wait:
            ok, frame = card.nfc.targetReceive(1000, quiet=True)
            if not ok or not frame:
                continue
            rx = bytes.fromhex(frame)
            # --- ISO 14443-3 anticollision (as emulateuid) ---
            if rx == b"\x52" or (rx == b"\x26" and not halted):       # WUPA / REQA
                halted = False
                level = 0
                activated = False
                send(atqa)
                continue
            if len(rx) == 4 and rx[:2] == b"\x50\x00":                 # HLTA
                halted = True
                continue
            if len(rx) == 2 and level < len(levels) and rx == bytes([levels[level][0], 0x20]):
                send(levels[level][1])                                 # ANTICOL: UID CLn + BCC
                continue
            if len(rx) == 9 and level < len(levels) and rx[0] == levels[level][0] and rx[1] == 0x70 \
                    and rx[2:7] == levels[level][1]:
                send(levels[level][2])                                 # SELECT: SAK + CRC (already appended)
                level += 1
                if level == len(levels):
                    activated = True
                    print("  %.3f selected as %s" % (time.time(), uid.hex().upper()))
                continue
            # --- ISO 14443-4 (T=CL), we are the card ---
            if activated:
                handle_tcl(rx, frame)
    except KeyboardInterrupt:
        pass
print()
if relay_reader is not None:
    for meth in ("disconnect", "powerOff", "deconfigure"):
        fn = getattr(relay_reader, meth, None)
        if fn:
            try:
                fn()
            except Exception:
                pass
card.shutdown()
