xref: /linux/fs/efivarfs/vars.c (revision 136114e0abf03005e182d75761ab694648e6d388)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Originally from efivars.c
4  *
5  * Copyright (C) 2001,2003,2004 Dell <Matt_Domsch@dell.com>
6  * Copyright (C) 2004 Intel Corporation <matthew.e.tolentino@intel.com>
7  */
8 
9 #include <linux/capability.h>
10 #include <linux/types.h>
11 #include <linux/errno.h>
12 #include <linux/hex.h>
13 #include <linux/init.h>
14 #include <linux/mm.h>
15 #include <linux/module.h>
16 #include <linux/string.h>
17 #include <linux/smp.h>
18 #include <linux/efi.h>
19 #include <linux/device.h>
20 #include <linux/slab.h>
21 #include <linux/ctype.h>
22 #include <linux/ucs2_string.h>
23 
24 #include "internal.h"
25 
26 MODULE_IMPORT_NS("EFIVAR");
27 
28 static bool
29 validate_device_path(efi_char16_t *var_name, int match, u8 *buffer,
30 		     unsigned long len)
31 {
32 	struct efi_generic_dev_path *node;
33 	int offset = 0;
34 
35 	node = (struct efi_generic_dev_path *)buffer;
36 
37 	if (len < sizeof(*node))
38 		return false;
39 
40 	while (offset <= len - sizeof(*node) &&
41 	       node->length >= sizeof(*node) &&
42 		node->length <= len - offset) {
43 		offset += node->length;
44 
45 		if ((node->type == EFI_DEV_END_PATH ||
46 		     node->type == EFI_DEV_END_PATH2) &&
47 		    node->sub_type == EFI_DEV_END_ENTIRE)
48 			return true;
49 
50 		node = (struct efi_generic_dev_path *)(buffer + offset);
51 	}
52 
53 	/*
54 	 * If we're here then either node->length pointed past the end
55 	 * of the buffer or we reached the end of the buffer without
56 	 * finding a device path end node.
57 	 */
58 	return false;
59 }
60 
61 static bool
62 validate_boot_order(efi_char16_t *var_name, int match, u8 *buffer,
63 		    unsigned long len)
64 {
65 	/* An array of 16-bit integers */
66 	if ((len % 2) != 0)
67 		return false;
68 
69 	return true;
70 }
71 
72 static bool
73 validate_load_option(efi_char16_t *var_name, int match, u8 *buffer,
74 		     unsigned long len)
75 {
76 	u16 filepathlength;
77 	int i, desclength = 0, namelen;
78 
79 	namelen = ucs2_strnlen(var_name, EFI_VAR_NAME_LEN);
80 
81 	/* Either "Boot" or "Driver" followed by four digits of hex */
82 	for (i = match; i < match+4; i++) {
83 		if (var_name[i] > 127 ||
84 		    hex_to_bin(var_name[i] & 0xff) < 0)
85 			return true;
86 	}
87 
88 	/* Reject it if there's 4 digits of hex and then further content */
89 	if (namelen > match + 4)
90 		return false;
91 
92 	/* A valid entry must be at least 8 bytes */
93 	if (len < 8)
94 		return false;
95 
96 	filepathlength = buffer[4] | buffer[5] << 8;
97 
98 	/*
99 	 * There's no stored length for the description, so it has to be
100 	 * found by hand
101 	 */
102 	desclength = ucs2_strsize((efi_char16_t *)(buffer + 6), len - 6) + 2;
103 
104 	/* Each boot entry must have a descriptor */
105 	if (!desclength)
106 		return false;
107 
108 	/*
109 	 * If the sum of the length of the description, the claimed filepath
110 	 * length and the original header are greater than the length of the
111 	 * variable, it's malformed
112 	 */
113 	if ((desclength + filepathlength + 6) > len)
114 		return false;
115 
116 	/*
117 	 * And, finally, check the filepath
118 	 */
119 	return validate_device_path(var_name, match, buffer + desclength + 6,
120 				    filepathlength);
121 }
122 
123 static bool
124 validate_uint16(efi_char16_t *var_name, int match, u8 *buffer,
125 		unsigned long len)
126 {
127 	/* A single 16-bit integer */
128 	if (len != 2)
129 		return false;
130 
131 	return true;
132 }
133 
134 static bool
135 validate_ascii_string(efi_char16_t *var_name, int match, u8 *buffer,
136 		      unsigned long len)
137 {
138 	int i;
139 
140 	for (i = 0; i < len; i++) {
141 		if (buffer[i] > 127)
142 			return false;
143 
144 		if (buffer[i] == 0)
145 			return true;
146 	}
147 
148 	return false;
149 }
150 
151 struct variable_validate {
152 	efi_guid_t vendor;
153 	char *name;
154 	bool (*validate)(efi_char16_t *var_name, int match, u8 *data,
155 			 unsigned long len);
156 };
157 
158 /*
159  * This is the list of variables we need to validate, as well as the
160  * whitelist for what we think is safe not to default to immutable.
161  *
162  * If it has a validate() method that's not NULL, it'll go into the
163  * validation routine.  If not, it is assumed valid, but still used for
164  * whitelisting.
165  *
166  * Note that it's sorted by {vendor,name}, but globbed names must come after
167  * any other name with the same prefix.
168  */
169 static const struct variable_validate variable_validate[] = {
170 	{ EFI_GLOBAL_VARIABLE_GUID, "BootNext", validate_uint16 },
171 	{ EFI_GLOBAL_VARIABLE_GUID, "BootOrder", validate_boot_order },
172 	{ EFI_GLOBAL_VARIABLE_GUID, "Boot*", validate_load_option },
173 	{ EFI_GLOBAL_VARIABLE_GUID, "DriverOrder", validate_boot_order },
174 	{ EFI_GLOBAL_VARIABLE_GUID, "Driver*", validate_load_option },
175 	{ EFI_GLOBAL_VARIABLE_GUID, "ConIn", validate_device_path },
176 	{ EFI_GLOBAL_VARIABLE_GUID, "ConInDev", validate_device_path },
177 	{ EFI_GLOBAL_VARIABLE_GUID, "ConOut", validate_device_path },
178 	{ EFI_GLOBAL_VARIABLE_GUID, "ConOutDev", validate_device_path },
179 	{ EFI_GLOBAL_VARIABLE_GUID, "ErrOut", validate_device_path },
180 	{ EFI_GLOBAL_VARIABLE_GUID, "ErrOutDev", validate_device_path },
181 	{ EFI_GLOBAL_VARIABLE_GUID, "Lang", validate_ascii_string },
182 	{ EFI_GLOBAL_VARIABLE_GUID, "OsIndications", NULL },
183 	{ EFI_GLOBAL_VARIABLE_GUID, "PlatformLang", validate_ascii_string },
184 	{ EFI_GLOBAL_VARIABLE_GUID, "Timeout", validate_uint16 },
185 	{ LINUX_EFI_CRASH_GUID, "*", NULL },
186 	{ NULL_GUID, "", NULL },
187 };
188 
189 /*
190  * Check if @var_name matches the pattern given in @match_name.
191  *
192  * @var_name: an array of @len non-NUL characters.
193  * @match_name: a NUL-terminated pattern string, optionally ending in "*". A
194  *              final "*" character matches any trailing characters @var_name,
195  *              including the case when there are none left in @var_name.
196  * @match: on output, the number of non-wildcard characters in @match_name
197  *         that @var_name matches, regardless of the return value.
198  * @return: whether @var_name fully matches @match_name.
199  */
200 static bool
201 variable_matches(const char *var_name, size_t len, const char *match_name,
202 		 int *match)
203 {
204 	for (*match = 0; ; (*match)++) {
205 		char c = match_name[*match];
206 
207 		switch (c) {
208 		case '*':
209 			/* Wildcard in @match_name means we've matched. */
210 			return true;
211 
212 		case '\0':
213 			/* @match_name has ended. Has @var_name too? */
214 			return (*match == len);
215 
216 		default:
217 			/*
218 			 * We've reached a non-wildcard char in @match_name.
219 			 * Continue only if there's an identical character in
220 			 * @var_name.
221 			 */
222 			if (*match < len && c == var_name[*match])
223 				continue;
224 			return false;
225 		}
226 	}
227 }
228 
229 char *
230 efivar_get_utf8name(const efi_char16_t *name16, efi_guid_t *vendor)
231 {
232 	int len = ucs2_utf8size(name16);
233 	char *name;
234 
235 	/* name, plus '-', plus GUID, plus NUL*/
236 	name = kmalloc(len + 1 + EFI_VARIABLE_GUID_LEN + 1, GFP_KERNEL);
237 	if (!name)
238 		return NULL;
239 
240 	ucs2_as_utf8(name, name16, len);
241 
242 	name[len] = '-';
243 
244 	efi_guid_to_str(vendor, name + len + 1);
245 
246 	name[len + EFI_VARIABLE_GUID_LEN+1] = '\0';
247 
248 	/* replace invalid slashes like kobject_set_name_vargs does for /sys/firmware/efi/vars. */
249 	strreplace(name, '/', '!');
250 
251 	return name;
252 }
253 
254 bool
255 efivar_validate(efi_guid_t vendor, efi_char16_t *var_name, u8 *data,
256 		unsigned long data_size)
257 {
258 	int i;
259 	unsigned long utf8_size;
260 	u8 *utf8_name;
261 
262 	utf8_size = ucs2_utf8size(var_name);
263 	utf8_name = kmalloc(utf8_size + 1, GFP_KERNEL);
264 	if (!utf8_name)
265 		return false;
266 
267 	ucs2_as_utf8(utf8_name, var_name, utf8_size);
268 	utf8_name[utf8_size] = '\0';
269 
270 	for (i = 0; variable_validate[i].name[0] != '\0'; i++) {
271 		const char *name = variable_validate[i].name;
272 		int match = 0;
273 
274 		if (efi_guidcmp(vendor, variable_validate[i].vendor))
275 			continue;
276 
277 		if (variable_matches(utf8_name, utf8_size+1, name, &match)) {
278 			if (variable_validate[i].validate == NULL)
279 				break;
280 			kfree(utf8_name);
281 			return variable_validate[i].validate(var_name, match,
282 							     data, data_size);
283 		}
284 	}
285 	kfree(utf8_name);
286 	return true;
287 }
288 
289 bool
290 efivar_variable_is_removable(efi_guid_t vendor, const char *var_name,
291 			     size_t len)
292 {
293 	int i;
294 	bool found = false;
295 	int match = 0;
296 
297 	/*
298 	 * Check if our variable is in the validated variables list
299 	 */
300 	for (i = 0; variable_validate[i].name[0] != '\0'; i++) {
301 		if (efi_guidcmp(variable_validate[i].vendor, vendor))
302 			continue;
303 
304 		if (variable_matches(var_name, len,
305 				     variable_validate[i].name, &match)) {
306 			found = true;
307 			break;
308 		}
309 	}
310 
311 	/*
312 	 * If it's in our list, it is removable.
313 	 */
314 	return found;
315 }
316 
317 /*
318  * Returns the size of variable_name, in bytes, including the
319  * terminating NULL character, or variable_name_size if no NULL
320  * character is found among the first variable_name_size bytes.
321  */
322 static unsigned long var_name_strnsize(efi_char16_t *variable_name,
323 				       unsigned long variable_name_size)
324 {
325 	unsigned long len;
326 	efi_char16_t c;
327 
328 	/*
329 	 * The variable name is, by definition, a NULL-terminated
330 	 * string, so make absolutely sure that variable_name_size is
331 	 * the value we expect it to be. If not, return the real size.
332 	 */
333 	for (len = 2; len <= variable_name_size; len += sizeof(c)) {
334 		c = variable_name[(len / sizeof(c)) - 1];
335 		if (!c)
336 			break;
337 	}
338 
339 	return min(len, variable_name_size);
340 }
341 
342 /*
343  * Print a warning when duplicate EFI variables are encountered and
344  * disable the sysfs workqueue since the firmware is buggy.
345  */
346 static void dup_variable_bug(efi_char16_t *str16, efi_guid_t *vendor_guid,
347 			     unsigned long len16)
348 {
349 	size_t i, len8 = len16 / sizeof(efi_char16_t);
350 	char *str8;
351 
352 	str8 = kzalloc(len8, GFP_KERNEL);
353 	if (!str8)
354 		return;
355 
356 	for (i = 0; i < len8; i++)
357 		str8[i] = str16[i];
358 
359 	printk(KERN_WARNING "efivars: duplicate variable: %s-%pUl\n",
360 	       str8, vendor_guid);
361 	kfree(str8);
362 }
363 
364 /**
365  * efivar_init - build the initial list of EFI variables
366  * @func: callback function to invoke for every variable
367  * @data: function-specific data to pass to @func
368  * @duplicate_check: fail if a duplicate variable is found
369  *
370  * Get every EFI variable from the firmware and invoke @func. @func
371  * should populate the initial dentry and inode tree.
372  *
373  * Returns 0 on success, or a kernel error code on failure.
374  */
375 int efivar_init(int (*func)(efi_char16_t *, efi_guid_t, unsigned long, void *),
376 		void *data, bool duplicate_check)
377 {
378 	unsigned long variable_name_size = 512;
379 	efi_char16_t *variable_name;
380 	efi_status_t status;
381 	efi_guid_t vendor_guid;
382 	int err = 0;
383 
384 	variable_name = kzalloc(variable_name_size, GFP_KERNEL);
385 	if (!variable_name) {
386 		printk(KERN_ERR "efivars: Memory allocation failed.\n");
387 		return -ENOMEM;
388 	}
389 
390 	err = efivar_lock();
391 	if (err)
392 		goto free;
393 
394 	/*
395 	 * A small set of old UEFI implementations reject sizes
396 	 * above a certain threshold, the lowest seen in the wild
397 	 * is 512.
398 	 */
399 
400 	do {
401 		variable_name_size = 512;
402 		BUILD_BUG_ON(EFI_VAR_NAME_LEN < 512);
403 
404 		status = efivar_get_next_variable(&variable_name_size,
405 						  variable_name,
406 						  &vendor_guid);
407 		switch (status) {
408 		case EFI_SUCCESS:
409 			variable_name_size = var_name_strnsize(variable_name,
410 							       variable_name_size);
411 
412 			/*
413 			 * Some firmware implementations return the
414 			 * same variable name on multiple calls to
415 			 * get_next_variable(). Terminate the loop
416 			 * immediately as there is no guarantee that
417 			 * we'll ever see a different variable name,
418 			 * and may end up looping here forever.
419 			 */
420 			if (duplicate_check &&
421 			    efivarfs_variable_is_present(variable_name,
422 							 &vendor_guid, data)) {
423 				dup_variable_bug(variable_name, &vendor_guid,
424 						 variable_name_size);
425 				status = EFI_NOT_FOUND;
426 			} else {
427 				err = func(variable_name, vendor_guid,
428 					   variable_name_size, data);
429 				if (err)
430 					status = EFI_NOT_FOUND;
431 			}
432 			break;
433 		case EFI_UNSUPPORTED:
434 			err = -EOPNOTSUPP;
435 			status = EFI_NOT_FOUND;
436 			break;
437 		case EFI_NOT_FOUND:
438 			break;
439 		case EFI_BUFFER_TOO_SMALL:
440 			pr_warn("efivars: Variable name size exceeds maximum (%lu > 512)\n",
441 				variable_name_size);
442 			status = EFI_NOT_FOUND;
443 			break;
444 		default:
445 			pr_warn("efivars: get_next_variable: status=%lx\n", status);
446 			status = EFI_NOT_FOUND;
447 			break;
448 		}
449 
450 	} while (status != EFI_NOT_FOUND);
451 
452 	efivar_unlock();
453 free:
454 	kfree(variable_name);
455 
456 	return err;
457 }
458 
459 /**
460  * efivar_entry_delete - delete variable
461  * @entry: entry containing variable to delete
462  *
463  * Delete the variable from the firmware. It is the caller's
464  * responsibility to free @entry (by deleting the dentry/inode) once
465  * we return.
466  *
467  * Returns 0 on success, -EINTR if we can't grab the semaphore,
468  * converted EFI status code if set_variable() fails.
469  */
470 int efivar_entry_delete(struct efivar_entry *entry)
471 {
472 	efi_status_t status;
473 	int err;
474 
475 	err = efivar_lock();
476 	if (err)
477 		return err;
478 
479 	status = efivar_set_variable_locked(entry->var.VariableName,
480 					    &entry->var.VendorGuid,
481 					    0, 0, NULL, false);
482 	efivar_unlock();
483 	if (!(status == EFI_SUCCESS || status == EFI_NOT_FOUND))
484 		return efi_status_to_err(status);
485 
486 	return 0;
487 }
488 
489 /**
490  * efivar_entry_size - obtain the size of a variable
491  * @entry: entry for this variable
492  * @size: location to store the variable's size
493  */
494 int efivar_entry_size(struct efivar_entry *entry, unsigned long *size)
495 {
496 	efi_status_t status;
497 	int err;
498 
499 	*size = 0;
500 
501 	err = efivar_lock();
502 	if (err)
503 		return err;
504 
505 	status = efivar_get_variable(entry->var.VariableName,
506 				     &entry->var.VendorGuid, NULL, size, NULL);
507 	efivar_unlock();
508 
509 	if (status != EFI_BUFFER_TOO_SMALL)
510 		return efi_status_to_err(status);
511 
512 	return 0;
513 }
514 
515 /**
516  * __efivar_entry_get - call get_variable()
517  * @entry: read data for this variable
518  * @attributes: variable attributes
519  * @size: size of @data buffer
520  * @data: buffer to store variable data
521  *
522  * The caller MUST call efivar_entry_iter_begin() and
523  * efivar_entry_iter_end() before and after the invocation of this
524  * function, respectively.
525  */
526 int __efivar_entry_get(struct efivar_entry *entry, u32 *attributes,
527 		       unsigned long *size, void *data)
528 {
529 	efi_status_t status;
530 
531 	status = efivar_get_variable(entry->var.VariableName,
532 				     &entry->var.VendorGuid,
533 				     attributes, size, data);
534 
535 	return efi_status_to_err(status);
536 }
537 
538 /**
539  * efivar_entry_get - call get_variable()
540  * @entry: read data for this variable
541  * @attributes: variable attributes
542  * @size: size of @data buffer
543  * @data: buffer to store variable data
544  */
545 int efivar_entry_get(struct efivar_entry *entry, u32 *attributes,
546 		     unsigned long *size, void *data)
547 {
548 	int err;
549 
550 	err = efivar_lock();
551 	if (err)
552 		return err;
553 	err = __efivar_entry_get(entry, attributes, size, data);
554 	efivar_unlock();
555 
556 	return err;
557 }
558 
559 /**
560  * efivar_entry_set_get_size - call set_variable() and get new size (atomic)
561  * @entry: entry containing variable to set and get
562  * @attributes: attributes of variable to be written
563  * @size: size of data buffer
564  * @data: buffer containing data to write
565  * @set: did the set_variable() call succeed?
566  *
567  * This is a pretty special (complex) function. See efivarfs_file_write().
568  *
569  * Atomically call set_variable() for @entry and if the call is
570  * successful, return the new size of the variable from get_variable()
571  * in @size. The success of set_variable() is indicated by @set.
572  *
573  * Returns 0 on success, -EINVAL if the variable data is invalid,
574  * -ENOSPC if the firmware does not have enough available space, or a
575  * converted EFI status code if either of set_variable() or
576  * get_variable() fail.
577  *
578  * If the EFI variable does not exist when calling set_variable()
579  * (EFI_NOT_FOUND).
580  */
581 int efivar_entry_set_get_size(struct efivar_entry *entry, u32 attributes,
582 			      unsigned long *size, void *data, bool *set)
583 {
584 	efi_char16_t *name = entry->var.VariableName;
585 	efi_guid_t *vendor = &entry->var.VendorGuid;
586 	efi_status_t status;
587 	int err;
588 
589 	*set = false;
590 
591 	if (efivar_validate(*vendor, name, data, *size) == false)
592 		return -EINVAL;
593 
594 	/*
595 	 * The lock here protects the get_variable call and the
596 	 * conditional set_variable call
597 	 */
598 	err = efivar_lock();
599 	if (err)
600 		return err;
601 
602 	status = efivar_set_variable_locked(name, vendor, attributes, *size,
603 					    data, false);
604 	if (status != EFI_SUCCESS) {
605 		err = efi_status_to_err(status);
606 		goto out;
607 	}
608 
609 	*set = true;
610 
611 	/*
612 	 * Writing to the variable may have caused a change in size (which
613 	 * could either be an append or an overwrite), or the variable to be
614 	 * deleted. Perform a GetVariable() so we can tell what actually
615 	 * happened.
616 	 */
617 	*size = 0;
618 	status = efivar_get_variable(entry->var.VariableName,
619 				    &entry->var.VendorGuid,
620 				    NULL, size, NULL);
621 
622 	efivar_unlock();
623 
624 	if (status && status != EFI_BUFFER_TOO_SMALL)
625 		return efi_status_to_err(status);
626 
627 	return 0;
628 
629 out:
630 	efivar_unlock();
631 	return err;
632 
633 }
634