command: Remove the cmd_tbl_t typedef
[oweals/u-boot.git] / lib / efi_loader / efi_variable.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * UEFI runtime variable services
4  *
5  * Copyright (c) 2017 Rob Clark
6  */
7
8 #include <common.h>
9 #include <efi_loader.h>
10 #include <env.h>
11 #include <env_internal.h>
12 #include <hexdump.h>
13 #include <malloc.h>
14 #include <rtc.h>
15 #include <search.h>
16 #include <uuid.h>
17 #include <crypto/pkcs7_parser.h>
18 #include <linux/compat.h>
19 #include <u-boot/crc.h>
20
21 enum efi_secure_mode {
22         EFI_MODE_SETUP,
23         EFI_MODE_USER,
24         EFI_MODE_AUDIT,
25         EFI_MODE_DEPLOYED,
26 };
27
28 const efi_guid_t efi_guid_cert_type_pkcs7 = EFI_CERT_TYPE_PKCS7_GUID;
29 static bool efi_secure_boot;
30 static int efi_secure_mode;
31 static u8 efi_vendor_keys;
32
33 #define READ_ONLY BIT(31)
34
35 static efi_status_t efi_get_variable_common(u16 *variable_name,
36                                             const efi_guid_t *vendor,
37                                             u32 *attributes,
38                                             efi_uintn_t *data_size, void *data);
39
40 static efi_status_t efi_set_variable_common(u16 *variable_name,
41                                             const efi_guid_t *vendor,
42                                             u32 attributes,
43                                             efi_uintn_t data_size,
44                                             const void *data,
45                                             bool ro_check);
46
47 /*
48  * Mapping between EFI variables and u-boot variables:
49  *
50  *   efi_$guid_$varname = {attributes}(type)value
51  *
52  * For example:
53  *
54  *   efi_8be4df61-93ca-11d2-aa0d-00e098032b8c_OsIndicationsSupported=
55  *      "{ro,boot,run}(blob)0000000000000000"
56  *   efi_8be4df61-93ca-11d2-aa0d-00e098032b8c_BootOrder=
57  *      "(blob)00010000"
58  *
59  * The attributes are a comma separated list of these possible
60  * attributes:
61  *
62  *   + ro   - read-only
63  *   + boot - boot-services access
64  *   + run  - runtime access
65  *
66  * NOTE: with current implementation, no variables are available after
67  * ExitBootServices, and all are persisted (if possible).
68  *
69  * If not specified, the attributes default to "{boot}".
70  *
71  * The required type is one of:
72  *
73  *   + utf8 - raw utf8 string
74  *   + blob - arbitrary length hex string
75  *
76  * Maybe a utf16 type would be useful to for a string value to be auto
77  * converted to utf16?
78  */
79
80 #define PREFIX_LEN (strlen("efi_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx_"))
81
82 /**
83  * efi_to_native() - convert the UEFI variable name and vendor GUID to U-Boot
84  *                   variable name
85  *
86  * The U-Boot variable name is a concatenation of prefix 'efi', the hexstring
87  * encoded vendor GUID, and the UTF-8 encoded UEFI variable name separated by
88  * underscores, e.g. 'efi_8be4df61-93ca-11d2-aa0d-00e098032b8c_BootOrder'.
89  *
90  * @native:             pointer to pointer to U-Boot variable name
91  * @variable_name:      UEFI variable name
92  * @vendor:             vendor GUID
93  * Return:              status code
94  */
95 static efi_status_t efi_to_native(char **native, const u16 *variable_name,
96                                   const efi_guid_t *vendor)
97 {
98         size_t len;
99         char *pos;
100
101         len = PREFIX_LEN + utf16_utf8_strlen(variable_name) + 1;
102         *native = malloc(len);
103         if (!*native)
104                 return EFI_OUT_OF_RESOURCES;
105
106         pos = *native;
107         pos += sprintf(pos, "efi_%pUl_", vendor);
108         utf16_utf8_strcpy(&pos, variable_name);
109
110         return EFI_SUCCESS;
111 }
112
113 /**
114  * prefix() - skip over prefix
115  *
116  * Skip over a prefix string.
117  *
118  * @str:        string with prefix
119  * @prefix:     prefix string
120  * Return:      string without prefix, or NULL if prefix not found
121  */
122 static const char *prefix(const char *str, const char *prefix)
123 {
124         size_t n = strlen(prefix);
125         if (!strncmp(prefix, str, n))
126                 return str + n;
127         return NULL;
128 }
129
130 /**
131  * parse_attr() - decode attributes part of variable value
132  *
133  * Convert the string encoded attributes of a UEFI variable to a bit mask.
134  * TODO: Several attributes are not supported.
135  *
136  * @str:        value of U-Boot variable
137  * @attrp:      pointer to UEFI attributes
138  * @timep:      pointer to time attribute
139  * Return:      pointer to remainder of U-Boot variable value
140  */
141 static const char *parse_attr(const char *str, u32 *attrp, u64 *timep)
142 {
143         u32 attr = 0;
144         char sep = '{';
145
146         if (*str != '{') {
147                 *attrp = EFI_VARIABLE_BOOTSERVICE_ACCESS;
148                 return str;
149         }
150
151         while (*str == sep) {
152                 const char *s;
153
154                 str++;
155
156                 if ((s = prefix(str, "ro"))) {
157                         attr |= READ_ONLY;
158                 } else if ((s = prefix(str, "nv"))) {
159                         attr |= EFI_VARIABLE_NON_VOLATILE;
160                 } else if ((s = prefix(str, "boot"))) {
161                         attr |= EFI_VARIABLE_BOOTSERVICE_ACCESS;
162                 } else if ((s = prefix(str, "run"))) {
163                         attr |= EFI_VARIABLE_RUNTIME_ACCESS;
164                 } else if ((s = prefix(str, "time="))) {
165                         attr |= EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
166                         hex2bin((u8 *)timep, s, sizeof(*timep));
167                         s += sizeof(*timep) * 2;
168                 } else if (*str == '}') {
169                         break;
170                 } else {
171                         printf("invalid attribute: %s\n", str);
172                         break;
173                 }
174
175                 str = s;
176                 sep = ',';
177         }
178
179         str++;
180
181         *attrp = attr;
182
183         return str;
184 }
185
186 /**
187  * efi_set_secure_state - modify secure boot state variables
188  * @sec_boot:           value of SecureBoot
189  * @setup_mode:         value of SetupMode
190  * @audit_mode:         value of AuditMode
191  * @deployed_mode:      value of DeployedMode
192  *
193  * Modify secure boot stat-related variables as indicated.
194  *
195  * Return:              status code
196  */
197 static efi_status_t efi_set_secure_state(int sec_boot, int setup_mode,
198                                          int audit_mode, int deployed_mode)
199 {
200         u32 attributes;
201         efi_status_t ret;
202
203         attributes = EFI_VARIABLE_BOOTSERVICE_ACCESS |
204                      EFI_VARIABLE_RUNTIME_ACCESS |
205                      READ_ONLY;
206         ret = efi_set_variable_common(L"SecureBoot", &efi_global_variable_guid,
207                                       attributes, sizeof(sec_boot), &sec_boot,
208                                       false);
209         if (ret != EFI_SUCCESS)
210                 goto err;
211
212         ret = efi_set_variable_common(L"SetupMode", &efi_global_variable_guid,
213                                       attributes, sizeof(setup_mode),
214                                       &setup_mode, false);
215         if (ret != EFI_SUCCESS)
216                 goto err;
217
218         ret = efi_set_variable_common(L"AuditMode", &efi_global_variable_guid,
219                                       attributes, sizeof(audit_mode),
220                                       &audit_mode, false);
221         if (ret != EFI_SUCCESS)
222                 goto err;
223
224         ret = efi_set_variable_common(L"DeployedMode",
225                                       &efi_global_variable_guid, attributes,
226                                       sizeof(deployed_mode), &deployed_mode,
227                                       false);
228 err:
229         return ret;
230 }
231
232 /**
233  * efi_transfer_secure_state - handle a secure boot state transition
234  * @mode:       new state
235  *
236  * Depending on @mode, secure boot related variables are updated.
237  * Those variables are *read-only* for users, efi_set_variable_common()
238  * is called here.
239  *
240  * Return:      status code
241  */
242 static efi_status_t efi_transfer_secure_state(enum efi_secure_mode mode)
243 {
244         efi_status_t ret;
245
246         debug("Switching secure state from %d to %d\n", efi_secure_mode, mode);
247
248         if (mode == EFI_MODE_DEPLOYED) {
249                 ret = efi_set_secure_state(1, 0, 0, 1);
250                 if (ret != EFI_SUCCESS)
251                         goto err;
252
253                 efi_secure_boot = true;
254         } else if (mode == EFI_MODE_AUDIT) {
255                 ret = efi_set_variable_common(L"PK", &efi_global_variable_guid,
256                                               EFI_VARIABLE_BOOTSERVICE_ACCESS |
257                                               EFI_VARIABLE_RUNTIME_ACCESS,
258                                               0, NULL, false);
259                 if (ret != EFI_SUCCESS)
260                         goto err;
261
262                 ret = efi_set_secure_state(0, 1, 1, 0);
263                 if (ret != EFI_SUCCESS)
264                         goto err;
265
266                 efi_secure_boot = true;
267         } else if (mode == EFI_MODE_USER) {
268                 ret = efi_set_secure_state(1, 0, 0, 0);
269                 if (ret != EFI_SUCCESS)
270                         goto err;
271
272                 efi_secure_boot = true;
273         } else if (mode == EFI_MODE_SETUP) {
274                 ret = efi_set_secure_state(0, 1, 0, 0);
275                 if (ret != EFI_SUCCESS)
276                         goto err;
277         } else {
278                 return EFI_INVALID_PARAMETER;
279         }
280
281         efi_secure_mode = mode;
282
283         return EFI_SUCCESS;
284
285 err:
286         /* TODO: What action should be taken here? */
287         printf("ERROR: Secure state transition failed\n");
288         return ret;
289 }
290
291 /**
292  * efi_init_secure_state - initialize secure boot state
293  *
294  * Return:      status code
295  */
296 static efi_status_t efi_init_secure_state(void)
297 {
298         enum efi_secure_mode mode;
299         efi_uintn_t size;
300         efi_status_t ret;
301
302         /*
303          * TODO:
304          * Since there is currently no "platform-specific" installation
305          * method of Platform Key, we can't say if VendorKeys is 0 or 1
306          * precisely.
307          */
308
309         size = 0;
310         ret = efi_get_variable_common(L"PK", &efi_global_variable_guid,
311                                       NULL, &size, NULL);
312         if (ret == EFI_BUFFER_TOO_SMALL) {
313                 if (IS_ENABLED(CONFIG_EFI_SECURE_BOOT))
314                         mode = EFI_MODE_USER;
315                 else
316                         mode = EFI_MODE_SETUP;
317
318                 efi_vendor_keys = 0;
319         } else if (ret == EFI_NOT_FOUND) {
320                 mode = EFI_MODE_SETUP;
321                 efi_vendor_keys = 1;
322         } else {
323                 goto err;
324         }
325
326         ret = efi_transfer_secure_state(mode);
327         if (ret == EFI_SUCCESS)
328                 ret = efi_set_variable_common(L"VendorKeys",
329                                               &efi_global_variable_guid,
330                                               EFI_VARIABLE_BOOTSERVICE_ACCESS |
331                                               EFI_VARIABLE_RUNTIME_ACCESS |
332                                               READ_ONLY,
333                                               sizeof(efi_vendor_keys),
334                                               &efi_vendor_keys, false);
335
336 err:
337         return ret;
338 }
339
340 /**
341  * efi_secure_boot_enabled - return if secure boot is enabled or not
342  *
343  * Return:      true if enabled, false if disabled
344  */
345 bool efi_secure_boot_enabled(void)
346 {
347         return efi_secure_boot;
348 }
349
350 #ifdef CONFIG_EFI_SECURE_BOOT
351 static u8 pkcs7_hdr[] = {
352         /* SEQUENCE */
353         0x30, 0x82, 0x05, 0xc7,
354         /* OID: pkcs7-signedData */
355         0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02,
356         /* Context Structured? */
357         0xa0, 0x82, 0x05, 0xb8,
358 };
359
360 /**
361  * efi_variable_parse_signature - parse a signature in variable
362  * @buf:        Pointer to variable's value
363  * @buflen:     Length of @buf
364  *
365  * Parse a signature embedded in variable's value and instantiate
366  * a pkcs7_message structure. Since pkcs7_parse_message() accepts only
367  * pkcs7's signedData, some header needed be prepended for correctly
368  * parsing authentication data, particularly for variable's.
369  *
370  * Return:      Pointer to pkcs7_message structure on success, NULL on error
371  */
372 static struct pkcs7_message *efi_variable_parse_signature(const void *buf,
373                                                           size_t buflen)
374 {
375         u8 *ebuf;
376         size_t ebuflen, len;
377         struct pkcs7_message *msg;
378
379         /*
380          * This is the best assumption to check if the binary is
381          * already in a form of pkcs7's signedData.
382          */
383         if (buflen > sizeof(pkcs7_hdr) &&
384             !memcmp(&((u8 *)buf)[4], &pkcs7_hdr[4], 11)) {
385                 msg = pkcs7_parse_message(buf, buflen);
386                 goto out;
387         }
388
389         /*
390          * Otherwise, we should add a dummy prefix sequence for pkcs7
391          * message parser to be able to process.
392          * NOTE: EDK2 also uses similar hack in WrapPkcs7Data()
393          * in CryptoPkg/Library/BaseCryptLib/Pk/CryptPkcs7VerifyCommon.c
394          * TODO:
395          * The header should be composed in a more refined manner.
396          */
397         debug("Makeshift prefix added to authentication data\n");
398         ebuflen = sizeof(pkcs7_hdr) + buflen;
399         if (ebuflen <= 0x7f) {
400                 debug("Data is too short\n");
401                 return NULL;
402         }
403
404         ebuf = malloc(ebuflen);
405         if (!ebuf) {
406                 debug("Out of memory\n");
407                 return NULL;
408         }
409
410         memcpy(ebuf, pkcs7_hdr, sizeof(pkcs7_hdr));
411         memcpy(ebuf + sizeof(pkcs7_hdr), buf, buflen);
412         len = ebuflen - 4;
413         ebuf[2] = (len >> 8) & 0xff;
414         ebuf[3] = len & 0xff;
415         len = ebuflen - 0x13;
416         ebuf[0x11] = (len >> 8) & 0xff;
417         ebuf[0x12] = len & 0xff;
418
419         msg = pkcs7_parse_message(ebuf, ebuflen);
420
421         free(ebuf);
422
423 out:
424         if (IS_ERR(msg))
425                 return NULL;
426
427         return msg;
428 }
429
430 /**
431  * efi_variable_authenticate - authenticate a variable
432  * @variable:   Variable name in u16
433  * @vendor:     Guid of variable
434  * @data_size:  Size of @data
435  * @data:       Pointer to variable's value
436  * @given_attr: Attributes to be given at SetVariable()
437  * @env_attr:   Attributes that an existing variable holds
438  * @time:       signed time that an existing variable holds
439  *
440  * Called by efi_set_variable() to verify that the input is correct.
441  * Will replace the given data pointer with another that points to
442  * the actual data to store in the internal memory.
443  * On success, @data and @data_size will be replaced with variable's
444  * actual data, excluding authentication data, and its size, and variable's
445  * attributes and signed time will also be returned in @env_attr and @time,
446  * respectively.
447  *
448  * Return:      status code
449  */
450 static efi_status_t efi_variable_authenticate(u16 *variable,
451                                               const efi_guid_t *vendor,
452                                               efi_uintn_t *data_size,
453                                               const void **data, u32 given_attr,
454                                               u32 *env_attr, u64 *time)
455 {
456         const struct efi_variable_authentication_2 *auth;
457         struct efi_signature_store *truststore, *truststore2;
458         struct pkcs7_message *var_sig;
459         struct efi_image_regions *regs;
460         struct efi_time timestamp;
461         struct rtc_time tm;
462         u64 new_time;
463         efi_status_t ret;
464
465         var_sig = NULL;
466         truststore = NULL;
467         truststore2 = NULL;
468         regs = NULL;
469         ret = EFI_SECURITY_VIOLATION;
470
471         if (*data_size < sizeof(struct efi_variable_authentication_2))
472                 goto err;
473
474         /* authentication data */
475         auth = *data;
476         if (*data_size < (sizeof(auth->time_stamp)
477                                 + auth->auth_info.hdr.dwLength))
478                 goto err;
479
480         if (guidcmp(&auth->auth_info.cert_type, &efi_guid_cert_type_pkcs7))
481                 goto err;
482
483         *data += sizeof(auth->time_stamp) + auth->auth_info.hdr.dwLength;
484         *data_size -= (sizeof(auth->time_stamp)
485                                 + auth->auth_info.hdr.dwLength);
486
487         memcpy(&timestamp, &auth->time_stamp, sizeof(timestamp));
488         memset(&tm, 0, sizeof(tm));
489         tm.tm_year = timestamp.year;
490         tm.tm_mon = timestamp.month;
491         tm.tm_mday = timestamp.day;
492         tm.tm_hour = timestamp.hour;
493         tm.tm_min = timestamp.minute;
494         tm.tm_sec = timestamp.second;
495         new_time = rtc_mktime(&tm);
496
497         if (!efi_secure_boot_enabled()) {
498                 /* finished checking */
499                 *time = new_time;
500                 return EFI_SUCCESS;
501         }
502
503         if (new_time <= *time)
504                 goto err;
505
506         /* data to be digested */
507         regs = calloc(sizeof(*regs) + sizeof(struct image_region) * 5, 1);
508         if (!regs)
509                 goto err;
510         regs->max = 5;
511         efi_image_region_add(regs, (uint8_t *)variable,
512                              (uint8_t *)variable
513                                 + u16_strlen(variable) * sizeof(u16), 1);
514         efi_image_region_add(regs, (uint8_t *)vendor,
515                              (uint8_t *)vendor + sizeof(*vendor), 1);
516         efi_image_region_add(regs, (uint8_t *)&given_attr,
517                              (uint8_t *)&given_attr + sizeof(given_attr), 1);
518         efi_image_region_add(regs, (uint8_t *)&timestamp,
519                              (uint8_t *)&timestamp + sizeof(timestamp), 1);
520         efi_image_region_add(regs, (uint8_t *)*data,
521                              (uint8_t *)*data + *data_size, 1);
522
523         /* variable's signature list */
524         if (auth->auth_info.hdr.dwLength < sizeof(auth->auth_info))
525                 goto err;
526         var_sig = efi_variable_parse_signature(auth->auth_info.cert_data,
527                                                auth->auth_info.hdr.dwLength
528                                                    - sizeof(auth->auth_info));
529         if (!var_sig) {
530                 debug("Parsing variable's signature failed\n");
531                 goto err;
532         }
533
534         /* signature database used for authentication */
535         if (u16_strcmp(variable, L"PK") == 0 ||
536             u16_strcmp(variable, L"KEK") == 0) {
537                 /* with PK */
538                 truststore = efi_sigstore_parse_sigdb(L"PK");
539                 if (!truststore)
540                         goto err;
541         } else if (u16_strcmp(variable, L"db") == 0 ||
542                    u16_strcmp(variable, L"dbx") == 0) {
543                 /* with PK and KEK */
544                 truststore = efi_sigstore_parse_sigdb(L"KEK");
545                 truststore2 = efi_sigstore_parse_sigdb(L"PK");
546
547                 if (!truststore) {
548                         if (!truststore2)
549                                 goto err;
550
551                         truststore = truststore2;
552                         truststore2 = NULL;
553                 }
554         } else {
555                 /* TODO: support private authenticated variables */
556                 goto err;
557         }
558
559         /* verify signature */
560         if (efi_signature_verify_with_sigdb(regs, var_sig, truststore, NULL)) {
561                 debug("Verified\n");
562         } else {
563                 if (truststore2 &&
564                     efi_signature_verify_with_sigdb(regs, var_sig,
565                                                     truststore2, NULL)) {
566                         debug("Verified\n");
567                 } else {
568                         debug("Verifying variable's signature failed\n");
569                         goto err;
570                 }
571         }
572
573         /* finished checking */
574         *time = rtc_mktime(&tm);
575         ret = EFI_SUCCESS;
576
577 err:
578         efi_sigstore_free(truststore);
579         efi_sigstore_free(truststore2);
580         pkcs7_free_message(var_sig);
581         free(regs);
582
583         return ret;
584 }
585 #else
586 static efi_status_t efi_variable_authenticate(u16 *variable,
587                                               const efi_guid_t *vendor,
588                                               efi_uintn_t *data_size,
589                                               const void **data, u32 given_attr,
590                                               u32 *env_attr, u64 *time)
591 {
592         return EFI_SUCCESS;
593 }
594 #endif /* CONFIG_EFI_SECURE_BOOT */
595
596 static efi_status_t efi_get_variable_common(u16 *variable_name,
597                                             const efi_guid_t *vendor,
598                                             u32 *attributes,
599                                             efi_uintn_t *data_size, void *data)
600 {
601         char *native_name;
602         efi_status_t ret;
603         unsigned long in_size;
604         const char *val = NULL, *s;
605         u64 time = 0;
606         u32 attr;
607
608         if (!variable_name || !vendor || !data_size)
609                 return EFI_EXIT(EFI_INVALID_PARAMETER);
610
611         ret = efi_to_native(&native_name, variable_name, vendor);
612         if (ret)
613                 return ret;
614
615         EFI_PRINT("get '%s'\n", native_name);
616
617         val = env_get(native_name);
618         free(native_name);
619         if (!val)
620                 return EFI_NOT_FOUND;
621
622         val = parse_attr(val, &attr, &time);
623
624         in_size = *data_size;
625
626         if ((s = prefix(val, "(blob)"))) {
627                 size_t len = strlen(s);
628
629                 /* number of hexadecimal digits must be even */
630                 if (len & 1)
631                         return EFI_DEVICE_ERROR;
632
633                 /* two characters per byte: */
634                 len /= 2;
635                 *data_size = len;
636
637                 if (in_size < len) {
638                         ret = EFI_BUFFER_TOO_SMALL;
639                         goto out;
640                 }
641
642                 if (!data) {
643                         debug("Variable with no data shouldn't exist.\n");
644                         return EFI_INVALID_PARAMETER;
645                 }
646
647                 if (hex2bin(data, s, len))
648                         return EFI_DEVICE_ERROR;
649
650                 EFI_PRINT("got value: \"%s\"\n", s);
651         } else if ((s = prefix(val, "(utf8)"))) {
652                 unsigned len = strlen(s) + 1;
653
654                 *data_size = len;
655
656                 if (in_size < len) {
657                         ret = EFI_BUFFER_TOO_SMALL;
658                         goto out;
659                 }
660
661                 if (!data) {
662                         debug("Variable with no data shouldn't exist.\n");
663                         return EFI_INVALID_PARAMETER;
664                 }
665
666                 memcpy(data, s, len);
667                 ((char *)data)[len] = '\0';
668
669                 EFI_PRINT("got value: \"%s\"\n", (char *)data);
670         } else {
671                 EFI_PRINT("invalid value: '%s'\n", val);
672                 return EFI_DEVICE_ERROR;
673         }
674
675 out:
676         if (attributes)
677                 *attributes = attr & EFI_VARIABLE_MASK;
678
679         return ret;
680 }
681
682 /**
683  * efi_efi_get_variable() - retrieve value of a UEFI variable
684  *
685  * This function implements the GetVariable runtime service.
686  *
687  * See the Unified Extensible Firmware Interface (UEFI) specification for
688  * details.
689  *
690  * @variable_name:      name of the variable
691  * @vendor:             vendor GUID
692  * @attributes:         attributes of the variable
693  * @data_size:          size of the buffer to which the variable value is copied
694  * @data:               buffer to which the variable value is copied
695  * Return:              status code
696  */
697 efi_status_t EFIAPI efi_get_variable(u16 *variable_name,
698                                      const efi_guid_t *vendor, u32 *attributes,
699                                      efi_uintn_t *data_size, void *data)
700 {
701         efi_status_t ret;
702
703         EFI_ENTRY("\"%ls\" %pUl %p %p %p", variable_name, vendor, attributes,
704                   data_size, data);
705
706         ret = efi_get_variable_common(variable_name, vendor, attributes,
707                                       data_size, data);
708         return EFI_EXIT(ret);
709 }
710
711 static char *efi_variables_list;
712 static char *efi_cur_variable;
713
714 /**
715  * parse_uboot_variable() - parse a u-boot variable and get uefi-related
716  *                          information
717  * @variable:           whole data of u-boot variable (ie. name=value)
718  * @variable_name_size: size of variable_name buffer in byte
719  * @variable_name:      name of uefi variable in u16, null-terminated
720  * @vendor:             vendor's guid
721  * @attributes:         attributes
722  *
723  * A uefi variable is encoded into a u-boot variable as described above.
724  * This function parses such a u-boot variable and retrieve uefi-related
725  * information into respective parameters. In return, variable_name_size
726  * is the size of variable name including NULL.
727  *
728  * Return:              EFI_SUCCESS if parsing is OK, EFI_NOT_FOUND when
729  *                      the entire variable list has been returned,
730  *                      otherwise non-zero status code
731  */
732 static efi_status_t parse_uboot_variable(char *variable,
733                                          efi_uintn_t *variable_name_size,
734                                          u16 *variable_name,
735                                          const efi_guid_t *vendor,
736                                          u32 *attributes)
737 {
738         char *guid, *name, *end, c;
739         size_t name_len;
740         efi_uintn_t old_variable_name_size;
741         u64 time;
742         u16 *p;
743
744         guid = strchr(variable, '_');
745         if (!guid)
746                 return EFI_INVALID_PARAMETER;
747         guid++;
748         name = strchr(guid, '_');
749         if (!name)
750                 return EFI_INVALID_PARAMETER;
751         name++;
752         end = strchr(name, '=');
753         if (!end)
754                 return EFI_INVALID_PARAMETER;
755
756         name_len = end - name;
757         old_variable_name_size = *variable_name_size;
758         *variable_name_size = sizeof(u16) * (name_len + 1);
759         if (old_variable_name_size < *variable_name_size)
760                 return EFI_BUFFER_TOO_SMALL;
761
762         end++; /* point to value */
763
764         /* variable name */
765         p = variable_name;
766         utf8_utf16_strncpy(&p, name, name_len);
767         variable_name[name_len] = 0;
768
769         /* guid */
770         c = *(name - 1);
771         *(name - 1) = '\0'; /* guid need be null-terminated here */
772         if (uuid_str_to_bin(guid, (unsigned char *)vendor,
773                             UUID_STR_FORMAT_GUID))
774                 /* The only error would be EINVAL. */
775                 return EFI_INVALID_PARAMETER;
776         *(name - 1) = c;
777
778         /* attributes */
779         parse_attr(end, attributes, &time);
780
781         return EFI_SUCCESS;
782 }
783
784 /**
785  * efi_get_next_variable_name() - enumerate the current variable names
786  *
787  * @variable_name_size: size of variable_name buffer in byte
788  * @variable_name:      name of uefi variable's name in u16
789  * @vendor:             vendor's guid
790  *
791  * This function implements the GetNextVariableName service.
792  *
793  * See the Unified Extensible Firmware Interface (UEFI) specification for
794  * details.
795  *
796  * Return: status code
797  */
798 efi_status_t EFIAPI efi_get_next_variable_name(efi_uintn_t *variable_name_size,
799                                                u16 *variable_name,
800                                                efi_guid_t *vendor)
801 {
802         char *native_name, *variable;
803         ssize_t name_len, list_len;
804         char regex[256];
805         char * const regexlist[] = {regex};
806         u32 attributes;
807         int i;
808         efi_status_t ret;
809
810         EFI_ENTRY("%p \"%ls\" %pUl", variable_name_size, variable_name, vendor);
811
812         if (!variable_name_size || !variable_name || !vendor)
813                 return EFI_EXIT(EFI_INVALID_PARAMETER);
814
815         if (variable_name[0]) {
816                 /* check null-terminated string */
817                 for (i = 0; i < *variable_name_size; i++)
818                         if (!variable_name[i])
819                                 break;
820                 if (i >= *variable_name_size)
821                         return EFI_EXIT(EFI_INVALID_PARAMETER);
822
823                 /* search for the last-returned variable */
824                 ret = efi_to_native(&native_name, variable_name, vendor);
825                 if (ret)
826                         return EFI_EXIT(ret);
827
828                 name_len = strlen(native_name);
829                 for (variable = efi_variables_list; variable && *variable;) {
830                         if (!strncmp(variable, native_name, name_len) &&
831                             variable[name_len] == '=')
832                                 break;
833
834                         variable = strchr(variable, '\n');
835                         if (variable)
836                                 variable++;
837                 }
838
839                 free(native_name);
840                 if (!(variable && *variable))
841                         return EFI_EXIT(EFI_INVALID_PARAMETER);
842
843                 /* next variable */
844                 variable = strchr(variable, '\n');
845                 if (variable)
846                         variable++;
847                 if (!(variable && *variable))
848                         return EFI_EXIT(EFI_NOT_FOUND);
849         } else {
850                 /*
851                  *new search: free a list used in the previous search
852                  */
853                 free(efi_variables_list);
854                 efi_variables_list = NULL;
855                 efi_cur_variable = NULL;
856
857                 snprintf(regex, 256, "efi_.*-.*-.*-.*-.*_.*");
858                 list_len = hexport_r(&env_htab, '\n',
859                                      H_MATCH_REGEX | H_MATCH_KEY,
860                                      &efi_variables_list, 0, 1, regexlist);
861
862                 if (list_len <= 1)
863                         return EFI_EXIT(EFI_NOT_FOUND);
864
865                 variable = efi_variables_list;
866         }
867
868         ret = parse_uboot_variable(variable, variable_name_size, variable_name,
869                                    vendor, &attributes);
870
871         return EFI_EXIT(ret);
872 }
873
874 static efi_status_t efi_set_variable_common(u16 *variable_name,
875                                             const efi_guid_t *vendor,
876                                             u32 attributes,
877                                             efi_uintn_t data_size,
878                                             const void *data,
879                                             bool ro_check)
880 {
881         char *native_name = NULL, *old_data = NULL, *val = NULL, *s;
882         efi_uintn_t old_size;
883         bool append, delete;
884         u64 time = 0;
885         u32 attr;
886         efi_status_t ret = EFI_SUCCESS;
887
888         debug("%s: set '%s'\n", __func__, native_name);
889
890         if (!variable_name || !*variable_name || !vendor ||
891             ((attributes & EFI_VARIABLE_RUNTIME_ACCESS) &&
892              !(attributes & EFI_VARIABLE_BOOTSERVICE_ACCESS))) {
893                 ret = EFI_INVALID_PARAMETER;
894                 goto err;
895         }
896
897         ret = efi_to_native(&native_name, variable_name, vendor);
898         if (ret)
899                 goto err;
900
901         /* check if a variable exists */
902         old_size = 0;
903         attr = 0;
904         ret = efi_get_variable_common(variable_name, vendor, &attr,
905                                       &old_size, NULL);
906         append = !!(attributes & EFI_VARIABLE_APPEND_WRITE);
907         attributes &= ~(u32)EFI_VARIABLE_APPEND_WRITE;
908         delete = !append && (!data_size || !attributes);
909
910         /* check attributes */
911         if (old_size) {
912                 if (ro_check && (attr & READ_ONLY)) {
913                         ret = EFI_WRITE_PROTECTED;
914                         goto err;
915                 }
916
917                 /* attributes won't be changed */
918                 if (!delete &&
919                     ((ro_check && attr != attributes) ||
920                      (!ro_check && ((attr & ~(u32)READ_ONLY)
921                                     != (attributes & ~(u32)READ_ONLY))))) {
922                         ret = EFI_INVALID_PARAMETER;
923                         goto err;
924                 }
925         } else {
926                 if (delete || append) {
927                         /*
928                          * Trying to delete or to update a non-existent
929                          * variable.
930                          */
931                         ret = EFI_NOT_FOUND;
932                         goto err;
933                 }
934         }
935
936         if (((!u16_strcmp(variable_name, L"PK") ||
937               !u16_strcmp(variable_name, L"KEK")) &&
938                 !guidcmp(vendor, &efi_global_variable_guid)) ||
939             ((!u16_strcmp(variable_name, L"db") ||
940               !u16_strcmp(variable_name, L"dbx")) &&
941                 !guidcmp(vendor, &efi_guid_image_security_database))) {
942                 /* authentication is mandatory */
943                 if (!(attributes &
944                       EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) {
945                         debug("%ls: AUTHENTICATED_WRITE_ACCESS required\n",
946                               variable_name);
947                         ret = EFI_INVALID_PARAMETER;
948                         goto err;
949                 }
950         }
951
952         /* authenticate a variable */
953         if (IS_ENABLED(CONFIG_EFI_SECURE_BOOT)) {
954                 if (attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) {
955                         ret = EFI_INVALID_PARAMETER;
956                         goto err;
957                 }
958                 if (attributes &
959                     EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) {
960                         ret = efi_variable_authenticate(variable_name, vendor,
961                                                         &data_size, &data,
962                                                         attributes, &attr,
963                                                         &time);
964                         if (ret != EFI_SUCCESS)
965                                 goto err;
966
967                         /* last chance to check for delete */
968                         if (!data_size)
969                                 delete = true;
970                 }
971         } else {
972                 if (attributes &
973                     (EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS |
974                      EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) {
975                         debug("Secure boot is not configured\n");
976                         ret = EFI_INVALID_PARAMETER;
977                         goto err;
978                 }
979         }
980
981         /* delete a variable */
982         if (delete) {
983                 /* !old_size case has been handled before */
984                 val = NULL;
985                 ret = EFI_SUCCESS;
986                 goto out;
987         }
988
989         if (append) {
990                 old_data = malloc(old_size);
991                 if (!old_data) {
992                         ret = EFI_OUT_OF_RESOURCES;
993                         goto err;
994                 }
995                 ret = efi_get_variable_common(variable_name, vendor,
996                                               &attr, &old_size, old_data);
997                 if (ret != EFI_SUCCESS)
998                         goto err;
999         } else {
1000                 old_size = 0;
1001         }
1002
1003         val = malloc(2 * old_size + 2 * data_size
1004                      + strlen("{ro,run,boot,nv,time=0123456701234567}(blob)")
1005                      + 1);
1006         if (!val) {
1007                 ret = EFI_OUT_OF_RESOURCES;
1008                 goto err;
1009         }
1010
1011         s = val;
1012
1013         /*
1014          * store attributes
1015          */
1016         attributes &= (READ_ONLY |
1017                        EFI_VARIABLE_NON_VOLATILE |
1018                        EFI_VARIABLE_BOOTSERVICE_ACCESS |
1019                        EFI_VARIABLE_RUNTIME_ACCESS |
1020                        EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS);
1021         s += sprintf(s, "{");
1022         while (attributes) {
1023                 attr = 1 << (ffs(attributes) - 1);
1024
1025                 if (attr == READ_ONLY) {
1026                         s += sprintf(s, "ro");
1027                 } else if (attr == EFI_VARIABLE_NON_VOLATILE) {
1028                         s += sprintf(s, "nv");
1029                 } else if (attr == EFI_VARIABLE_BOOTSERVICE_ACCESS) {
1030                         s += sprintf(s, "boot");
1031                 } else if (attr == EFI_VARIABLE_RUNTIME_ACCESS) {
1032                         s += sprintf(s, "run");
1033                 } else if (attr ==
1034                            EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) {
1035                         s += sprintf(s, "time=");
1036                         s = bin2hex(s, (u8 *)&time, sizeof(time));
1037                 }
1038
1039                 attributes &= ~attr;
1040                 if (attributes)
1041                         s += sprintf(s, ",");
1042         }
1043         s += sprintf(s, "}");
1044         s += sprintf(s, "(blob)");
1045
1046         /* store payload: */
1047         if (append)
1048                 s = bin2hex(s, old_data, old_size);
1049         s = bin2hex(s, data, data_size);
1050         *s = '\0';
1051
1052         EFI_PRINT("setting: %s=%s\n", native_name, val);
1053
1054 out:
1055         if (env_set(native_name, val)) {
1056                 ret = EFI_DEVICE_ERROR;
1057         } else {
1058                 bool vendor_keys_modified = false;
1059
1060                 if ((u16_strcmp(variable_name, L"PK") == 0 &&
1061                      guidcmp(vendor, &efi_global_variable_guid) == 0)) {
1062                         ret = efi_transfer_secure_state(
1063                                         (delete ? EFI_MODE_SETUP :
1064                                                   EFI_MODE_USER));
1065                         if (ret != EFI_SUCCESS)
1066                                 goto err;
1067
1068                         if (efi_secure_mode != EFI_MODE_SETUP)
1069                                 vendor_keys_modified = true;
1070                 } else if ((u16_strcmp(variable_name, L"KEK") == 0 &&
1071                      guidcmp(vendor, &efi_global_variable_guid) == 0)) {
1072                         if (efi_secure_mode != EFI_MODE_SETUP)
1073                                 vendor_keys_modified = true;
1074                 }
1075
1076                 /* update VendorKeys */
1077                 if (vendor_keys_modified & efi_vendor_keys) {
1078                         efi_vendor_keys = 0;
1079                         ret = efi_set_variable_common(
1080                                                 L"VendorKeys",
1081                                                 &efi_global_variable_guid,
1082                                                 EFI_VARIABLE_BOOTSERVICE_ACCESS
1083                                                  | EFI_VARIABLE_RUNTIME_ACCESS
1084                                                  | READ_ONLY,
1085                                                 sizeof(efi_vendor_keys),
1086                                                 &efi_vendor_keys,
1087                                                 false);
1088                 } else {
1089                         ret = EFI_SUCCESS;
1090                 }
1091         }
1092
1093 err:
1094         free(native_name);
1095         free(old_data);
1096         free(val);
1097
1098         return ret;
1099 }
1100
1101 /**
1102  * efi_set_variable() - set value of a UEFI variable
1103  *
1104  * This function implements the SetVariable runtime service.
1105  *
1106  * See the Unified Extensible Firmware Interface (UEFI) specification for
1107  * details.
1108  *
1109  * @variable_name:      name of the variable
1110  * @vendor:             vendor GUID
1111  * @attributes:         attributes of the variable
1112  * @data_size:          size of the buffer with the variable value
1113  * @data:               buffer with the variable value
1114  * Return:              status code
1115  */
1116 efi_status_t EFIAPI efi_set_variable(u16 *variable_name,
1117                                      const efi_guid_t *vendor, u32 attributes,
1118                                      efi_uintn_t data_size, const void *data)
1119 {
1120         EFI_ENTRY("\"%ls\" %pUl %x %zu %p", variable_name, vendor, attributes,
1121                   data_size, data);
1122
1123         /* READ_ONLY bit is not part of API */
1124         attributes &= ~(u32)READ_ONLY;
1125
1126         return EFI_EXIT(efi_set_variable_common(variable_name, vendor,
1127                                                 attributes, data_size, data,
1128                                                 true));
1129 }
1130
1131 /**
1132  * efi_query_variable_info() - get information about EFI variables
1133  *
1134  * This function implements the QueryVariableInfo() runtime service.
1135  *
1136  * See the Unified Extensible Firmware Interface (UEFI) specification for
1137  * details.
1138  *
1139  * @attributes:                         bitmask to select variables to be
1140  *                                      queried
1141  * @maximum_variable_storage_size:      maximum size of storage area for the
1142  *                                      selected variable types
1143  * @remaining_variable_storage_size:    remaining size of storage are for the
1144  *                                      selected variable types
1145  * @maximum_variable_size:              maximum size of a variable of the
1146  *                                      selected type
1147  * Returns:                             status code
1148  */
1149 efi_status_t __efi_runtime EFIAPI efi_query_variable_info(
1150                         u32 attributes,
1151                         u64 *maximum_variable_storage_size,
1152                         u64 *remaining_variable_storage_size,
1153                         u64 *maximum_variable_size)
1154 {
1155         return EFI_UNSUPPORTED;
1156 }
1157
1158 /**
1159  * efi_get_variable_runtime() - runtime implementation of GetVariable()
1160  *
1161  * @variable_name:      name of the variable
1162  * @vendor:             vendor GUID
1163  * @attributes:         attributes of the variable
1164  * @data_size:          size of the buffer to which the variable value is copied
1165  * @data:               buffer to which the variable value is copied
1166  * Return:              status code
1167  */
1168 static efi_status_t __efi_runtime EFIAPI
1169 efi_get_variable_runtime(u16 *variable_name, const efi_guid_t *vendor,
1170                          u32 *attributes, efi_uintn_t *data_size, void *data)
1171 {
1172         return EFI_UNSUPPORTED;
1173 }
1174
1175 /**
1176  * efi_get_next_variable_name_runtime() - runtime implementation of
1177  *                                        GetNextVariable()
1178  *
1179  * @variable_name_size: size of variable_name buffer in byte
1180  * @variable_name:      name of uefi variable's name in u16
1181  * @vendor:             vendor's guid
1182  * Return: status code
1183  */
1184 static efi_status_t __efi_runtime EFIAPI
1185 efi_get_next_variable_name_runtime(efi_uintn_t *variable_name_size,
1186                                    u16 *variable_name, efi_guid_t *vendor)
1187 {
1188         return EFI_UNSUPPORTED;
1189 }
1190
1191 /**
1192  * efi_set_variable_runtime() - runtime implementation of SetVariable()
1193  *
1194  * @variable_name:      name of the variable
1195  * @vendor:             vendor GUID
1196  * @attributes:         attributes of the variable
1197  * @data_size:          size of the buffer with the variable value
1198  * @data:               buffer with the variable value
1199  * Return:              status code
1200  */
1201 static efi_status_t __efi_runtime EFIAPI
1202 efi_set_variable_runtime(u16 *variable_name, const efi_guid_t *vendor,
1203                          u32 attributes, efi_uintn_t data_size,
1204                          const void *data)
1205 {
1206         return EFI_UNSUPPORTED;
1207 }
1208
1209 /**
1210  * efi_variables_boot_exit_notify() - notify ExitBootServices() is called
1211  */
1212 void efi_variables_boot_exit_notify(void)
1213 {
1214         efi_runtime_services.get_variable = efi_get_variable_runtime;
1215         efi_runtime_services.get_next_variable_name =
1216                                 efi_get_next_variable_name_runtime;
1217         efi_runtime_services.set_variable = efi_set_variable_runtime;
1218         efi_update_table_header_crc32(&efi_runtime_services.hdr);
1219 }
1220
1221 /**
1222  * efi_init_variables() - initialize variable services
1223  *
1224  * Return:      status code
1225  */
1226 efi_status_t efi_init_variables(void)
1227 {
1228         efi_status_t ret;
1229
1230         ret = efi_init_secure_state();
1231
1232         return ret;
1233 }