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