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.
libagent/gpg/agent.py ADDED
@@ -0,0 +1,385 @@
1
+ """GPG-agent utilities."""
2
+ import binascii
3
+ import hashlib
4
+ import logging
5
+
6
+ from cryptography.hazmat.primitives.keywrap import (InvalidUnwrap,
7
+ aes_key_unwrap)
8
+
9
+ from .. import util
10
+ from . import client, decode, keyring, protocol
11
+
12
+ log = logging.getLogger(__name__)
13
+
14
+
15
+ def yield_connections(sock):
16
+ """Run a server on the specified socket."""
17
+ while True:
18
+ log.debug('waiting for connection on %s', sock.getsockname())
19
+ try:
20
+ conn, _ = sock.accept()
21
+ except KeyboardInterrupt:
22
+ return
23
+ conn.settimeout(None)
24
+ log.debug('accepted connection on %s', sock.getsockname())
25
+ yield conn
26
+
27
+
28
+ def sig_encode(r, s):
29
+ """Serialize ECDSA signature data into GPG S-expression."""
30
+ r = util.assuan_serialize(util.num2bytes(r, 32))
31
+ s = util.assuan_serialize(util.num2bytes(s, 32))
32
+ return b'(7:sig-val(5:ecdsa(1:r32:' + r + b')(1:s32:' + s + b')))'
33
+
34
+
35
+ def sig_encode_rsa(s, length):
36
+ """Encode RSA signature data into GPG S-expression."""
37
+ s = util.assuan_serialize(util.num2bytes(s, length))
38
+ if length == 256:
39
+ return b'(7:sig-val(3:rsa(1:s256:' + s + b')))'
40
+ elif length == 512:
41
+ return b'(7:sig-val(3:rsa(1:s512:' + s + b')))'
42
+
43
+
44
+ def _serialize_point(data):
45
+ prefix = '{}:'.format(len(data)).encode('ascii')
46
+ # https://www.gnupg.org/documentation/manuals/assuan/Server-responses.html
47
+ return b'(5:value' + util.assuan_serialize(prefix + data) + b')'
48
+
49
+
50
+ def _serialize_rsa(data):
51
+ # https://www.gnupg.org/documentation/manuals/assuan/Server-responses.html
52
+ if data[0] == 9:
53
+ # AES with 256-bit key
54
+ # https://datatracker.ietf.org/doc/html/rfc4880#section-9.2
55
+ data = data[0:35]
56
+ elif data[0] == 7:
57
+ # AES with 128-bit key
58
+ data = data[0:19]
59
+
60
+ prefix = '{}:'.format(len(data)).encode('ascii')
61
+ return b'(5:value' + util.assuan_serialize(prefix + data) + b')'
62
+
63
+
64
+ def parse_ciphertext(line):
65
+ """Parse a PKDECRYPT ciphertext: its algorithm (ecdh, rsa or ecc) and parameters."""
66
+ prefix, line = line.split(b' ', 1)
67
+ assert prefix == b'D'
68
+ exp, leftover = keyring.parse(keyring.unescape(line))
69
+ log.debug('PKDECRYPT s-exp: %r', exp)
70
+ assert not leftover
71
+ label, exp = exp
72
+ assert label == b'enc-val'
73
+ # ecdh and rsa: GnuPG up to 2.4. ecc: GnuPG 2.5's PKDECRYPT --kem=PGP.
74
+ assert exp[0] in (b'ecdh', b'rsa', b'ecc')
75
+ return exp[0], dict(exp[1:])
76
+
77
+
78
+ def parse_decrypt(line):
79
+ """Parse ECDH request and return remote public key."""
80
+ algo, params = parse_ciphertext(line)
81
+ return params[b'a'] if algo == b'rsa' else params[b'e']
82
+
83
+
84
+ # OpenPGP ids, as GnuPG 2.5 sends them in (c ...) and (h ...) (RFC 4880 9.2, 9.4).
85
+ _KEM_KEYWRAP_KEY_LEN = {7: 16, 8: 24, 9: 32} # AES-128, AES-192, AES-256
86
+ _KEM_KDF_HASH = {8: hashlib.sha256, 9: hashlib.sha384, 10: hashlib.sha512}
87
+
88
+
89
+ def _ecdh_x(point):
90
+ """The shared secret RFC 6637 feeds to its KDF: the x-coordinate of the ECDH point."""
91
+ if len(point) == 33 and point[0] in (0x04, 0x40): # Curve25519, with a prefix byte
92
+ return point[1:]
93
+ if len(point) == 65 and point[0] == 0x04: # uncompressed NIST/secp256k1 point
94
+ return point[1:33]
95
+ if len(point) == 64: # x || y
96
+ return point[:32]
97
+ if len(point) == 32:
98
+ return point
99
+ raise ValueError('unexpected ECDH result length {}'.format(len(point)))
100
+
101
+
102
+ def kem_pgp_session_key(params, shared_point):
103
+ """
104
+ Finish GnuPG 2.5's PKDECRYPT --kem=PGP: the KDF and the key unwrap gpg did itself up to 2.4.
105
+
106
+ RFC 6637 section 8: KEK = Hash(00 00 00 01 || Z || kdf-params), truncated to the
107
+ key-wrap key length; the session key is AES-key-unwrapped from s, whose first
108
+ byte is the length of the rest.
109
+ """
110
+ if params.get(b't') is not None:
111
+ raise AgentError(b'ERR 67108924 Not supported <GPG Agent>') # RFC 9580 X25519 keys
112
+ cipher, hash_algo = int(params[b'c']), int(params[b'h'])
113
+ if cipher not in _KEM_KEYWRAP_KEY_LEN or hash_algo not in _KEM_KDF_HASH:
114
+ raise AgentError(b'ERR 67108924 Not supported <GPG Agent>')
115
+ wrapped = params[b's']
116
+ if not wrapped or wrapped[0] != len(wrapped) - 1:
117
+ raise AgentError(b'ERR 67108943 Invalid data <GPG Agent>')
118
+ digest = _KEM_KDF_HASH[hash_algo](
119
+ b'\x00\x00\x00\x01' + _ecdh_x(shared_point) + params[b'kdf-params']).digest()
120
+ kek = digest[:_KEM_KEYWRAP_KEY_LEN[cipher]]
121
+ try:
122
+ return aes_key_unwrap(kek, wrapped[1:])
123
+ except InvalidUnwrap as e:
124
+ raise AgentError(b'ERR 67109016 Decryption failed <GPG Agent>') from e
125
+
126
+
127
+ def _key_info(conn, args):
128
+ """
129
+ Dummy reply (mainly for 'gpg --edit' to succeed).
130
+
131
+ For details, see GnuPG agent KEYINFO command help.
132
+ https://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob;f=agent/command.c;h=c8b34e9882076b1b724346787781f657cac75499;hb=refs/heads/master#l1082
133
+ """
134
+ fmt = 'S KEYINFO {0} X - - - - - - -'
135
+ keygrip, = args
136
+ keyring.sendline(conn, fmt.format(keygrip).encode('ascii'))
137
+
138
+
139
+ class AgentError(Exception):
140
+ """GnuPG agent-related error."""
141
+
142
+
143
+ class AgentStop(Exception):
144
+ """Raised to close the agent."""
145
+
146
+
147
+ # pylint: disable=too-many-instance-attributes
148
+ class Handler:
149
+ """GPG agent requests' handler."""
150
+
151
+ def _get_options(self):
152
+ return self.options
153
+
154
+ def __init__(self, device, pubkey_bytes):
155
+ """C-tor."""
156
+ self.reset()
157
+ self.options = []
158
+ device.ui.options_getter = self._get_options
159
+ self.client = client.Client(device=device)
160
+ # Cache public keys from GnuPG
161
+ self.pubkey_bytes = pubkey_bytes
162
+ # "Clone" existing GPG version
163
+ self.version = keyring.gpg_version()
164
+
165
+ self.handlers = {
166
+ b'RESET': lambda *_: self.reset(),
167
+ b'OPTION': lambda _, args: self.handle_option(*args),
168
+ b'SETKEYDESC': None,
169
+ b'NOP': None,
170
+ b'GETINFO': self.handle_getinfo,
171
+ b'AGENT_ID': lambda conn, _: keyring.sendline(conn, b'D ONLYKEY'), # "Fake" agent ID
172
+ b'SIGKEY': lambda _, args: self.set_key(*args),
173
+ b'SETKEY': lambda _, args: self.set_key(*args),
174
+ b'SETHASH': lambda _, args: self.set_hash(*args),
175
+ b'PKSIGN': lambda conn, _: self.pksign(conn),
176
+ b'PKDECRYPT': self.pkdecrypt,
177
+ b'HAVEKEY': lambda conn, args: self.have_key(conn, *args),
178
+ b'KEYINFO': _key_info,
179
+ b'SCD': self.handle_scd,
180
+ b'GET_PASSPHRASE': self.handle_get_passphrase,
181
+ b'GET_CONFIRMATION': self.handle_get_confirmation,
182
+ }
183
+
184
+ def reset(self):
185
+ """Reset agent's state variables."""
186
+ self.keygrip = None
187
+ self.digest = None
188
+ self.algo = None
189
+
190
+ def handle_option(self, opt):
191
+ """Store GPG agent-related options (e.g. for pinentry)."""
192
+ self.options.append(opt)
193
+ log.debug('options: %s', self.options)
194
+
195
+ def handle_get_confirmation(self, conn, _):
196
+ """Prompt user for OnlyKey Challenge Code."""
197
+
198
+ def handle_get_passphrase(self, conn, _):
199
+ """Allow simple GPG symmetric encryption (using a passphrase)."""
200
+ p1 = self.client.device.ui.get_passphrase('Symmetric encryption:')
201
+ p2 = self.client.device.ui.get_passphrase('Re-enter encryption:')
202
+ if p1 == p2:
203
+ result = b'D ' + util.assuan_serialize(p1.encode('ascii'))
204
+ keyring.sendline(conn, result, confidential=True)
205
+ else:
206
+ log.warning('Passphrase does not match!')
207
+
208
+ def handle_getinfo(self, conn, args):
209
+ """Handle some of the GETINFO messages."""
210
+ result = None
211
+ if args[0] == b'version':
212
+ result = self.version
213
+ elif args[0] == b's2k_count':
214
+ # Use highest number of S2K iterations.
215
+ # https://www.gnupg.org/documentation/manuals/gnupg/OpenPGP-Options.html
216
+ # https://tools.ietf.org/html/rfc4880#section-3.7.1.3
217
+ result = '{}'.format(64 << 20).encode('ascii')
218
+ else:
219
+ log.warning('Unknown GETINFO command: %s', args)
220
+
221
+ if result:
222
+ keyring.sendline(conn, b'D ' + result)
223
+
224
+ def handle_scd(self, conn, args):
225
+ """No support for smart-card device protocol."""
226
+ reply = {
227
+ (b'GETINFO', b'version'): self.version,
228
+ }.get(args)
229
+ if reply is None:
230
+ raise AgentError(b'ERR 100696144 No such device <SCD>')
231
+ keyring.sendline(conn, b'D ' + reply)
232
+
233
+ @util.memoize_method # global cache for key grips
234
+ def get_identity(self, keygrip):
235
+ """
236
+ Returns device.interface.Identity that matches specified keygrip.
237
+
238
+ In case of missing keygrip, KeyError will be raised.
239
+ """
240
+ keygrip_bytes = binascii.unhexlify(keygrip)
241
+ pubkey_dict, user_ids = decode.load_by_keygrip(
242
+ pubkey_bytes=self.pubkey_bytes, keygrip=keygrip_bytes)
243
+ # We assume the first user ID is used to generate Agent-based GPG keys.
244
+ user_id = user_ids[0]['value'].decode('utf-8')
245
+ if pubkey_dict['algo'] not in {1, 2, 3}:
246
+ curve_name = protocol.get_curve_name_by_oid(pubkey_dict['curve_oid'])
247
+ ecdh = pubkey_dict['algo'] == protocol.ECDH_ALGO_ID
248
+ identity = client.create_identity(
249
+ user_id=user_id, curve_name=curve_name, keygrip=keygrip)
250
+ verifying_key = self.client.pubkey(identity=identity, ecdh=ecdh)
251
+ pubkey = protocol.PublicKey(
252
+ curve_name=curve_name, created=pubkey_dict['created'],
253
+ verifying_key=verifying_key, ecdh=ecdh)
254
+ assert pubkey.key_id() == pubkey_dict['key_id']
255
+ assert pubkey.keygrip() == keygrip_bytes
256
+ elif len(pubkey_dict['_to_hash']) < 350:
257
+ identity = client.create_identity(
258
+ user_id=user_id, curve_name='rsa2048', keygrip=keygrip)
259
+ verifying_key = self.client.pubkey(identity=identity, ecdh=False)
260
+ pubkey = protocol.PublicKey(
261
+ curve_name='rsa2048', created=pubkey_dict['created'],
262
+ verifying_key=verifying_key, ecdh=False)
263
+ elif len(pubkey_dict['_to_hash']) < 700:
264
+ identity = client.create_identity(
265
+ user_id=user_id, curve_name='rsa4096', keygrip=keygrip)
266
+ verifying_key = self.client.pubkey(identity=identity, ecdh=False)
267
+ pubkey = protocol.PublicKey(
268
+ curve_name='rsa4096', created=pubkey_dict['created'],
269
+ verifying_key=verifying_key, ecdh=False)
270
+ else:
271
+ identity = 'unknown identity type'
272
+ log.error(identity)
273
+
274
+ log.info('IDENTITY(%s)', identity)
275
+ return identity
276
+
277
+ def pksign(self, conn):
278
+ """Sign a message digest using a private EC key."""
279
+ log.debug('signing %r digest (algo #%s)', self.digest, self.algo)
280
+ identity = self.get_identity(keygrip=self.keygrip)
281
+ if identity.curve_name == 'rsa2048':
282
+ s = self.client.sign(identity=identity,
283
+ digest=binascii.unhexlify(self.digest))
284
+ result = sig_encode_rsa(s, 256)
285
+ elif identity.curve_name == 'rsa4096':
286
+ s = self.client.sign(identity=identity,
287
+ digest=binascii.unhexlify(self.digest))
288
+ result = sig_encode_rsa(s, 512)
289
+ else:
290
+ r, s = self.client.sign(identity=identity,
291
+ digest=binascii.unhexlify(self.digest))
292
+ result = sig_encode(r, s)
293
+ log.debug('result: %r', result)
294
+ keyring.sendline(conn, b'D ' + result)
295
+
296
+ def pkdecrypt(self, conn, args=()):
297
+ """Handle decryption using ECDH/RSA."""
298
+ kem = None
299
+ for arg in args:
300
+ if arg.startswith(b'--kem'):
301
+ kem = arg.split(b'=', 1)[1] if b'=' in arg else b'PQC-PGP'
302
+ if kem not in (None, b'PGP'):
303
+ raise AgentError(b'ERR 67108924 Not supported <GPG Agent>')
304
+
305
+ for msg in [b'S INQUIRE_MAXLEN 4096', b'INQUIRE CIPHERTEXT']:
306
+ keyring.sendline(conn, msg)
307
+
308
+ line = keyring.recvline(conn)
309
+ assert keyring.recvline(conn) == b'END'
310
+ algo, params = parse_ciphertext(line)
311
+ remote_pubkey = params[b'a'] if algo == b'rsa' else params[b'e']
312
+
313
+ identity = self.get_identity(keygrip=self.keygrip)
314
+ if kem == b'PGP':
315
+ # GnuPG 2.5 hands the KDF and the key unwrap to the agent and expects the
316
+ # session key back, without a PADDING status.
317
+ shared_point = self.client.ecdh(identity=identity, pubkey=remote_pubkey)
318
+ dvalue = _serialize_point(kem_pgp_session_key(params, shared_point))
319
+ # The session key: never into the log.
320
+ keyring.sendline(conn, b'D ' + dvalue, confidential=True)
321
+ return
322
+ if identity.curve_name in ('rsa2048', 'rsa4096'):
323
+ dvalue = _serialize_rsa(self.client.ecdh(identity=identity, pubkey=remote_pubkey))
324
+ else:
325
+ dvalue = _serialize_point(self.client.ecdh(identity=identity, pubkey=remote_pubkey))
326
+
327
+ keyring.sendline(conn, b'S PADDING 0')
328
+ # The shared point / RSA plaintext gpg derives the session key from.
329
+ keyring.sendline(conn, b'D ' + dvalue, confidential=True)
330
+
331
+ def have_key(self, conn, *keygrips):
332
+ """Check if any keygrip corresponds to a TREZOR-based key."""
333
+ if len(keygrips) == 1 and keygrips[0].startswith(b"--list="):
334
+ # Support "fast-path" key listing:
335
+ # https://dev.gnupg.org/rG40da61b89b62dcb77847dc79eb159e885f52f817
336
+ keygrips = list(decode.iter_keygrips(pubkey_bytes=self.pubkey_bytes))
337
+ log.debug('keygrips: %r', keygrips)
338
+ keyring.sendline(conn, b'D ' + util.assuan_serialize(b''.join(keygrips)))
339
+ return
340
+
341
+ for keygrip in keygrips:
342
+ try:
343
+ self.get_identity(keygrip=keygrip)
344
+ break
345
+ except KeyError as e:
346
+ log.warning('HAVEKEY(%s) failed: %s', keygrip, e)
347
+ else:
348
+ raise AgentError(b'ERR 67108881 No secret key <GPG Agent>')
349
+
350
+ def set_key(self, keygrip):
351
+ """Set hexadecimal keygrip for next operation."""
352
+ self.keygrip = keygrip
353
+
354
+ def set_hash(self, algo, digest):
355
+ """Set algorithm ID and hexadecimal digest for next operation."""
356
+ self.algo = algo
357
+ self.digest = digest
358
+
359
+ def handle(self, conn):
360
+ """Handle connection from GPG binary using the ASSUAN protocol."""
361
+ keyring.sendline(conn, b'OK')
362
+ for line in keyring.iterlines(conn):
363
+ parts = line.split(b' ')
364
+ command = parts[0]
365
+ args = tuple(parts[1:])
366
+
367
+ if command == b'BYE':
368
+ return
369
+ elif command == b'KILLAGENT':
370
+ keyring.sendline(conn, b'OK')
371
+ raise AgentStop()
372
+
373
+ if command not in self.handlers:
374
+ log.error('unknown request: %r', line)
375
+ continue
376
+
377
+ handler = self.handlers[command]
378
+ if handler:
379
+ try:
380
+ handler(conn, args)
381
+ except AgentError as e:
382
+ msg, = e.args
383
+ keyring.sendline(conn, msg)
384
+ continue
385
+ keyring.sendline(conn, b'OK')
libagent/gpg/client.py ADDED
@@ -0,0 +1,55 @@
1
+ """Device abstraction layer for GPG operations."""
2
+
3
+ import logging
4
+
5
+ from .. import formats, util
6
+ from ..device import interface
7
+
8
+ log = logging.getLogger(__name__)
9
+
10
+
11
+ def create_identity(user_id, curve_name, keygrip=None):
12
+ """Create GPG identity for hardware device."""
13
+ result = interface.Identity(identity_str='gpg://', curve_name=curve_name)
14
+ result.identity_dict['host'] = user_id
15
+ result.identity_dict['keygrip'] = keygrip
16
+ return result
17
+
18
+
19
+ class Client:
20
+ """Sign messages and get public keys from a hardware device."""
21
+
22
+ def __init__(self, device):
23
+ """C-tor."""
24
+ self.device = device
25
+
26
+ def pubkey(self, identity, ecdh=False):
27
+ """Return public key as VerifyingKey object."""
28
+ with self.device:
29
+ return self.device.pubkey(ecdh=ecdh, identity=identity)
30
+
31
+ def sign(self, identity, digest):
32
+ """Sign the digest and return a serialized signature."""
33
+ log.info('please confirm GPG signature on %s for "%s"...',
34
+ self.device, identity.to_string())
35
+ if identity.curve_name == formats.CURVE_NIST256:
36
+ digest = digest[:32] # sign the first 256 bits
37
+ log.debug('signing digest: %s', util.hexlify(digest))
38
+ log.debug('identity type: %s', identity.curve_name)
39
+ if identity.curve_name in ('rsa2048', 'rsa4096') and len(digest) == 32:
40
+ self.device.sig_hash(b'rsa-sha2-256')
41
+ elif identity.curve_name in ('rsa2048', 'rsa4096') and len(digest) == 64:
42
+ self.device.sig_hash(b'rsa-sha2-512')
43
+ with self.device:
44
+ sig = self.device.sign(blob=digest, identity=identity)
45
+ if identity.curve_name in ('rsa2048', 'rsa4096'):
46
+ return util.bytes2num(sig)
47
+ else:
48
+ return (util.bytes2num(sig[:32]), util.bytes2num(sig[32:]))
49
+
50
+ def ecdh(self, identity, pubkey):
51
+ """Derive shared secret using ECDH from remote public key."""
52
+ log.info('please confirm GPG decryption on %s for "%s"...',
53
+ self.device, identity.to_string())
54
+ with self.device:
55
+ return self.device.ecdh(pubkey=pubkey, identity=identity)