efi_loader: signature: move efi_guid_cert_type_pkcs7 to efi_signature.c
[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/bitops.h>
19 #include <linux/compat.h>
20 #include <u-boot/crc.h>
21
22 enum efi_secure_mode {
23         EFI_MODE_SETUP,
24         EFI_MODE_USER,
25         EFI_MODE_AUDIT,
26         EFI_MODE_DEPLOYED,
27 };
28
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         if (!variable_name || !*variable_name || !vendor ||
889             ((attributes & EFI_VARIABLE_RUNTIME_ACCESS) &&
890              !(attributes & EFI_VARIABLE_BOOTSERVICE_ACCESS))) {
891                 ret = EFI_INVALID_PARAMETER;
892                 goto err;
893         }
894
895         ret = efi_to_native(&native_name, variable_name, vendor);
896         if (ret)
897                 goto err;
898
899         /* check if a variable exists */
900         old_size = 0;
901         attr = 0;
902         ret = efi_get_variable_common(variable_name, vendor, &attr,
903                                       &old_size, NULL);
904         append = !!(attributes & EFI_VARIABLE_APPEND_WRITE);
905         attributes &= ~(u32)EFI_VARIABLE_APPEND_WRITE;
906         delete = !append && (!data_size || !attributes);
907
908         /* check attributes */
909         if (old_size) {
910                 if (ro_check && (attr & READ_ONLY)) {
911                         ret = EFI_WRITE_PROTECTED;
912                         goto err;
913                 }
914
915                 /* attributes won't be changed */
916                 if (!delete &&
917                     ((ro_check && attr != attributes) ||
918                      (!ro_check && ((attr & ~(u32)READ_ONLY)
919                                     != (attributes & ~(u32)READ_ONLY))))) {
920                         ret = EFI_INVALID_PARAMETER;
921                         goto err;
922                 }
923         } else {
924                 if (delete || append) {
925                         /*
926                          * Trying to delete or to update a non-existent
927                          * variable.
928                          */
929                         ret = EFI_NOT_FOUND;
930                         goto err;
931                 }
932         }
933
934         if (((!u16_strcmp(variable_name, L"PK") ||
935               !u16_strcmp(variable_name, L"KEK")) &&
936                 !guidcmp(vendor, &efi_global_variable_guid)) ||
937             ((!u16_strcmp(variable_name, L"db") ||
938               !u16_strcmp(variable_name, L"dbx")) &&
939                 !guidcmp(vendor, &efi_guid_image_security_database))) {
940                 /* authentication is mandatory */
941                 if (!(attributes &
942                       EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) {
943                         debug("%ls: AUTHENTICATED_WRITE_ACCESS required\n",
944                               variable_name);
945                         ret = EFI_INVALID_PARAMETER;
946                         goto err;
947                 }
948         }
949
950         /* authenticate a variable */
951         if (IS_ENABLED(CONFIG_EFI_SECURE_BOOT)) {
952                 if (attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) {
953                         ret = EFI_INVALID_PARAMETER;
954                         goto err;
955                 }
956                 if (attributes &
957                     EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) {
958                         ret = efi_variable_authenticate(variable_name, vendor,
959                                                         &data_size, &data,
960                                                         attributes, &attr,
961                                                         &time);
962                         if (ret != EFI_SUCCESS)
963                                 goto err;
964
965                         /* last chance to check for delete */
966                         if (!data_size)
967                                 delete = true;
968                 }
969         } else {
970                 if (attributes &
971                     (EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS |
972                      EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) {
973                         debug("Secure boot is not configured\n");
974                         ret = EFI_INVALID_PARAMETER;
975                         goto err;
976                 }
977         }
978
979         /* delete a variable */
980         if (delete) {
981                 /* !old_size case has been handled before */
982                 val = NULL;
983                 ret = EFI_SUCCESS;
984                 goto out;
985         }
986
987         if (append) {
988                 old_data = malloc(old_size);
989                 if (!old_data) {
990                         ret = EFI_OUT_OF_RESOURCES;
991                         goto err;
992                 }
993                 ret = efi_get_variable_common(variable_name, vendor,
994                                               &attr, &old_size, old_data);
995                 if (ret != EFI_SUCCESS)
996                         goto err;
997         } else {
998                 old_size = 0;
999         }
1000
1001         val = malloc(2 * old_size + 2 * data_size
1002                      + strlen("{ro,run,boot,nv,time=0123456701234567}(blob)")
1003                      + 1);
1004         if (!val) {
1005                 ret = EFI_OUT_OF_RESOURCES;
1006                 goto err;
1007         }
1008
1009         s = val;
1010
1011         /*
1012          * store attributes
1013          */
1014         attributes &= (READ_ONLY |
1015                        EFI_VARIABLE_NON_VOLATILE |
1016                        EFI_VARIABLE_BOOTSERVICE_ACCESS |
1017                        EFI_VARIABLE_RUNTIME_ACCESS |
1018                        EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS);
1019         s += sprintf(s, "{");
1020         while (attributes) {
1021                 attr = 1 << (ffs(attributes) - 1);
1022
1023                 if (attr == READ_ONLY) {
1024                         s += sprintf(s, "ro");
1025                 } else if (attr == EFI_VARIABLE_NON_VOLATILE) {
1026                         s += sprintf(s, "nv");
1027                 } else if (attr == EFI_VARIABLE_BOOTSERVICE_ACCESS) {
1028                         s += sprintf(s, "boot");
1029                 } else if (attr == EFI_VARIABLE_RUNTIME_ACCESS) {
1030                         s += sprintf(s, "run");
1031                 } else if (attr ==
1032                            EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) {
1033                         s += sprintf(s, "time=");
1034                         s = bin2hex(s, (u8 *)&time, sizeof(time));
1035                 }
1036
1037                 attributes &= ~attr;
1038                 if (attributes)
1039                         s += sprintf(s, ",");
1040         }
1041         s += sprintf(s, "}");
1042         s += sprintf(s, "(blob)");
1043
1044         /* store payload: */
1045         if (append)
1046                 s = bin2hex(s, old_data, old_size);
1047         s = bin2hex(s, data, data_size);
1048         *s = '\0';
1049
1050         EFI_PRINT("setting: %s=%s\n", native_name, val);
1051
1052 out:
1053         if (env_set(native_name, val)) {
1054                 ret = EFI_DEVICE_ERROR;
1055         } else {
1056                 bool vendor_keys_modified = false;
1057
1058                 if ((u16_strcmp(variable_name, L"PK") == 0 &&
1059                      guidcmp(vendor, &efi_global_variable_guid) == 0)) {
1060                         ret = efi_transfer_secure_state(
1061                                         (delete ? EFI_MODE_SETUP :
1062                                                   EFI_MODE_USER));
1063                         if (ret != EFI_SUCCESS)
1064                                 goto err;
1065
1066                         if (efi_secure_mode != EFI_MODE_SETUP)
1067                                 vendor_keys_modified = true;
1068                 } else if ((u16_strcmp(variable_name, L"KEK") == 0 &&
1069                      guidcmp(vendor, &efi_global_variable_guid) == 0)) {
1070                         if (efi_secure_mode != EFI_MODE_SETUP)
1071                                 vendor_keys_modified = true;
1072                 }
1073
1074                 /* update VendorKeys */
1075                 if (vendor_keys_modified & efi_vendor_keys) {
1076                         efi_vendor_keys = 0;
1077                         ret = efi_set_variable_common(
1078                                                 L"VendorKeys",
1079                                                 &efi_global_variable_guid,
1080                                                 EFI_VARIABLE_BOOTSERVICE_ACCESS
1081                                                  | EFI_VARIABLE_RUNTIME_ACCESS
1082                                                  | READ_ONLY,
1083                                                 sizeof(efi_vendor_keys),
1084                                                 &efi_vendor_keys,
1085                                                 false);
1086                 } else {
1087                         ret = EFI_SUCCESS;
1088                 }
1089         }
1090
1091 err:
1092         free(native_name);
1093         free(old_data);
1094         free(val);
1095
1096         return ret;
1097 }
1098
1099 /**
1100  * efi_set_variable() - set value of a UEFI variable
1101  *
1102  * This function implements the SetVariable runtime service.
1103  *
1104  * See the Unified Extensible Firmware Interface (UEFI) specification for
1105  * details.
1106  *
1107  * @variable_name:      name of the variable
1108  * @vendor:             vendor GUID
1109  * @attributes:         attributes of the variable
1110  * @data_size:          size of the buffer with the variable value
1111  * @data:               buffer with the variable value
1112  * Return:              status code
1113  */
1114 efi_status_t EFIAPI efi_set_variable(u16 *variable_name,
1115                                      const efi_guid_t *vendor, u32 attributes,
1116                                      efi_uintn_t data_size, const void *data)
1117 {
1118         EFI_ENTRY("\"%ls\" %pUl %x %zu %p", variable_name, vendor, attributes,
1119                   data_size, data);
1120
1121         /* READ_ONLY bit is not part of API */
1122         attributes &= ~(u32)READ_ONLY;
1123
1124         return EFI_EXIT(efi_set_variable_common(variable_name, vendor,
1125                                                 attributes, data_size, data,
1126                                                 true));
1127 }
1128
1129 /**
1130  * efi_query_variable_info() - get information about EFI variables
1131  *
1132  * This function implements the QueryVariableInfo() runtime service.
1133  *
1134  * See the Unified Extensible Firmware Interface (UEFI) specification for
1135  * details.
1136  *
1137  * @attributes:                         bitmask to select variables to be
1138  *                                      queried
1139  * @maximum_variable_storage_size:      maximum size of storage area for the
1140  *                                      selected variable types
1141  * @remaining_variable_storage_size:    remaining size of storage are for the
1142  *                                      selected variable types
1143  * @maximum_variable_size:              maximum size of a variable of the
1144  *                                      selected type
1145  * Returns:                             status code
1146  */
1147 efi_status_t __efi_runtime EFIAPI efi_query_variable_info(
1148                         u32 attributes,
1149                         u64 *maximum_variable_storage_size,
1150                         u64 *remaining_variable_storage_size,
1151                         u64 *maximum_variable_size)
1152 {
1153         return EFI_UNSUPPORTED;
1154 }
1155
1156 /**
1157  * efi_get_variable_runtime() - runtime implementation of GetVariable()
1158  *
1159  * @variable_name:      name of the variable
1160  * @vendor:             vendor GUID
1161  * @attributes:         attributes of the variable
1162  * @data_size:          size of the buffer to which the variable value is copied
1163  * @data:               buffer to which the variable value is copied
1164  * Return:              status code
1165  */
1166 static efi_status_t __efi_runtime EFIAPI
1167 efi_get_variable_runtime(u16 *variable_name, const efi_guid_t *vendor,
1168                          u32 *attributes, efi_uintn_t *data_size, void *data)
1169 {
1170         return EFI_UNSUPPORTED;
1171 }
1172
1173 /**
1174  * efi_get_next_variable_name_runtime() - runtime implementation of
1175  *                                        GetNextVariable()
1176  *
1177  * @variable_name_size: size of variable_name buffer in byte
1178  * @variable_name:      name of uefi variable's name in u16
1179  * @vendor:             vendor's guid
1180  * Return: status code
1181  */
1182 static efi_status_t __efi_runtime EFIAPI
1183 efi_get_next_variable_name_runtime(efi_uintn_t *variable_name_size,
1184                                    u16 *variable_name, efi_guid_t *vendor)
1185 {
1186         return EFI_UNSUPPORTED;
1187 }
1188
1189 /**
1190  * efi_set_variable_runtime() - runtime implementation of SetVariable()
1191  *
1192  * @variable_name:      name of the variable
1193  * @vendor:             vendor GUID
1194  * @attributes:         attributes of the variable
1195  * @data_size:          size of the buffer with the variable value
1196  * @data:               buffer with the variable value
1197  * Return:              status code
1198  */
1199 static efi_status_t __efi_runtime EFIAPI
1200 efi_set_variable_runtime(u16 *variable_name, const efi_guid_t *vendor,
1201                          u32 attributes, efi_uintn_t data_size,
1202                          const void *data)
1203 {
1204         return EFI_UNSUPPORTED;
1205 }
1206
1207 /**
1208  * efi_variables_boot_exit_notify() - notify ExitBootServices() is called
1209  */
1210 void efi_variables_boot_exit_notify(void)
1211 {
1212         efi_runtime_services.get_variable = efi_get_variable_runtime;
1213         efi_runtime_services.get_next_variable_name =
1214                                 efi_get_next_variable_name_runtime;
1215         efi_runtime_services.set_variable = efi_set_variable_runtime;
1216         efi_update_table_header_crc32(&efi_runtime_services.hdr);
1217 }
1218
1219 /**
1220  * efi_init_variables() - initialize variable services
1221  *
1222  * Return:      status code
1223  */
1224 efi_status_t efi_init_variables(void)
1225 {
1226         efi_status_t ret;
1227
1228         ret = efi_init_secure_state();
1229
1230         return ret;
1231 }