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,155 @@
1
+ """Device abstraction layer."""
2
+
3
+ import hashlib
4
+ import io
5
+ import logging
6
+ import re
7
+ import struct
8
+
9
+ import unidecode
10
+
11
+ from .. import formats, util
12
+
13
+ log = logging.getLogger(__name__)
14
+
15
+ _identity_regexp = re.compile(''.join([
16
+ '^'
17
+ r'(?:(?P<proto>.*)://)?',
18
+ r'(?:(?P<user>.*)@)?',
19
+ r'(?P<host>.*?)',
20
+ r'(?::(?P<port>\w*))?',
21
+ r'(?P<path>/.*)?',
22
+ '$'
23
+ ]))
24
+
25
+
26
+ def string_to_identity(identity_str):
27
+ """Parse string into Identity dictionary."""
28
+ m = _identity_regexp.match(identity_str)
29
+ result = m.groupdict()
30
+ log.debug('parsed identity: %s', result)
31
+ return {k: v for k, v in result.items() if v}
32
+
33
+
34
+ def identity_to_string(identity_dict):
35
+ """Dump Identity dictionary into its string representation."""
36
+ result = []
37
+ if identity_dict.get('proto'):
38
+ result.append(identity_dict['proto'] + '://')
39
+ if identity_dict.get('user'):
40
+ result.append(identity_dict['user'] + '@')
41
+ result.append(identity_dict['host'])
42
+ if identity_dict.get('port'):
43
+ result.append(':' + identity_dict['port'])
44
+ if identity_dict.get('path'):
45
+ result.append(identity_dict['path'])
46
+ log.debug('identity parts: %s', result)
47
+ return ''.join(result)
48
+
49
+
50
+ class Error(Exception):
51
+ """Device-related error."""
52
+
53
+
54
+ class NotFoundError(Error):
55
+ """Device could not be found."""
56
+
57
+
58
+ class DeviceError(Error):
59
+ """Error during device operation."""
60
+
61
+
62
+ class Identity:
63
+ """Represent SLIP-0013 identity, together with a elliptic curve choice."""
64
+
65
+ def __init__(self, identity_str, curve_name):
66
+ """Configure for specific identity and elliptic curve usage."""
67
+ self.identity_dict = string_to_identity(identity_str)
68
+ self.curve_name = curve_name
69
+
70
+ def items(self):
71
+ """Return a copy of identity_dict items."""
72
+ return [(k, unidecode.unidecode(v))
73
+ for k, v in self.identity_dict.items()]
74
+
75
+ def to_bytes(self):
76
+ """Transliterate Unicode into ASCII."""
77
+ s = identity_to_string(self.identity_dict)
78
+ return unidecode.unidecode(s).encode('ascii')
79
+
80
+ def to_string(self):
81
+ """Return identity serialized to string."""
82
+ return '<{}|{}>'.format(identity_to_string(self.identity_dict), self.curve_name)
83
+
84
+ def get_bip32_address(self, ecdh=False):
85
+ """Compute BIP32 derivation address according to SLIP-0013/0017."""
86
+ index = struct.pack('<L', self.identity_dict.get('index', 0))
87
+ addr = index + self.to_bytes()
88
+ log.debug('bip32 address string: %r', addr)
89
+ digest = hashlib.sha256(addr).digest()
90
+ s = io.BytesIO(bytearray(digest))
91
+
92
+ hardened = 0x80000000
93
+ addr_0 = 17 if bool(ecdh) else 13
94
+ address_n = [addr_0] + list(util.recv(s, '<LLLL'))
95
+ return [(hardened | value) for value in address_n]
96
+
97
+ def get_curve_name(self, ecdh=False):
98
+ """Return correct curve name for device operations."""
99
+ if ecdh:
100
+ return formats.get_ecdh_curve_name(self.curve_name)
101
+ else:
102
+ return self.curve_name
103
+
104
+
105
+ class Device:
106
+ """Abstract cryptographic hardware device interface."""
107
+
108
+ def __init__(self):
109
+ """C-tor."""
110
+ self.conn = None
111
+
112
+ @classmethod
113
+ def prepare(cls):
114
+ """Per-process setup, on the thread that will outlive the agent's worker threads."""
115
+
116
+ def connect(self):
117
+ """Connect to device, otherwise raise NotFoundError."""
118
+ raise NotImplementedError()
119
+
120
+ def close(self):
121
+ """Close connection to device.
122
+
123
+ By default, close the underlying connection. Overriding classes
124
+ can perform their own cleanup.
125
+ """
126
+ self.conn.close()
127
+
128
+ def __enter__(self):
129
+ """Allow usage as context manager."""
130
+ self.conn = self.connect()
131
+ return self
132
+
133
+ def __exit__(self, *args):
134
+ """Close and mark as disconnected."""
135
+ try:
136
+ self.close()
137
+ except Exception as e: # pylint: disable=broad-except
138
+ log.exception('close failed: %s', e)
139
+ self.conn = None
140
+
141
+ def pubkey(self, identity, ecdh=False):
142
+ """Get public key (as bytes)."""
143
+ raise NotImplementedError()
144
+
145
+ def sign(self, identity, blob):
146
+ """Sign given blob and return the signature (as bytes)."""
147
+ raise NotImplementedError()
148
+
149
+ def ecdh(self, identity, pubkey):
150
+ """Get shared session key using Elliptic Curve Diffie-Hellman."""
151
+ raise NotImplementedError()
152
+
153
+ def __str__(self):
154
+ """Human-readable representation."""
155
+ return '{}'.format(self.__class__.__name__)
@@ -0,0 +1,143 @@
1
+ """Jade-related code (see https://blockstream.com/jade/)."""
2
+
3
+ import logging
4
+
5
+ import ecdsa
6
+ import semver
7
+
8
+ from .. import formats, util
9
+ from . import interface
10
+
11
+ log = logging.getLogger(__name__)
12
+
13
+
14
+ def _verify_support(identity, ecdh):
15
+ """Make sure the device supports given configuration."""
16
+ if identity.get_curve_name(ecdh=ecdh) != formats.CURVE_NIST256:
17
+ raise NotImplementedError(
18
+ 'Unsupported elliptic curve: {}'.format(identity.curve_name))
19
+
20
+
21
+ class BlockstreamJade(interface.Device):
22
+ """Connection to Blockstream Jade device."""
23
+
24
+ MIN_SUPPORTED_FW_VERSION = semver.VersionInfo(0, 1, 33)
25
+ DEVICE_IDS = [(0x10c4, 0xea60), (0x1a86, 0x55d4)]
26
+ connection = None
27
+
28
+ @classmethod
29
+ def package_name(cls):
30
+ """Python package name (at PyPI)."""
31
+ return 'jade-agent'
32
+
33
+ def connect(self):
34
+ """Connect to the first matching device."""
35
+ # pylint: disable=import-error
36
+ from jadepy import JadeAPI
37
+ from serial.tools import list_ports
38
+
39
+ # Return the existing connection if we have one
40
+ if BlockstreamJade.connection is not None:
41
+ return BlockstreamJade.connection
42
+
43
+ # Jade is a serial (over usb) device, it shows as a serial/com port device.
44
+ # Scan com ports looking for the relevant vid and pid, and connect to the
45
+ # first matching device. Then call 'auth_user' - this usually requires network
46
+ # access in order to unlock the device with a PIN and the remote blind pinserver.
47
+ for devinfo in list_ports.comports():
48
+ device_product_key = (devinfo.vid, devinfo.pid)
49
+ if device_product_key in self.DEVICE_IDS:
50
+ try:
51
+ jade = JadeAPI.create_serial(devinfo.device)
52
+
53
+ # Monkey-patch a no-op 'close()' method to suppress logged errors
54
+ jade.close = lambda: log.debug("Close called")
55
+
56
+ # Connect and fetch version info
57
+ jade.connect()
58
+ verinfo = jade.get_version_info()
59
+
60
+ # Check minimum supported firmware version (ignore candidate/build parts)
61
+ fwversion = semver.VersionInfo.parse(verinfo['JADE_VERSION'])
62
+ if self.MIN_SUPPORTED_FW_VERSION > fwversion.finalize_version():
63
+ msg = ('Outdated {} firmware for device. Please update using'
64
+ ' a Blockstream Green companion app')
65
+ raise ValueError(msg.format(fwversion))
66
+
67
+ # Authenticate the user (unlock with pin)
68
+ # NOTE: usually requires network access unless already unlocked
69
+ # (or temporary 'Emergency Restore' wallet is already in use).
70
+ network = 'testnet' if verinfo.get('JADE_NETWORKS') == 'TEST' else 'mainnet'
71
+ while not jade.auth_user(network):
72
+ log.warning("PIN incorrect, please try again")
73
+
74
+ # Cache the connection to jade
75
+ BlockstreamJade.connection = jade
76
+ return jade
77
+ except Exception as e:
78
+ raise interface.NotFoundError(
79
+ '{} not connected: "{}"'.format(self, e))
80
+ return None
81
+
82
+ @staticmethod
83
+ def _get_identity_string(identity):
84
+ return interface.identity_to_string(identity.identity_dict)
85
+
86
+ @staticmethod
87
+ def _load_uncompressed_pubkey(pubkey, curve_name):
88
+ assert curve_name == formats.CURVE_NIST256
89
+ assert len(pubkey) == 65 and pubkey[0] == 0x04
90
+ curve = ecdsa.NIST256p
91
+ point = ecdsa.ellipticcurve.Point(curve.curve,
92
+ util.bytes2num(pubkey[1:33]),
93
+ util.bytes2num(pubkey[33:65]))
94
+ return ecdsa.VerifyingKey.from_public_point(point, curve=curve,
95
+ hashfunc=formats.hashfunc)
96
+
97
+ def pubkey(self, identity, ecdh=False):
98
+ """Get PublicKey object for specified BIP32 address and elliptic curve."""
99
+ _verify_support(identity, ecdh)
100
+ identity_string = self._get_identity_string(identity)
101
+ curve_name = identity.get_curve_name(ecdh=ecdh)
102
+ key_type = 'slip-0017' if ecdh else 'slip-0013'
103
+
104
+ log.debug('"%s" getting %s public key (%s) from %s',
105
+ identity_string, key_type, curve_name, self)
106
+ result = self.conn.get_identity_pubkey(identity_string, curve_name, key_type)
107
+ log.debug('result: %s', result)
108
+
109
+ assert len(result) == 33 or len(result) == 65
110
+ convert_pubkey = (formats.decompress_pubkey
111
+ if len(result) == 33 else
112
+ self._load_uncompressed_pubkey)
113
+ return convert_pubkey(pubkey=result, curve_name=curve_name)
114
+
115
+ def sign(self, identity, blob):
116
+ """Sign given blob and return the signature (as bytes)."""
117
+ _verify_support(identity, ecdh=False)
118
+ identity_string = self._get_identity_string(identity)
119
+ curve_name = identity.get_curve_name(ecdh=False)
120
+
121
+ log.debug('"%s" signing %r (%s) on %s',
122
+ identity_string, blob, curve_name, self)
123
+ result = self.conn.sign_identity(identity_string, curve_name, blob)
124
+ log.debug('result: %s', result)
125
+
126
+ signature = result['signature']
127
+ assert len(signature) == 64 or (len(signature) == 65 and signature[0] == 0x00)
128
+ if len(signature) == 65:
129
+ signature = signature[1:]
130
+ return signature
131
+
132
+ def ecdh(self, identity, pubkey):
133
+ """Get shared session key using Elliptic Curve Diffie-Hellman."""
134
+ _verify_support(identity, ecdh=True)
135
+ identity_string = self._get_identity_string(identity)
136
+ curve_name = identity.get_curve_name(ecdh=True)
137
+
138
+ log.debug('"%s" shared session key (%s) for %r from %s',
139
+ identity_string, curve_name, pubkey, self)
140
+ result = self.conn.get_identity_shared_key(identity_string, curve_name, pubkey)
141
+ log.debug('result: %s', result)
142
+
143
+ return result
@@ -0,0 +1,45 @@
1
+ """KeepKey-related code (see https://www.keepkey.com/)."""
2
+
3
+ from .. import formats
4
+ from . import trezor
5
+
6
+
7
+ def _verify_support(identity, ecdh):
8
+ """Make sure the device supports given configuration."""
9
+ protocol = identity.identity_dict['proto']
10
+ if protocol not in {'ssh'}:
11
+ raise NotImplementedError(
12
+ 'Unsupported protocol: {}'.format(protocol))
13
+ if ecdh:
14
+ raise NotImplementedError('No support for ECDH')
15
+ if identity.curve_name not in {formats.CURVE_NIST256}:
16
+ raise NotImplementedError(
17
+ 'Unsupported elliptic curve: {}'.format(identity.curve_name))
18
+
19
+
20
+ class KeepKey(trezor.Trezor):
21
+ """Connection to KeepKey device."""
22
+
23
+ @classmethod
24
+ def package_name(cls):
25
+ """Python package name (at PyPI)."""
26
+ return 'keepkey-agent'
27
+
28
+ @property
29
+ def _defs(self):
30
+ from . import keepkey_defs
31
+ return keepkey_defs
32
+
33
+ required_version = '>=1.0.5'
34
+
35
+ def _override_state_handler(self, _):
36
+ """No support for `state` handling on Keepkey."""
37
+
38
+ def pubkey(self, identity, ecdh=False):
39
+ """Return public key."""
40
+ _verify_support(identity, ecdh)
41
+ return trezor.Trezor.pubkey(self, identity=identity, ecdh=ecdh)
42
+
43
+ def ecdh(self, identity, pubkey):
44
+ """No support for ECDH in KeepKey firmware."""
45
+ _verify_support(identity, ecdh=True)
@@ -0,0 +1,24 @@
1
+ """KeepKey-related definitions."""
2
+
3
+ # pylint: disable=unused-import,import-error
4
+
5
+ from keepkeylib.client import CallException
6
+ from keepkeylib.client import KeepKeyClient as Client
7
+ from keepkeylib.client import PinException
8
+ from keepkeylib.messages_pb2 import PassphraseAck, PinMatrixAck
9
+ from keepkeylib.transport_hid import HidTransport
10
+ from keepkeylib.transport_webusb import WebUsbTransport
11
+ from keepkeylib.types_pb2 import IdentityType
12
+
13
+ get_public_node = Client.get_public_node
14
+ sign_identity = Client.sign_identity
15
+ Client.state = None
16
+
17
+
18
+ def find_device():
19
+ """Returns first WebUSB or HID transport."""
20
+ for d in WebUsbTransport.enumerate():
21
+ return WebUsbTransport(d)
22
+
23
+ for d in HidTransport.enumerate():
24
+ return HidTransport(d)
@@ -0,0 +1,178 @@
1
+ """Ledger-related code (see https://www.ledgerwallet.com/)."""
2
+
3
+ import binascii
4
+ import logging
5
+ import struct
6
+
7
+ from ledgerblue import comm # pylint: disable=import-error
8
+
9
+ from .. import formats
10
+ from . import interface
11
+
12
+ log = logging.getLogger(__name__)
13
+
14
+
15
+ def _expand_path(path):
16
+ """Convert BIP32 path into bytes."""
17
+ return b''.join((struct.pack('>I', e) for e in path))
18
+
19
+
20
+ def _convert_public_key(ecdsa_curve_name, result):
21
+ """Convert Ledger reply into PublicKey object."""
22
+ if ecdsa_curve_name == 'nist256p1':
23
+ if (result[64] & 1) != 0:
24
+ result = bytearray([0x03]) + result[1:33]
25
+ else:
26
+ result = bytearray([0x02]) + result[1:33]
27
+ else:
28
+ result = result[1:]
29
+ keyX = bytearray(result[0:32])
30
+ keyY = bytearray(result[32:][::-1])
31
+ if (keyX[31] & 1) != 0:
32
+ keyY[31] |= 0x80
33
+ result = b'\x00' + bytes(keyY)
34
+ return bytes(result)
35
+
36
+
37
+ class LedgerNanoS(interface.Device):
38
+ """Connection to Ledger Nano S device."""
39
+
40
+ LEDGER_APP_NAME = "SSH/PGP Agent"
41
+ ledger_app_version = None
42
+ ledger_app_supports_end_of_frame_byte = True
43
+
44
+ def get_app_name_and_version(self, dongle):
45
+ """Retrieve currently running Ledger application name and its version string."""
46
+ device_version_answer = dongle.exchange(binascii.unhexlify('B001000000'))
47
+ offset = 1
48
+ app_name_length = struct.unpack_from("B", device_version_answer, offset)[0]
49
+ offset += 1
50
+ app_name = device_version_answer[offset: offset + app_name_length]
51
+ offset += app_name_length
52
+ app_version_length = struct.unpack_from("B", device_version_answer, offset)[0]
53
+ offset += 1
54
+ app_version = device_version_answer[offset: offset + app_version_length]
55
+ log.debug("running app %s, version %s", app_name, app_version)
56
+ return (app_name.decode(), app_version.decode())
57
+
58
+ @classmethod
59
+ def package_name(cls):
60
+ """Python package name (at PyPI)."""
61
+ return 'ledger-agent'
62
+
63
+ def connect(self):
64
+ """Enumerate and connect to the first USB HID interface."""
65
+ try:
66
+ dongle = comm.getDongle(debug=True)
67
+ (app_name, self.ledger_app_version) = self.get_app_name_and_version(dongle)
68
+
69
+ version_parts = self.ledger_app_version.split(".")
70
+ if (version_parts[0] == "0" and version_parts[1] == "0" and int(version_parts[2]) <= 7):
71
+ self.ledger_app_supports_end_of_frame_byte = False
72
+
73
+ if app_name != LedgerNanoS.LEDGER_APP_NAME:
74
+ # we could launch the app here if we are in the dashboard
75
+ raise interface.DeviceError(f'{self} is not running {LedgerNanoS.LEDGER_APP_NAME}')
76
+
77
+ return dongle
78
+ except comm.CommException as e:
79
+ raise interface.DeviceError(
80
+ 'Error ({}) communicating with {}'.format(e, self))
81
+
82
+ def pubkey(self, identity, ecdh=False):
83
+ """Get PublicKey object for specified BIP32 address and elliptic curve."""
84
+ curve_name = identity.get_curve_name(ecdh)
85
+ path = _expand_path(identity.get_bip32_address(ecdh))
86
+ if curve_name == 'nist256p1':
87
+ p2 = '01'
88
+ else:
89
+ p2 = '02'
90
+ apdu = '800200' + p2
91
+ apdu = binascii.unhexlify(apdu)
92
+ apdu += bytearray([len(path) + 1, len(path) // 4])
93
+ apdu += path
94
+ log.debug('apdu: %r', apdu)
95
+ result = bytearray(self.conn.exchange(bytes(apdu)))
96
+ log.debug('result: %r', result)
97
+ return formats.decompress_pubkey(
98
+ pubkey=_convert_public_key(curve_name, result[1:]),
99
+ curve_name=identity.curve_name)
100
+
101
+ def sign(self, identity, blob):
102
+ """Sign given blob and return the signature (as bytes)."""
103
+ # pylint: disable=too-many-locals,too-many-branches
104
+ path = _expand_path(identity.get_bip32_address(ecdh=False))
105
+ offset = 0
106
+ result = None
107
+ while offset != len(blob):
108
+ data = bytes()
109
+ if offset == 0:
110
+ data += bytearray([len(path) // 4]) + path
111
+ chunk_size = min(len(blob) - offset, 255 - len(data))
112
+ data += blob[offset:offset + chunk_size]
113
+
114
+ if identity.identity_dict['proto'] == 'ssh':
115
+ ins = '04'
116
+ else:
117
+ ins = '08'
118
+
119
+ if identity.curve_name == 'nist256p1':
120
+ p2 = '81' if identity.identity_dict['proto'] == 'ssh' else '01'
121
+ else:
122
+ p2 = '82' if identity.identity_dict['proto'] == 'ssh' else '02'
123
+
124
+ if offset + chunk_size == len(blob) and self.ledger_app_supports_end_of_frame_byte:
125
+ # mark that we are at the end of the frame
126
+ p1 = "80" if offset == 0 else "81"
127
+ else:
128
+ p1 = "00" if offset == 0 else "01"
129
+
130
+ apdu = binascii.unhexlify('80' + ins + p1 + p2) + len(data).to_bytes(1, 'little') + data
131
+
132
+ log.debug('apdu: %r', apdu)
133
+ try:
134
+ result = bytearray(self.conn.exchange(bytes(apdu)))
135
+ except comm.CommException as e:
136
+ raise interface.DeviceError(
137
+ 'Error ({}) communicating with {}'.format(e, self))
138
+
139
+ offset += chunk_size
140
+
141
+ log.debug('result: %r', result)
142
+ if identity.curve_name == 'nist256p1':
143
+ offset = 3
144
+ length = result[offset]
145
+ r = result[offset+1:offset+1+length]
146
+ if r[0] == 0:
147
+ r = r[1:]
148
+ offset = offset + 1 + length + 1
149
+ length = result[offset]
150
+ s = result[offset+1:offset+1+length]
151
+ if s[0] == 0:
152
+ s = s[1:]
153
+ offset = offset + 1 + length
154
+ return bytes(r) + bytes(s)
155
+ else:
156
+ return bytes(result[:64])
157
+
158
+ def ecdh(self, identity, pubkey):
159
+ """Get shared session key using Elliptic Curve Diffie-Hellman."""
160
+ path = _expand_path(identity.get_bip32_address(ecdh=True))
161
+ if identity.curve_name == 'nist256p1':
162
+ p2 = '01'
163
+ else:
164
+ p2 = '02'
165
+ apdu = '800a00' + p2
166
+ apdu = binascii.unhexlify(apdu)
167
+ apdu += bytearray([len(pubkey) + len(path) + 1])
168
+ apdu += bytearray([len(path) // 4]) + path
169
+ apdu += pubkey
170
+ log.debug('apdu: %r', apdu)
171
+ try:
172
+ result = bytearray(self.conn.exchange(bytes(apdu)))
173
+ except comm.CommException as e:
174
+ raise interface.DeviceError(
175
+ 'Error ({}) communicating with {}'.format(e, self))
176
+ log.debug('result: %r', result)
177
+ assert result[0] == 0x04
178
+ return bytes(result)