diff --git a/.github/workflows/auth.yml b/.github/workflows/auth.yml new file mode 100644 index 0000000..833cbf9 --- /dev/null +++ b/.github/workflows/auth.yml @@ -0,0 +1,28 @@ +name: Auth Go checks +on: + pull_request: + paths: + - 'cmd/auth/**' + - 'do/build-auth' + - 'bin/auth.py' + - 'tests/test_auth.py' + - '.github/workflows/auth.yml' +permissions: + contents: read +jobs: + test: + runs-on: ubuntu-latest + defaults: + run: + working-directory: cmd/auth + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.23.x' + cache: false + - run: sudo apt-get update && sudo apt-get install -y libpcsclite-dev pkg-config + - run: go test -mod=mod ./... + - run: go vet -mod=mod ./... + - run: go build -mod=mod . + - run: python3 -m unittest discover -s ../../tests -p test_auth.py -v diff --git a/.gitignore b/.gitignore index 624506d..2adace1 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ pkg/ dist/ qb +/bin/auth diff --git a/bin/auth.py b/bin/auth.py new file mode 100755 index 0000000..475b0ec --- /dev/null +++ b/bin/auth.py @@ -0,0 +1,544 @@ +#!/usr/bin/python3 +"""Local YubiKey authenticator; no credential storage or background process.""" +import argparse +import base64 +import contextlib +import getpass +import math +import os +import re +import shutil +import signal +import subprocess +import sys +import time +import unicodedata +import warnings + +VERSION = "0.1.0" +POLICY = { + "Yubico OTP": "Disabled", "FIDO U2F": "Disabled", + "FIDO2": "Enabled", "OATH": "Enabled", "PIV": "Disabled", + "OpenPGP": "Enabled", "YubiHSM Auth": "Disabled", +} +READ_COMMANDS = { + ("--version",), ("list", "--serials"), ("info",), + ("fido", "credentials", "list"), ("openpgp", "info"), + ("openpgp", "keys", "info", "--help"), + ("openpgp", "keys", "info", "sig"), + ("openpgp", "keys", "info", "enc"), + ("openpgp", "keys", "info", "dec"), + ("openpgp", "keys", "info", "aut"), +} + + +class AuthError(Exception): + pass + + +def safe(value): + """Do not let hardware-controlled strings inject terminal controls.""" + return "".join(c if c.isprintable() else "?" for c in str(value)) + + +def backend(args, serial=None, interactive=False): + if tuple(args) not in READ_COMMANDS: + raise AuthError("Backend command not permitted") + if not shutil.which("ykman"): + raise AuthError("ykman is not installed") + cmd = ["ykman"] + if serial is not None: + cmd += ["--device", str(serial)] + cmd += list(args) + try: + result = subprocess.run( + cmd, text=True, check=False, + stdin=None if interactive else subprocess.DEVNULL, + stdout=None if interactive else subprocess.PIPE, + stderr=None if interactive else subprocess.PIPE, + timeout=None if interactive else 15, + ) + except subprocess.TimeoutExpired: + raise AuthError("ykman timed out") from None + if result.returncode: + detail = (result.stderr or "").lower() + reason = ("permission denied" if "permission" in detail else + "device not found" if "not found" in detail else + "unsupported command or application" if "not supported" in detail + or "no such command" in detail else "backend failed") + raise AuthError("ykman " + " ".join(args) + ": " + reason) + return result.stdout or "" + + +def serials(): + result = backend(("list", "--serials")) + lines = result.splitlines() + if any(not re.fullmatch(r"\d+", line.strip()) for line in lines): + raise AuthError("Unrecognized device inventory") + return list(dict.fromkeys(line.strip() for line in lines)) + + +def select_serial(requested, explicit=False): + devices = serials() + if requested: + if requested not in devices: + raise AuthError("Selected YubiKey not detected") + return requested + if not devices: + raise AuthError("No serial-numbered YubiKey detected; check USB access") + if len(devices) != 1 or explicit: + raise AuthError("Select a YubiKey explicitly with --device SERIAL") + return devices[0] + + +def terminal(): + return sys.stdin.isatty() and sys.stdout.isatty() + + +def secret(prompt): + if not terminal(): + raise AuthError("Secure input requires an interactive terminal") + with warnings.catch_warnings(): + warnings.simplefilter("error", getpass.GetPassWarning) + try: + return getpass.getpass(prompt) + except getpass.GetPassWarning: + raise AuthError("Cannot disable terminal echo") from None + + +@contextlib.contextmanager +def oath_session(serial): + # Use the installed Yubico SDK for OATH only: CLI code can trigger a + # lone HOTP credential or automatically delete a corrupted credential. + try: + from ykman.device import list_all_devices + from yubikit.core.smartcard import SmartCardConnection + from yubikit.oath import OathSession + except ImportError: + raise AuthError("Install ykman and its Python SDK for system Python") from None + matches = [dev for dev, info in list_all_devices([SmartCardConnection]) + if str(info.serial) == serial] + if len(matches) != 1: + raise AuthError("Selected YubiKey CCID access unavailable or ambiguous") + with matches[0].open_connection(SmartCardConnection) as connection: + session = OathSession(connection) + if session.locked: + session.validate(session.derive_key(secret("OATH password: "))) + yield session + + +def account_id(cred): + return cred.id.decode("utf-8") + + +def resolve(accounts, query): + matches = [c for c in accounts if query.casefold() in account_id(c).casefold()] + if not query or not matches: + raise AuthError("No matching OATH account") + if len(matches) != 1: + raise AuthError("Ambiguous OATH query; use a more specific fragment") + return matches[0] + + +def visible_accounts(session): + return sorted(c for c in session.list_credentials() if c.issuer != "_hidden") + + +def is_hotp(cred): + return cred.oath_type.name == "HOTP" + + +def fetch_codes(session, timestamp, target=None): + # calculate_all explicitly excludes HOTP and touch-required credentials. + # No CLI repair fallback, no implicit calculate_code on a lone HOTP. + entries = session.calculate_all(timestamp) + if target is not None: + entries = {c: code for c, code in entries.items() if c.id == target} + if len(entries) != 1: + raise AuthError("Selected OATH account disappeared") + rows = [] + for cred, code in sorted(entries.items()): + if cred.issuer == "_hidden": + continue + if is_hotp(cred): + rows.append((account_id(cred), "HOTP - on demand only", None, None)) + elif cred.touch_required: + rows.append((account_id(cred), "Touch required", None, None)) + elif code is not None and cred.period > 0: + if cred.issuer == "Steam": + from ykman.oath import calculate_steam + if cred.period != 30: + raise AuthError("Unsupported Steam credential period") + value = calculate_steam(session, cred, timestamp) + else: + value = code.value + rows.append((account_id(cred), value, code.valid_from, code.valid_to)) + else: + rows.append((account_id(cred), "Unavailable", None, None)) + return rows + + +def valid(row, now): + return row[2] is not None and row[2] <= now < row[3] + + +def needs_refresh(rows, now): + return any(row[2] is not None and not valid(row, now) for row in rows) + + +def render(rows, now): + lines = ["ACCOUNT / CODE / EXPIRES"] + for name, value, start, end in rows: + if start is None: + status = value + elif valid((name, value, start, end), now): + seconds = math.ceil(end - now) + fraction = min(10, math.ceil(10 * seconds / (end - start))) + status = f"{value} {seconds}s [{'#' * fraction}{'.' * (10 - fraction)}]" + else: + status = "Expired - refreshing" + lines.append(f"{safe(name)} {safe(status)}") + if not rows: + lines.append("No visible OATH accounts") + return lines + + +def fit(line, width): + """Conservatively reserve two columns for every non-ASCII character.""" + result = [] + remaining = max(0, width - 1) + for char in safe(line): + size = 1 if char.isascii() else 2 + if remaining < size: + break + result.append(char) + remaining -= size + return "".join(result) + + +def watch(session, query): + target = resolve(visible_accounts(session), query).id if query else None + live = terminal() and os.environ.get("TERM", "dumb") != "dumb" + old_count = 0 + dimensions = shutil.get_terminal_size() + try: + rows = fetch_codes(session, int(time.time()), target) + if target is not None and len(rows) == 1 and rows[0][1] == "Touch required": + if not live: + raise AuthError("Touch credential requires an interactive terminal") + # Re-read metadata before the explicit touch operation; never HOTP. + matches = [c for c in session.list_credentials() if c.id == target] + if len(matches) != 1 or is_hotp(matches[0]): + raise AuthError("Selected credential changed") + cred = matches[0] + print("Touch your YubiKey (one code only).", file=sys.stderr) + if cred.issuer == "Steam": + raise AuthError("Touch-required Steam credentials are not supported") + code = session.calculate_code(cred) + value = code.value + rows = [(account_id(cred), value, code.valid_from, code.valid_to)] + live = False + if not live: + if needs_refresh(rows, time.time()): + rows = fetch_codes(session, int(time.time()), target) + print("\n".join(render(rows, time.time()))) + return + while True: + now = time.time() + if (shutil.get_terminal_size() != dimensions + or len(render(rows, now)) >= dimensions.lines): + print("Watch stopped: terminal size or account count changed.") + return + if needs_refresh(rows, now): + # Invalidate old codes on screen before potentially slow I/O. + expired = render(rows, now) + if old_count: + draw(expired, old_count, dimensions.columns) + rows = fetch_codes(session, int(time.time()), target) + now = time.time() + lines = render(rows, now) + if (shutil.get_terminal_size() != dimensions + or len(lines) >= dimensions.lines + or (old_count and old_count != len(lines))): + # Resizing/reflow makes previous cursor coordinates unreliable. + print("Watch stopped: terminal size or account count changed.") + return + draw(lines, old_count, dimensions.columns) + old_count = len(lines) + if not any(row[2] is not None for row in rows): + return + next_end = min(row[3] for row in rows if row[3] is not None) + time.sleep(max(0.05, min(1.0, next_end - time.time()))) + finally: + # No alternate screen, cursor hiding or terminal-wide erase is used. + sys.stdout.flush() + + +def draw(lines, previous, width): + if previous: + sys.stdout.write(f"\x1b[{previous}A") + for line in lines: + sys.stdout.write("\r\x1b[2K" + fit(line, width) + "\n") + sys.stdout.flush() + + +def confirm(message): + if not terminal(): + raise AuthError("Hardware writes require an interactive terminal") + print(message, file=sys.stderr) + return input("Proceed? [y/N] ").strip().lower() == "y" + + +def name_parts(value, default_issuer=None): + issuer, name = value.split(":", 1) if ":" in value else (default_issuer, value) + if not name or any(not c.isprintable() for c in value) or issuer == "_hidden": + raise AuthError("Invalid account name or issuer") + return issuer or None, name + + +def write_oath(session, serial, command, args, options): + from yubikit.oath import CredentialData, OATH_TYPE, HASH_ALGORITHM + accounts = session.list_credentials() + if command == "add": + if not terminal(): + raise AuthError("Enrollment requires an interactive terminal") + value = args[0] if args else input("Account name: ").strip() + issuer, name = name_parts(value) + if issuer is None: + issuer = input("Issuer (optional): ").strip() or None + if issuer and (":" in issuer or issuer == "_hidden" + or any(not c.isprintable() for c in issuer)): + raise AuthError("Invalid issuer") + kind = OATH_TYPE[options.oath_type] + if options.counter and kind != OATH_TYPE.HOTP: + raise AuthError("Counter is only valid for HOTP") + if kind == OATH_TYPE.HOTP and options.period != 30: + raise AuthError("Period is only valid for TOTP") + data = CredentialData(name, kind, HASH_ALGORITHM[options.algorithm], + b"", options.digits, options.period, + options.counter, issuer) + if any(c.id == data.get_id() for c in accounts): + raise AuthError("Account already exists; refusing overwrite") + if not confirm(f"Persistently enroll {safe(data.get_id().decode())} on YubiKey {serial}; no touch required. Can be removed later."): + raise AuthError("Enrollment cancelled") + try: + raw = secret("Base32 secret: ").upper().replace(" ", "") + data.secret = base64.b32decode(raw + "=" * (-len(raw) % 8)) + if len(data.secret) < 2: + raise ValueError() + except (ValueError, TypeError): + raise AuthError("Invalid Base32 secret") from None + if any(c.id == data.get_id() for c in session.list_credentials()): + raise AuthError("Account appeared; refusing overwrite") + session.put_credential(data, touch_required=False) + if not any(c.id == data.get_id() for c in session.list_credentials()): + raise AuthError("Enrollment not verified") + print("Enrolled.") + return + cred = resolve(accounts, args[0]) + if command == "rename": + issuer, name = name_parts(args[1], cred.issuer) + if is_hotp(cred): + raise AuthError("HOTP rename not supported: SDK rename assumes TOTP identity format") + if session.version < (5, 3, 1): + raise AuthError("Rename requires firmware 5.3.1 or later") + data = CredentialData(name, cred.oath_type, HASH_ALGORITHM.SHA1, + b"", period=cred.period, issuer=issuer) + if any(c.id == data.get_id() for c in accounts): + raise AuthError("Destination account already exists") + if not confirm(f"Persistently rename {safe(account_id(cred))} on YubiKey {serial} to {safe(data.get_id().decode())}. Reversible by renaming again."): + raise AuthError("Rename cancelled") + if any(c.id == data.get_id() for c in session.list_credentials()): + raise AuthError("Destination appeared; refusing overwrite") + new_id = session.rename_credential(cred.id, name, issuer) + remaining = {c.id for c in session.list_credentials()} + if new_id != data.get_id() or new_id not in remaining or cred.id in remaining: + raise AuthError("Rename not verified") + print("Renamed.") + else: + if not confirm(f"Permanently delete {safe(account_id(cred))} from YubiKey {serial}. Cannot recover without the original secret."): + raise AuthError("Deletion cancelled") + session.delete_credential(cred.id) + if any(c.id == cred.id for c in session.list_credentials()): + raise AuthError("Deletion not verified") + print("Deleted.") + + +def compare_info(info): + """Return (check, status, observed, expected) records; never guess NFC.""" + checks = [] + fields = {} + apps = {} + columns = None + for line in info.splitlines(): + match = re.fullmatch(r"\s*Applications\s*(USB)?\s*(NFC)?\s*", line) + if match: + columns = ("USB", "NFC") if match.group(2) and match.group(1) else ("USB",) if not match.group(2) else ("NFC",) + continue + if ":" in line: + key, value = line.split(":", 1) + fields[key.strip()] = value.strip() + for app in POLICY: + if columns and re.match(re.escape(app) + r"\s+", line.strip()): + tail = line.strip()[len(app):].strip() + values = re.findall(r"Not available|Not supported|Disabled|Enabled", tail, re.I) + if len(values) == len(columns) and " ".join(tail.split()).casefold() == " ".join(values).casefold(): + apps[app] = dict(zip(columns, values)) + def check(label, actual, expected): + if actual is None: + status = "UNKNOWN" + elif actual.lower() in ("not available", "not supported"): + status = "UNSUPPORTED" + else: + status = "OK" if actual.casefold() == expected.casefold() else "MISMATCH" + checks.append((label, status, actual or "not reported", expected)) + interfaces = fields.get("Enabled USB interfaces") + if interfaces is not None: + interfaces = ", ".join(sorted(x.strip() for x in interfaces.split(","))) + check("USB interfaces", interfaces, "CCID, FIDO") + nfc = re.search(r"(?im)^NFC transport is (enabled|disabled)\s*$", info) + check("NFC transport", nfc.group(1) if nfc else None, "enabled") + for app, expected in POLICY.items(): + for transport in ("USB", "NFC"): + check(f"{app} / {transport}", apps.get(app, {}).get(transport), expected) + return checks + + +def doctor(requested): + print("ENVIRONMENT") + print(" ykman OK " + safe(backend(("--version",)).strip())) + try: + clock = subprocess.run(["timedatectl", "show", "-p", "NTPSynchronized", "--value"], + capture_output=True, text=True, timeout=5) + synced = clock.stdout.strip() if clock.returncode == 0 else "" + except (OSError, subprocess.TimeoutExpired): + synced = "" + clock_status = "OK" if synced == "yes" else "MISMATCH" if synced == "no" else "UNKNOWN" + print(f" Clock sync {clock_status:12} {synced if synced in ('yes', 'no') else 'not reported'} (not proof of accuracy)") + devices = serials() + if requested: + if requested not in devices: + raise AuthError("Selected YubiKey not detected") + devices = [requested] + if not devices: + raise AuthError("No serial-numbered devices detected; check USB permissions") + result = 1 if clock_status == "MISMATCH" else 0 + for serial in devices: + print(f"\nDEVICE {serial}") + try: + info = backend(("info",), serial) + except AuthError as exc: + print(f" Device access ERROR {exc}; check USB/CCID permissions") + result = 2 + continue + for line in info.splitlines(): + if line.startswith(("Device type:", "Firmware version:", "Form factor:")): + print(" " + safe(line)) + for label, status, actual, expected in compare_info(info): + print(f" {label:24} {status:12} actual: {safe(actual)}; expected: {expected}") + if status != "OK": + result = max(result, 1 if status == "MISMATCH" else 2) + print("\nResult: " + ("Application policy verified." if result == 0 else + "Review the observed/expected differences with ykman info; no changes made.")) + return result + + +def pgp(serial): + print(safe_multiline(backend(("openpgp", "info"), serial))) + help_text = backend(("openpgp", "keys", "info", "--help"), serial) + # Documented aliases vary; use advertised spelling, otherwise enc. + slot = "dec" if re.search(r"\bdec\b", help_text) and not re.search(r"\benc\b", help_text) else "enc" + result = 0 + for key in ("sig", slot, "aut"): + print(f"\n{key.upper()}") + try: + output = backend(("openpgp", "keys", "info", key), serial) + print(safe_multiline(output) if output.strip() else "Metadata unavailable") + if not output.strip(): + result = 2 + except AuthError as exc: + print(f"Unknown/inaccessible: {exc}") + result = 2 + return result + + +def safe_multiline(value): + return "\n".join(safe(line) for line in value.splitlines()) + + +def parse(argv): + parser = argparse.ArgumentParser(description="YubiKey authenticator", + epilog="Commands: list (ls), add [name], rename QUERY NAME, rm (remove) QUERY, fido, pgp, doctor, help. No command watches TOTP; a query selects one account.") + parser.add_argument("--version", action="version", version=VERSION) + parser.add_argument("--device", metavar="SERIAL") + parser.add_argument("--algorithm", choices=("SHA1", "SHA256", "SHA512"), default="SHA1") + parser.add_argument("--digits", type=int, choices=(6, 7, 8), default=6) + parser.add_argument("--period", type=int, default=30) + parser.add_argument("--oath-type", choices=("TOTP", "HOTP"), default="TOTP") + parser.add_argument("--counter", type=int, default=0) + parser.add_argument("command", nargs="?") + parser.add_argument("args", nargs="*") + options = parser.parse_args(argv) + command = {"ls": "list", "remove": "rm"}.get(options.command, options.command) + if command == "help": + parser.print_help() + return None + if options.device and not re.fullmatch(r"\d+", options.device): + parser.error("device must be a serial number") + if not 1 <= options.period <= 86400 or not 0 <= options.counter <= 0xffffffff: + parser.error("invalid period or counter") + if command != "add" and (options.algorithm, options.digits, options.period, + options.oath_type, options.counter) != ("SHA1", 6, 30, "TOTP", 0): + parser.error("enrollment options require add") + counts = {"list": (0,), "add": (0, 1), "rename": (2,), "rm": (1,), + "fido": (0,), "pgp": (0,), "doctor": (0,)} + if len(options.args) not in counts.get(command, (0,)): + parser.error("wrong number of arguments") + return command, options + + +def main(argv=None): + try: + parsed = parse(argv) + if parsed is None: + return 0 + command, options = parsed + if command == "doctor": + return doctor(options.device) + serial = select_serial(options.device) + if command == "fido": + if not terminal(): + raise AuthError("FIDO inventory requires an interactive terminal for secure PIN input") + print("Discoverable credentials only; not all FIDO registrations. Incorrect PIN can reduce retries.", flush=True) + backend(("fido", "credentials", "list"), serial, interactive=True) + return 0 + if command == "pgp": + return pgp(serial) + with oath_session(serial) as session: + if command == "list": + for cred in visible_accounts(session): + print(safe(account_id(cred)), cred.oath_type.name, f"{cred.period}s" if not is_hotp(cred) else "", sep="\t") + elif command in ("add", "rename", "rm"): + write_oath(session, serial, command, options.args, options) + else: + watch(session, command) + return 0 + except AuthError as exc: + print("auth: " + safe(exc), file=sys.stderr) + return 2 + except KeyboardInterrupt: + print("\nauth: interrupted", file=sys.stderr) + return 130 + except (EOFError, BrokenPipeError): + return 2 + except Exception as exc: + # SDK errors may contain secret-bearing APDU data. Never echo them. + print(f"auth: device or backend error ({type(exc).__name__}); check connection and application access", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + def terminate(_signum, _frame): + raise KeyboardInterrupt + signal.signal(signal.SIGTERM, terminate) + sys.exit(main()) diff --git a/cmd/auth/auth_test.go b/cmd/auth/auth_test.go new file mode 100644 index 0000000..efa90b1 --- /dev/null +++ b/cmd/auth/auth_test.go @@ -0,0 +1,92 @@ +package main + +import ( + "bytes" + "encoding/binary" + "strings" + "testing" +) + +type fakeCard struct { + calls [][]byte + replies [][]byte +} + +func (f *fakeCard) Transmit(command []byte)([]byte,error) { + f.calls=append(f.calls,append([]byte(nil),command...)) + reply:=f.replies[0] + f.replies=f.replies[1:] + return reply,nil +} +func reply(data []byte) []byte { return append(data,0x90,0) } + +func TestBulkHOTPIsNeverCalculated(t *testing.T) { + raw:=append(encodeTLV(tagName,[]byte("Counter")),encodeTLV(tagHOTP,[]byte{6})...) + f:=&fakeCard{replies:[][]byte{reply(raw)}} + s:=oathSession{cardSession:cardSession{f}} + rows,err:=s.codes([]account{{ID:"Counter",Kind:typeHOTP}},"Counter",60,true) + if err!=nil || len(rows)!=1 || !strings.Contains(rows[0].Code,"HOTP") { t.Fatalf("unexpected HOTP result: %v",err) } + if len(f.calls)!=1 || f.calls[0][1]!=0xa4 { t.Fatal("unexpected card instruction") } + if _,err=s.calculateOne(account{Kind:typeHOTP},60); err==nil { t.Fatal("HOTP guard failed") } +} +func TestBulkTouchIsNotTriggered(t *testing.T) { + raw:=append(encodeTLV(tagName,[]byte("Example")),encodeTLV(tagTouch,[]byte{6})...) + f:=&fakeCard{replies:[][]byte{reply(raw)}} + s:=oathSession{cardSession:cardSession{f}} + rows,err:=s.codes([]account{{ID:"Example",Kind:typeTOTP,Period:30}},"",60,false) + if err!=nil || len(rows)!=1 || rows[0].Code!="Touch required" || len(f.calls)!=1 { t.Fatal("bulk touch safety failed") } +} +func TestTimer(t *testing.T) { + rows:=[]codeRow{{"A","000001",30,60},{"B","123456",30,60}} + if countdown(rows,59)!="Expires in 1s" { t.Fatal("wrong shared timer") } + if strings.Contains(strings.Join(table(rows,60),"\n"),"000001") { t.Fatal("expired code displayed") } + if end,ok:=nextExpiry(rows,29); !ok || end!=29 { t.Fatal("clock rollback not detected") } + rows[1].Start=0 + if countdown(rows,59)!="Next expiry in 1s" { t.Fatal("mixed-period timer mislabeled") } +} +func TestFormatting(t *testing.T) { + raw:=[]byte{6,0,0,0,1} + code,err:=formatCode(raw) + if err!=nil || code!="000001" { t.Fatal("leading zeroes lost") } + if _,err=formatCode([]byte{6,0});err==nil { t.Fatal("malformed response accepted") } + if got:=binary.BigEndian.Uint64(challengeAt(59,30));got!=1 { t.Fatal("wrong time step") } +} +func TestTLV(t *testing.T) { + raw:=bytes.Repeat([]byte{7},130) + items,err:=parseTLV(encodeTLV(0x71,raw)) + if err!=nil || len(items)!=1 || !bytes.Equal(items[0].value,raw) { t.Fatal("TLV round trip failed") } + if _,err:=parseTLV([]byte{0x71,0x82,0x01});err==nil { t.Fatal("invalid length accepted") } +} +func TestNames(t *testing.T) { + a,err:=parseAccount("60/Example:Account",typeTOTP) + if err!=nil || a.Period!=60 || a.Issuer!="Example" { t.Fatal("period parsing failed") } + id,err:=accountName("New",a.Issuer,a.Kind,a.Period) + if err!=nil || id!="60/Example:New" { t.Fatal("rename did not preserve metadata") } + if _,err:=resolve([]account{{ID:"Example"},{ID:"Example2"}},"Example");err==nil { t.Fatal("ambiguous query accepted") } +} +func TestPolicy(t *testing.T) { + raw:="Enabled USB interfaces: FIDO, CCID\nNFC transport is enabled\nApplications USB NFC\n" + for _,p:=range policy { raw+=p.Name+" "+p.Expected+" "+p.Expected+"\n" } + checks:=compareInfo(raw) + if len(checks)!=16 { t.Fatal("incomplete policy") } + for _,c:=range checks { if c.Status!="OK" { t.Fatalf("unexpected check: %+v",c) } } + checks=compareInfo(strings.Replace(raw,"FIDO2 Enabled Enabled","FIDO2 Disabled Not available",1)) + for _,c:=range checks { + if c.Label=="FIDO2 / USB" && c.Status!="MISMATCH" { t.Fatal("USB mismatch hidden") } + if c.Label=="FIDO2 / NFC" && c.Status!="UNSUPPORTED" { t.Fatal("unsupported NFC hidden") } + } + for _,c:=range compareInfo("") { if c.Status!="UNKNOWN" { t.Fatal("missing field was not unknown") } } +} +func TestDraw(t *testing.T) { + var out bytes.Buffer + draw(&out,[]string{"Expires in 1s"},1,80) + if !strings.Contains(out.String(),"\x1b[1A") { t.Fatal("missing bounded cursor movement") } + for _,bad:=range []string{"\x1b[2J","\x1b[3J","\x1b[?1049h"} { + if strings.Contains(out.String(),bad) { t.Fatal("screen clear or alternate screen") } + } +} +func TestAllowlist(t *testing.T) { + for _,args:=range [][]string{{"oath","accounts","code"},{"config","usb"},{"fido","credentials","delete"},{"openpgp","keys","set-touch"}} { + if allowed(args) { t.Fatal("unsafe backend command admitted") } + } +} diff --git a/cmd/auth/doctor.go b/cmd/auth/doctor.go new file mode 100644 index 0000000..ff1e4da --- /dev/null +++ b/cmd/auth/doctor.go @@ -0,0 +1,137 @@ +package main + +// Device diagnostics are deliberately separate from OATH write operations. +// All ykman commands here are on the read-only allowlist in main.go. + +import ( + "context" + "errors" + "fmt" + "os/exec" + "regexp" + "sort" + "strings" + "time" +) + +type policyEntry struct { Name, Expected string } +var policy=[]policyEntry{ + {"Yubico OTP","Disabled"},{"FIDO U2F","Disabled"},{"FIDO2","Enabled"}, + {"OATH","Enabled"},{"PIV","Disabled"},{"OpenPGP","Enabled"},{"YubiHSM Auth","Disabled"}, +} +type check struct { Label, Status, Actual, Expected string } +var headerPattern=regexp.MustCompile("^Applications(?:\\s+(USB))?(?:\\s+(NFC))?$") +var statePattern=regexp.MustCompile("(?i)Not available|Not supported|Disabled|Enabled") + +func comparison(label,actual,expected string) check { + status:="MISMATCH" + switch { + case actual=="": status="UNKNOWN"; actual="not reported" + case strings.EqualFold(actual,"Not available") || strings.EqualFold(actual,"Not supported"): status="UNSUPPORTED" + case strings.EqualFold(actual,expected): status="OK" + } + return check{label,status,actual,expected} +} + +func compareInfo(raw string) []check { + fields:=map[string]string{} + apps:=map[string]map[string]string{} + var columns []string + nfc:="" + for _,line:=range strings.Split(raw,"\n") { + line=strings.TrimSpace(line) + if m:=headerPattern.FindStringSubmatch(line); m!=nil { + columns=nil + if m[1]!="" || m[2]=="" { columns=append(columns,"USB") } + if m[2]!="" { columns=append(columns,"NFC") } + continue + } + if key,value,ok:=strings.Cut(line,":"); ok { fields[key]=strings.TrimSpace(value) } + if line=="NFC transport is enabled" { nfc="enabled" } + if line=="NFC transport is disabled" { nfc="disabled" } + for _,p:=range policy { + if len(columns)==0 || !strings.HasPrefix(line,p.Name+" ") { continue } + tail:=strings.TrimSpace(strings.TrimPrefix(line,p.Name)) + values:=statePattern.FindAllString(tail,-1) + if len(values)==len(columns) && strings.EqualFold(strings.Join(strings.Fields(tail)," "),strings.Join(values," ")) { + if apps[p.Name]!=nil { apps[p.Name]=map[string]string{}; continue } + apps[p.Name]=map[string]string{} + for i,c:=range columns { apps[p.Name][c]=values[i] } + } + } + } + interfaces:=fields["Enabled USB interfaces"] + if interfaces!="" { + parts:=strings.Split(interfaces,",") + for i:=range parts { parts[i]=strings.TrimSpace(parts[i]) } + sort.Strings(parts) + interfaces=strings.Join(parts,", ") + } + result:=[]check{comparison("USB interfaces",interfaces,"CCID, FIDO"),comparison("NFC transport",nfc,"enabled")} + for _,p:=range policy { + for _,transport:=range []string{"USB","NFC"} { + result=append(result,comparison(p.Name+" / "+transport,apps[p.Name][transport],p.Expected)) + } + } + return result +} +func doctor(ctx context.Context,requested string)(int,error) { + fmt.Println("ENVIRONMENT") + version,err:=ykman(ctx,"",false,"--version") + if err!=nil { return 2,err } + fmt.Println(" ykman OK "+safe(strings.TrimSpace(version))) + clockCtx,cancel:=context.WithTimeout(ctx,5*time.Second) + defer cancel() + raw,clockErr:=exec.CommandContext(clockCtx,"timedatectl","show","-p","NTPSynchronized","--value").Output() + clock:=strings.TrimSpace(string(raw)) + result:=0 + switch { + case clockErr==nil && clock=="yes": fmt.Println(" Clock sync OK synchronized (not proof of exact accuracy)") + case clockErr==nil && clock=="no": fmt.Println(" Clock sync MISMATCH expected yes; observed no"); result=1 + default: fmt.Println(" Clock sync UNKNOWN unavailable") + } + all,err:=devices(ctx) + if err!=nil { return 2,err } + if requested!="" { + found:=false + for _,id:=range all { if id==requested { found=true } } + if !found { return 2,errors.New("selected YubiKey not detected") } + all=[]string{requested} + } + if len(all)==0 { return 2,errors.New("no serial-numbered YubiKey detected") } + for _,id:=range all { + fmt.Println("\nDEVICE "+id) + info,e:=ykman(ctx,id,false,"info") + if e!=nil { fmt.Println(" Device access ERROR "+safe(e.Error())); result=2; continue } + for _,line:=range strings.Split(info,"\n") { + if strings.HasPrefix(line,"Device type:") || strings.HasPrefix(line,"Firmware version:") || strings.HasPrefix(line,"Form factor:") { fmt.Println(" "+safe(line)) } + } + for _,c:=range compareInfo(info) { + fmt.Printf(" %-24s %-12s actual: %s; expected: %s\n",c.Label,c.Status,safe(c.Actual),c.Expected) + if c.Status=="MISMATCH" { result=max(result,1) } else if c.Status!="OK" { result=2 } + } + } + if result==0 { fmt.Println("\nApplication policy verified.") } else { fmt.Println("\nReview differences with ykman info; no changes made.") } + return result,nil +} +func pgp(ctx context.Context,serial string) error { + info,err:=ykman(ctx,serial,false,"openpgp","info") + if err!=nil { return err } + printSafeLines(info) + help,err:=ykman(ctx,serial,false,"openpgp","keys","info","--help") + if err!=nil { return err } + slot:="enc" + if regexp.MustCompile("\\bdec\\b").MatchString(help) && !regexp.MustCompile("\\benc\\b").MatchString(help) { slot="dec" } + var failed bool + for _,key:=range []string{"sig",slot,"aut"} { + fmt.Println("\n"+strings.ToUpper(key)) + raw,e:=ykman(ctx,serial,false,"openpgp","keys","info",key) + if e!=nil || strings.TrimSpace(raw)=="" { fmt.Println("Unknown/inaccessible"); failed=true; continue } + printSafeLines(raw) + } + if failed { return errors.New("one or more slot metadata checks failed") } + return nil +} +func printSafeLines(raw string) { + for _,line:=range strings.Split(strings.TrimRight(raw,"\n"),"\n") { fmt.Println(safe(line)) } +} diff --git a/cmd/auth/go.mod b/cmd/auth/go.mod new file mode 100644 index 0000000..89ad3b8 --- /dev/null +++ b/cmd/auth/go.mod @@ -0,0 +1,9 @@ +module github.com/axjab/scripts/cmd/auth + +go 1.23.0 + +require ( + github.com/ebfe/scard v0.0.0-20190212122703-c3d1b1916a95 + golang.org/x/crypto v0.31.0 + golang.org/x/term v0.29.0 +) diff --git a/cmd/auth/main.go b/cmd/auth/main.go new file mode 100644 index 0000000..22e778d --- /dev/null +++ b/cmd/auth/main.go @@ -0,0 +1,442 @@ +// auth is a local YubiKey authenticator. Start here when maintaining the CLI: +// main -> run -> command function -> hardware adapter in oath.go or ykman. +package main + +import ( + "bufio" + "context" + "encoding/base32" + "errors" + "flag" + "fmt" + "io" + "os" + "os/exec" + "os/signal" + "regexp" + "sort" + "strconv" + "strings" + "syscall" + "time" + "unicode" + "unicode/utf8" + + "golang.org/x/term" +) + +const version = "0.2.0" + +var stderr io.Writer = os.Stderr +var input = bufio.NewReader(os.Stdin) +var serialPattern = regexp.MustCompile("^[0-9]+$") + +// A context carries cancellation to blocking subprocesses. The native +// smart-card transport may finish an in-flight command before exiting. +func main() { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + code, err := run(ctx, os.Args[1:]) + if err != nil { fmt.Fprintln(stderr, "auth:", safe(err.Error())) } + if ctx.Err() != nil { os.Exit(130) } + os.Exit(code) +} + +type options struct { + device, algorithm, kind string + digits, period int + counter uint64 +} + +func usage() { + fmt.Fprintln(os.Stdout, "auth [options] [QUERY | list | add [NAME] | rename QUERY NAME | rm QUERY | fido | pgp | doctor]\n"+ + "No arguments: watch TOTP with one global countdown. ls/remove are aliases.\n"+ + "Options before command: --device SERIAL, --version, --help;\n"+ + "add options: --algorithm SHA1|SHA256|SHA512, --digits 6|7|8,\n"+ + "--period SECONDS, --oath-type TOTP|HOTP, --counter N.") +} + +func run(ctx context.Context, args []string) (int, error) { + f := flag.NewFlagSet("auth", flag.ContinueOnError) + f.SetOutput(stderr) + f.Usage = usage + var o options + f.StringVar(&o.device,"device","","YubiKey serial") + f.StringVar(&o.algorithm,"algorithm","SHA1","enrollment hash") + f.StringVar(&o.kind,"oath-type","TOTP","enrollment type") + f.IntVar(&o.digits,"digits",6,"enrollment digits") + f.IntVar(&o.period,"period",30,"enrollment period") + f.Uint64Var(&o.counter,"counter",0,"initial HOTP counter") + showVersion := f.Bool("version",false,"print version") + if err:=f.Parse(args); err!=nil { + if errors.Is(err,flag.ErrHelp) { return 0,nil } + return 2,err + } + if *showVersion { fmt.Println(version); return 0,nil } + args=f.Args() + command:="" + if len(args)>0 { command=args[0]; args=args[1:] } + if command=="ls" { command="list" } + if command=="remove" { command="rm" } + if command=="help" && len(args)==0 { usage(); return 0,nil } + if o.device!="" && !serialPattern.MatchString(o.device) { return 2,errors.New("device must be a numeric serial") } + if o.period<1 || o.period>86400 || o.counter>0xffffffff || o.digits<6 || o.digits>8 || + (o.kind!="TOTP" && o.kind!="HOTP") || (o.algorithm!="SHA1" && o.algorithm!="SHA256" && o.algorithm!="SHA512") { + return 2,errors.New("invalid enrollment options") + } + if command!="add" && (o.algorithm!="SHA1" || o.kind!="TOTP" || o.digits!=6 || o.period!=30 || o.counter!=0) { + return 2,errors.New("enrollment options require add") + } + if command=="add" { + if len(args)>1 { return 2,errors.New("add accepts one name") } + } else if command=="rename" { + if len(args)!=2 { return 2,errors.New("rename requires query and new name") } + } else if command=="rm" { + if len(args)!=1 { return 2,errors.New("rm requires a query") } + } else if len(args)!=0 { return 2,errors.New("unexpected extra arguments") } + if command=="doctor" { return doctor(ctx,o.device) } + serial,err:=selectDevice(ctx,o.device) + if err!=nil { return 2,err } + switch command { + case "fido": + if !interactive() { return 2,errors.New("FIDO inventory requires a terminal for PIN entry") } + fmt.Println("Discoverable credentials only; not all FIDO registrations. Incorrect PIN may reduce retries.") + _,err=ykman(ctx,serial,true,"fido","credentials","list") + case "pgp": + err=pgp(ctx,serial) + default: + err=withOATH(serial,func(s oathSession) error { + switch command { + case "list": + accounts,e:=s.list() + if e!=nil { return e } + for _,a:=range visible(accounts) { + if a.Kind==typeHOTP { fmt.Printf("%s\tHOTP\n",safe(a.ID)) } else { fmt.Printf("%s\tTOTP\t%ds\n",safe(a.ID),a.Period) } + } + return nil + case "add","rename","rm": + return writeOATH(ctx,s,serial,command,args,o) + default: + return watch(ctx,s,command) + } + }) + } + if err!=nil { return 2,err } + return 0,nil +} + +func safe(s string) string { + return strings.Map(func(r rune) rune { + if !unicode.IsPrint(r) || unicode.Is(unicode.Cf,r) { return '?' } + return r + },s) +} + +func validName(s string) bool { + return s!="" && utf8.ValidString(s) && safe(s)==s +} +func interactive() bool { return term.IsTerminal(int(os.Stdin.Fd())) && term.IsTerminal(int(os.Stdout.Fd())) } + +func readSecret(prompt string) ([]byte,error) { + if !interactive() { return nil,errors.New("secure input requires an interactive terminal") } + fmt.Fprint(stderr,prompt) + secret,err:=term.ReadPassword(int(os.Stdin.Fd())) + fmt.Fprintln(stderr) + if err!=nil { return nil,errors.New("secure input failed") } + return secret,nil +} +func ask(prompt string) (string,error) { + if !interactive() { return "",errors.New("interactive terminal required") } + fmt.Fprint(stderr,prompt) + value,err:=input.ReadString('\n') + if err!=nil { return "",errors.New("input cancelled") } + return strings.TrimSpace(value),nil +} +func confirm(message string) error { + fmt.Fprintln(stderr,safe(message)) + answer,err:=ask("Proceed? [y/N] ") + if err!=nil { return err } + if !strings.EqualFold(answer,"y") { return errors.New("cancelled; no write performed") } + return nil +} + +// The read-only command allowlist is intentionally explicit. No general +// ykman passthrough, config/reset, credential deletion or code command. +func allowed(args []string) bool { + switch strings.Join(args," ") { + case "--version","list --serials","info","fido credentials list","openpgp info", + "openpgp keys info --help","openpgp keys info sig","openpgp keys info enc", + "openpgp keys info dec","openpgp keys info aut": + return true + } + return false +} +func ykman(ctx context.Context, serial string, direct bool, args ...string) (string,error) { + if !allowed(args) { return "",errors.New("backend command not permitted") } + if _,err:=exec.LookPath("ykman"); err!=nil { return "",errors.New("ykman is not installed") } + if serial!="" { args=append([]string{"--device",serial},args...) } + if direct { + cmd:=exec.CommandContext(ctx,"ykman",args...) + cmd.Stdin,cmd.Stdout,cmd.Stderr=os.Stdin,os.Stdout,os.Stderr + if err:=cmd.Run(); err!=nil { return "",errors.New("ykman command failed; see backend output") } + return "",nil + } + ctx,cancel:=context.WithTimeout(ctx,15*time.Second) + defer cancel() + cmd:=exec.CommandContext(ctx,"ykman",args...) + raw,err:=cmd.Output() + if err!=nil { + if ctx.Err()!=nil { return "",errors.New("ykman timed out or cancelled") } + var exit *exec.ExitError + if errors.As(err,&exit) { + detail:=strings.ToLower(string(exit.Stderr)) + switch { + case strings.Contains(detail,"permission"): return "",errors.New("ykman permission denied") + case strings.Contains(detail,"not found"): return "",errors.New("ykman device not found") + case strings.Contains(detail,"not supported") || strings.Contains(detail,"no such command"): return "",errors.New("ykman command or application unsupported") + } + } + return "",errors.New("ykman failed; check connection/application access") + } + return string(raw),nil +} +func devices(ctx context.Context) ([]string,error) { + raw,err:=ykman(ctx,"",false,"list","--serials") + if err!=nil { return nil,err } + var result []string + seen:=map[string]bool{} + for _,line:=range strings.Split(strings.TrimSpace(raw),"\n") { + line=strings.TrimSpace(line) + if line=="" { continue } + if !serialPattern.MatchString(line) || seen[line] { return nil,errors.New("unexpected device inventory") } + seen[line]=true; result=append(result,line) + } + return result,nil +} +func selectDevice(ctx context.Context, requested string) (string,error) { + all,err:=devices(ctx) + if err!=nil { return "",err } + if requested!="" { + for _,id:=range all { if id==requested { return id,nil } } + return "",errors.New("selected YubiKey not detected") + } + if len(all)==0 { return "",errors.New("no serial-numbered YubiKey detected") } + if len(all)!=1 { return "",errors.New("multiple keys; select --device SERIAL") } + return all[0],nil +} + +func visible(accounts []account) []account { + var result []account + for _,a:=range accounts { if a.Issuer!="_hidden" { result=append(result,a) } } + sort.Slice(result,func(i,j int)bool{return result[i].ID64 { return "",errors.New("OATH identifier exceeds 64 bytes") } + return id,nil +} + +func writeOATH(ctx context.Context,s oathSession,serial,command string,args []string,o options) error { + if !interactive() { return errors.New("hardware writes require interactive confirmation") } + accounts,err:=s.list() + if err!=nil { return err } + if command=="add" { + name:="" + if len(args)==1 { name=args[0] } else if name,err=ask("Account name: "); err!=nil { return err } + issuer:="" + if !strings.Contains(name,":") { if issuer,err=ask("Issuer (optional): "); err!=nil { return err } } + kind:=byte(typeTOTP) + if o.kind=="HOTP" { kind=typeHOTP } + if (kind==typeHOTP && o.period!=30) || (kind==typeTOTP && o.counter!=0) { return errors.New("counter is HOTP only; period is TOTP only") } + id,err:=accountName(name,issuer,kind,int64(o.period)) + if err!=nil { return err } + if hasID(accounts,id) { return errors.New("credential exists; refusing overwrite") } + if err=confirm(fmt.Sprintf("Persistently enroll %s on key %s, without touch. Remove to undo.",id,serial)); err!=nil { return err } + if ctx.Err()!=nil { return ctx.Err() } + raw,err:=readSecret("Base32 secret: ") + if err!=nil { return err } + defer clear(raw) + // Decode into memory only; never put the secret in a process argument. + normalized:=make([]byte,0,len(raw)) + defer func(){clear(normalized)}() + for _,b:=range raw { + if b==' ' { continue } + if b>='a' && b<='z' { b-=32 } + normalized=append(normalized,b) + } + for len(normalized)>0 && normalized[len(normalized)-1]=='=' { normalized=normalized[:len(normalized)-1] } + secret:=make([]byte,base32.StdEncoding.DecodedLen(len(normalized))) + defer clear(secret) + n,e:=base32.StdEncoding.WithPadding(base32.NoPadding).Decode(secret,normalized) + if e!=nil || n<2 { return errors.New("invalid Base32 secret") } + e=ctx.Err() + if e!=nil { return e } + alg:=map[string]byte{"SHA1":1,"SHA256":2,"SHA512":3}[o.algorithm] + if err=s.add(enrollment{id,kind,alg,byte(o.digits),uint32(o.counter),secret[:n]}); err!=nil { return err } + accounts,err=s.list() + if err!=nil || !hasID(accounts,id) { return errors.New("enrollment result not verified; inspect list before retrying") } + fmt.Println("Enrolled.") + return nil + } + a,err:=resolve(accounts,args[0]) + if err!=nil { return err } + if command=="rename" { + id,e:=accountName(args[1],a.Issuer,a.Kind,a.Period) + if e!=nil { return e } + if hasID(accounts,id) { return errors.New("destination exists; refusing overwrite") } + if e=confirm(fmt.Sprintf("Persistently rename %s to %s on key %s. Rename back to undo.",a.ID,id,serial)); e!=nil { return e } + if ctx.Err()!=nil { return ctx.Err() } + if e=s.rename(a.ID,id); e!=nil { return e } + accounts,e=s.list() + if e!=nil || !hasID(accounts,id) || hasID(accounts,a.ID) { return errors.New("rename result not verified; inspect list") } + fmt.Println("Renamed.") + return nil + } + if err=confirm(fmt.Sprintf("Permanently delete %s from key %s. Cannot recover without original secret.",a.ID,serial)); err!=nil { return err } + if ctx.Err()!=nil { return ctx.Err() } + if err=s.remove(a.ID); err!=nil { return err } + accounts,err=s.list() + if err!=nil || hasID(accounts,a.ID) { return errors.New("deletion result not verified; inspect list") } + fmt.Println("Deleted.") + return nil +} + +// A single countdown shows the NEXT code expiry. For ordinary 30-second +// accounts this is the same expiry for every entry. Custom periods are +// supported, but labeled with their period instead of extra countdowns. +func nextExpiry(rows []codeRow,now int64) (int64,bool) { + var end int64 + for _,r:=range rows { + if r.End==0 { continue } + if now=r.End { return now,true } + if end==0 || r.End=r.End) { code="Expired - refreshing" } + suffix:="" + if r.End!=0 && r.End-r.Start!=30 { suffix=fmt.Sprintf(" (%ds period)",r.End-r.Start) } + lines=append(lines,fmt.Sprintf("%-32s %s%s",safe(r.ID),safe(code),suffix)) + } + if len(rows)==0 { lines=append(lines,"No visible OATH accounts") } + return lines +} +func countdown(rows []codeRow,now int64) string { + end,ok:=nextExpiry(rows,now) + if !ok { return "No timed codes" } + left:=max(int64(0),end-now) + mixed:=false + for _,r:=range rows { if r.End!=0 && r.End-r.Start!=30 { mixed=true } } + label:="Expires in" + if mixed { label="Next expiry in" } + return fmt.Sprintf("%s %ds",label,left) +} +func fit(s string,width int) string { + var out strings.Builder + for _,r:=range safe(s) { + size:=1 + if r>127 { size=2 } // conservative width: prevents wrapping wide Unicode + if width<=size { break } + width-=size + out.WriteRune(r) + } + return out.String() +} + +// Only our previously printed lines are replaced. No full-screen erases, +// alternate screen or cursor hiding. Stop on resize rather than risk reflow. +func draw(w io.Writer,lines []string,previous,width int) { + if previous>0 { fmt.Fprintf(w,"\x1b[%dA",previous) } + for _,line:=range lines { fmt.Fprintf(w,"\r\x1b[2K%s\n",fit(line,width)) } +} +func watch(ctx context.Context,s oathSession,query string) error { + accounts,err:=s.list() + if err!=nil { return err } + selected:="" + if query!="" { + a,e:=resolve(visible(accounts),query) + if e!=nil { return e } + selected=a.ID + } + live:=interactive() && os.Getenv("TERM")!="" && os.Getenv("TERM")!="dumb" + now:=unixNow() + rows,err:=s.codes(accounts,selected,now,false) + if err!=nil { return err } + // Only an explicit account query on a real terminal may trigger touch. + // Ordinary selected TOTP accounts use the same live view as the full list. + if selected!="" && len(rows)==1 && rows[0].Code=="Touch required" && live { + rows,err=s.codes(accounts,selected,unixNow(),true) + if err!=nil { return err } + live=false + } + if !live { + for _,line:=range table(rows,unixNow()) { fmt.Println(line) } + fmt.Println(countdown(rows,unixNow())) + return nil + } + width,height,err:=term.GetSize(int(os.Stdout.Fd())) + if err!=nil { return errors.New("cannot determine terminal size") } + lines:=append(table(rows,unixNow()),countdown(rows,unixNow())) + if len(lines)>=height { return errors.New("terminal too short; enlarge or pipe to a snapshot") } + draw(os.Stdout,lines,0,width) + // Align updates to actual Unix seconds, not to the time auth started. + for { + end,timed:=nextExpiry(rows,unixNow()) + if !timed { return nil } + delay:=time.Until(time.Unix(unixNow()+1,0)) + if delay<0 { delay=0 } + timer:=time.NewTimer(delay) + select { + case <-ctx.Done(): timer.Stop(); return ctx.Err() + case <-timer.C: + } + w,h,e:=term.GetSize(int(os.Stdout.Fd())) + if e!=nil || w!=width || h!=height { return errors.New("terminal resized; restart watch") } + now=unixNow() + current,expired:=nextExpiry(rows,now) + if expired && current<=now || now>=end { + // Replace expired codes before the potentially slow hardware call. + draw(os.Stdout,append(table(rows,now),"Refreshing..."),len(lines),width) + rows,e=s.codes(accounts,selected,now,false) + if e!=nil { return e } + w,h,e=term.GetSize(int(os.Stdout.Fd())) + if e!=nil || w!=width || h!=height { return errors.New("terminal resized; restart watch") } + fresh:=append(table(rows,unixNow()),countdown(rows,unixNow())) + if len(fresh)!=len(lines) { return errors.New("account count changed; restart watch") } + draw(os.Stdout,fresh,len(lines),width) + lines=fresh + } else { + // The common case replaces just the single countdown line. + draw(os.Stdout,[]string{countdown(rows,now)},1,width) + } + } +} diff --git a/cmd/auth/oath.go b/cmd/auth/oath.go new file mode 100644 index 0000000..2d631e9 --- /dev/null +++ b/cmd/auth/oath.go @@ -0,0 +1,424 @@ +package main + +// This file is the hardware boundary. PC/SC provides a connection to the card; +// the YubiKey performs the actual OATH calculations. We use Go's cryptography +// libraries only for the documented OATH password handshake and key normalization. +// FIDO and OpenPGP remain delegated to ykman. + +import ( + "bytes" + "crypto/hmac" + "crypto/rand" + "crypto/sha1" + "crypto/sha256" + "crypto/sha512" + "encoding/binary" + "errors" + "fmt" + "hash" + "regexp" + "strconv" + "strings" + "time" + + "github.com/ebfe/scard" + "golang.org/x/crypto/pbkdf2" +) + +const ( + tagName = 0x71 + tagList = 0x72 + tagKey = 0x73 + tagChallenge = 0x74 + tagResponse = 0x75 + tagTruncated = 0x76 + tagHOTP = 0x77 + tagVersion = 0x79 + tagCounter = 0x7a + tagAlgorithm = 0x7b + tagTouch = 0x7c + typeHOTP = 0x10 + typeTOTP = 0x20 +) + +var ( + managementAID = []byte{0xa0, 0, 0, 5, 0x27, 0x47, 0x11, 0x17} + oathAID = []byte{0xa0, 0, 0, 5, 0x27, 0x21, 1} + periodPrefix = regexp.MustCompile("^([0-9]+)/") +) + +// An interface describes behavior, not a concrete implementation. This tiny +// interface allows tests to substitute a fake card without accessing hardware. +type transmitter interface { + Transmit([]byte) ([]byte, error) +} + +type tlv struct { + tag byte + value []byte +} + +// TLV is the card's Tag-Length-Value encoding. Reject truncated/unknown +// length forms rather than interpreting an incomplete response as success. +func parseTLV(raw []byte) ([]tlv, error) { + var result []tlv + for len(raw) > 0 { + if len(raw) < 2 { return nil, errors.New("truncated TLV header") } + tag, n := raw[0], int(raw[1]) + raw = raw[2:] + if n >= 128 { + count := n & 127 + if count < 1 || count > 2 || len(raw) < count { + return nil, errors.New("invalid TLV length") + } + n = 0 + for _, b := range raw[:count] { n = n*256 + int(b) } + raw = raw[count:] + } + if n > len(raw) { return nil, errors.New("truncated TLV value") } + result = append(result, tlv{tag, raw[:n]}) + raw = raw[n:] + } + return result, nil +} + +func encodeTLV(tag byte, value []byte) []byte { + result := []byte{tag} + switch { + case len(value) < 128: + result = append(result, byte(len(value))) + case len(value) <= 255: + result = append(result, 0x81, byte(len(value))) + default: + result = append(result, 0x82, byte(len(value)>>8), byte(len(value))) + } + return append(result, value...) +} + +func uniqueTLV(items []tlv, tag byte) ([]byte, error) { + var found []byte + count := 0 + for _, item := range items { + if item.tag == tag { found = item.value; count++ } + } + if count > 1 { return nil, errors.New("duplicate card field") } + return found, nil +} + +type cardSession struct { card transmitter } + +// exchange sends only the commands chosen by the typed methods below. +// Never log APDUs: enrollment requests contain the shared secret. +func (s cardSession) exchange(ins, p1, p2 byte, data []byte, continuation byte) ([]byte, error) { + if len(data) > 255 { return nil, errors.New("card command too long") } + cmd := []byte{0, ins, p1, p2} + // Short APDUs require an explicit zero length even when data is empty. + cmd = append(append(cmd, byte(len(data))), data...) + var all []byte + for i := 0; i < 256; i++ { + raw, err := s.card.Transmit(cmd) + if err != nil { return nil, errors.New("smart-card communication failed; check connection") } + if len(raw) < 2 { return nil, errors.New("short smart-card response") } + sw1, sw2 := raw[len(raw)-2], raw[len(raw)-1] + all = append(all, raw[:len(raw)-2]...) + if sw1 == 0x90 && sw2 == 0 { return all, nil } + if sw1 == 0x61 { + cmd = []byte{0, continuation, 0, 0, 0} + continue + } + return nil, fmt.Errorf("card rejected command (status %02x%02x)", sw1, sw2) + } + return nil, errors.New("too many card response fragments") +} + +func (s cardSession) selectApp(aid []byte, continuation byte) ([]byte, error) { + return s.exchange(0xa4, 4, 0, aid, continuation) +} + +// Read the serial on the SAME physical card connection that will be used for +// OATH. Reader order and USB product IDs are not device identity. +func (s cardSession) serial() (string, error) { + if _, err := s.selectApp(managementAID, 0xc0); err != nil { return "", err } + raw, err := s.exchange(0x1d, 0, 0, nil, 0xc0) + if err != nil { return "", err } + if len(raw) < 1 || int(raw[0]) != len(raw)-1 { return "", errors.New("invalid management response") } + items, err := parseTLV(raw[1:]) + if err != nil { return "", err } + value, err := uniqueTLV(items, 2) + if err != nil || len(value) != 4 { return "", errors.New("card serial unavailable") } + return strconv.FormatUint(uint64(binary.BigEndian.Uint32(value)), 10), nil +} + +// openCard selects by verified serial, not by the first PC/SC reader. +// A transaction prevents another client from changing the selected app or +// credential inventory between a check and a write. +func openCard(serial string) (*scard.Context, *scard.Card, error) { + ctx, err := scard.EstablishContext() + if err != nil { return nil, nil, errors.New("PC/SC unavailable; check pcscd and CCID access") } + readers, err := ctx.ListReaders() + if err != nil { ctx.Release(); return nil, nil, errors.New("cannot enumerate PC/SC readers") } + for _, reader := range readers { + if !strings.Contains(strings.ToLower(reader), "yubikey") { continue } + card, err := ctx.Connect(reader, scard.ShareShared, scard.ProtocolAny) + if err != nil { continue } + if err = card.BeginTransaction(); err != nil { card.Disconnect(scard.LeaveCard); continue } + id, err := (cardSession{card}).serial() + if err == nil && id == serial { return ctx, card, nil } + card.EndTransaction(scard.LeaveCard) + card.Disconnect(scard.LeaveCard) + } + ctx.Release() + return nil, nil, errors.New("selected YubiKey not accessible over PC/SC or serial not verified") +} + +type oathSession struct { + cardSession + version []byte +} + +// Select and, if protected, authenticate once per command. Only the official +// protocol's challenge/response is sent; no password or PIN is in argv. +// No access-key or OTP is written to storage. +func openOATH(card transmitter) (oathSession, error) { + s := oathSession{cardSession: cardSession{card}} + raw, err := s.selectApp(oathAID, 0xa5) + if err != nil { return s, err } + items, err := parseTLV(raw) + if err != nil { return s, err } + s.version, err = uniqueTLV(items, tagVersion) + if err != nil || len(s.version) != 3 { return s, errors.New("OATH version unavailable") } + challenge, err := uniqueTLV(items, tagChallenge) + if err != nil { return s, err } + if len(challenge) == 0 { return s, nil } + salt, err := uniqueTLV(items, tagName) + if err != nil || len(salt) == 0 { return s, errors.New("OATH salt unavailable") } + algo, err := uniqueTLV(items, tagAlgorithm) + if err != nil || (len(algo) != 0 && !bytes.Equal(algo, []byte{1})) { + return s, errors.New("unsupported OATH access-key algorithm") + } + if len(challenge) != 8 { return s, errors.New("invalid OATH challenge") } + password, err := readSecret("OATH password: ") + if err != nil { return s, err } + defer clear(password) + key := pbkdf2.Key(password, salt, 1000, 16, sha1.New) + defer clear(key) + mac := func(message []byte) []byte { + h := hmac.New(sha1.New, key) + h.Write(message) + return h.Sum(nil) + } + hostChallenge := make([]byte, 8) + if _, err = rand.Read(hostChallenge); err != nil { return s, errors.New("randomness unavailable") } + data := append(encodeTLV(tagResponse, mac(challenge)), encodeTLV(tagChallenge, hostChallenge)...) + raw, err = s.exchange(0xa3, 0, 0, data, 0xa5) + if err != nil { return s, errors.New("OATH authentication failed; no retry attempted") } + items, err = parseTLV(raw) + if err != nil { return s, err } + response, err := uniqueTLV(items, tagResponse) + if err != nil || !hmac.Equal(response, mac(hostChallenge)) { + return s, errors.New("card authentication failed") + } + return s, nil +} + +type account struct { + ID string + Kind byte + Period int64 + Issuer string +} + +// The period is encoded in a Yubico account ID, e.g. 60/Issuer:Account. +// Standard TOTP IDs omit that prefix. HOTP has no time period. +func parseAccount(id string, kind byte) (account, error) { + a := account{ID: id, Kind: kind} + if !validName(id) { return a, errors.New("invalid card account identifier") } + name := id + switch kind { + case typeTOTP: + a.Period = 30 + if m := periodPrefix.FindStringSubmatch(id); m != nil { + period, err := strconv.ParseInt(m[1], 10, 64) + if err != nil || period < 1 || period > 86400 { return a, errors.New("unsupported TOTP period") } + a.Period = period + name = id[len(m[0]):] + } + case typeHOTP: + default: + return a, errors.New("unknown OATH credential type") + } + if issuer, rest, ok := strings.Cut(name, ":"); ok && issuer != "" && rest != "" { a.Issuer = issuer } + return a, nil +} + +func (s oathSession) list() ([]account, error) { + raw, err := s.exchange(0xa1, 0, 0, nil, 0xa5) + if err != nil { return nil, err } + items, err := parseTLV(raw) + if err != nil { return nil, err } + var result []account + seen := map[string]bool{} + for _, item := range items { + if item.tag != tagList || len(item.value) < 2 { return nil, errors.New("unexpected OATH inventory field") } + a, err := parseAccount(string(item.value[1:]), item.value[0]&0xf0) + if err != nil { return nil, err } + if seen[a.ID] { return nil, errors.New("duplicate credential identifier") } + seen[a.ID] = true + result = append(result, a) + } + return result, nil +} + +type codeRow struct { + ID, Code string + Start, End int64 // zero End means no timed code (HOTP, touch, unsupported). +} + +func challengeAt(now, period int64) []byte { + b := make([]byte, 8) + binary.BigEndian.PutUint64(b, uint64(now/period)) + return b +} + +// YubiKey returns a truncated 31-bit value and digit count; formatting that +// value is not calculating an OTP on the host. Preserve leading zeroes. +func formatCode(raw []byte) (string, error) { + if len(raw) != 5 || raw[0] < 6 || raw[0] > 8 { return "", errors.New("invalid OTP response") } + mod := uint32(1) + for i := byte(0); i < raw[0]; i++ { mod *= 10 } + return fmt.Sprintf("%0*d", int(raw[0]), (binary.BigEndian.Uint32(raw[1:])&0x7fffffff)%mod), nil +} + +func (s oathSession) calculateOne(a account, now int64) (string, error) { + // This guard is essential: CALCULATE on HOTP advances its counter. + if a.Kind != typeTOTP || a.Period <= 0 { return "", errors.New("refusing HOTP calculation") } + data := append(encodeTLV(tagName, []byte(a.ID)), encodeTLV(tagChallenge, challengeAt(now, a.Period))...) + raw, err := s.exchange(0xa2, 0, 1, data, 0xa5) + if err != nil { return "", err } + items, err := parseTLV(raw) + if err != nil || len(items) != 1 || items[0].tag != tagTruncated { + return "", errors.New("unexpected individual OTP response") + } + return formatCode(items[0].value) +} + +func timedRow(a account, code string, now int64) codeRow { + start := now/a.Period*a.Period + return codeRow{ID:a.ID, Code:code, Start:start, End:start+a.Period} +} + +// CALCULATE ALL does not advance HOTP and does not request touch. We never +// use ykman's CLI "accounts code" (which has an automatic repair path). +func (s oathSession) codes(accounts []account, selected string, now int64, touch bool) ([]codeRow, error) { + raw, err := s.exchange(0xa4, 0, 1, encodeTLV(tagChallenge, challengeAt(now, 30)), 0xa5) + if err != nil { return nil, err } + items, err := parseTLV(raw) + if err != nil || len(items)%2 != 0 { return nil, errors.New("invalid bulk OATH response") } + byID := map[string]account{} + for _, a := range accounts { byID[a.ID] = a } + seen := map[string]bool{} + var rows []codeRow + for i:=0; i h.BlockSize() { h.Write(secret); secret = h.Sum(nil); defer clear(secret) } + result := make([]byte, max(14, len(secret))) + copy(result, secret) + return result, nil +} + +func (s oathSession) add(e enrollment) error { + key, err := normalizeKey(e.Secret, e.Algorithm) + if err != nil { return err } + defer clear(key) + payload := append([]byte{e.Kind|e.Algorithm, e.Digits}, key...) + defer clear(payload) + data := append(encodeTLV(tagName, []byte(e.ID)), encodeTLV(tagKey, payload)...) + if e.Counter != 0 { + b := make([]byte, 4) + binary.BigEndian.PutUint32(b, e.Counter) + data = append(data, encodeTLV(tagCounter, b)...) + } + defer clear(data) + // No touch property is included. Do not add a force or overwrite flag. + _, err = s.exchange(1, 0, 0, data, 0xa5) + return err +} + +func (s oathSession) rename(old, new string) error { + if bytes.Compare(s.version, []byte{5,3,1}) < 0 { return errors.New("rename requires firmware 5.3.1 or later") } + data := append(encodeTLV(tagName, []byte(old)), encodeTLV(tagName, []byte(new))...) + _, err := s.exchange(5, 0, 0, data, 0xa5) + return err +} + +func (s oathSession) remove(id string) error { + _, err := s.exchange(2, 0, 0, encodeTLV(tagName, []byte(id)), 0xa5) + return err +} + +// Release the card between operations when possible; an OATH watch keeps its +// transaction until exit to avoid losing the selected/authenticated app. +func withOATH(serial string, fn func(oathSession) error) error { + ctx, card, err := openCard(serial) + if err != nil { return err } + defer ctx.Release() + defer card.Disconnect(scard.LeaveCard) + defer card.EndTransaction(scard.LeaveCard) + session, err := openOATH(card) + if err != nil { return err } + return fn(session) +} + +func unixNow() int64 { return time.Now().Unix() } diff --git a/do/build-auth b/do/build-auth new file mode 100755 index 0000000..1701bdb --- /dev/null +++ b/do/build-auth @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd) +cd "$root/cmd/auth" +go build -mod=mod -trimpath -o "$root/bin/auth" . diff --git a/docs/auth.md b/docs/auth.md new file mode 100644 index 0000000..d726809 --- /dev/null +++ b/docs/auth.md @@ -0,0 +1,127 @@ +# auth + +Go implementation of the local YubiKey authenticator for Debian 13 / compatible +Linux. The previous Python implementation is preserved verbatim as +`bin/auth.py` (and its tests are retained). The Go executable does not call it +or import the Yubico Python SDK. It uses native PC/SC for OATH and the existing +`ykman` CLI for read-only device, FIDO and OpenPGP information. + +## Build and install + +From the repository root: + +~~~sh +sudo apt install golang-go build-essential pkg-config libpcsclite-dev pcscd yubikey-manager +./do/build-auth +install -Dm755 bin/auth ~/.local/bin/auth +~~~ + +The build installs no packages itself; the first command changes host packages, +not the YubiKey. The Go module lives in cmd/auth, and its dependencies are +version-pinned. The build uses CGO and links the system PC/SC library; it is not +a fully static binary. Target systems need PC/SC runtime, CCID access and ykman. +Cross-compile for the target OS/architecture with a suitable C toolchain. +The generated binary is intentionally not committed. Remove +`~/.local/bin/auth` to uninstall. + +## Commands + +| Command | Behavior | +| --- | --- | +| auth | Watch TOTP, one global countdown, no terminal clear | +| auth QUERY | Watch one matching TOTP; explicit touch is a one-shot | +| auth list / ls | OATH names/types, no code generation | +| auth add [issuer:name] | Persistent enrollment; no touch, SHA1/6 digits/30s defaults | +| auth rename QUERY NAME | Persistent exact-ID rename, retains issuer/period | +| auth rm QUERY / remove QUERY | Irreversible deletion, confirmation defaults to No | +| auth fido | Native discoverable FIDO2 inventory; PIN prompt | +| auth pgp | Native general and slot metadata | +| auth doctor | Read-only device/clock/application policy report | +| auth --help / help / --version | Help and version | + +Use options before the command, e.g. `auth --device SERIAL list` or +`auth --digits 8 add Example`. Enrollment also accepts --algorithm, +--period, --oath-type and --counter. Multiple keys require explicit serial +selection except doctor; the card's serial is verified on the same connection +before OATH access. Doctor inspects all detected serial-numbered keys. + +Illustrative output (fictional): + +~~~text +ACCOUNT CODE +Example 012345 +Other 573891 +Expires in 18s +~~~ + +All standard 30-second TOTP accounts share the Unix-time boundary. For +nonstandard periods, the same single countdown reports the next expiration, +and nonstandard entries are labeled with their period. Non-TTY stdout prints +one snapshot and exits. HOTP is never calculated by this tool. Steam-format +credentials are not supported in the native Go backend; the preserved Python +implementation or Yubico Authenticator can be used deliberately. An explicit touch-required query is a one-shot. Resize, disconnect, or hardware error +requires restarting watch. + +## Code map for a Go beginner + +- main.go: argument parsing, cancellation, command routing, secure prompts, + account matching, confirmation and watch rendering. +- oath.go: PC/SC transport, serial verification, OATH protocol request/response + parsing, list/calculation/CRUD and password challenge-response. Comments + explain interfaces, error handling, and the reasons behind safety checks. +- doctor.go: policy comparison and native OpenPGP/FIDO-related diagnostics. +- auth_test.go: hardware-free tests using a fake card and pure functions. +- go.mod: pinned build dependencies. + +## Safety and limitations + +No OTP, password or Base32 secret is stored on disk, passed as a process +argument or sent to a logging system. The YubiKey performs OTP calculations. +The OATH protocol uses native PC/SC with standard Go crypto libraries for the +documented authentication handshake; no FIDO/OpenPGP algorithms are implemented. +The upstream ykman accounts code command can advance HOTP when a single +account matches and can attempt automatic repair/deletion on corruption. +We never call that command. The card transport uses exact IDs and an exclusive +PC/SC transaction to prevent interleaving with other clients between check and +write. Watch holds that transaction until exit, so other CCID consumers may +wait; stop watch before using those consumers. No driver or daemon is +automatically modified or restarted. SIGINT/SIGTERM cancels watch, but a native +in-flight card operation may complete first. Read-only FIDO inventory may +consume a PIN attempt on incorrect PIN; never automatically retries. + +Exit 0 success, 1 verified doctor policy mismatch, 2 usage/backend failure or +unverifiable policy, 130 interrupt. Clock unknown is informational. + +## Tests and review + +~~~sh +cd cmd/auth +go mod tidy +gofmt -w *.go +go test ./... +go vet ./... +~~~ + +Run original Python tests from the repo root: +`python3 -m unittest discover -s tests -p test_auth.py -v`. + +No attached physical key or installed ykman is available during authoring. +Dependency resolution, Go compilation, tests, and actual card protocol behavior +remain unverified until run on an appropriate host. Do not merge as production +ready before those gates pass. Review native PC/SC code against Yubico's +protocol and test hardware with expendable credentials first. Test each key +independently. + +1. Read-only: verify ykman version/help, auth doctor, auth list, multi-key + selection, FIDO inventory, OpenPGP slots, 30-second and custom TOTP + boundaries, watch resize/interrupt, non-TTY snapshot, disconnection, + protected OATH, HOTP-only and touch-only cases. No HOTP calculation. +2. With explicit permission and a disposable secret: add (persistent; + removable), rename (persistent; rename back), remove (irreversible without + original secret). Verify by listing after every operation. +3. Never use production credentials for write testing. + +References: [Yubico OATH protocol](https://developers.yubico.com/OATH/YKOATH_Protocol.html), +[Yubico SDK source](https://github.com/Yubico/yubikey-manager/blob/5.6.1/yubikit/oath.py), +[management SDK](https://github.com/Yubico/yubikey-manager/blob/5.6.1/yubikit/management.py), +[ykman guide](https://docs.yubico.com/software/yubikey/tools/ykman/). diff --git a/tests/test_auth.py b/tests/test_auth.py new file mode 100644 index 0000000..0dabdbb --- /dev/null +++ b/tests/test_auth.py @@ -0,0 +1,118 @@ +"""Hardware-free regression tests for auth.""" +import contextlib +import io +import pathlib +import runpy +import types +import unittest +from unittest.mock import patch + +auth = types.SimpleNamespace(**runpy.run_path(str(pathlib.Path(__file__).resolve().parents[1] / "bin/auth.py"))) +G = auth.main.__globals__ + + +def credential(name, kind="TOTP", touch=False, period=30): + return types.SimpleNamespace(id=name.encode(), oath_type=types.SimpleNamespace(name=kind), + issuer=None, touch_required=touch, period=period) + + +class Credential: + def __init__(self, name, kind="TOTP", touch=False, period=30): + self.__dict__.update(credential(name, kind, touch, period).__dict__) + + def __lt__(self, other): + return self.id < other.id + + +class AuthTests(unittest.TestCase): + def test_aliases(self): + self.assertEqual(auth.parse(["ls"])[0], "list") + self.assertEqual(auth.parse(["remove", "x"])[0], "rm") + + def test_unique(self): + a, b = credential("Example"), credential("Example 2") + self.assertIs(auth.resolve([a, b], "2"), b) + with self.assertRaises(auth.AuthError): + auth.resolve([a, b], "Example") + with self.assertRaises(auth.AuthError): + auth.resolve([a, b], "absent") + + def test_only_hotp_never_calculates_individual(self): + c = Credential("Counter", "HOTP") + class Session: + def calculate_all(self, timestamp): + return {c: None} + self.assertEqual(auth.fetch_codes(Session(), 60)[0][1], "HOTP - on demand only") + + def test_touch_not_triggered_by_bulk(self): + c = Credential("Touch", touch=True) + class Session: + def calculate_all(self, timestamp): + return {c: None} + self.assertEqual(auth.fetch_codes(Session(), 60)[0][1], "Touch required") + + def test_periods_and_leading_zeroes(self): + a, b = Credential("A"), Credential("B", period=60) + class Session: + def calculate_all(self, timestamp): + return {a: types.SimpleNamespace(value="000001", valid_from=30, valid_to=60), + b: types.SimpleNamespace(value="123456", valid_from=0, valid_to=60)} + rows = auth.fetch_codes(Session(), 59) + self.assertIn("000001 1s", auth.render(rows, 59)[1]) + self.assertFalse(auth.needs_refresh(rows, 59)) + self.assertTrue(auth.needs_refresh(rows, 60)) + self.assertTrue(auth.needs_refresh(rows, 29)) + self.assertNotIn("000001", auth.render(rows, 60)[1]) + + def test_terminal_no_clear(self): + out = io.StringIO() + with contextlib.redirect_stdout(out): + auth.draw(["first", "second"], 2, 80) + value = out.getvalue() + self.assertIn("\x1b[2A", value) + for forbidden in ("\x1b[2J", "\x1b[3J", "\x1b[?1049h"): + self.assertNotIn(forbidden, value) + + def test_non_tty_snapshot(self): + out = io.StringIO() + with patch.dict(G, {"terminal": lambda: False, + "fetch_codes": lambda *args: [("Example", "000001", 0, 30)], + "time": types.SimpleNamespace(time=lambda: 1)}), contextlib.redirect_stdout(out): + auth.watch(None, None) + self.assertIn("000001", out.getvalue()) + self.assertNotIn("\x1b", out.getvalue()) + + def test_policy(self): + info = "Enabled USB interfaces: FIDO, CCID\nNFC transport is enabled\nApplications USB NFC\n" + info += "\n".join(f"{a} {v} {v}" for a, v in auth.POLICY.items()) + self.assertEqual(len(auth.compare_info(info)), 16) + self.assertTrue(all(r[1] == "OK" for r in auth.compare_info(info))) + changed = info.replace("FIDO2 Enabled Enabled", "FIDO2 Disabled Not available") + results = {r[0]: r[1] for r in auth.compare_info(changed)} + self.assertEqual(results["FIDO2 / USB"], "MISMATCH") + self.assertEqual(results["FIDO2 / NFC"], "UNSUPPORTED") + self.assertTrue(all(r[1] == "UNKNOWN" for r in auth.compare_info(""))) + + def test_single_transport(self): + rows = auth.compare_info("Applications\nFIDO2 Enabled") + self.assertIn(("FIDO2 / USB", "OK", "Enabled", "Enabled"), rows) + self.assertIn(("FIDO2 / NFC", "UNKNOWN", "not reported", "Enabled"), rows) + + def test_read_allowlist(self): + for cmd in [("config", "usb"), ("fido", "credentials", "delete"), + ("openpgp", "keys", "set-touch"), ("oath", "accounts", "code")]: + with self.assertRaises(auth.AuthError): + auth.backend(cmd) + + def test_multi_key_requires_selection(self): + with patch.dict(G, {"serials": lambda: ["1", "2"]}): + with self.assertRaises(auth.AuthError): + auth.select_serial(None) + self.assertEqual(auth.select_serial("2"), "2") + + def test_sanitize(self): + self.assertEqual(auth.safe("a\x1b[2J"), "a?[2J") + + +if __name__ == "__main__": + unittest.main()