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