lib-agent 1.0.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,153 @@
1
+ """
2
+ libagent/device/onlykey_pqc.py — composite post-quantum PGP for the OnlyKey backend.
3
+
4
+ Bridges lib-agent's GPG sign/decrypt to the composite PQC keys loaded on the OnlyKey
5
+ (trustcrypto/libraries PR #31). One RSA slot (1-4) holds the composite key; the device
6
+ does each half on-device, the host does the OpenPGP composite framing (concat sig /
7
+ SHA3-256 key combine + AES key-unwrap), exactly like the openpgp.js `pqc` branch.
8
+
9
+ Composite algorithms (draft-ietf-openpgp-pqc):
10
+ * pqc_mldsa_ed25519 (algo 30): sign = Ed25519 sig (64) || ML-DSA-65 sig (3309)
11
+ * pqc_mlkem_x25519 (algo 35): decrypt = X25519 + ML-KEM-768, combined per
12
+ draft-ietf-openpgp-pqc-10 section 4.2.1 - SHA3-256 over mlkemKeyShare,
13
+ ecdhKeyShare, ecdhCipherText, ecdhPublicKey, algId, "OpenPGPCompositeKDFv1"
14
+ and its length - then RFC 3394 AES-256 key-unwrap.
15
+
16
+ Wire protocol (okpqc.cpp on the device):
17
+ * OKSIGN, slot, payload = [selector] + digest (selector 0=Ed25519, 1=ML-DSA)
18
+ * OKDECRYPT, slot, payload = 32-B X25519 point -> 32-B shared secret (ECC half)
19
+ * OKDECRYPT, slot, payload = 1088-B ML-KEM ct -> 32-B shared secret (PQC half)
20
+
21
+ UNTESTED against hardware — by inspection; mirror-verified against openpgp.js kem.js.
22
+ GnuPG cannot consume these keys. It is on the LibrePGP track: v5 keys, its own
23
+ Kyber codepoint 8 (PUBKEY_ALGO_KYBER in common/openpgpdefs.h) and no ML-DSA at
24
+ all, and it rejects a v6 key packet outright. Checked against 2.4.8 and 2.5.21;
25
+ no released version supports RFC 9580 v6 keys. rpgp >= 0.20 with the `draft-pqc`
26
+ feature is the interoperable implementation.
27
+ """
28
+ import hashlib
29
+ import struct
30
+
31
+ # component selectors (match okpqc.h)
32
+ HALF_ECC = 0
33
+ HALF_PQC = 1
34
+
35
+ # sizes
36
+ X25519_PT_LEN = 32
37
+ MLKEM_CT_LEN = 1088
38
+ SS_LEN = 32
39
+ ED25519_SIG_LEN = 64
40
+ MLDSA_SIG_LEN = 3309
41
+
42
+ # IANA-assigned (draft-ietf-openpgp-pqc-10). This is NOT just a tag: it is an
43
+ # input to the key combiner in composite_decrypt() below, so it is bound into
44
+ # the derived KEK. It was 105 - a PRIVATE/experimental codepoint - and every key
45
+ # or message produced under that value is unreadable here and everywhere else.
46
+ MLKEM_ALGO_ID = 35 # pqc_mlkem_x25519
47
+ COMPOSITE_KDF_LABEL = b"OpenPGPCompositeKDFv1"
48
+
49
+
50
+ # --------------------------- device dual-ops ---------------------------------
51
+
52
+ def _read_exact(ok, want, timeout_s=22):
53
+ import time
54
+ out = bytearray()
55
+ t_end = time.time() + timeout_s
56
+ while time.time() < t_end and len(out) < want:
57
+ try:
58
+ part = ok.read_bytes(timeout_ms=100)
59
+ except Exception:
60
+ continue
61
+ if part:
62
+ out.extend(part)
63
+ return bytes(out[:want])
64
+
65
+
66
+ def device_sign_half(ok, slot, selector, digest):
67
+ """OKSIGN one half. Returns the raw signature (64 B Ed25519 / 3309 B ML-DSA)."""
68
+ ok.send_large_message2(msg=ok_msg(ok, 'OKSIGN'), slot_id=slot,
69
+ payload=bytes([selector]) + bytes(digest))
70
+ want = ED25519_SIG_LEN if selector == HALF_ECC else MLDSA_SIG_LEN
71
+ return _read_exact(ok, want)
72
+
73
+
74
+ def device_decap_half(ok, slot, data):
75
+ """OKDECRYPT one half. `data` is the 32-B X25519 point or the 1088-B ML-KEM ct;
76
+ the device selects by size and returns the 32-B shared secret."""
77
+ ok.send_large_message2(msg=ok_msg(ok, 'OKDECRYPT'), slot_id=slot, payload=bytes(data))
78
+ return _read_exact(ok, SS_LEN)
79
+
80
+
81
+ def ok_msg(ok, name):
82
+ """Resolve the Message enum from whatever onlykey client the backend holds."""
83
+ from onlykey.client import Message
84
+ return getattr(Message, name)
85
+
86
+
87
+ # --------------------------- composite sign ----------------------------------
88
+
89
+ def composite_sign(ok, slot, digest):
90
+ """pqc_mldsa_ed25519 signature = Ed25519(64) || ML-DSA-65(3309)."""
91
+ ecc = device_sign_half(ok, slot, HALF_ECC, digest)
92
+ pqc = device_sign_half(ok, slot, HALF_PQC, digest)
93
+ if len(ecc) != ED25519_SIG_LEN or len(pqc) != MLDSA_SIG_LEN:
94
+ raise ValueError("composite sign: bad half lengths %d/%d" % (len(ecc), len(pqc)))
95
+ return ecc + pqc
96
+
97
+
98
+ # --------------------------- composite decrypt -------------------------------
99
+
100
+ def _sha3_256(*parts):
101
+ h = hashlib.sha3_256()
102
+ for p in parts:
103
+ h.update(p)
104
+ return h.digest()
105
+
106
+
107
+ def _aes_key_unwrap(kek, wrapped):
108
+ """RFC 3394 AES key unwrap (AES-256)."""
109
+ from cryptography.hazmat.primitives.keywrap import aes_key_unwrap
110
+ return aes_key_unwrap(bytes(kek), bytes(wrapped))
111
+
112
+
113
+ def composite_decrypt(ok, slot, ecc_ct, mlkem_ct, ecc_pub, mlkem_pub, wrapped_key,
114
+ algo_id=MLKEM_ALGO_ID):
115
+ """pqc_mlkem_x25519 decrypt -> session key.
116
+
117
+ ecc_ct: 32-B X25519 ephemeral point; mlkem_ct: 1088-B ML-KEM ciphertext;
118
+ ecc_pub: 32-B recipient X25519 pubkey; mlkem_pub: 1184-B ML-KEM ek; wrapped_key: C.
119
+ Mirrors openpgp.js kem.js decrypt exactly.
120
+ """
121
+ # 1) device does both halves
122
+ ecc_ss = device_decap_half(ok, slot, ecc_ct) # X25519(k, ephemeral)
123
+ mlkem_ss = device_decap_half(ok, slot, mlkem_ct) # ML-KEM decapsulate
124
+
125
+ # 2) ECC key share IS the raw X25519 shared secret - draft-10 section
126
+ # 4.1.1.1, x25519Kem.Decaps(): "Set the output ecdhKeyShare to X". It is
127
+ # NOT hashed with the ciphertext and recipient key first, which is what
128
+ # this tree used to do.
129
+ ecc_key_share = ecc_ss
130
+ mlkem_key_share = mlkem_ss
131
+
132
+ # 3) Key combiner - draft-10 section 4.2.1, verbatim:
133
+ # KEK = SHA3-256( mlkemKeyShare || ecdhKeyShare || ecdhCipherText ||
134
+ # ecdhPublicKey || algId || domSep || len(domSep) )
135
+ # where domSep is "OpenPGPCompositeKDFv1" and len(domSep) is one octet,
136
+ # decimal 21.
137
+ #
138
+ # NOT KMAC256, and neither the ML-KEM ciphertext nor its public key is
139
+ # an input. This tree previously used KMAC256 over data that included
140
+ # both, and a KEK built that way fails AES key unwrap against a
141
+ # conforming peer.
142
+ kek = _sha3_256(
143
+ mlkem_key_share,
144
+ ecc_key_share,
145
+ ecc_ct,
146
+ ecc_pub,
147
+ bytes([algo_id]),
148
+ COMPOSITE_KDF_LABEL,
149
+ bytes([len(COMPOSITE_KDF_LABEL)]),
150
+ )
151
+
152
+ # 4) AES-256 key unwrap -> session key
153
+ return _aes_key_unwrap(kek, wrapped_key)
@@ -0,0 +1,154 @@
1
+ """TREZOR-related code (see http://bitcointrezor.com/)."""
2
+
3
+ import binascii
4
+ import logging
5
+
6
+ import semver
7
+
8
+ from .. import formats
9
+ from . import interface
10
+
11
+ log = logging.getLogger(__name__)
12
+
13
+
14
+ class Trezor(interface.Device):
15
+ """Connection to TREZOR device."""
16
+
17
+ @classmethod
18
+ def package_name(cls):
19
+ """Python package name (at PyPI)."""
20
+ return 'trezor-agent'
21
+
22
+ @property
23
+ def _defs(self):
24
+ from . import trezor_defs
25
+ return trezor_defs
26
+
27
+ required_version = '>=1.4.0'
28
+
29
+ ui = None # can be overridden by device's users
30
+ cached_session_id = None
31
+
32
+ def _verify_version(self, connection):
33
+ f = connection.features
34
+ log.debug('connected to %s %s', self, f.device_id)
35
+ log.debug('label : %s', f.label)
36
+ log.debug('vendor : %s', f.vendor)
37
+ current_version = '{}.{}.{}'.format(f.major_version,
38
+ f.minor_version,
39
+ f.patch_version)
40
+ log.debug('version : %s', current_version)
41
+ log.debug('revision : %s', binascii.hexlify(f.revision))
42
+ if not semver.match(current_version, self.required_version):
43
+ fmt = ('Please upgrade your {} firmware to {} version'
44
+ ' (current: {})')
45
+ raise ValueError(fmt.format(self, self.required_version,
46
+ current_version))
47
+
48
+ def connect(self):
49
+ """Enumerate and connect to the first available interface."""
50
+ transport = self._defs.find_device()
51
+ if not transport:
52
+ raise interface.NotFoundError('{} not connected'.format(self))
53
+
54
+ log.debug('using transport: %s', transport)
55
+ for _ in range(5): # Retry a few times in case of PIN failures
56
+ connection = self._defs.Client(transport=transport,
57
+ ui=self.ui,
58
+ session_id=self.__class__.cached_session_id)
59
+ self._verify_version(connection)
60
+
61
+ try:
62
+ # unlock PIN and passphrase
63
+ self._defs.get_address(connection,
64
+ "Testnet",
65
+ self._defs.PASSPHRASE_TEST_PATH)
66
+ return connection
67
+ except (self._defs.PinException, ValueError) as e:
68
+ log.error('Invalid PIN: %s, retrying...', e)
69
+ continue
70
+ except Exception as e:
71
+ log.exception('ping failed: %s', e)
72
+ connection.close() # so the next HID open() will succeed
73
+ raise
74
+ return None
75
+
76
+ def close(self):
77
+ """Close connection."""
78
+ self.__class__.cached_session_id = self.conn.session_id
79
+ super().close()
80
+
81
+ def pubkey(self, identity, ecdh=False):
82
+ """Return public key."""
83
+ curve_name = identity.get_curve_name(ecdh=ecdh)
84
+ log.debug('"%s" getting public key (%s) from %s',
85
+ identity.to_string(), curve_name, self)
86
+ addr = identity.get_bip32_address(ecdh=ecdh)
87
+ result = self._defs.get_public_node(
88
+ self.conn,
89
+ n=addr,
90
+ ecdsa_curve_name=curve_name)
91
+ log.debug('result: %s', result)
92
+ pubkey = bytes(result.node.public_key)
93
+ return formats.decompress_pubkey(pubkey=pubkey, curve_name=identity.curve_name)
94
+
95
+ def _identity_proto(self, identity):
96
+ result = self._defs.IdentityType()
97
+ for name, value in identity.items():
98
+ setattr(result, name, value)
99
+ return result
100
+
101
+ def sign(self, identity, blob):
102
+ """Sign given blob and return the signature (as bytes)."""
103
+ sig, _ = self.sign_with_pubkey(identity, blob)
104
+ return sig
105
+
106
+ def sign_with_pubkey(self, identity, blob):
107
+ """Sign given blob and return the signature (as bytes)."""
108
+ curve_name = identity.get_curve_name(ecdh=False)
109
+ log.debug('"%s" signing %r (%s) on %s',
110
+ identity.to_string(), blob, curve_name, self)
111
+ try:
112
+ result = self._defs.sign_identity(
113
+ self.conn,
114
+ identity=self._identity_proto(identity),
115
+ challenge_hidden=blob,
116
+ challenge_visual='',
117
+ ecdsa_curve_name=curve_name)
118
+ log.debug('result: %s', result)
119
+ assert len(result.signature) == 65
120
+ assert result.signature[:1] == b'\x00'
121
+ return bytes(result.signature[1:]), bytes(result.public_key)
122
+ except self._defs.TrezorFailure as e:
123
+ msg = '{} error: {}'.format(self, e)
124
+ log.debug(msg, exc_info=True)
125
+ raise interface.DeviceError(msg)
126
+
127
+ def ecdh(self, identity, pubkey):
128
+ """Get shared session key using Elliptic Curve Diffie-Hellman."""
129
+ session_key, _ = self.ecdh_with_pubkey(identity, pubkey)
130
+ return session_key
131
+
132
+ def ecdh_with_pubkey(self, identity, pubkey):
133
+ """Get shared session key using Elliptic Curve Diffie-Hellman & self public key."""
134
+ curve_name = identity.get_curve_name(ecdh=True)
135
+ log.debug('"%s" shared session key (%s) for %r from %s',
136
+ identity.to_string(), curve_name, pubkey, self)
137
+ try:
138
+ result = self._defs.get_ecdh_session_key(
139
+ self.conn,
140
+ identity=self._identity_proto(identity),
141
+ peer_public_key=pubkey,
142
+ ecdsa_curve_name=curve_name)
143
+ log.debug('result: %s', result)
144
+ assert len(result.session_key) in {65, 33} # NIST256 or Curve25519
145
+ assert result.session_key[:1] == b'\x04'
146
+ self_pubkey = result.public_key
147
+ if self_pubkey:
148
+ self_pubkey = bytes(self_pubkey[1:])
149
+
150
+ return bytes(result.session_key), self_pubkey
151
+ except self._defs.TrezorFailure as e:
152
+ msg = '{} error: {}'.format(self, e)
153
+ log.debug(msg, exc_info=True)
154
+ raise interface.DeviceError(msg)
@@ -0,0 +1,30 @@
1
+ """TREZOR-related definitions."""
2
+
3
+ # pylint: disable=unused-import,import-error,no-name-in-module,no-member
4
+ import logging
5
+ import os
6
+
7
+ import mnemonic
8
+ import semver
9
+ import trezorlib
10
+ from trezorlib.btc import get_address, get_public_node
11
+ from trezorlib.client import PASSPHRASE_TEST_PATH
12
+ from trezorlib.client import TrezorClient as Client
13
+ from trezorlib.exceptions import PinException, TrezorFailure
14
+ from trezorlib.messages import IdentityType
15
+ from trezorlib.misc import get_ecdh_session_key, sign_identity
16
+ from trezorlib.transport import get_transport
17
+
18
+ log = logging.getLogger(__name__)
19
+
20
+
21
+ def find_device():
22
+ """Selects a transport based on `TREZOR_PATH` environment variable.
23
+
24
+ If unset, picks first connected device.
25
+ """
26
+ try:
27
+ return get_transport(os.environ.get("TREZOR_PATH"), prefix_search=True)
28
+ except Exception as e: # pylint: disable=broad-except
29
+ log.debug("Failed to find a Trezor device: %s", e)
30
+ return None
libagent/device/ui.py ADDED
@@ -0,0 +1,159 @@
1
+ """UIs for PIN/passphrase entry."""
2
+
3
+ import logging
4
+ import os
5
+ import subprocess
6
+ import sys
7
+
8
+ from .. import util
9
+
10
+ try:
11
+ from trezorlib.client import PASSPHRASE_ON_DEVICE
12
+ except ImportError:
13
+ PASSPHRASE_ON_DEVICE = object()
14
+
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+
19
+ class UI:
20
+ """UI for PIN/passphrase entry (for TREZOR devices)."""
21
+
22
+ def __init__(self, device_type, config=None):
23
+ """C-tor."""
24
+ default_pinentry = 'pinentry' # by default, use GnuPG pinentry tool
25
+ if config is None:
26
+ config = {}
27
+ self.pin_entry_binary = config.get('pin_entry_binary',
28
+ default_pinentry)
29
+ self.passphrase_entry_binary = config.get('passphrase_entry_binary',
30
+ default_pinentry)
31
+ self.options_getter = create_default_options_getter()
32
+ self.device_name = device_type.__name__
33
+ self.cached_passphrase_ack = util.ExpiringCache(
34
+ seconds=float(config.get('cache_expiry_seconds', 'inf')))
35
+
36
+ def get_pin(self, _code=None):
37
+ """Ask the user for (scrambled) PIN."""
38
+ description = (
39
+ 'Use the numeric keypad to describe number positions.\n'
40
+ 'The layout is:\n'
41
+ ' 7 8 9\n'
42
+ ' 4 5 6\n'
43
+ ' 1 2 3')
44
+ return interact(
45
+ title='{} PIN'.format(self.device_name),
46
+ prompt='PIN:',
47
+ description=description,
48
+ binary=self.pin_entry_binary,
49
+ options=self.options_getter())
50
+
51
+ def get_passphrase(self, prompt='Passphrase:', available_on_device=False):
52
+ """Ask the user for passphrase."""
53
+ passphrase = None
54
+ if self.cached_passphrase_ack:
55
+ passphrase = self.cached_passphrase_ack.get()
56
+ if passphrase is None:
57
+ env_passphrase = os.environ.get("TREZOR_PASSPHRASE")
58
+ if env_passphrase is not None:
59
+ passphrase = env_passphrase
60
+ elif available_on_device:
61
+ passphrase = PASSPHRASE_ON_DEVICE
62
+ else:
63
+ passphrase = interact(
64
+ title='{} passphrase'.format(self.device_name),
65
+ prompt=prompt,
66
+ description=None,
67
+ binary=self.passphrase_entry_binary,
68
+ options=self.options_getter())
69
+ if self.cached_passphrase_ack:
70
+ self.cached_passphrase_ack.set(passphrase)
71
+ return passphrase
72
+
73
+ def button_request(self, _code=None):
74
+ """Called by TrezorClient when device interaction is required."""
75
+ # XXX: show notification to the user?
76
+
77
+
78
+ def create_default_options_getter():
79
+ """Return current TTY and DISPLAY settings for GnuPG pinentry."""
80
+ options = []
81
+ if sys.stdin.isatty(): # short-circuit calling `tty`
82
+ try:
83
+ ttyname = subprocess.check_output(args=['tty']).strip()
84
+ options.append(b'ttyname=' + ttyname)
85
+ except (subprocess.CalledProcessError, OSError) as e:
86
+ # OSError: no `tty` program at all. Windows has none outside a
87
+ # Git Bash or MSYS shell, and there isatty() is also true for NUL,
88
+ # the stdin a detached agent gets.
89
+ log.warning('no TTY found: %s', e)
90
+
91
+ display = os.environ.get('DISPLAY')
92
+ if display is not None:
93
+ options.append('display={}'.format(display).encode('ascii'))
94
+ else:
95
+ log.warning('DISPLAY not defined')
96
+
97
+ log.info('using %s for pinentry options', options)
98
+ return lambda: options
99
+
100
+
101
+ def write(p, line):
102
+ """Send and flush a single line to the subprocess' stdin."""
103
+ log.debug('%s <- %r', p.args, line)
104
+ p.stdin.write(line)
105
+ p.stdin.flush()
106
+
107
+
108
+ class UnexpectedError(Exception):
109
+ """Unexpected response."""
110
+
111
+
112
+ def expect(p, prefixes, confidential=False):
113
+ """Read a line and return it without required prefix."""
114
+ resp = p.stdout.readline()
115
+ log.debug('%s -> %r', p.args, resp if not confidential else '********')
116
+ for prefix in prefixes:
117
+ if resp.startswith(prefix):
118
+ return resp[len(prefix):]
119
+ raise UnexpectedError(resp)
120
+
121
+
122
+ def interact(title, description, prompt, binary, options):
123
+ """Use GPG pinentry program to interact with the user."""
124
+ args = [binary]
125
+ p = subprocess.Popen(args=args,
126
+ stdin=subprocess.PIPE,
127
+ stdout=subprocess.PIPE,
128
+ env=os.environ)
129
+ p.args = args # TODO: remove after Python 2 deprecation.
130
+ expect(p, [b'OK'])
131
+
132
+ title = util.assuan_serialize(title.encode('ascii'))
133
+ write(p, b'SETTITLE ' + title + b'\n')
134
+ expect(p, [b'OK'])
135
+
136
+ if description:
137
+ description = util.assuan_serialize(description.encode('ascii'))
138
+ write(p, b'SETDESC ' + description + b'\n')
139
+ expect(p, [b'OK'])
140
+
141
+ if prompt:
142
+ prompt = util.assuan_serialize(prompt.encode('ascii'))
143
+ write(p, b'SETPROMPT ' + prompt + b'\n')
144
+ expect(p, [b'OK'])
145
+
146
+ log.debug('setting %d options', len(options))
147
+ for opt in options:
148
+ write(p, b'OPTION ' + opt + b'\n')
149
+ expect(p, [b'OK', b'ERR'])
150
+
151
+ write(p, b'GETPIN\n')
152
+ pin = expect(p, [b'OK', b'D '], confidential=True)
153
+
154
+ p.communicate() # close stdin and wait for the process to exit
155
+ exit_code = p.wait()
156
+ if exit_code:
157
+ raise subprocess.CalledProcessError(exit_code, binary)
158
+
159
+ return pin.decode('ascii').strip()