Debian Codegraph @

src/nitrokey/trussed/_bootloader/nrf52_upload/dfu/dfu_transport_serial.py

raw
1 #
2 # Copyright (c) 2016 Nordic Semiconductor ASA
3 # All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or without modification,
6 # are permitted provided that the following conditions are met:
7 #
8 # 1. Redistributions of source code must retain the above copyright notice, this
9 # list of conditions and the following disclaimer.
10 #
11 # 2. Redistributions in binary form must reproduce the above copyright notice, this
12 # list of conditions and the following disclaimer in the documentation and/or
13 # other materials provided with the distribution.
14 #
15 # 3. Neither the name of Nordic Semiconductor ASA nor the names of other
16 # contributors to this software may be used to endorse or promote products
17 # derived from this software without specific prior written permission.
18 #
19 # 4. This software must only be used in or with a processor manufactured by Nordic
20 # Semiconductor ASA, or in or with a processor manufactured by a third party that
21 # is used in combination with a processor manufactured by Nordic Semiconductor.
22 #
23 # 5. Any software provided in binary or object form under this license must not be
24 # reverse engineered, decompiled, modified and/or disassembled.
25 #
26 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
27 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
28 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
29 # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
30 # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
31 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
33 # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 #
37
38 import binascii
39 import logging
40 import struct
41
42 # Python imports
43 import time
44 from datetime import datetime, timedelta
45 from typing import Optional
46
47 # Python 3rd party imports
48 from serial import Serial
49 from serial.serialutil import SerialException
50
51 # from pc_ble_driver_py.exceptions import NordicSemiException
52 from ..exceptions import NordicSemiException
53 from ..lister.device_lister import DeviceLister
54 from ..lister.enumerated_device import EnumeratedDevice
55
56 # Nordic Semiconductor imports
57 from .dfu_transport import TRANSPORT_LOGGING_LEVEL, DfuEvent, DfuTransport
58
59
60 class ValidationException(NordicSemiException):
61 """ "
62 Exception used when validation failed
63 """
64
65 pass
66
67
68 logger = logging.getLogger(__name__)
69
70
71 class Slip:
72 SLIP_BYTE_END = 0o300
73 SLIP_BYTE_ESC = 0o333
74 SLIP_BYTE_ESC_END = 0o334
75 SLIP_BYTE_ESC_ESC = 0o335
76
77 SLIP_STATE_DECODING = 1
78 SLIP_STATE_ESC_RECEIVED = 2
79 SLIP_STATE_CLEARING_INVALID_PACKET = 3
80
81 @staticmethod
82 def encode(data: list[int]) -> list[int]:
83 newData = []
84 for elem in data:
85 if elem == Slip.SLIP_BYTE_END:
86 newData.append(Slip.SLIP_BYTE_ESC)
87 newData.append(Slip.SLIP_BYTE_ESC_END)
88 elif elem == Slip.SLIP_BYTE_ESC:
89 newData.append(Slip.SLIP_BYTE_ESC)
90 newData.append(Slip.SLIP_BYTE_ESC_ESC)
91 else:
92 newData.append(elem)
93 newData.append(Slip.SLIP_BYTE_END)
94 return newData
95
96 @staticmethod
97 def decode_add_byte(
98 c: int, decoded_data: list[int], current_state: int
99 ) -> tuple[bool, int, list[int]]:
100 finished = False
101 if current_state == Slip.SLIP_STATE_DECODING:
102 if c == Slip.SLIP_BYTE_END:
103 finished = True
104 elif c == Slip.SLIP_BYTE_ESC:
105 current_state = Slip.SLIP_STATE_ESC_RECEIVED
106 else:
107 decoded_data.append(c)
108 elif current_state == Slip.SLIP_STATE_ESC_RECEIVED:
109 if c == Slip.SLIP_BYTE_ESC_END:
110 decoded_data.append(Slip.SLIP_BYTE_END)
111 current_state = Slip.SLIP_STATE_DECODING
112 elif c == Slip.SLIP_BYTE_ESC_ESC:
113 decoded_data.append(Slip.SLIP_BYTE_ESC)
114 current_state = Slip.SLIP_STATE_DECODING
115 else:
116 current_state = Slip.SLIP_STATE_CLEARING_INVALID_PACKET
117 elif current_state == Slip.SLIP_STATE_CLEARING_INVALID_PACKET:
118 if c == Slip.SLIP_BYTE_END:
119 current_state = Slip.SLIP_STATE_DECODING
120 decoded_data = []
121
122 return (finished, current_state, decoded_data)
123
124
125 class DFUAdapter:
126 def __init__(self, serial_port: Serial) -> None:
127 self.serial_port = serial_port
128
129 def send_message(self, data: list[int]) -> None:
130 packet = Slip.encode(data)
131 logger.log(TRANSPORT_LOGGING_LEVEL, "SLIP: --> " + str(data))
132 try:
133 self.serial_port.write(packet)
134 except SerialException as e:
135 raise NordicSemiException(
136 "Writing to serial port failed: " + str(e) + ". "
137 "If MSD is enabled on the target device, try to disable it ref. "
138 "https://wiki.segger.com/index.php?title=J-Link-OB_SAM3U"
139 ) from e
140
141 def get_message(self) -> Optional[list[int]]:
142 current_state = Slip.SLIP_STATE_DECODING
143 finished = False
144 decoded_data: list[int] = []
145
146 while finished is False:
147 byte = self.serial_port.read(1)
148 if byte:
149 (unpacked_byte) = struct.unpack("B", byte)[0]
150 (finished, current_state, decoded_data) = Slip.decode_add_byte(
151 unpacked_byte, decoded_data, current_state
152 )
153 else:
154 current_state = Slip.SLIP_STATE_CLEARING_INVALID_PACKET
155 return None
156
157 logger.log(TRANSPORT_LOGGING_LEVEL, "SLIP: <-- " + str(decoded_data))
158
159 return decoded_data
160
161
162 class DfuTransportSerial(DfuTransport):
163 DEFAULT_BAUD_RATE = 115200
164 DEFAULT_FLOW_CONTROL = True
165 DEFAULT_TIMEOUT = 30.0 # Timeout time for board response
166 DEFAULT_SERIAL_PORT_TIMEOUT = 1.0 # Timeout time on serial port read
167 DEFAULT_PRN = 0
168 DEFAULT_DO_PING = True
169
170 OP_CODE = {
171 "CreateObject": 0x01,
172 "SetPRN": 0x02,
173 "CalcChecSum": 0x03,
174 "Execute": 0x04,
175 "ReadError": 0x05,
176 "ReadObject": 0x06,
177 "GetSerialMTU": 0x07,
178 "WriteObject": 0x08,
179 "Ping": 0x09,
180 "Response": 0x60,
181 }
182
183 def __init__(
184 self,
185 com_port: str,
186 baud_rate: int = DEFAULT_BAUD_RATE,
187 flow_control: bool = DEFAULT_FLOW_CONTROL,
188 timeout: float = DEFAULT_TIMEOUT,
189 prn: int = DEFAULT_PRN,
190 do_ping: bool = DEFAULT_DO_PING,
191 ) -> None:
192 super().__init__()
193 self.com_port = com_port
194 self.baud_rate = baud_rate
195 self.flow_control = 1 if flow_control else 0
196 self.timeout = timeout
197 self.prn = prn
198 self.serial_port: Optional[Serial] = None
199 self.dfu_adapter: Optional[DFUAdapter] = None
200 self.ping_id = 0
201 self.do_ping = do_ping
202
203 self.mtu = 0
204
205 """:type: serial.Serial """
206
207 def open(self) -> None:
208 try:
209 self.__ensure_bootloader()
210 self.serial_port = Serial(
211 port=self.com_port,
212 baudrate=self.baud_rate,
213 rtscts=self.flow_control,
214 timeout=self.DEFAULT_SERIAL_PORT_TIMEOUT,
215 )
216 self.dfu_adapter = DFUAdapter(self.serial_port)
217 except OSError as e:
218 raise NordicSemiException(
219 "Serial port could not be opened on {0}. Reason: {1}".format(
220 self.com_port, e.strerror
221 )
222 ) from e
223
224 if self.do_ping:
225 ping_success = False
226 start = datetime.now()
227 while (
228 datetime.now() - start < timedelta(seconds=self.timeout) and ping_success is False
229 ):
230 if self.__ping() is True:
231 ping_success = True
232
233 if ping_success is False:
234 raise NordicSemiException("No ping response after opening COM port")
235
236 self.__set_prn()
237 self.__get_mtu()
238
239 def close(self) -> None:
240 assert self.serial_port
241 self.serial_port.close()
242
243 def send_init_packet(self, init_packet: bytes) -> None:
244 def try_to_recover() -> bool:
245 if response["offset"] == 0 or response["offset"] > len(init_packet):
246 # There is no init packet or present init packet is too long.
247 return False
248
249 expected_crc = binascii.crc32(init_packet[: response["offset"]]) & 0xFFFFFFFF
250
251 if expected_crc != response["crc"]:
252 # Present init packet is invalid.
253 return False
254
255 if len(init_packet) > response["offset"]:
256 # Send missing part.
257 try:
258 self.__stream_data(
259 data=init_packet[response["offset"] :],
260 crc=expected_crc,
261 offset=response["offset"],
262 )
263 except ValidationException:
264 return False
265
266 self.__execute()
267 return True
268
269 response = self.__select_command()
270 assert len(init_packet) <= response["max_size"], "Init command is too long"
271
272 if try_to_recover():
273 return
274
275 try:
276 self.__create_command(len(init_packet))
277 self.__stream_data(data=init_packet)
278 self.__execute()
279 except ValidationException as e:
280 raise NordicSemiException("Failed to send init packet") from e
281
282 def send_firmware(self, firmware: bytes) -> None:
283 def try_to_recover() -> None:
284 if response["offset"] == 0:
285 # Nothing to recover
286 return
287
288 expected_crc = binascii.crc32(firmware[: response["offset"]]) & 0xFFFFFFFF
289 remainder = response["offset"] % response["max_size"]
290
291 if expected_crc != response["crc"]:
292 # Invalid CRC. Remove corrupted data.
293 response["offset"] -= remainder if remainder != 0 else response["max_size"]
294 response["crc"] = binascii.crc32(firmware[: response["offset"]]) & 0xFFFFFFFF
295 return
296
297 if (remainder != 0) and (response["offset"] != len(firmware)):
298 # Send rest of the page.
299 try:
300 to_send = firmware[
301 response["offset"] : response["offset"] + response["max_size"] - remainder
302 ]
303 response["crc"] = self.__stream_data(
304 data=to_send, crc=response["crc"], offset=response["offset"]
305 )
306 response["offset"] += len(to_send)
307 except ValidationException:
308 # Remove corrupted data.
309 response["offset"] -= remainder
310 response["crc"] = binascii.crc32(firmware[: response["offset"]]) & 0xFFFFFFFF
311 return
312
313 self.__execute()
314 self._send_event(event_type=DfuEvent.PROGRESS_EVENT, progress=response["offset"])
315
316 response = self.__select_data()
317 try_to_recover()
318 for i in range(response["offset"], len(firmware), response["max_size"]):
319 data = firmware[i : i + response["max_size"]]
320 try:
321 self.__create_data(len(data))
322 response["crc"] = self.__stream_data(data=data, crc=response["crc"], offset=i)
323 self.__execute()
324 except ValidationException as e:
325 raise NordicSemiException("Failed to send firmware") from e
326
327 self._send_event(event_type=DfuEvent.PROGRESS_EVENT, progress=len(data))
328
329 def __ensure_bootloader(self) -> None:
330 lister = DeviceLister()
331
332 device = None
333 start = datetime.now()
334 while not device and datetime.now() - start < timedelta(seconds=self.timeout):
335 time.sleep(0.5)
336 device = lister.get_device(com=self.com_port)
337
338 if device:
339 if not self.__is_device_in_bootloader_mode(device):
340 logger.info(
341 "Serial: Device is either not in bootloader mode, or using an unsupported bootloader."
342 )
343
344 def __is_device_in_bootloader_mode(self, device: Optional[EnumeratedDevice]) -> bool:
345 if not device:
346 return False
347
348 # TODO: Add Nitrokey IDs
349 # Return true if nrf bootloader or Jlink interface detected.
350 return (
351 (
352 device.vendor_id.lower() == "1915" and device.product_id.lower() == "521f"
353 ) # nRF52 SDFU USB
354 or (
355 device.vendor_id.lower() == "1366" and device.product_id.lower() == "0105"
356 ) # JLink CDC UART Port
357 or (device.vendor_id.lower() == "1366" and device.product_id.lower() == "1015")
358 ) # JLink CDC UART Port (MSD)
359
360 def __set_prn(self) -> None:
361 assert self.dfu_adapter
362 logger.debug("Serial: Set Packet Receipt Notification {}".format(self.prn))
363 self.dfu_adapter.send_message(
364 [DfuTransportSerial.OP_CODE["SetPRN"]] + list(struct.pack("<H", self.prn))
365 )
366 self.__get_response(DfuTransportSerial.OP_CODE["SetPRN"])
367
368 def __get_mtu(self) -> None:
369 assert self.dfu_adapter
370 self.dfu_adapter.send_message([DfuTransportSerial.OP_CODE["GetSerialMTU"]])
371 response = self.__get_response(DfuTransportSerial.OP_CODE["GetSerialMTU"])
372
373 assert response is not None
374 self.mtu = struct.unpack("<H", bytearray(response))[0]
375
376 def __ping(self) -> bool:
377 assert self.dfu_adapter
378 self.ping_id = (self.ping_id + 1) % 256
379
380 self.dfu_adapter.send_message([DfuTransportSerial.OP_CODE["Ping"], self.ping_id])
381 resp = self.dfu_adapter.get_message() # Receive raw response to check return code
382
383 if not resp:
384 logger.debug("Serial: No ping response")
385 return False
386
387 if resp[0] != DfuTransportSerial.OP_CODE["Response"]:
388 logger.debug("Serial: No Response: 0x{:02X}".format(resp[0]))
389 return False
390
391 if resp[1] != DfuTransportSerial.OP_CODE["Ping"]:
392 logger.debug(
393 "Serial: Unexpected Executed OP_CODE.\n"
394 + "Expected: 0x{:02X} Received: 0x{:02X}".format(
395 DfuTransportSerial.OP_CODE["Ping"], resp[1]
396 )
397 )
398 return False
399
400 if resp[2] != DfuTransport.RES_CODE["Success"]:
401 # Returning an error code is seen as good enough. The bootloader is up and running
402 return True
403 else:
404 if struct.unpack("B", bytearray(resp[3:]))[0] == self.ping_id:
405 return True
406 else:
407 return False
408
409 def __create_command(self, size: int) -> None:
410 self.__create_object(0x01, size)
411
412 def __create_data(self, size: int) -> None:
413 self.__create_object(0x02, size)
414
415 def __create_object(self, object_type: int, size: int) -> None:
416 assert self.dfu_adapter
417 self.dfu_adapter.send_message(
418 [DfuTransportSerial.OP_CODE["CreateObject"], object_type]
419 + list(struct.pack("<L", size))
420 )
421 self.__get_response(DfuTransportSerial.OP_CODE["CreateObject"])
422
423 def __calculate_checksum(self) -> dict[str, int]:
424 assert self.dfu_adapter
425 self.dfu_adapter.send_message([DfuTransportSerial.OP_CODE["CalcChecSum"]])
426 response = self.__get_response(DfuTransportSerial.OP_CODE["CalcChecSum"])
427
428 if response is None:
429 raise NordicSemiException(
430 "Did not receive checksum response from DFU target. "
431 "If MSD is enabled on the target device, try to disable it ref. "
432 "https://wiki.segger.com/index.php?title=J-Link-OB_SAM3U"
433 )
434
435 (offset, crc) = struct.unpack("<II", bytearray(response))
436 return {"offset": offset, "crc": crc}
437
438 def __execute(self) -> None:
439 assert self.dfu_adapter
440 self.dfu_adapter.send_message([DfuTransportSerial.OP_CODE["Execute"]])
441 self.__get_response(DfuTransportSerial.OP_CODE["Execute"])
442
443 def __select_command(self) -> dict[str, int]:
444 return self.__select_object(0x01)
445
446 def __select_data(self) -> dict[str, int]:
447 return self.__select_object(0x02)
448
449 def __select_object(self, object_type: int) -> dict[str, int]:
450 assert self.dfu_adapter
451 logger.debug("Serial: Selecting Object: type:{}".format(object_type))
452 self.dfu_adapter.send_message([DfuTransportSerial.OP_CODE["ReadObject"], object_type])
453
454 response = self.__get_response(DfuTransportSerial.OP_CODE["ReadObject"])
455 assert response is not None
456 (max_size, offset, crc) = struct.unpack("<III", bytearray(response))
457
458 logger.debug(
459 "Serial: Object selected: "
460 + " max_size:{} offset:{} crc:{}".format(max_size, offset, crc)
461 )
462 return {"max_size": max_size, "offset": offset, "crc": crc}
463
464 def __get_checksum_response(self) -> dict[str, int]:
465 resp = self.__get_response(DfuTransportSerial.OP_CODE["CalcChecSum"])
466
467 assert resp is not None
468 (offset, crc) = struct.unpack("<II", bytearray(resp))
469 return {"offset": offset, "crc": crc}
470
471 def __stream_data(self, data: bytes, crc: int = 0, offset: int = 0) -> int:
472 assert self.dfu_adapter
473 logger.debug(
474 "Serial: Streaming Data: "
475 + "len:{0} offset:{1} crc:0x{2:08X}".format(len(data), offset, crc)
476 )
477
478 def validate_crc() -> None:
479 if crc != response["crc"]:
480 raise ValidationException(
481 "Failed CRC validation.\n"
482 + "Expected: {} Received: {}.".format(crc, response["crc"])
483 )
484 if offset != response["offset"]:
485 raise ValidationException(
486 "Failed offset validation.\n"
487 + "Expected: {} Received: {}.".format(offset, response["offset"])
488 )
489
490 current_pnr = 0
491
492 for i in range(0, len(data), (self.mtu - 1) // 2 - 1):
493 # append the write data opcode to the front
494 # here the maximum data size is self.mtu/2,
495 # due to the slip encoding which at maximum doubles the size
496 to_transmit = data[i : i + (self.mtu - 1) // 2 - 1]
497 to_transmit = struct.pack("B", DfuTransportSerial.OP_CODE["WriteObject"]) + to_transmit
498
499 self.dfu_adapter.send_message(list(to_transmit))
500 crc = binascii.crc32(to_transmit[1:], crc) & 0xFFFFFFFF
501 offset += len(to_transmit) - 1
502 current_pnr += 1
503 if self.prn == current_pnr:
504 current_pnr = 0
505 response = self.__get_checksum_response()
506 validate_crc()
507 response = self.__calculate_checksum()
508 validate_crc()
509 return crc
510
511 def __get_response(self, operation: int) -> Optional[list[int]]:
512 def get_dict_key(dictionary: dict[str, int], value: int) -> Optional[str]:
513 return next((key for key, val in list(dictionary.items()) if val == value), None)
514
515 assert self.dfu_adapter
516 resp = self.dfu_adapter.get_message()
517
518 if not resp:
519 return None
520
521 if resp[0] != DfuTransportSerial.OP_CODE["Response"]:
522 raise NordicSemiException("No Response: 0x{:02X}".format(resp[0]))
523
524 if resp[1] != operation:
525 raise NordicSemiException(
526 "Unexpected Executed OP_CODE.\n"
527 + "Expected: 0x{:02X} Received: 0x{:02X}".format(operation, resp[1])
528 )
529
530 if resp[2] == DfuTransport.RES_CODE["Success"]:
531 return resp[3:]
532
533 elif resp[2] == DfuTransport.RES_CODE["ExtendedError"]:
534 try:
535 data = DfuTransport.EXT_ERROR_CODE[resp[3]]
536 except IndexError:
537 data = "Unsupported extended error type {}".format(resp[3])
538 raise NordicSemiException("Extended Error 0x{:02X}: {}".format(resp[3], data))
539 else:
540 raise NordicSemiException(
541 "Response Code {}".format(get_dict_key(DfuTransport.RES_CODE, resp[2]))
542 )