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.
- lib_agent-1.0.9.dist-info/METADATA +44 -0
- lib_agent-1.0.9.dist-info/RECORD +35 -0
- lib_agent-1.0.9.dist-info/WHEEL +5 -0
- lib_agent-1.0.9.dist-info/licenses/LICENSE +166 -0
- lib_agent-1.0.9.dist-info/top_level.txt +1 -0
- libagent/__init__.py +1 -0
- libagent/age/__init__.py +180 -0
- libagent/age/client.py +48 -0
- libagent/device/__init__.py +3 -0
- libagent/device/fake_device.py +74 -0
- libagent/device/interface.py +155 -0
- libagent/device/jade.py +143 -0
- libagent/device/keepkey.py +45 -0
- libagent/device/keepkey_defs.py +24 -0
- libagent/device/ledger.py +178 -0
- libagent/device/onlykey.py +613 -0
- libagent/device/onlykey_defs.py +10 -0
- libagent/device/onlykey_pqc.py +153 -0
- libagent/device/trezor.py +154 -0
- libagent/device/trezor_defs.py +30 -0
- libagent/device/ui.py +159 -0
- libagent/formats.py +274 -0
- libagent/gpg/__init__.py +439 -0
- libagent/gpg/agent.py +385 -0
- libagent/gpg/client.py +55 -0
- libagent/gpg/decode.py +346 -0
- libagent/gpg/encode.py +103 -0
- libagent/gpg/keyring.py +270 -0
- libagent/gpg/protocol.py +291 -0
- libagent/server.py +400 -0
- libagent/signify/__init__.py +127 -0
- libagent/ssh/__init__.py +379 -0
- libagent/ssh/client.py +92 -0
- libagent/ssh/protocol.py +179 -0
- libagent/util.py +292 -0
|
@@ -0,0 +1,613 @@
|
|
|
1
|
+
# pylint: disable=too-many-locals,too-many-statements,too-many-branches
|
|
2
|
+
# pylint: disable=attribute-defined-outside-init
|
|
3
|
+
"""OnlyKey-related code (see https://www.onlykey.io/)."""
|
|
4
|
+
|
|
5
|
+
import codecs
|
|
6
|
+
import hashlib
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
from os import path
|
|
13
|
+
|
|
14
|
+
import ecdsa
|
|
15
|
+
import nacl.signing
|
|
16
|
+
import unidecode
|
|
17
|
+
|
|
18
|
+
from . import interface
|
|
19
|
+
|
|
20
|
+
# import pgpy
|
|
21
|
+
# from pgpy import PGPKey
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
log = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class OnlyKey(interface.Device):
|
|
28
|
+
"""Connection to OnlyKey device."""
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
def package_name(cls):
|
|
32
|
+
"""Python package name (at PyPI)."""
|
|
33
|
+
return 'onlykey-agent'
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def _defs(self):
|
|
37
|
+
from . import onlykey_defs
|
|
38
|
+
return onlykey_defs
|
|
39
|
+
|
|
40
|
+
def connect(self):
|
|
41
|
+
"""Enumerate and connect to the first USB HID interface.
|
|
42
|
+
|
|
43
|
+
The HID handle is opened exactly once and always closed again on any
|
|
44
|
+
failure. The previous version constructed a fresh OnlyKey() - each of
|
|
45
|
+
which opens a USB HID handle - on every iteration of a retry loop and
|
|
46
|
+
never closed the earlier ones when the version string came back short,
|
|
47
|
+
so a client that hit that path (a running onlykey-gpg-agent in
|
|
48
|
+
particular) leaked open handles that the OS kept claimed, blocking
|
|
49
|
+
every other process - onlykey-cli, the OnlyKey App - from enumerating
|
|
50
|
+
the key until the agent was killed.
|
|
51
|
+
"""
|
|
52
|
+
self.device_name = 'OnlyKey'
|
|
53
|
+
self.ok = None
|
|
54
|
+
t_end = time.time() + 2.5
|
|
55
|
+
while time.time() < t_end:
|
|
56
|
+
try:
|
|
57
|
+
self.ok = self._defs.OnlyKey()
|
|
58
|
+
self.ok.set_time(time.time())
|
|
59
|
+
self.okversion = self.ok.read_string(timeout_ms=100)
|
|
60
|
+
if len(self.okversion) > 8:
|
|
61
|
+
self.okversion = self.okversion[8:]
|
|
62
|
+
if self.okversion and self.okversion[0] == 'v':
|
|
63
|
+
self._probe_capabilities()
|
|
64
|
+
return
|
|
65
|
+
# Not the reply we wanted (device still booting / another
|
|
66
|
+
# client mid-exchange): drop this handle before retrying so we
|
|
67
|
+
# never hold more than one open at a time.
|
|
68
|
+
self._safe_close()
|
|
69
|
+
time.sleep(0.1)
|
|
70
|
+
except Exception as exc:
|
|
71
|
+
self._safe_close()
|
|
72
|
+
raise interface.NotFoundError(
|
|
73
|
+
'{} not connected: "{}"'.format(self.device_name, exc)) from exc
|
|
74
|
+
# Timed out without a good version - do not leave a handle open for the
|
|
75
|
+
# caller to inherit; it thinks connect() succeeded otherwise.
|
|
76
|
+
self._safe_close()
|
|
77
|
+
raise interface.NotFoundError(
|
|
78
|
+
'{} not connected: no version response'.format(self.device_name))
|
|
79
|
+
|
|
80
|
+
def _probe_capabilities(self):
|
|
81
|
+
"""Ask the firmware what it supports; None on firmware without the report."""
|
|
82
|
+
self.caps = None
|
|
83
|
+
try:
|
|
84
|
+
self.caps = self.ok.getcapabilities()
|
|
85
|
+
except Exception as exc: # best effort - old firmware, busy device
|
|
86
|
+
log.debug('capabilities probe failed: %s', exc)
|
|
87
|
+
if self.caps:
|
|
88
|
+
log.info('firmware %s flags=%s', self.caps.get('version'),
|
|
89
|
+
[f.name for f in self.caps.get('flags', [])])
|
|
90
|
+
|
|
91
|
+
def _require_derived_v2(self, slot):
|
|
92
|
+
if self._derived_version(slot) != 2:
|
|
93
|
+
return
|
|
94
|
+
if self.caps:
|
|
95
|
+
supported = self._defs.CapabilityFlag.HKDF_V2_DERIVATION in self.caps.get('flags', [])
|
|
96
|
+
else:
|
|
97
|
+
m = re.match(r'v(\d+)\.(\d+)\.(\d+)', getattr(self, 'okversion', '') or '')
|
|
98
|
+
supported = not m or tuple(int(x) for x in m.groups()) >= (3, 0, 5)
|
|
99
|
+
if not supported:
|
|
100
|
+
raise interface.DeviceError(
|
|
101
|
+
'derived-v2 needs OnlyKey firmware v3.1.0 or later (this OnlyKey has {})'.format(
|
|
102
|
+
getattr(self, 'okversion', None) or 'older firmware'))
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
def prepare(cls):
|
|
106
|
+
if sys.platform == 'darwin':
|
|
107
|
+
# hidapi's IOHIDManager belongs to the thread that creates it; created on
|
|
108
|
+
# an agent worker thread, hid_exit() segfaults when Python exits.
|
|
109
|
+
import hid
|
|
110
|
+
hid.enumerate(0x1d50, 0x60fc)
|
|
111
|
+
|
|
112
|
+
def _is_duo(self):
|
|
113
|
+
return bool(self.caps) and self._defs.CapabilityFlag.DUO in self.caps.get('flags', [])
|
|
114
|
+
|
|
115
|
+
def _challenge(self, raw_message, identity):
|
|
116
|
+
"""Print the 3-digit code the device wants in challenge-code mode."""
|
|
117
|
+
b1, b2, b3 = self._defs.challenge_code(raw_message, duo=self._is_duo())
|
|
118
|
+
print('Confirm on OnlyKey to authorize ' + identity.to_string() +
|
|
119
|
+
': press any button, or enter {} {} {} if derivedkeymode/storedkeymode is 0'
|
|
120
|
+
.format(b1, b2, b3), file=sys.stderr, flush=True)
|
|
121
|
+
|
|
122
|
+
def _raise_if_error(self, result):
|
|
123
|
+
"""Raise DeviceError when a raw report is an Error/ERROR string from the device."""
|
|
124
|
+
kind, text = self._defs.classify_response(result)[:2]
|
|
125
|
+
if kind == 'error':
|
|
126
|
+
raise interface.DeviceError(text)
|
|
127
|
+
|
|
128
|
+
def _safe_close(self):
|
|
129
|
+
"""Close and drop self.ok if it is open, swallowing any error."""
|
|
130
|
+
if getattr(self, 'ok', None) is not None:
|
|
131
|
+
try:
|
|
132
|
+
self.ok.close()
|
|
133
|
+
except Exception: # pylint: disable=broad-except
|
|
134
|
+
pass
|
|
135
|
+
self.ok = None
|
|
136
|
+
|
|
137
|
+
def set_skey(self, skey):
|
|
138
|
+
"""Set signing key to use."""
|
|
139
|
+
if isinstance(skey, str):
|
|
140
|
+
skey = convert_keyslot(self, skey)
|
|
141
|
+
self.skeyslot = skey
|
|
142
|
+
log.debug('Setting skey slot = %s', skey)
|
|
143
|
+
|
|
144
|
+
def set_dkey(self, dkey):
|
|
145
|
+
"""Set decryption key to use."""
|
|
146
|
+
if isinstance(dkey, str):
|
|
147
|
+
dkey = convert_keyslot(self, dkey)
|
|
148
|
+
self.dkeyslot = dkey
|
|
149
|
+
log.debug('Setting dkey slot = %s', dkey)
|
|
150
|
+
|
|
151
|
+
def import_pub(self, pubkey):
|
|
152
|
+
"""Import PGP public key."""
|
|
153
|
+
self.import_pubkey = pubkey
|
|
154
|
+
log.debug('Public key to import = %s', pubkey)
|
|
155
|
+
# self.import_pubkey_obj, _ = pgpy.PGPKey.from_blob(pubkey)
|
|
156
|
+
# self.import_pubkey_bytes = bytes(self.import_pubkey_obj)
|
|
157
|
+
|
|
158
|
+
def get_key_by_keygrip(self, keygrip):
|
|
159
|
+
"""Return key-slot info for the given keygrip."""
|
|
160
|
+
if keygrip is None:
|
|
161
|
+
return None
|
|
162
|
+
keygriplong = keygrip
|
|
163
|
+
keygrip = keygrip[:16]
|
|
164
|
+
log.info(keygrip)
|
|
165
|
+
keygrips = {}
|
|
166
|
+
keylabels = self.ok.getkeylabels()
|
|
167
|
+
for i in keylabels:
|
|
168
|
+
if i.number + 72 >= 100:
|
|
169
|
+
keygrips[i.label.replace("ÿ", " ").encode('ascii')] = i.number + 72
|
|
170
|
+
else:
|
|
171
|
+
keygrips[i.label.replace("ÿ", " ").encode('ascii')] = i.number - 24
|
|
172
|
+
if keygrip in keygrips:
|
|
173
|
+
return keygrips[keygrip]
|
|
174
|
+
for i in keylabels:
|
|
175
|
+
if re.search(r'[A-F0-9]{16}', i.label):
|
|
176
|
+
raise KeyError('keygrip %s not found' % keygriplong)
|
|
177
|
+
return None
|
|
178
|
+
|
|
179
|
+
DEFAULT_SLOT = 132 # derived v1 (released SHA256 KDF), a.k.a. ECC32
|
|
180
|
+
DERIVED_V2_SLOT = 232 # derived v2 (HKDF): --skey/--dkey derived-v2 or ECC32v2
|
|
181
|
+
|
|
182
|
+
@classmethod
|
|
183
|
+
def _derived_version(cls, slot):
|
|
184
|
+
"""1 for the released derived key (132), 2 for the HKDF one (232), else 0."""
|
|
185
|
+
if slot == cls.DEFAULT_SLOT:
|
|
186
|
+
return 1
|
|
187
|
+
if slot == cls.DERIVED_V2_SLOT:
|
|
188
|
+
return 2
|
|
189
|
+
return 0
|
|
190
|
+
|
|
191
|
+
def _derived_code(self, slot, curve_name, op):
|
|
192
|
+
"""Sign/decrypt code for a derived identity from the shared protocol table."""
|
|
193
|
+
ver = 'v%d' % self._derived_version(slot)
|
|
194
|
+
table = self._defs.AGENT_DERIVATION[ver][op]
|
|
195
|
+
kt = self._defs.KeyType
|
|
196
|
+
curve = {'ed25519': kt.ED25519, 'nist256p1': kt.P256R1,
|
|
197
|
+
'curve25519': kt.CURVE25519}.get(curve_name, kt.P256K1)
|
|
198
|
+
return table[curve]
|
|
199
|
+
|
|
200
|
+
_SKEY_SLOT_RE = re.compile(r'--skey-slot=(\S+)')
|
|
201
|
+
_DKEY_SLOT_RE = re.compile(r'--dkey-slot=(\S+)')
|
|
202
|
+
|
|
203
|
+
@staticmethod
|
|
204
|
+
def _parse_slot_value(value):
|
|
205
|
+
"""Convert a --(s|d)key-slot=VALUE token (e.g. 'ECC1', 'RSA2', '132').
|
|
206
|
+
|
|
207
|
+
Returns an int slot number, or None if VALUE can't be parsed.
|
|
208
|
+
"""
|
|
209
|
+
if not value:
|
|
210
|
+
return None
|
|
211
|
+
try:
|
|
212
|
+
if value.lower() in ('derived-v2', 'ecc32v2'):
|
|
213
|
+
return 232
|
|
214
|
+
if value.startswith('ECC'):
|
|
215
|
+
return int(value[3:]) + 100
|
|
216
|
+
if value.startswith('RSA'):
|
|
217
|
+
return int(value[3:])
|
|
218
|
+
return int(value)
|
|
219
|
+
except ValueError:
|
|
220
|
+
log.warning('Unrecognized key-slot value %r in run-agent.sh/.cmd', value)
|
|
221
|
+
return None
|
|
222
|
+
|
|
223
|
+
def get_sk_dk(self):
|
|
224
|
+
"""Get signing key and decryption key slots from config."""
|
|
225
|
+
homedir = os.environ.get('AGENTHOMEDIR') or os.environ.get('GNUPGHOME')
|
|
226
|
+
if not homedir:
|
|
227
|
+
log.debug(
|
|
228
|
+
'Neither AGENTHOMEDIR nor GNUPGHOME set; using default slot %d',
|
|
229
|
+
self.DEFAULT_SLOT)
|
|
230
|
+
self.set_skey(self.DEFAULT_SLOT)
|
|
231
|
+
self.set_dkey(self.DEFAULT_SLOT)
|
|
232
|
+
return
|
|
233
|
+
|
|
234
|
+
# The slots are read back from the launcher `onlykey-gpg init` wrote,
|
|
235
|
+
# and on Windows that is run-agent.cmd (gpg cannot start a shell
|
|
236
|
+
# script there). Missing it would silently fall back to the default.
|
|
237
|
+
name = 'run-agent.cmd' if sys.platform == 'win32' else 'run-agent.sh'
|
|
238
|
+
fpath = os.path.join(homedir, name)
|
|
239
|
+
log.debug('Path to %s = %s', name, fpath)
|
|
240
|
+
if not path.exists(fpath):
|
|
241
|
+
self.set_skey(self.DEFAULT_SLOT)
|
|
242
|
+
self.set_dkey(self.DEFAULT_SLOT)
|
|
243
|
+
return
|
|
244
|
+
|
|
245
|
+
with open(fpath) as f:
|
|
246
|
+
content = f.read()
|
|
247
|
+
|
|
248
|
+
skey_match = self._SKEY_SLOT_RE.search(content)
|
|
249
|
+
dkey_match = self._DKEY_SLOT_RE.search(content)
|
|
250
|
+
|
|
251
|
+
skey = self._parse_slot_value(skey_match.group(1)) if skey_match else None
|
|
252
|
+
dkey = self._parse_slot_value(dkey_match.group(1)) if dkey_match else None
|
|
253
|
+
|
|
254
|
+
self.set_skey(skey if skey is not None else self.DEFAULT_SLOT)
|
|
255
|
+
self.set_dkey(dkey if dkey is not None else self.DEFAULT_SLOT)
|
|
256
|
+
|
|
257
|
+
def sig_hash(self, sighash):
|
|
258
|
+
"""Set signature hashing algorithm to use."""
|
|
259
|
+
if sighash in (b'rsa-sha2-512', b'rsa-sha2-256'):
|
|
260
|
+
self.sighash = sighash
|
|
261
|
+
log.info('Setting RSA signature Hash Type =%s', sighash)
|
|
262
|
+
|
|
263
|
+
def close(self):
|
|
264
|
+
"""Close connection."""
|
|
265
|
+
log.info('disconnected from %s', self.device_name)
|
|
266
|
+
self._safe_close()
|
|
267
|
+
|
|
268
|
+
def pubkey(self, identity, ecdh=False):
|
|
269
|
+
"""Return public key."""
|
|
270
|
+
curve_name = identity.get_curve_name(ecdh=ecdh)
|
|
271
|
+
keygrip_slot_id = None
|
|
272
|
+
if identity.identity_dict['proto'] != 'ssh' and hasattr(self, 'skeyslot') is False:
|
|
273
|
+
self.get_sk_dk()
|
|
274
|
+
if identity.identity_dict['proto'] != 'ssh':
|
|
275
|
+
log.info('Looking for keygrip =%s', identity.identity_dict['keygrip'])
|
|
276
|
+
keygrip = identity.identity_dict['keygrip']
|
|
277
|
+
keygrip_slot_id = self.get_key_by_keygrip(keygrip)
|
|
278
|
+
|
|
279
|
+
if keygrip_slot_id is not None:
|
|
280
|
+
this_slot_id = keygrip_slot_id
|
|
281
|
+
elif identity.identity_dict['proto'] != 'ssh' and self.dkeyslot < 132 and ecdh is True:
|
|
282
|
+
this_slot_id = self.dkeyslot
|
|
283
|
+
log.info('Key Slot =%s', this_slot_id)
|
|
284
|
+
elif self.skeyslot < 132 and ecdh is False:
|
|
285
|
+
this_slot_id = self.skeyslot
|
|
286
|
+
log.info('Key Slot =%s', this_slot_id)
|
|
287
|
+
else:
|
|
288
|
+
# derived identity: 132 = v1 (SHA256 KDF), 232 = v2 (HKDF); same request shape
|
|
289
|
+
this_slot_id = self.dkeyslot if ecdh else self.skeyslot
|
|
290
|
+
if not self._derived_version(this_slot_id):
|
|
291
|
+
this_slot_id = self.DEFAULT_SLOT
|
|
292
|
+
self._require_derived_v2(this_slot_id)
|
|
293
|
+
|
|
294
|
+
log.info('Requesting public key from key slot =%s', this_slot_id)
|
|
295
|
+
|
|
296
|
+
log.debug('"%s" getting public key (%s) from %s',
|
|
297
|
+
identity.to_string(), curve_name, self)
|
|
298
|
+
|
|
299
|
+
# Calculate hash for key derivation input data
|
|
300
|
+
if identity.identity_dict['proto'] == 'ssh':
|
|
301
|
+
if identity.identity_dict.get('user'):
|
|
302
|
+
id_parts = unidecode.unidecode(identity.identity_dict['user'] + '@' +
|
|
303
|
+
identity.identity_dict['host']).encode('ascii')
|
|
304
|
+
else:
|
|
305
|
+
id_parts = unidecode.unidecode(identity.identity_dict['host']).encode('ascii')
|
|
306
|
+
else:
|
|
307
|
+
id_parts = identity.to_bytes()
|
|
308
|
+
log.info('Identity to hash =%s', id_parts)
|
|
309
|
+
h1 = hashlib.sha256()
|
|
310
|
+
h1.update(id_parts)
|
|
311
|
+
data = h1.hexdigest()
|
|
312
|
+
log.info('Identity hash =%s', data)
|
|
313
|
+
|
|
314
|
+
if this_slot_id > 100:
|
|
315
|
+
if curve_name == 'curve25519':
|
|
316
|
+
data = '04' + data
|
|
317
|
+
elif curve_name == 'secp256k1':
|
|
318
|
+
# Not currently supported by agent, for future use
|
|
319
|
+
data = '03' + data
|
|
320
|
+
elif curve_name == 'nist256p1':
|
|
321
|
+
data = '02' + data
|
|
322
|
+
elif curve_name == 'ed25519':
|
|
323
|
+
data = '01' + data
|
|
324
|
+
else:
|
|
325
|
+
data = '00' + data
|
|
326
|
+
|
|
327
|
+
self.ok.send_message(msg=self._defs.Message.OKGETPUBKEY, slot_id=this_slot_id, payload=data)
|
|
328
|
+
log.info('curve name= %s', repr(curve_name))
|
|
329
|
+
t_end = time.time() + 1.5
|
|
330
|
+
if 'rsa' not in curve_name:
|
|
331
|
+
while time.time() < t_end:
|
|
332
|
+
try:
|
|
333
|
+
ok_pubkey = self.ok.read_bytes(timeout_ms=100)
|
|
334
|
+
if len(ok_pubkey) == 64 and len(set(ok_pubkey[0:63])) != 1:
|
|
335
|
+
break
|
|
336
|
+
except Exception as e:
|
|
337
|
+
raise interface.DeviceError(e)
|
|
338
|
+
|
|
339
|
+
log.info('received= %s', repr(ok_pubkey))
|
|
340
|
+
self._raise_if_error(ok_pubkey)
|
|
341
|
+
if len(set(ok_pubkey[34:63])) == 1:
|
|
342
|
+
if curve_name in ('nist256p1', 'secp256k1'):
|
|
343
|
+
raise interface.DeviceError("Public key curve does not match requested type")
|
|
344
|
+
ok_pubkey = bytearray(ok_pubkey[0:32])
|
|
345
|
+
log.info('Received Public Key generated by OnlyKey= %s', repr(ok_pubkey.hex()))
|
|
346
|
+
vk = nacl.signing.VerifyKey(bytes(ok_pubkey),
|
|
347
|
+
encoder=nacl.encoding.RawEncoder)
|
|
348
|
+
log.info('vk= %s', repr(vk))
|
|
349
|
+
# time.sleep(3)
|
|
350
|
+
return vk
|
|
351
|
+
elif len(ok_pubkey) == 64:
|
|
352
|
+
ok_pubkey = bytearray(ok_pubkey[0:64])
|
|
353
|
+
if curve_name in ('ed25519', 'curve25519'):
|
|
354
|
+
raise interface.DeviceError("Public key curve does not match requested type")
|
|
355
|
+
log.info('Received Public Key generated by OnlyKey= %s', repr(ok_pubkey))
|
|
356
|
+
if identity.curve_name == 'nist256p1':
|
|
357
|
+
vk = ecdsa.VerifyingKey.from_string(ok_pubkey, curve=ecdsa.NIST256p)
|
|
358
|
+
else:
|
|
359
|
+
vk = ecdsa.VerifyingKey.from_string(ok_pubkey, curve=ecdsa.SECP256k1)
|
|
360
|
+
return vk
|
|
361
|
+
else:
|
|
362
|
+
ok_pubkey = []
|
|
363
|
+
if curve_name == 'rsa2048':
|
|
364
|
+
publen = 256
|
|
365
|
+
elif 'rsa' in curve_name:
|
|
366
|
+
publen = 512
|
|
367
|
+
while time.time() < t_end:
|
|
368
|
+
try:
|
|
369
|
+
ok_pub_part = self.ok.read_bytes(timeout_ms=100)
|
|
370
|
+
if len(ok_pub_part) == 64 and len(set(ok_pub_part[0:63])) != 1:
|
|
371
|
+
log.info('received part= %s', repr(ok_pub_part))
|
|
372
|
+
ok_pubkey += ok_pub_part
|
|
373
|
+
if len(ok_pubkey) == publen:
|
|
374
|
+
break
|
|
375
|
+
# Todo know RSA type to know how many packets
|
|
376
|
+
except Exception as e:
|
|
377
|
+
raise interface.DeviceError(e)
|
|
378
|
+
|
|
379
|
+
log.info('Received Public Key generated by OnlyKey= %s', repr(ok_pubkey))
|
|
380
|
+
log.info(len(ok_pubkey))
|
|
381
|
+
if len(ok_pubkey) == 256:
|
|
382
|
+
if identity.identity_dict['proto'] == 'ssh':
|
|
383
|
+
# https://security.stackexchange.com/questions/42268/how-do-i-get-the-rsa-bit-length-with-the-pubkey-and-openssl
|
|
384
|
+
ok_pubkey = b'\x00\x00\x00\x07' + b'\x73\x73\x68\x2d\x72\x73\x61' + \
|
|
385
|
+
b'\x00\x00\x00\x03' + b'\x01\x00\x01' + \
|
|
386
|
+
b'\x00\x00\x01\x01' + b'\x00' + bytes(ok_pubkey)
|
|
387
|
+
# (legacy commented-out raw SSH RSA pubkey assembly omitted)
|
|
388
|
+
else:
|
|
389
|
+
ok_pubkey = bytes(ok_pubkey)
|
|
390
|
+
elif len(ok_pubkey) == 512:
|
|
391
|
+
if identity.identity_dict['proto'] == 'ssh':
|
|
392
|
+
ok_pubkey = b'\x00\x00\x00\x07' + b'\x73\x73\x68\x2d\x72\x73\x61' + \
|
|
393
|
+
b'\x00\x00\x00\x03' + b'\x01\x00\x01' + \
|
|
394
|
+
b'\x00\x00\x02\x01' + b'\x00' + bytes(ok_pubkey)
|
|
395
|
+
else:
|
|
396
|
+
ok_pubkey = bytes(ok_pubkey)
|
|
397
|
+
else:
|
|
398
|
+
raise interface.DeviceError("Error response length is not a valid public key")
|
|
399
|
+
log.info('pubkey len = %s', len(ok_pubkey))
|
|
400
|
+
return ok_pubkey
|
|
401
|
+
|
|
402
|
+
def sign(self, identity, blob):
|
|
403
|
+
"""Sign given blob and return the signature (as bytes)."""
|
|
404
|
+
curve_name = identity.get_curve_name(ecdh=False)
|
|
405
|
+
log.debug('"%s" signing %r (%s) on %s',
|
|
406
|
+
identity.to_string(), blob, curve_name, self)
|
|
407
|
+
keygrip_slot_id = None
|
|
408
|
+
if identity.identity_dict['proto'] != 'ssh' and hasattr(self, 'skeyslot') is False:
|
|
409
|
+
self.get_sk_dk()
|
|
410
|
+
if identity.identity_dict['proto'] != 'ssh':
|
|
411
|
+
log.info('Looking for keygrip =%s', identity.identity_dict['keygrip'])
|
|
412
|
+
keygrip = identity.identity_dict['keygrip']
|
|
413
|
+
keygrip_slot_id = self.get_key_by_keygrip(keygrip)
|
|
414
|
+
# Calculate hash for SSH signing
|
|
415
|
+
if 'rsa' in curve_name:
|
|
416
|
+
if self.sighash == b'rsa-sha2-512':
|
|
417
|
+
log.info('rsa-sha2-512')
|
|
418
|
+
h1 = hashlib.sha512()
|
|
419
|
+
h1.update(blob)
|
|
420
|
+
data = h1.hexdigest()
|
|
421
|
+
data = codecs.decode(data, 'hex_codec')
|
|
422
|
+
elif self.sighash == b'rsa-sha2-256':
|
|
423
|
+
log.info('rsa-sha2-256')
|
|
424
|
+
h1 = hashlib.sha256()
|
|
425
|
+
h1.update(blob)
|
|
426
|
+
data = h1.hexdigest()
|
|
427
|
+
data = codecs.decode(data, 'hex_codec')
|
|
428
|
+
else:
|
|
429
|
+
# Calculate hash for key derivation input data
|
|
430
|
+
h1 = hashlib.sha256()
|
|
431
|
+
if identity.identity_dict['proto'] == 'ssh':
|
|
432
|
+
if identity.identity_dict.get('user'):
|
|
433
|
+
id_parts = unidecode.unidecode(identity.identity_dict['user'] + '@' +
|
|
434
|
+
identity.identity_dict['host']).encode('ascii')
|
|
435
|
+
else:
|
|
436
|
+
id_parts = unidecode.unidecode(identity.identity_dict['host']).encode('ascii')
|
|
437
|
+
else:
|
|
438
|
+
id_parts = identity.to_bytes()
|
|
439
|
+
h1.update(id_parts)
|
|
440
|
+
data = h1.hexdigest()
|
|
441
|
+
data = codecs.decode(data, 'hex_codec')
|
|
442
|
+
log.info('Identity to hash =%s', id_parts)
|
|
443
|
+
log.info('Identity hash =%s', data)
|
|
444
|
+
# Determine type of key to derive on OnlyKey for signature
|
|
445
|
+
# Slot 132 used for derived key, slots 101-116 used for stored ecc keys
|
|
446
|
+
# slots 1-4 used for stored RSA keys
|
|
447
|
+
if keygrip_slot_id is not None:
|
|
448
|
+
this_slot_id = keygrip_slot_id
|
|
449
|
+
log.info('Key Slot =%s', this_slot_id)
|
|
450
|
+
if curve_name != 'rsa':
|
|
451
|
+
raw_message = blob
|
|
452
|
+
else:
|
|
453
|
+
raw_message = data
|
|
454
|
+
elif self._derived_version(self.skeyslot):
|
|
455
|
+
self._require_derived_v2(self.skeyslot)
|
|
456
|
+
this_slot_id = self._derived_code(self.skeyslot, curve_name, 'sign')
|
|
457
|
+
log.info('Derived v%d %s sign code %d', self._derived_version(self.skeyslot), curve_name, this_slot_id)
|
|
458
|
+
# Send data and identity hash
|
|
459
|
+
raw_message = blob + data
|
|
460
|
+
elif curve_name != 'rsa':
|
|
461
|
+
this_slot_id = self.skeyslot
|
|
462
|
+
# Send just data to sign
|
|
463
|
+
raw_message = blob
|
|
464
|
+
else:
|
|
465
|
+
this_slot_id = self.skeyslot
|
|
466
|
+
# Send just hash
|
|
467
|
+
raw_message = data
|
|
468
|
+
|
|
469
|
+
log.info('Key Slot =%s', this_slot_id)
|
|
470
|
+
self._challenge(raw_message, identity)
|
|
471
|
+
t_end = time.time() + 22
|
|
472
|
+
if 'rsa' not in curve_name:
|
|
473
|
+
self.ok.send_large_message2(msg=self._defs.Message.OKSIGN, payload=raw_message,
|
|
474
|
+
slot_id=this_slot_id)
|
|
475
|
+
while time.time() < t_end:
|
|
476
|
+
try:
|
|
477
|
+
result = self.ok.read_bytes(timeout_ms=100)
|
|
478
|
+
if len(result) == 64 and len(set(result[0:63])) != 1:
|
|
479
|
+
break
|
|
480
|
+
except Exception as e:
|
|
481
|
+
raise interface.DeviceError(e)
|
|
482
|
+
|
|
483
|
+
self._raise_if_error(result)
|
|
484
|
+
if len(result) >= 60:
|
|
485
|
+
log.info('received= %s', repr(result))
|
|
486
|
+
while len(result) < 64:
|
|
487
|
+
result.append(0)
|
|
488
|
+
log.info('disconnected from %s', self.device_name)
|
|
489
|
+
self.ok.close()
|
|
490
|
+
return bytes(result)
|
|
491
|
+
else:
|
|
492
|
+
log.info('Signature packet =%d', raw_message)
|
|
493
|
+
self.ok.send_large_message2(msg=self._defs.Message.OKSIGN, payload=raw_message,
|
|
494
|
+
slot_id=this_slot_id)
|
|
495
|
+
result = []
|
|
496
|
+
if curve_name == 'rsa2048':
|
|
497
|
+
siglen = 256
|
|
498
|
+
elif 'rsa' in curve_name:
|
|
499
|
+
siglen = 512
|
|
500
|
+
while time.time() < t_end:
|
|
501
|
+
try:
|
|
502
|
+
sig_part = self.ok.read_bytes(timeout_ms=100)
|
|
503
|
+
if len(sig_part) == 64 and len(set(sig_part[0:63])) != 1:
|
|
504
|
+
self._raise_if_error(sig_part)
|
|
505
|
+
log.info('received part= %s', repr(sig_part))
|
|
506
|
+
result += sig_part
|
|
507
|
+
if len(result) == siglen:
|
|
508
|
+
log.info('received len= %d', len(result))
|
|
509
|
+
break
|
|
510
|
+
t_end = time.time() + 1
|
|
511
|
+
# Todo know RSA type to know how many packets
|
|
512
|
+
except Exception as e:
|
|
513
|
+
raise interface.DeviceError(e)
|
|
514
|
+
|
|
515
|
+
log.info('received= %s', repr(result))
|
|
516
|
+
return bytes(result)
|
|
517
|
+
raise interface.Error('failed to sign challenge')
|
|
518
|
+
|
|
519
|
+
def ecdh_with_pubkey(self, identity, pubkey):
|
|
520
|
+
"""Get shared session key using Elliptic Curve Diffie-Hellman & self public key."""
|
|
521
|
+
self_pubkey = self.pubkey(ecdh=False, identity=identity)
|
|
522
|
+
log.info('Using self_pubkey= %s', self_pubkey)
|
|
523
|
+
session_key = self.ecdh(identity, pubkey)
|
|
524
|
+
return session_key, self_pubkey
|
|
525
|
+
|
|
526
|
+
def ecdh(self, identity, pubkey):
|
|
527
|
+
"""Get shared session key using Elliptic Curve Diffie-Hellman."""
|
|
528
|
+
curve_name = identity.get_curve_name(ecdh=True)
|
|
529
|
+
log.debug('"%s" shared session key (%s) for %r from %s',
|
|
530
|
+
identity.to_string(), curve_name, pubkey, self)
|
|
531
|
+
# Calculate hash for key derivation input data
|
|
532
|
+
h1 = hashlib.sha256()
|
|
533
|
+
if identity.identity_dict['proto'] == 'ssh':
|
|
534
|
+
if identity.identity_dict.get('user'):
|
|
535
|
+
id_parts = unidecode.unidecode(identity.identity_dict['user'] + '@' +
|
|
536
|
+
identity.identity_dict['host']).encode('ascii')
|
|
537
|
+
else:
|
|
538
|
+
id_parts = unidecode.unidecode(identity.identity_dict['host']).encode('ascii')
|
|
539
|
+
else:
|
|
540
|
+
id_parts = identity.to_bytes()
|
|
541
|
+
h1.update(id_parts)
|
|
542
|
+
log.info('Identity to hash =%s', id_parts)
|
|
543
|
+
data = h1.hexdigest()
|
|
544
|
+
log.info('Identity hash =%s', data)
|
|
545
|
+
data = codecs.decode(data, 'hex_codec')
|
|
546
|
+
# Determine type of key to derive on OnlyKey for ecdh
|
|
547
|
+
# Slot 132 used for derived key, slots 101-116 used for stored ecc keys,
|
|
548
|
+
# slots 1-4 used for stored RSA keys
|
|
549
|
+
keygrip_slot_id = None
|
|
550
|
+
if identity.identity_dict['proto'] != 'ssh':
|
|
551
|
+
log.info('Looking for keygrip =%s', identity.identity_dict['keygrip'])
|
|
552
|
+
keygrip = identity.identity_dict['keygrip']
|
|
553
|
+
keygrip_slot_id = self.get_key_by_keygrip(keygrip)
|
|
554
|
+
|
|
555
|
+
if self._derived_version(self.dkeyslot):
|
|
556
|
+
self._require_derived_v2(self.dkeyslot)
|
|
557
|
+
this_slot_id = self._derived_code(self.dkeyslot, curve_name, 'decrypt')
|
|
558
|
+
log.info('Derived v%d %s decrypt code %d', self._derived_version(self.dkeyslot), curve_name, this_slot_id)
|
|
559
|
+
raw_message = pubkey + data
|
|
560
|
+
else:
|
|
561
|
+
if keygrip_slot_id is not None:
|
|
562
|
+
this_slot_id = keygrip_slot_id
|
|
563
|
+
else:
|
|
564
|
+
this_slot_id = self.dkeyslot
|
|
565
|
+
raw_message = pubkey
|
|
566
|
+
log.info('Key Slot =%s', this_slot_id)
|
|
567
|
+
log.info('data hash =%s', data)
|
|
568
|
+
self.ok.send_large_message2(msg=self._defs.Message.OKDECRYPT, payload=raw_message,
|
|
569
|
+
slot_id=this_slot_id)
|
|
570
|
+
self._challenge(raw_message, identity)
|
|
571
|
+
t_end = time.time() + 22
|
|
572
|
+
if 'rsa' not in curve_name:
|
|
573
|
+
while time.time() < t_end:
|
|
574
|
+
try:
|
|
575
|
+
result = self.ok.read_bytes(timeout_ms=100)
|
|
576
|
+
if len(result) == 64 and len(set(result[0:63])) != 1:
|
|
577
|
+
break
|
|
578
|
+
except Exception as e:
|
|
579
|
+
raise interface.DeviceError(e)
|
|
580
|
+
self._raise_if_error(result)
|
|
581
|
+
if len(set(result[34:63])) == 1:
|
|
582
|
+
result = b'\x04' + bytes(result[0:32])
|
|
583
|
+
else:
|
|
584
|
+
result = []
|
|
585
|
+
while time.time() < t_end:
|
|
586
|
+
try:
|
|
587
|
+
dec_part = self.ok.read_bytes(timeout_ms=100)
|
|
588
|
+
if len(dec_part) == 64 and len(set(dec_part[0:63])) != 1:
|
|
589
|
+
self._raise_if_error(dec_part)
|
|
590
|
+
log.debug('received part of %d bytes', len(dec_part))
|
|
591
|
+
result += dec_part
|
|
592
|
+
t_end = time.time() + 1
|
|
593
|
+
# Todo know RSA type to know how many packets
|
|
594
|
+
except Exception as e:
|
|
595
|
+
raise interface.DeviceError(e)
|
|
596
|
+
|
|
597
|
+
log.debug('received %d bytes', len(result))
|
|
598
|
+
log.info('disconnected from %s', self.device_name)
|
|
599
|
+
self.ok.close()
|
|
600
|
+
return bytes(result)
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def convert_keyslot(self, s): # pylint: disable=unused-argument
|
|
604
|
+
"""Return key slot number."""
|
|
605
|
+
if s.lower() in ('derived-v2', 'ecc32v2'):
|
|
606
|
+
return 232
|
|
607
|
+
if 'ECC' in s:
|
|
608
|
+
if len(s) == 5:
|
|
609
|
+
return int(s[3:5]) + 100
|
|
610
|
+
else:
|
|
611
|
+
return int(s[3:4]) + 100
|
|
612
|
+
elif 'RSA' in s:
|
|
613
|
+
return int(s[3:4])
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""OnlyKey-related definitions."""
|
|
2
|
+
|
|
3
|
+
# pylint: disable=unused-import,import-error,no-name-in-module
|
|
4
|
+
|
|
5
|
+
from onlykey import Message, OnlyKey
|
|
6
|
+
# Shared protocol logic (generated from libraries/onlykey/protocol/onlykey-protocol.json):
|
|
7
|
+
# the 3-digit challenge rule and the "is this reply an Error string?" classifier live
|
|
8
|
+
# there, not here.
|
|
9
|
+
from onlykey.protocol import (AGENT_DERIVATION, CapabilityFlag, KeyType,
|
|
10
|
+
challenge_code, classify_response)
|