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