-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathcommU2F.py
More file actions
345 lines (299 loc) · 11.7 KB
/
Copy pathcommU2F.py
File metadata and controls
345 lines (299 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# Copyright (c) 2013 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
*******************************************************************************
* Ledger Blue
* (c) 2016 Ledger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************
"""
import os
import traceback
from .Dongle import Dongle, DongleWait
import time
import hid
from u2flib_host.device import U2FDevice
from u2flib_host.yubicommon.compat import byte2int, int2byte
from u2flib_host.constants import INS_SIGN
from u2flib_host import exc
from hashlib import sha256
from .commException import CommException
TIMEOUT = 30000
DEVICES = [
(0x1050, 0x0200), # Gnubby
(0x1050, 0x0113), # YubiKey NEO U2F
(0x1050, 0x0114), # YubiKey NEO OTP+U2F
(0x1050, 0x0115), # YubiKey NEO U2F+CCID
(0x1050, 0x0116), # YubiKey NEO OTP+U2F+CCID
(0x1050, 0x0120), # Security Key by Yubico
(0x1050, 0x0410), # YubiKey Plus
(0x1050, 0x0402), # YubiKey 4 U2F
(0x1050, 0x0403), # YubiKey 4 OTP+U2F
(0x1050, 0x0406), # YubiKey 4 U2F+CCID
(0x1050, 0x0407), # YubiKey 4 OTP+U2F+CCID
(0x2581, 0xF1D0), # Plug-Up U2F Security Key
(0x2581, 0xF1D1), # Ledger Production U2F Dongle
(0x2C97, 0x0000), # Ledger Blue
(0x2C97, 0x0001), # Ledger Nano S
(0x2C97, 0x0002), # Ledger Aramis
(0x2C97, 0x0003), # Ledger HW2
(0x2C97, 0x0004), # Ledger Blend
(0x2C97, 0xF1D0), # Plug-Up U2F Security Key
]
HID_RPT_SIZE = 64
TYPE_INIT = 0x80
U2F_VENDOR_FIRST = 0x40
CMD_INIT = 0x06
CMD_WINK = 0x08
CMD_APDU = 0x03
U2FHID_YUBIKEY_DEVICE_CONFIG = U2F_VENDOR_FIRST
STAT_ERR = 0xBF
def _read_timeout(dev, size, timeout=TIMEOUT):
if timeout > 0:
timeout += time.time()
while timeout == 0 or time.time() < timeout:
resp = dev.read(size)
if resp:
return resp
time.sleep(0.01)
return []
class U2FHIDError(Exception):
def __init__(self, code):
super(Exception, self).__init__("U2FHIDError: 0x%02x" % code)
self.code = code
class HIDDevice(U2FDevice):
"""
U2FDevice implementation using the HID transport.
"""
def __init__(self, path):
self.path = path
self.cid = b"\xff\xff\xff\xff"
def open(self):
self.handle = hid.device()
self.handle.open_path(self.path)
self.handle.set_nonblocking(True)
self.init()
def close(self):
if hasattr(self, "handle"):
self.handle.close()
del self.handle
def init(self):
nonce = os.urandom(8)
resp = self.call(CMD_INIT, nonce)
while resp[:8] != nonce:
print("Wrong nonce, read again...")
resp = self._read_resp(self.cid, CMD_INIT)
self.cid = resp[8:12]
def set_mode(self, mode):
data = mode + b"\x0f\x00\x00"
self.call(U2FHID_YUBIKEY_DEVICE_CONFIG, data)
def _do_send_apdu(self, apdu_data):
return self.call(CMD_APDU, apdu_data)
def wink(self):
self.call(CMD_WINK)
def _send_req(self, cid, cmd, data):
size = len(data)
bc_l = int2byte(size & 0xFF)
bc_h = int2byte(size >> 8 & 0xFF)
payload = (
cid + int2byte(TYPE_INIT | cmd) + bc_h + bc_l + data[: HID_RPT_SIZE - 7]
)
payload += b"\0" * (HID_RPT_SIZE - len(payload))
if self.handle.write([0] + [byte2int(c) for c in payload]) < 0:
raise exc.DeviceError("Cannot write to device!")
data = data[HID_RPT_SIZE - 7 :]
seq = 0
while len(data) > 0:
payload = cid + int2byte(0x7F & seq) + data[: HID_RPT_SIZE - 5]
payload += b"\0" * (HID_RPT_SIZE - len(payload))
if self.handle.write([0] + [byte2int(c) for c in payload]) < 0:
raise exc.DeviceError("Cannot write to device!")
data = data[HID_RPT_SIZE - 5 :]
seq += 1
def _read_resp(self, cid, cmd):
resp = b"."
header = cid + int2byte(TYPE_INIT | cmd)
while resp and resp[:5] != header:
# allow for timeout
resp_vals = _read_timeout(self.handle, HID_RPT_SIZE)
resp = b"".join(int2byte(v) for v in resp_vals)
if resp[:5] == cid + int2byte(STAT_ERR):
raise U2FHIDError(byte2int(resp[7]))
if not resp:
raise exc.DeviceError("Invalid response from device!")
data_len = (byte2int(resp[5]) << 8) + byte2int(resp[6])
data = resp[7 : min(7 + data_len, HID_RPT_SIZE)]
data_len -= len(data)
seq = 0
while data_len > 0:
resp_vals = _read_timeout(self.handle, HID_RPT_SIZE)
resp = b"".join(int2byte(v) for v in resp_vals)
if resp[:4] != cid:
raise exc.DeviceError("Wrong CID from device!")
if resp[4] != (seq & 0x7F):
raise exc.DeviceError(
"Wrong SEQ from device! {} != {}".format(resp[4], seq)
)
seq += 1
new_data = resp[5 : min(5 + data_len, HID_RPT_SIZE)]
data_len -= len(new_data)
data += new_data
return data
def call(self, cmd, data=b""):
if isinstance(data, int):
data = int2byte(data)
self._send_req(self.cid, cmd, data)
return self._read_resp(self.cid, cmd)
class U2FTunnelDongle(Dongle, DongleWait):
def __init__(self, device, scrambleKey="", ledger=False, debug=False):
self.device = device
self.scrambleKey = scrambleKey
self.ledger = ledger
self.debug = debug
self.waitImpl = self
self.opened = True
self.device.open()
def exchange(self, apdu, timeout=TIMEOUT):
if self.debug:
print("U2F => %s" % apdu.hex())
if len(apdu) >= 256:
raise CommException("Too long APDU to transport")
# wrap apdu
i = 0
keyHandle = b""
while i < len(apdu):
val = apdu[i : i + 1]
if len(self.scrambleKey) > 0:
val = b"" + int2byte(
ord(val) ^ ord(self.scrambleKey[i % len(self.scrambleKey)])
)
keyHandle += val
i += 1
client_param = sha256("u2f_tunnel".encode("utf8")).digest()
app_param = sha256("u2f_tunnel".encode("utf8")).digest()
request = client_param + app_param + int2byte(len(keyHandle)) + keyHandle
start = time.time()
while time.time() - start < timeout:
# p1 = 0x07 if check_only else 0x03
p1 = 0x03
p2 = 0
try:
response = self.device.send_apdu(INS_SIGN, p1, p2, request)
except exc.APDUError as e:
if e.code == 0x6985:
time.sleep(0.25)
continue
raise e
if self.debug:
print("U2F <= %s%.2x" % (response.hex(), 0x9000))
# check replied status words of the command (within the APDU tunnel)
if response[-2:] != b"\x90\x00":
raise CommException(
"Invalid status words received: " + response[-2:].hex()
)
else:
break
# api expect a byte array, remove the appended status words, remove the user presence and counter
return bytearray(response[5:-2])
def apduMaxDataSize(self):
return 256 - 5
def close(self):
self.device.close()
def waitFirstResponse(self, timeout):
raise CommException("Invalid use")
def getDongles(dev_class=None, scrambleKey="", debug=False):
dev_class = dev_class or HIDDevice
devices = []
for d in hid.enumerate(0, 0):
usage_page = d["usage_page"]
if usage_page == 0xF1D0 and d["usage"] == 1:
devices.append(
U2FTunnelDongle(dev_class(d["path"]), scrambleKey, debug=debug)
)
# Usage page doesn't work on Linux
# well known devices
elif (d["vendor_id"], d["product_id"]) in DEVICES:
device = HIDDevice(d["path"])
try:
device.open()
device.close()
devices.append(
U2FTunnelDongle(dev_class(d["path"]), scrambleKey, debug=debug)
)
except (exc.DeviceError, IOError, OSError):
pass
# unknown devices
else:
device = HIDDevice(d["path"])
try:
device.open()
# try a ping command to ensure a FIDO device, else timeout (BEST here, modulate the timeout, 2 seconds is way too big)
device.ping()
device.close()
devices.append(
U2FTunnelDongle(dev_class(d["path"]), scrambleKey, debug=debug)
)
except (exc.DeviceError, IOError, OSError):
pass
return devices
def getDongle(path=None, dev_class=None, scrambleKey="", debug=False):
# if path is none, then use the first device
dev_class = dev_class or HIDDevice
devices = []
for d in hid.enumerate(0, 0):
if path is None or d["path"] == path:
usage_page = d["usage_page"]
if usage_page == 0xF1D0 and d["usage"] == 1:
return U2FTunnelDongle(dev_class(d["path"]), scrambleKey, debug=debug)
# Usage page doesn't work on Linux
# well known devices
elif (d["vendor_id"], d["product_id"]) in DEVICES and (
"interface_number" not in d or d["interface_number"] == 1
):
# print d
device = HIDDevice(d["path"])
try:
device.open()
device.close()
return U2FTunnelDongle(
dev_class(d["path"]), scrambleKey, debug=debug
)
except (exc.DeviceError, IOError, OSError):
traceback.print_exc()
pass
raise CommException("No dongle found")