Debian Codegraph @

src/boot/random-seed.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "efi-efivars.h"
4 #include "efi-log.h"
5 #include "memory-util.h"
6 #include "proto/rng.h"
7 #include "random-seed.h"
8 #include "secure-boot.h"
9 #include "sha256.h"
10 #include "util.h"
11
12 #define RANDOM_MAX_SIZE_MIN (32U)
13 #define RANDOM_MAX_SIZE_MAX (32U*1024U)
14
15 /* SHA256 gives us 256/8=32 bytes */
16 #define HASH_VALUE_SIZE 32
17
18 /* Linux's RNG is 256 bits, so let's provide this much */
19 #define DESIRED_SEED_SIZE 32
20
21 /* Some basic domain separation in case somebody uses this data elsewhere */
22 #define HASH_LABEL "systemd-boot random seed label v1"
23
24 static EFI_STATUS acquire_rng(void *ret, size_t size) {
25 EFI_RNG_PROTOCOL *rng;
26 EFI_STATUS err;
27
28 assert(ret);
29
30 /* Try to acquire the specified number of bytes from the UEFI RNG */
31
32 err = BS->LocateProtocol(MAKE_GUID_PTR(EFI_RNG_PROTOCOL), NULL, (void **) &rng);
33 if (err != EFI_SUCCESS)
34 return err;
35 if (!rng)
36 return EFI_UNSUPPORTED;
37
38 err = rng->GetRNG(rng, NULL, size, ret);
39 /* On some systems the RNG might not be ready during early boot, handle gracefully and don't log. */
40 if (err == EFI_NOT_READY)
41 return err;
42 if (err != EFI_SUCCESS)
43 return log_warning_status(err, "Failed to acquire RNG data, proceeding without: %m");
44 return EFI_SUCCESS;
45 }
46
47 static EFI_STATUS acquire_system_token(void **ret, size_t *ret_size) {
48 _cleanup_free_ char *data = NULL;
49 EFI_STATUS err;
50 size_t size;
51
52 assert(ret);
53 assert(ret_size);
54
55 err = efivar_get_raw(MAKE_GUID_PTR(LOADER), u"LoaderSystemToken", (void**) &data, &size);
56 if (err != EFI_SUCCESS) {
57 if (err != EFI_NOT_FOUND)
58 log_error_status(err, "Failed to read LoaderSystemToken EFI variable: %m");
59 return err;
60 }
61
62 if (size <= 0)
63 return log_error_status(EFI_NOT_FOUND, "System token too short, ignoring.");
64
65 *ret = TAKE_PTR(data);
66 *ret_size = size;
67
68 return EFI_SUCCESS;
69 }
70
71 static void validate_sha256(void) {
72
73 #ifdef EFI_DEBUG
74 /* Let's validate our SHA256 implementation. We stole it from glibc, and converted it to UEFI
75 * style. We better check whether it does the right stuff. We use the simpler test vectors from the
76 * SHA spec. Note that we strip this out in optimization builds. */
77
78 static const struct {
79 const char *string;
80 uint8_t hash[HASH_VALUE_SIZE];
81 } array[] = {
82 { "abc",
83 { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea,
84 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,
85 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,
86 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad }},
87
88 { "",
89 { 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14,
90 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24,
91 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c,
92 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55 }},
93
94 { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
95 { 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8,
96 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39,
97 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67,
98 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1 }},
99
100 { "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
101 { 0xcf, 0x5b, 0x16, 0xa7, 0x78, 0xaf, 0x83, 0x80,
102 0x03, 0x6c, 0xe5, 0x9e, 0x7b, 0x04, 0x92, 0x37,
103 0x0b, 0x24, 0x9b, 0x11, 0xe8, 0xf0, 0x7a, 0x51,
104 0xaf, 0xac, 0x45, 0x03, 0x7a, 0xfe, 0xe9, 0xd1 }},
105 };
106
107 FOREACH_ELEMENT(i, array)
108 assert(memcmp(SHA256_DIRECT(i->string, strlen8(i->string)), i->hash, HASH_VALUE_SIZE) == 0);
109 #endif
110 }
111
112 EFI_STATUS process_random_seed(EFI_FILE *root_dir) {
113 uint8_t random_bytes[DESIRED_SEED_SIZE], hash_key[HASH_VALUE_SIZE];
114 _cleanup_free_ struct linux_efi_random_seed *new_seed_table = NULL;
115 struct linux_efi_random_seed *previous_seed_table = NULL;
116 _cleanup_free_ void *seed = NULL, *system_token = NULL;
117 _cleanup_file_close_ EFI_FILE *handle = NULL;
118 _cleanup_free_ EFI_FILE_INFO *info = NULL;
119 struct sha256_ctx hash;
120 uint64_t uefi_monotonic_counter = 0;
121 size_t size, rsize, wsize;
122 bool seeded_by_efi = false;
123 EFI_STATUS err;
124 EFI_TIME now;
125
126 CLEANUP_ERASE(random_bytes);
127 CLEANUP_ERASE(hash_key);
128 CLEANUP_ERASE(hash);
129
130 assert(root_dir);
131 assert_cc(DESIRED_SEED_SIZE == HASH_VALUE_SIZE);
132
133 validate_sha256();
134
135 /* hash = LABEL || sizeof(input1) || input1 || ... || sizeof(inputN) || inputN */
136 sha256_init_ctx(&hash);
137
138 /* Some basic domain separation in case somebody uses this data elsewhere */
139 sha256_process_bytes(HASH_LABEL, sizeof(HASH_LABEL) - 1, &hash);
140
141 previous_seed_table = find_configuration_table(MAKE_GUID_PTR(LINUX_EFI_RANDOM_SEED_TABLE));
142 if (!previous_seed_table) {
143 size = 0;
144 sha256_process_bytes(&size, sizeof(size), &hash);
145 } else {
146 size = previous_seed_table->size;
147 seeded_by_efi = size >= DESIRED_SEED_SIZE;
148 sha256_process_bytes(&size, sizeof(size), &hash);
149 sha256_process_bytes(previous_seed_table->seed, size, &hash);
150
151 /* Zero and free the previous seed table only at the end after we've managed to install a new
152 * one, so that in case this function fails or aborts, Linux still receives whatever the
153 * previous bootloader chain set. So, the next line of this block is not an explicit_bzero()
154 * call. */
155 }
156
157 /* Request some random data from the UEFI RNG. We don't need this to work safely, but it's a good
158 * idea to use it because it helps us for cases where users mistakenly include a random seed in
159 * golden master images that are replicated many times. */
160 err = acquire_rng(random_bytes, sizeof(random_bytes));
161 if (err != EFI_SUCCESS) {
162 size = 0;
163 /* If we can't get any randomness from EFI itself, then we'll only be relying on what's in
164 * ESP. But ESP is mutable, so if secure boot is enabled, we probably shouldn't trust that
165 * alone, in which case we bail out early. */
166 if (!seeded_by_efi && secure_boot_enabled())
167 return EFI_NOT_FOUND;
168 } else {
169 seeded_by_efi = true;
170 size = sizeof(random_bytes);
171 }
172 sha256_process_bytes(&size, sizeof(size), &hash);
173 sha256_process_bytes(random_bytes, size, &hash);
174
175 /* Get some system specific seed that the installer might have placed in an EFI variable. We include
176 * it in our hash. This is protection against golden master image sloppiness, and it remains on the
177 * system, even when disk images are duplicated or swapped out. */
178 size = 0;
179 err = acquire_system_token(&system_token, &size);
180 if ((err != EFI_SUCCESS || size < DESIRED_SEED_SIZE) && !seeded_by_efi)
181 return err;
182 sha256_process_bytes(&size, sizeof(size), &hash);
183 if (system_token) {
184 sha256_process_bytes(system_token, size, &hash);
185 explicit_bzero_safe(system_token, size);
186 }
187
188 bool created = false;
189 err = root_dir->Open(
190 root_dir,
191 &handle,
192 (char16_t *) u"\\loader\\random-seed",
193 EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE,
194 0);
195 if (err == EFI_NOT_FOUND && seeded_by_efi) {
196 /* If the file does not exist, but we are reasonably well seeded, create the seed file */
197 created = true;
198 err = root_dir->Open(
199 root_dir,
200 &handle,
201 (char16_t *) u"\\loader\\random-seed",
202 EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE | EFI_FILE_MODE_CREATE,
203 0);
204 }
205 if (err != EFI_SUCCESS) {
206 if (!IN_SET(err, EFI_NOT_FOUND, EFI_WRITE_PROTECTED))
207 log_error_status(err, "Failed to open random seed file: %m");
208 return err;
209 }
210
211 if (!created) {
212 err = get_file_info(handle, &info, /* ret_size= */ NULL);
213 if (err != EFI_SUCCESS)
214 return log_error_status(err, "Failed to get file info for random seed: %m");
215
216 /* Treat a short file just like a freshly created one for robustness reasons: consider a case
217 * where in a previous run a file was just created and the system was then powered off. In
218 * such a case the file will already exist, but be too short. */
219 created = info->FileSize < RANDOM_MAX_SIZE_MIN;
220 }
221
222 if (created) {
223 size = 0;
224 sha256_process_bytes(&size, sizeof(size), &hash);
225 } else {
226 size = info->FileSize;
227 if (size > RANDOM_MAX_SIZE_MAX)
228 return log_error_status(EFI_INVALID_PARAMETER, "Random seed file is too large.");
229
230 seed = xmalloc(size);
231 rsize = size;
232 err = handle->Read(handle, &rsize, seed);
233 if (err != EFI_SUCCESS)
234 return log_error_status(err, "Failed to read random seed file: %m");
235 if (rsize != size) {
236 explicit_bzero_safe(seed, rsize);
237 return log_error_status(EFI_PROTOCOL_ERROR, "Short read on random seed file.");
238 }
239
240 sha256_process_bytes(&size, sizeof(size), &hash);
241 sha256_process_bytes(seed, size, &hash);
242 explicit_bzero_safe(seed, size);
243
244 err = handle->SetPosition(handle, 0);
245 if (err != EFI_SUCCESS)
246 return log_error_status(err, "Failed to seek to beginning of random seed file: %m");
247 }
248
249 /* Let's also include the UEFI monotonic counter (which is supposedly increasing on every single
250 * boot) in the hash, so that even if the changes to the ESP for some reason should not be
251 * persistent, the random seed we generate will still be different on every single boot. */
252 err = BS->GetNextMonotonicCount(&uefi_monotonic_counter);
253 if (err != EFI_SUCCESS && !seeded_by_efi)
254 return log_error_status(err, "Failed to acquire UEFI monotonic counter: %m");
255 size = sizeof(uefi_monotonic_counter);
256 sha256_process_bytes(&size, sizeof(size), &hash);
257 sha256_process_bytes(&uefi_monotonic_counter, size, &hash);
258
259 err = RT->GetTime(&now, NULL);
260 size = err == EFI_SUCCESS ? sizeof(now) : 0; /* Known to be flaky, so don't bark on error. */
261 sha256_process_bytes(&size, sizeof(size), &hash);
262 sha256_process_bytes(&now, size, &hash);
263
264 /* hash_key = HASH(hash) */
265 sha256_finish_ctx(&hash, hash_key);
266
267 /* hash = hash_key || 0 */
268 sha256_init_ctx(&hash);
269 sha256_process_bytes(hash_key, sizeof(hash_key), &hash);
270 sha256_process_bytes(&(const uint8_t){ 0 }, sizeof(uint8_t), &hash);
271 /* random_bytes = HASH(hash) */
272 sha256_finish_ctx(&hash, random_bytes);
273
274 size = sizeof(random_bytes);
275 /* If the file size is too large, zero out the remaining bytes on disk. */
276 if (!created && size < info->FileSize) {
277 err = handle->SetPosition(handle, size);
278 if (err != EFI_SUCCESS)
279 return log_error_status(err, "Failed to seek to offset of random seed file: %m");
280 wsize = info->FileSize - size;
281 err = handle->Write(handle, &wsize, seed /* All zeros now */);
282 if (err != EFI_SUCCESS)
283 return log_error_status(err, "Failed to write random seed file: %m");
284 if (wsize != info->FileSize - size)
285 return log_error_status(EFI_PROTOCOL_ERROR, "Short write on random seed file.");
286 err = handle->Flush(handle);
287 if (err != EFI_SUCCESS)
288 return log_error_status(err, "Failed to flush random seed file: %m");
289 err = handle->SetPosition(handle, 0);
290 if (err != EFI_SUCCESS)
291 return log_error_status(err, "Failed to seek to beginning of random seed file: %m");
292
293 /* We could truncate the file here with something like:
294 *
295 * info->FileSize = size;
296 * err = handle->SetInfo(handle, &GenericFileInfo, info->Size, info);
297 * if (err != EFI_SUCCESS)
298 * return log_error_status(err, "Failed to truncate random seed file: %u");
299 *
300 * But this is considered slightly risky, because EFI filesystem drivers are a little bit
301 * flimsy. So instead we rely on userspace eventually truncating this when it writes a new
302 * seed. For now the best we do is zero it. */
303 }
304 /* Update the random seed on disk before we use it */
305 wsize = size;
306 err = handle->Write(handle, &wsize, random_bytes);
307 if (err != EFI_SUCCESS)
308 return log_error_status(err, "Failed to write random seed file: %m");
309 if (wsize != size)
310 return log_error_status(EFI_PROTOCOL_ERROR, "Short write on random seed file.");
311 err = handle->Flush(handle);
312 if (err != EFI_SUCCESS)
313 return log_error_status(err, "Failed to flush random seed file: %m");
314
315 err = BS->AllocatePool(EfiACPIReclaimMemory,
316 offsetof(struct linux_efi_random_seed, seed) + DESIRED_SEED_SIZE,
317 (void **) &new_seed_table);
318 if (err != EFI_SUCCESS)
319 return log_error_status(err, "Failed to allocate EFI table for random seed: %m");
320 new_seed_table->size = DESIRED_SEED_SIZE;
321
322 /* hash = hash_key || 1 */
323 sha256_init_ctx(&hash);
324 sha256_process_bytes(hash_key, sizeof(hash_key), &hash);
325 sha256_process_bytes(&(const uint8_t){ 1 }, sizeof(uint8_t), &hash);
326 /* new_seed_table->seed = HASH(hash) */
327 sha256_finish_ctx(&hash, new_seed_table->seed);
328
329 err = BS->InstallConfigurationTable(MAKE_GUID_PTR(LINUX_EFI_RANDOM_SEED_TABLE), new_seed_table);
330 if (err != EFI_SUCCESS)
331 return log_error_status(err, "Failed to install EFI table for random seed: %m");
332 TAKE_PTR(new_seed_table);
333
334 if (previous_seed_table) {
335 /* Now that we've succeeded in installing the new table, we can safely nuke the old one. */
336 explicit_bzero_safe(previous_seed_table->seed, previous_seed_table->size);
337 explicit_bzero_safe(previous_seed_table, sizeof(*previous_seed_table));
338 free(previous_seed_table);
339 }
340
341 return EFI_SUCCESS;
342 }