Debian Codegraph @

src/nitrokey/trussed/_bootloader/lpc55_upload/sbfile/misc.py

raw
1 #!/usr/bin/env python
2 # -*- coding: UTF-8 -*-
3 #
4 # Copyright 2020-2023 NXP
5 #
6 # SPDX-License-Identifier: BSD-3-Clause
7
8 """Miscellaneous functions in SBFile module."""
9
10 from datetime import datetime, timezone
11 from typing import Any, Sequence, Union
12
13 from ..exceptions import SPSDKError
14 from ..utils import misc
15
16
17 class SecBootBlckSize:
18 """Helper methods allowing to convert size to number of blocks and back.
19
20 Note: The class is not intended to be instantiated
21 """
22
23 # Size of cipher block in bytes
24 BLOCK_SIZE = 16
25
26 @staticmethod
27 def is_aligned(size: int) -> bool:
28 """Whether size is aligned to cipher block size.
29
30 :param size: given size in bytes
31 :return: True if yes, False otherwise
32 """
33 return size % SecBootBlckSize.BLOCK_SIZE == 0
34
35 @staticmethod
36 def align(size: int) -> int:
37 """Align given size to block size.
38
39 :param size: in bytes
40 :return: size aligned up to block size
41 """
42 return misc.align(size, SecBootBlckSize.BLOCK_SIZE)
43
44 @staticmethod
45 def to_num_blocks(size: int) -> int:
46 """Converts size to number of cipher blocks.
47
48 :param size: to be converted, the size must be aligned to block boundary
49 :return: corresponding number of cipher blocks
50 :raises SPSDKError: Raised when size is not aligned to block boundary
51 """
52 if not SecBootBlckSize.is_aligned(size):
53 raise SPSDKError(
54 f"Invalid size {size}, expected number aligned to BLOCK size {SecBootBlckSize.BLOCK_SIZE}"
55 )
56 return size // SecBootBlckSize.BLOCK_SIZE
57
58 @staticmethod
59 def align_block_fill_random(data: bytes) -> bytes:
60 """Align block size to cipher block size.
61
62 :param data: to be aligned
63 :return: data aligned to cipher block size, filled with random values
64 """
65 return misc.align_block_fill_random(data, SecBootBlckSize.BLOCK_SIZE)
66
67
68 # the type represents input formats for BcdVersion3 value, see BcdVersion3.to_version
69 BcdVersion3Format = Union["BcdVersion3", str]
70
71
72 class BcdVersion3:
73 """Version in format #.#.#, where # is BCD number (1-4 digits)."""
74
75 # default value
76 DEFAULT = "999.999.999"
77
78 @staticmethod
79 def _check_number(num: int) -> bool:
80 """Check given number is a valid version number.
81
82 :param num: to be checked
83 :return: True if number format is valid
84 :raises SPSDKError: If number format is not valid
85 """
86 if num < 0 or num > 0x9999:
87 raise SPSDKError("Invalid number range")
88 for index in range(4):
89 if (num >> 4 * index) & 0xF > 0x9:
90 raise SPSDKError("Invalid number, contains digit > 9")
91 return True
92
93 @staticmethod
94 def _num_from_str(text: str) -> int:
95 """Converts BCD number from text to int.
96
97 :param text: given string to be converted to a version number
98 :return: version number
99 :raises SPSDKError: If format is not valid
100 """
101 if len(text) < 0 or len(text) > 4:
102 raise SPSDKError("Invalid text length")
103 result = int(text, 16)
104 BcdVersion3._check_number(result)
105 return result
106
107 @staticmethod
108 def from_str(text: str) -> "BcdVersion3":
109 """Convert string to BcdVersion instance.
110
111 :param text: version in format #.#.#, where # is 1-4 decimal digits
112 :return: BcdVersion3 instance
113 :raises SPSDKError: If format is not valid
114 """
115 parts = text.split(".")
116 if len(parts) != 3:
117 raise SPSDKError("Invalid length")
118 major = BcdVersion3._num_from_str(parts[0])
119 minor = BcdVersion3._num_from_str(parts[1])
120 service = BcdVersion3._num_from_str(parts[2])
121 return BcdVersion3(major, minor, service)
122
123 @staticmethod
124 def to_version(input_version: BcdVersion3Format) -> "BcdVersion3":
125 """Convert different input formats into BcdVersion3 instance.
126
127 :param input_version: either directly BcdVersion3 or string
128 :raises SPSDKError: Raises when the format is unsupported
129 :return: BcdVersion3 instance
130 """
131 if isinstance(input_version, BcdVersion3):
132 return input_version
133 if isinstance(input_version, str):
134 return BcdVersion3.from_str(input_version)
135 raise SPSDKError("unsupported format")
136
137 def __init__(self, major: int = 1, minor: int = 0, service: int = 0) -> None:
138 """Initialize BcdVersion3.
139
140 :param major: number in BCD format, 1-4 decimal digits
141 :param minor: number in BCD format, 1-4 decimal digits
142 :param service: number in BCD format, 1-4 decimal digits
143 :raises SPSDKError: Invalid version
144 """
145 if not all(
146 [
147 BcdVersion3._check_number(major),
148 BcdVersion3._check_number(minor),
149 BcdVersion3._check_number(service),
150 ]
151 ):
152 raise SPSDKError("Invalid version")
153 self.major = major
154 self.minor = minor
155 self.service = service
156
157 def __str__(self) -> str:
158 return f"{self.major:X}.{self.minor:X}.{self.service:X}"
159
160 def __repr__(self) -> str:
161 return self.__class__.__name__ + ": " + self.__str__()
162
163 def __eq__(self, other: Any) -> bool:
164 return (
165 isinstance(other, BcdVersion3)
166 and (self.major == other.major)
167 and (self.minor == other.minor)
168 and (self.service == other.service)
169 )
170
171 @property
172 def nums(self) -> Sequence[int]:
173 """Return array of version numbers: [major, minor, service]."""
174 return [self.major, self.minor, self.service]
175
176
177 def unpack_timestamp(value: int) -> datetime:
178 """Converts timestamp in milliseconds into datetime.
179
180 :param value: number of milliseconds since 1.1.2000 00:00:00; 64-bit integer
181 :return: corresponding datetime
182 :raises SPSDKError: When there is incorrect result of conversion
183 """
184 assert isinstance(value, int)
185 if value < 0 or value > 0xFFFFFFFFFFFFFFFF:
186 raise SPSDKError("Incorrect result of conversion")
187 start = int(datetime(2000, 1, 1, 0, 0, 0, 0, tzinfo=timezone.utc).timestamp() * 1000000)
188 return datetime.fromtimestamp((start + value) / 1000000)