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/formats.py ADDED
@@ -0,0 +1,274 @@
1
+ """SSH format parsing and formatting tools."""
2
+ import base64
3
+ import hashlib
4
+ import io
5
+ import logging
6
+
7
+ import ecdsa
8
+ import nacl.signing
9
+ from Crypto.Hash import SHA256, SHA512
10
+ from Crypto.PublicKey import RSA
11
+ from Crypto.Signature import pkcs1_15
12
+
13
+ from . import util
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+ # Supported algorithms for SSH and GPG (ECC Curves and RSA)
18
+ CURVE_NIST256 = 'nist256p1'
19
+ CURVE_ED25519 = 'ed25519'
20
+ RSA2048 = 'rsa2048'
21
+ RSA4096 = 'rsa4096'
22
+ SUPPORTED_CURVES = {CURVE_NIST256, CURVE_ED25519, RSA2048, RSA4096}
23
+
24
+ # Supported ECDH curves (for GPG)
25
+ ECDH_NIST256 = 'nist256p1'
26
+ ECDH_CURVE25519 = 'curve25519'
27
+
28
+ # SSH key types
29
+ SSH_NIST256_DER_OCTET = b'\x04'
30
+ SSH_NIST256_KEY_PREFIX = b'ecdsa-sha2-'
31
+ SSH_NIST256_CURVE_NAME = b'nistp256'
32
+ SSH_NIST256_KEY_TYPE = SSH_NIST256_KEY_PREFIX + SSH_NIST256_CURVE_NAME
33
+ SSH_NIST256_CERT_POSTFIX = b'-cert-v01@openssh.com'
34
+ SSH_NIST256_CERT_TYPE = SSH_NIST256_KEY_TYPE + SSH_NIST256_CERT_POSTFIX
35
+ SSH_ED25519_KEY_TYPE = b'ssh-ed25519'
36
+ SSH_RSA_KEY_TYPE = b'ssh-rsa'
37
+ SUPPORTED_KEY_TYPES = {SSH_NIST256_KEY_TYPE,
38
+ SSH_NIST256_CERT_TYPE, SSH_ED25519_KEY_TYPE, SSH_RSA_KEY_TYPE}
39
+
40
+ hashfunc = hashlib.sha256
41
+
42
+
43
+ def fingerprint(blob):
44
+ """
45
+ Compute SSH fingerprint for specified blob.
46
+
47
+ See https://en.wikipedia.org/wiki/Public_key_fingerprint for details.
48
+ """
49
+ digest = hashlib.md5(blob).digest()
50
+ return ':'.join('{:02x}'.format(c) for c in bytearray(digest))
51
+
52
+
53
+ def parse_pubkey(blob):
54
+ """
55
+ Parse SSH public key from given blob.
56
+
57
+ Construct a verifier for ECDSA signatures.
58
+ The verifier returns the signatures in the required SSH format.
59
+ Currently, NIST256P1 and ED25519 elliptic curves are supported.
60
+ """
61
+ # pylint: disable=too-many-locals
62
+ fp = fingerprint(blob)
63
+ s = io.BytesIO(blob)
64
+ key_type = util.read_frame(s)
65
+ log.debug('key type: %s', key_type)
66
+ assert key_type in SUPPORTED_KEY_TYPES, key_type
67
+
68
+ result = {'blob': blob, 'type': key_type, 'fingerprint': fp}
69
+
70
+ if key_type in (SSH_NIST256_KEY_TYPE, SSH_NIST256_CERT_TYPE):
71
+ if key_type == SSH_NIST256_CERT_TYPE:
72
+ _nonce = util.read_frame(s)
73
+
74
+ curve_name = util.read_frame(s)
75
+ log.debug('curve name: %s', curve_name)
76
+ point = util.read_frame(s)
77
+
78
+ if key_type == SSH_NIST256_CERT_TYPE:
79
+ _serial_number = util.recv(s, '>Q')
80
+ _type = util.recv(s, '>L')
81
+ _key_id = util.read_frame(s)
82
+ _valid_principals = util.read_frame(s)
83
+ _valid_after = util.recv(s, '>Q')
84
+ _valid_before = util.recv(s, '>Q')
85
+ _critical_options = util.read_frame(s)
86
+ _extensions = util.read_frame(s)
87
+ _reserved = util.read_frame(s)
88
+ _signature_key = util.read_frame(s)
89
+ _signature = util.read_frame(s)
90
+
91
+ assert s.read() == b''
92
+ _type, point = point[:1], point[1:]
93
+ assert _type == SSH_NIST256_DER_OCTET
94
+ size = len(point) // 2
95
+ assert len(point) == 2 * size
96
+ coords = (util.bytes2num(point[:size]), util.bytes2num(point[size:]))
97
+
98
+ curve = ecdsa.NIST256p
99
+ point = ecdsa.ellipticcurve.Point(curve.curve, *coords)
100
+
101
+ def ecdsa_verifier(sig, msg):
102
+ assert len(sig) == 2 * size
103
+ sig_decode = ecdsa.util.sigdecode_string
104
+ vk = ecdsa.VerifyingKey.from_public_point(point, curve, hashfunc)
105
+ vk.verify(signature=sig, data=msg, sigdecode=sig_decode)
106
+ parts = [sig[:size], sig[size:]]
107
+ return b''.join([util.frame(b'\x00' + p) for p in parts])
108
+
109
+ result.update(point=coords, curve=CURVE_NIST256,
110
+ verifier=ecdsa_verifier)
111
+
112
+ if key_type == SSH_ED25519_KEY_TYPE:
113
+ pubkey = util.read_frame(s)
114
+ assert s.read() == b''
115
+
116
+ def ed25519_verify(sig, msg):
117
+ assert len(sig) == 64
118
+ vk = nacl.signing.VerifyKey(bytes(pubkey),
119
+ encoder=nacl.encoding.RawEncoder)
120
+ vk.verify(msg, sig)
121
+ log.debug('verify signature')
122
+ return sig
123
+
124
+ result.update(curve=CURVE_ED25519, verifier=ed25519_verify)
125
+
126
+ if key_type == SSH_RSA_KEY_TYPE:
127
+ pubkey = blob
128
+ log.debug('RSA pubkey: %s', pubkey)
129
+
130
+ def rsa_verify(sig, msg):
131
+ pub = bytes(b'ssh-rsa ' + base64.b64encode(blob))
132
+ log.debug('RSA pubkey: %s', pub)
133
+ vk = RSA.importKey(pub)
134
+ log.debug('message: %s', msg)
135
+ if b'rsa-sha2-512' in msg:
136
+ h = SHA512.new(msg)
137
+ log.debug('rsa-sha2-512')
138
+ elif b'rsa-sha2-256' in msg:
139
+ h = SHA256.new(msg)
140
+ log.debug('rsa-sha2-256')
141
+ log.debug('hash: %s', h.hexdigest())
142
+ try:
143
+ pkcs1_15.new(vk).verify(h, sig)
144
+ log.debug('The RSA signature is valid.')
145
+ except (ValueError, TypeError):
146
+ log.debug('The RSA signature is not valid.')
147
+ return sig
148
+
149
+ result.update(verifier=rsa_verify)
150
+
151
+ return result
152
+
153
+
154
+ def _decompress_ed25519(pubkey):
155
+ """Load public key from the serialized blob (stripping the prefix byte)."""
156
+ if pubkey[:1] in {b'\x00', b'\x01'}:
157
+ # set by Trezor fsm_msgSignIdentity() and fsm_msgGetPublicKey()
158
+ return nacl.signing.VerifyKey(pubkey[1:], encoder=nacl.encoding.RawEncoder)
159
+ else:
160
+ return None
161
+
162
+
163
+ def _decompress_nist256(pubkey):
164
+ """
165
+ Load public key from the serialized blob.
166
+
167
+ The leading byte least-significant bit is used to decide how to recreate
168
+ the y-coordinate from the specified x-coordinate. See bitcoin/main.py#L198
169
+ (from https://github.com/vbuterin/pybitcointools/) for details.
170
+ """
171
+ if pubkey[:1] in {b'\x02', b'\x03'}: # set by ecdsa_get_public_key33()
172
+ curve = ecdsa.NIST256p
173
+ P = curve.curve.p()
174
+ A = curve.curve.a()
175
+ B = curve.curve.b()
176
+ x = util.bytes2num(pubkey[1:33])
177
+ beta = pow(int(x * x * x + A * x + B), int((P + 1) // 4), int(P))
178
+
179
+ p0 = util.bytes2num(pubkey[:1])
180
+ y = (P - beta) if ((beta + p0) % 2) else beta
181
+
182
+ point = ecdsa.ellipticcurve.Point(curve.curve, x, y)
183
+ return ecdsa.VerifyingKey.from_public_point(point, curve=curve,
184
+ hashfunc=hashfunc)
185
+ else:
186
+ return None
187
+
188
+
189
+ def decompress_pubkey(pubkey, curve_name):
190
+ """
191
+ Load public key from the serialized blob.
192
+
193
+ Raise ValueError on parsing error.
194
+ """
195
+ vk = None
196
+ if len(pubkey) == 33:
197
+ decompress = {
198
+ CURVE_NIST256: _decompress_nist256,
199
+ CURVE_ED25519: _decompress_ed25519,
200
+ ECDH_CURVE25519: _decompress_ed25519,
201
+ }[curve_name]
202
+ vk = decompress(pubkey)
203
+
204
+ if not vk:
205
+ msg = 'invalid {!s} public key: {!r}'.format(curve_name, pubkey)
206
+ raise ValueError(msg)
207
+
208
+ return vk
209
+
210
+
211
+ def serialize_verifying_key(vk):
212
+ """
213
+ Serialize a public key into SSH format (for exporting to text format).
214
+
215
+ Currently, NIST256P1 and ED25519 elliptic curves are supported.
216
+ Raise TypeError on unsupported key format.
217
+ """
218
+ if isinstance(vk, nacl.signing.VerifyKey):
219
+ pubkey = vk.encode(encoder=nacl.encoding.RawEncoder)
220
+ key_type = SSH_ED25519_KEY_TYPE
221
+ blob = util.frame(SSH_ED25519_KEY_TYPE) + util.frame(pubkey)
222
+ return key_type, blob
223
+
224
+ if isinstance(vk, ecdsa.keys.VerifyingKey):
225
+ curve_name = SSH_NIST256_CURVE_NAME
226
+ key_blob = SSH_NIST256_DER_OCTET + vk.to_string()
227
+ parts = [SSH_NIST256_KEY_TYPE, curve_name, key_blob]
228
+ key_type = SSH_NIST256_KEY_TYPE
229
+ blob = b''.join([util.frame(p) for p in parts])
230
+ return key_type, blob
231
+
232
+ if (len(vk) == 279 or len(vk) == 535):
233
+ # RSA 2048 or RSA 4096
234
+ pubkey = vk
235
+ key_type = SSH_RSA_KEY_TYPE
236
+ return key_type, pubkey
237
+
238
+ raise TypeError('unsupported {!r}'.format(vk))
239
+
240
+
241
+ def export_public_key(vk, label):
242
+ """
243
+ Export public key to text format.
244
+
245
+ The resulting string can be written into a .pub file or
246
+ appended to the ~/.ssh/authorized_keys file.
247
+ """
248
+ key_type, blob = serialize_verifying_key(vk)
249
+ log.debug('fingerprint: %s', fingerprint(blob))
250
+ b64 = base64.b64encode(blob).decode('ascii')
251
+ return '{} {} {}\n'.format(key_type.decode('ascii'), b64, label)
252
+
253
+
254
+ def import_public_key(line):
255
+ """Parse public key textual format, as saved at a .pub file."""
256
+ log.debug('loading SSH public key: %r', line)
257
+ file_type, base64blob, name = line.split()
258
+ blob = base64.b64decode(base64blob)
259
+ result = parse_pubkey(blob)
260
+ result['name'] = name.encode('utf-8')
261
+ assert result['type'] == file_type.encode('ascii')
262
+ log.debug('loaded %s public key: %s', file_type, result['fingerprint'])
263
+ return result
264
+
265
+
266
+ def get_ecdh_curve_name(signature_curve_name):
267
+ """Return appropriate curve for ECDH for specified signing curve."""
268
+ return {
269
+ CURVE_NIST256: ECDH_NIST256,
270
+ CURVE_ED25519: ECDH_CURVE25519,
271
+ ECDH_CURVE25519: ECDH_CURVE25519,
272
+ RSA2048: RSA2048,
273
+ RSA4096: RSA4096,
274
+ }[signature_curve_name]