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,270 @@
1
+ """Tools for doing signature using gpg-agent."""
2
+ from __future__ import absolute_import, print_function, unicode_literals
3
+
4
+ import binascii
5
+ import io
6
+ import logging
7
+ import os
8
+ import re
9
+ import socket
10
+ import subprocess
11
+ from urllib.parse import unquote, unquote_to_bytes
12
+
13
+ from .. import util
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+
18
+ def check_output(args, env=None, sp=subprocess):
19
+ """Call an external binary and return its stdout."""
20
+ log.debug('calling %s with env %s', args, env)
21
+ p = sp.Popen(args=args, env=env, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
22
+ (output, error) = p.communicate()
23
+ log.debug('output: %r', output)
24
+ if error:
25
+ log.debug('error: %r', error)
26
+ return output
27
+
28
+
29
+ def get_agent_sock_path(env=None, sp=subprocess):
30
+ """Parse gpgconf output to find out GPG agent UNIX socket path."""
31
+ args = [util.which('gpgconf'), '--list-dirs']
32
+ output = check_output(args=args, env=env, sp=sp)
33
+ # gpgconf percent-escapes its values (':' becomes '%3a', so a Windows path
34
+ # reads 'C%3a\...') and ends its lines with '\r\n' on Windows.
35
+ lines = output.strip().splitlines()
36
+ dirs = {name: unquote_to_bytes(value)
37
+ for name, value in (line.split(b':', 1) for line in lines)}
38
+ log.debug('%s: %s', args, dirs)
39
+ return dirs[b'agent-socket']
40
+
41
+
42
+ def connect_to_agent(env=None, sp=subprocess):
43
+ """Connect to GPG agent's UNIX socket."""
44
+ sock_path = get_agent_sock_path(sp=sp, env=env)
45
+ # Make sure the original gpg-agent is running.
46
+ check_output(args=['gpg-connect-agent', '/bye'], sp=sp)
47
+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
48
+ sock.connect(sock_path)
49
+ return sock
50
+
51
+
52
+ def communicate(sock, msg):
53
+ """Send a message and receive a single line."""
54
+ sendline(sock, msg.encode('ascii'))
55
+ return recvline(sock)
56
+
57
+
58
+ def sendline(sock, msg, confidential=False):
59
+ """Send a binary message, followed by EOL."""
60
+ log.debug('<- %r', ('<snip>' if confidential else msg))
61
+ sock.sendall(msg + b'\n')
62
+
63
+
64
+ def recvline(sock):
65
+ """Receive a single line from the socket."""
66
+ reply = io.BytesIO()
67
+
68
+ while True:
69
+ c = sock.recv(1)
70
+ if not c:
71
+ return None # socket is closed
72
+
73
+ if c == b'\n':
74
+ break
75
+ reply.write(c)
76
+
77
+ result = reply.getvalue()
78
+ log.debug('-> %r', result)
79
+ return result
80
+
81
+
82
+ def iterlines(conn):
83
+ """Iterate over input, split by lines."""
84
+ while True:
85
+ line = recvline(conn)
86
+ if line is None:
87
+ break
88
+ yield line
89
+
90
+
91
+ def unescape(s):
92
+ """Unescape ASSUAN message (0xAB <-> '%AB')."""
93
+ s = bytearray(s)
94
+ i = 0
95
+ while i < len(s):
96
+ if s[i] == ord('%'):
97
+ hex_bytes = bytes(s[i+1:i+3])
98
+ value = int(hex_bytes.decode('ascii'), 16)
99
+ s[i:i+3] = [value]
100
+ i += 1
101
+ return bytes(s)
102
+
103
+
104
+ def parse_term(s):
105
+ """Parse single s-expr term from bytes."""
106
+ size, s = s.split(b':', 1)
107
+ size = int(size)
108
+ return s[:size], s[size:]
109
+
110
+
111
+ def parse(s):
112
+ """Parse full s-expr from bytes."""
113
+ if s.startswith(b'('):
114
+ s = s[1:]
115
+ name, s = parse_term(s)
116
+ values = [name]
117
+ while not s.startswith(b')'):
118
+ value, s = parse(s)
119
+ values.append(value)
120
+ return values, s[1:]
121
+
122
+ return parse_term(s)
123
+
124
+
125
+ def _parse_ecdsa_sig(args):
126
+ (r, sig_r), (s, sig_s) = args
127
+ assert r == b'r'
128
+ assert s == b's'
129
+ return (util.bytes2num(sig_r),
130
+ util.bytes2num(sig_s))
131
+
132
+
133
+ # DSA and EDDSA happen to have the same structure as ECDSA signatures
134
+ _parse_dsa_sig = _parse_ecdsa_sig
135
+ _parse_eddsa_sig = _parse_ecdsa_sig
136
+
137
+
138
+ def _parse_rsa_sig(args):
139
+ (s, sig_s), = args
140
+ assert s == b's'
141
+ return (util.bytes2num(sig_s),)
142
+
143
+
144
+ def parse_sig(sig):
145
+ """Parse signature integer values from s-expr."""
146
+ label, sig = sig
147
+ assert label == b'sig-val'
148
+ algo_name = sig[0]
149
+ parser = {b'rsa': _parse_rsa_sig,
150
+ b'ecdsa': _parse_ecdsa_sig,
151
+ b'eddsa': _parse_eddsa_sig,
152
+ b'dsa': _parse_dsa_sig}[algo_name]
153
+ return parser(args=sig[1:])
154
+
155
+
156
+ def sign_digest(sock, keygrip, digest, sp=subprocess, environ=None):
157
+ """Sign a digest using specified key using GPG agent."""
158
+ hash_algo = 8 # SHA256
159
+ assert len(digest) == 32
160
+
161
+ assert communicate(sock, 'RESET').startswith(b'OK')
162
+
163
+ ttyname = check_output(args=['tty'], sp=sp).strip()
164
+ options = ['ttyname={}'.format(ttyname)] # set TTY for passphrase entry
165
+
166
+ display = (environ or os.environ).get('DISPLAY')
167
+ if display is not None:
168
+ options.append('display={}'.format(display))
169
+
170
+ for opt in options:
171
+ assert communicate(sock, 'OPTION {}'.format(opt)) == b'OK'
172
+
173
+ assert communicate(sock, 'SIGKEY {}'.format(keygrip)) == b'OK'
174
+ hex_digest = binascii.hexlify(digest).upper().decode('ascii')
175
+ assert communicate(sock, 'SETHASH {} {}'.format(hash_algo,
176
+ hex_digest)) == b'OK'
177
+
178
+ assert communicate(sock, 'SETKEYDESC '
179
+ 'Sign+a+new+TREZOR-based+subkey') == b'OK'
180
+ assert communicate(sock, 'PKSIGN') == b'OK'
181
+ while True:
182
+ line = recvline(sock).strip()
183
+ if not line.startswith(b'S PROGRESS'):
184
+ break
185
+ line = unescape(line)
186
+ log.debug('unescaped: %r', line)
187
+ prefix, sig = line.split(b' ', 1)
188
+ if prefix != b'D':
189
+ raise ValueError(prefix)
190
+
191
+ sig, leftover = parse(sig)
192
+ assert not leftover, leftover
193
+ return parse_sig(sig)
194
+
195
+
196
+ def get_gnupg_components(sp=subprocess):
197
+ """Parse GnuPG components' paths."""
198
+ args = [util.which('gpgconf'), '--list-components']
199
+ output = check_output(args=args, sp=sp)
200
+ # Same escaping as in get_agent_sock_path(): unescape the path and drop the
201
+ # '\r' of a Windows line ending, which '.*' would otherwise keep.
202
+ components = {name: unquote(path.rstrip('\r'))
203
+ for name, path in re.findall('(.*):.*:(.*)', output.decode('utf-8'))}
204
+ log.debug('gpgconf --list-components: %s', components)
205
+ return components
206
+
207
+
208
+ @util.memoize
209
+ def get_gnupg_binary(sp=subprocess, neopg_binary=None):
210
+ """Starting GnuPG 2.2.x, the default installation uses `gpg`."""
211
+ if neopg_binary:
212
+ return neopg_binary
213
+ return get_gnupg_components(sp=sp)['gpg']
214
+
215
+
216
+ def gpg_command(args, env=None):
217
+ """Prepare common GPG command line arguments."""
218
+ if env is None:
219
+ env = os.environ
220
+ cmd = get_gnupg_binary(neopg_binary=env.get('NEOPG_BINARY'))
221
+ return [cmd] + args
222
+
223
+
224
+ def get_keygrip(user_id, sp=subprocess):
225
+ """Get a keygrip of the primary GPG key of the specified user."""
226
+ args = gpg_command(['--list-keys', '--with-keygrip', user_id])
227
+ output = check_output(args=args, sp=sp).decode('utf-8')
228
+ return re.findall(r'Keygrip = (\w+)', output)[0]
229
+
230
+
231
+ def gpg_version(sp=subprocess):
232
+ """Get a keygrip of the primary GPG key of the specified user."""
233
+ args = gpg_command(['--version'])
234
+ output = check_output(args=args, sp=sp)
235
+ # rstrip(): on Windows the line ends with '\r', which semver rejects.
236
+ line = output.split(b'\n', maxsplit=1)[0].rstrip() # b'gpg (GnuPG) 2.1.11'
237
+ line = line.split(b' ')[-1] # b'2.1.11'
238
+ line = line.split(b'-')[0] # remove trailing version parts
239
+ return line.split(b'v')[-1] # remove 'v' prefix
240
+
241
+
242
+ def export_public_key(user_id, env=None, sp=subprocess):
243
+ """Export GPG public key for specified `user_id`."""
244
+ args = gpg_command(['--export', user_id])
245
+ result = check_output(args=args, env=env, sp=sp)
246
+ if not result:
247
+ log.error('could not find public key %r in local GPG keyring', user_id)
248
+ raise KeyError(user_id)
249
+ return result
250
+
251
+
252
+ def export_public_keys(env=None, sp=subprocess):
253
+ """Export all GPG public keys."""
254
+ args = gpg_command(['--export'])
255
+ result = check_output(args=args, env=env, sp=sp)
256
+ if not result:
257
+ raise KeyError('No GPG public keys found at env: {!r}'.format(env))
258
+ return result
259
+
260
+
261
+ def create_agent_signer(user_id):
262
+ """Sign digest with existing GPG keys using gpg-agent tool."""
263
+ sock = connect_to_agent(env=os.environ)
264
+ keygrip = get_keygrip(user_id)
265
+
266
+ def sign(digest):
267
+ """Sign the digest and return an ECDSA/RSA/DSA signature."""
268
+ return sign_digest(sock=sock, keygrip=keygrip, digest=digest)
269
+
270
+ return sign
@@ -0,0 +1,291 @@
1
+ """GPG protocol utilities."""
2
+
3
+ import base64
4
+ import hashlib
5
+ import logging
6
+ import struct
7
+
8
+ import nacl.signing
9
+
10
+ from .. import formats, util
11
+
12
+ log = logging.getLogger(__name__)
13
+
14
+
15
+ def packet(tag, blob):
16
+ """Create small GPG packet."""
17
+ assert len(blob) < 2**32
18
+
19
+ if len(blob) < 2**8:
20
+ length_type = 0
21
+ elif len(blob) < 2**16:
22
+ length_type = 1
23
+ else:
24
+ length_type = 2
25
+
26
+ fmt = ['>B', '>H', '>L'][length_type]
27
+ leading_byte = 0x80 | (tag << 2) | (length_type)
28
+ return struct.pack('>B', leading_byte) + util.prefix_len(fmt, blob)
29
+
30
+
31
+ def subpacket(subpacket_type, fmt, *values):
32
+ """Create GPG subpacket."""
33
+ blob = struct.pack(fmt, *values) if values else fmt
34
+ return struct.pack('>B', subpacket_type) + blob
35
+
36
+
37
+ def subpacket_long(subpacket_type, value):
38
+ """Create GPG subpacket with 32-bit unsigned integer."""
39
+ return subpacket(subpacket_type, '>L', value)
40
+
41
+
42
+ def subpacket_time(value):
43
+ """Create GPG subpacket with time in seconds (since Epoch)."""
44
+ return subpacket_long(2, value)
45
+
46
+
47
+ def subpacket_byte(subpacket_type, value):
48
+ """Create GPG subpacket with 8-bit unsigned integer."""
49
+ return subpacket(subpacket_type, '>B', value)
50
+
51
+
52
+ def subpacket_bytes(subpacket_type, values):
53
+ """Create GPG subpacket with 8-bit unsigned integers."""
54
+ return subpacket(subpacket_type, '>' + 'B'*len(values), *values)
55
+
56
+
57
+ def subpacket_prefix_len(item):
58
+ """Prefix subpacket length according to RFC 4880 section-5.2.3.1."""
59
+ n = len(item)
60
+ if n >= 8384:
61
+ prefix = b'\xFF' + struct.pack('>L', n)
62
+ elif n >= 192:
63
+ n = n - 192
64
+ prefix = struct.pack('BB', (n // 256) + 192, n % 256)
65
+ else:
66
+ prefix = struct.pack('B', n)
67
+ return prefix + item
68
+
69
+
70
+ def subpackets(*items):
71
+ """Serialize several GPG subpackets."""
72
+ prefixed = [subpacket_prefix_len(item) for item in items]
73
+ return util.prefix_len('>H', b''.join(prefixed))
74
+
75
+
76
+ def mpi(value):
77
+ """Serialize multipresicion integer using GPG format."""
78
+ bits = value.bit_length()
79
+ data_size = (bits + 7) // 8
80
+ data_bytes = bytearray(data_size)
81
+ for i in range(data_size):
82
+ data_bytes[i] = value & 0xFF
83
+ value = value >> 8
84
+
85
+ data_bytes.reverse()
86
+ return struct.pack('>H', bits) + bytes(data_bytes)
87
+
88
+
89
+ def _serialize_nist256(vk):
90
+ return mpi((4 << 512) |
91
+ (vk.pubkey.point.x() << 256) |
92
+ (vk.pubkey.point.y()))
93
+
94
+
95
+ def _serialize_ed25519(vk):
96
+ return mpi((0x40 << 256) |
97
+ util.bytes2num(vk.encode(encoder=nacl.encoding.RawEncoder)))
98
+
99
+
100
+ def _compute_keygrip(params):
101
+ parts = []
102
+ for name, value in params:
103
+ exp = '{}:{}{}:'.format(len(name), name, len(value))
104
+ parts.append(b'(' + exp.encode('ascii') + value + b')')
105
+
106
+ return hashlib.sha1(b''.join(parts)).digest()
107
+
108
+
109
+ def keygrip_nist256(vk):
110
+ """Compute keygrip for NIST256 curve public keys."""
111
+ curve = vk.curve.curve
112
+ gen = vk.curve.generator
113
+ g = (4 << 512) | (gen.x() << 256) | gen.y()
114
+ point = vk.pubkey.point
115
+ q = (4 << 512) | (point.x() << 256) | point.y()
116
+
117
+ return _compute_keygrip([
118
+ ['p', util.num2bytes(curve.p(), size=32)],
119
+ ['a', util.num2bytes(curve.a() % curve.p(), size=32)],
120
+ ['b', util.num2bytes(curve.b() % curve.p(), size=32)],
121
+ ['g', util.num2bytes(g, size=65)],
122
+ ['n', util.num2bytes(vk.curve.order, size=32)],
123
+ ['q', util.num2bytes(q, size=65)],
124
+ ])
125
+
126
+
127
+ def keygrip_rsa(n, length):
128
+ """Compute keygrip for rsa public keys."""
129
+ nhex = b'\x00' + util.num2bytes(n, size=int(length/8))
130
+ return hashlib.sha1(nhex).digest()
131
+
132
+
133
+ def keygrip_ed25519(vk):
134
+ """Compute keygrip for Ed25519 public keys."""
135
+ # pylint: disable=line-too-long
136
+ return _compute_keygrip([
137
+ ['p', util.num2bytes(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED, size=32)], # nopep8
138
+ ['a', b'\x01'],
139
+ ['b', util.num2bytes(0x2DFC9311D490018C7338BF8688861767FF8FF5B2BEBE27548A14B235ECA6874A, size=32)], # nopep8
140
+ ['g', util.num2bytes(0x04216936D3CD6E53FEC0A4E231FDD6DC5C692CC7609525A7B2C9562D608F25D51A6666666666666666666666666666666666666666666666666666666666666658, size=65)], # nopep8
141
+ ['n', util.num2bytes(0x1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED, size=32)], # nopep8
142
+ ['q', vk.encode(encoder=nacl.encoding.RawEncoder)],
143
+ ])
144
+
145
+
146
+ def keygrip_curve25519(vk):
147
+ """Compute keygrip for Curve25519 public keys."""
148
+ # pylint: disable=line-too-long
149
+ return _compute_keygrip([
150
+ ['p', util.num2bytes(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED, size=32)], # nopep8
151
+ ['a', b'\x01\xDB\x41'],
152
+ ['b', b'\x01'],
153
+ ['g', util.num2bytes(0x04000000000000000000000000000000000000000000000000000000000000000920ae19a1b8a086b4e01edd2c7748d14c923d4d7e6d7c61b229e9c5a27eced3d9, size=65)], # nopep8
154
+ ['n', util.num2bytes(0x1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED, size=32)], # nopep8
155
+ ['q', vk.encode(encoder=nacl.encoding.RawEncoder)],
156
+ ])
157
+
158
+
159
+ SUPPORTED_CURVES = {
160
+ formats.CURVE_NIST256: {
161
+ # https://tools.ietf.org/html/rfc6637#section-11
162
+ 'oid': b'\x2A\x86\x48\xCE\x3D\x03\x01\x07',
163
+ 'algo_id': 19,
164
+ 'serialize': _serialize_nist256,
165
+ 'keygrip': keygrip_nist256,
166
+ },
167
+ formats.CURVE_ED25519: {
168
+ 'oid': b'\x2B\x06\x01\x04\x01\xDA\x47\x0F\x01',
169
+ 'algo_id': 22,
170
+ 'serialize': _serialize_ed25519,
171
+ 'keygrip': keygrip_ed25519,
172
+ },
173
+ formats.ECDH_CURVE25519: {
174
+ 'oid': b'\x2B\x06\x01\x04\x01\x97\x55\x01\x05\x01',
175
+ 'algo_id': 18,
176
+ 'serialize': _serialize_ed25519,
177
+ 'keygrip': keygrip_curve25519,
178
+ },
179
+ }
180
+
181
+ ECDH_ALGO_ID = 18
182
+
183
+ CUSTOM_KEY_LABEL = b'ONLYKEY-GPG' # marks "our" pubkey
184
+ CUSTOM_SUBPACKET_ID = 26 # use "policy URL" subpacket
185
+ CUSTOM_SUBPACKET = subpacket(CUSTOM_SUBPACKET_ID, CUSTOM_KEY_LABEL)
186
+
187
+
188
+ def get_curve_name_by_oid(oid):
189
+ """Return curve name matching specified OID, or raise KeyError."""
190
+ for curve_name, info in SUPPORTED_CURVES.items():
191
+ if info['oid'] == oid:
192
+ return curve_name
193
+ raise KeyError('Unknown OID: {!r}'.format(oid))
194
+
195
+
196
+ class PublicKey:
197
+ """GPG representation for public key packets."""
198
+
199
+ def __init__(self, curve_name, created, verifying_key, ecdh=False):
200
+ """Contruct using a ECDSA VerifyingKey object."""
201
+ self.curve_name = curve_name
202
+ if curve_name not in ('rsa2048', 'rsa4096'):
203
+ self.curve_info = SUPPORTED_CURVES[curve_name]
204
+ self.ecdh = bool(ecdh)
205
+ if ecdh:
206
+ self.algo_id = ECDH_ALGO_ID
207
+ self.ecdh_packet = b'\x03\x01\x08\x07'
208
+ else:
209
+ self.algo_id = self.curve_info['algo_id']
210
+ self.ecdh_packet = b''
211
+ else:
212
+ self.algo_id = 1 # RSA (Encrypt or Sign) (0x1)
213
+ self.created = int(created) # time since Epoch
214
+ self.verifying_key = verifying_key
215
+
216
+ def keygrip(self):
217
+ """Compute GPG keygrip of the verifying key."""
218
+ return self.curve_info['keygrip'](self.verifying_key)
219
+
220
+ def data(self):
221
+ """Data for packet creation."""
222
+ header = struct.pack('>BLB',
223
+ 4, # version
224
+ self.created, # creation
225
+ self.algo_id) # public key algorithm ID
226
+ if self.algo_id != 1: # ECC
227
+ oid = util.prefix_len('>B', self.curve_info['oid'])
228
+ blob = self.curve_info['serialize'](self.verifying_key)
229
+ return header + oid + blob + self.ecdh_packet
230
+ else: # RSA
231
+ blob = util.bytes2num(self.verifying_key)
232
+ return header + blob
233
+
234
+ def data_to_hash(self):
235
+ """Data for digest computation."""
236
+ return b'\x99' + util.prefix_len('>H', self.data())
237
+
238
+ def _fingerprint(self):
239
+ return hashlib.sha1(self.data_to_hash()).digest()
240
+
241
+ def key_id(self):
242
+ """Short (8 byte) GPG key ID."""
243
+ return self._fingerprint()[-8:]
244
+
245
+ def __repr__(self):
246
+ """Short (8 hexadecimal digits) GPG key ID."""
247
+ hex_key_id = util.hexlify(self.key_id())[-8:]
248
+ return 'GPG public key {}/{}'.format(self.curve_name, hex_key_id)
249
+
250
+ __str__ = __repr__
251
+
252
+
253
+ def _split_lines(body, size):
254
+ lines = []
255
+ for i in range(0, len(body), size):
256
+ lines.append(body[i:i+size] + '\n')
257
+ return ''.join(lines)
258
+
259
+
260
+ def armor(blob, type_str):
261
+ """See https://tools.ietf.org/html/rfc4880#section-6 for details."""
262
+ head = '-----BEGIN PGP {}-----\nVersion: GnuPG v2\n\n'.format(type_str)
263
+ body = base64.b64encode(blob).decode('ascii')
264
+ checksum = base64.b64encode(util.crc24(blob)).decode('ascii')
265
+ tail = '-----END PGP {}-----\n'.format(type_str)
266
+ return head + _split_lines(body, 64) + '=' + checksum + '\n' + tail
267
+
268
+
269
+ def make_signature(signer_func, data_to_sign, public_algo,
270
+ hashed_subpackets, unhashed_subpackets, sig_type=0):
271
+ """Create new GPG signature."""
272
+ # pylint: disable=too-many-arguments
273
+ header = struct.pack('>BBBB',
274
+ 4, # version
275
+ sig_type, # rfc4880 (section-5.2.1)
276
+ public_algo,
277
+ 8) # hash_alg (SHA256)
278
+ hashed = subpackets(*hashed_subpackets)
279
+ unhashed = subpackets(*unhashed_subpackets)
280
+ tail = b'\x04\xff' + struct.pack('>L', len(header) + len(hashed))
281
+ data_to_hash = data_to_sign + header + hashed + tail
282
+
283
+ log.debug('hashing %d bytes', len(data_to_hash))
284
+ digest = hashlib.sha256(data_to_hash).digest()
285
+ log.debug('signing digest: %s', util.hexlify(digest))
286
+ params = signer_func(digest=digest)
287
+ sig = b''.join(mpi(p) for p in params)
288
+
289
+ return bytes(header + hashed + unhashed +
290
+ digest[:2] + # used for decoder's sanity check
291
+ sig) # actual ECDSA signature