1 /*
2  * Copyright 2021 Google LLC
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "stddef.h"
18 
19 #include <assert.h>
20 #include <libcr51sign/cr51_image_descriptor.h>
21 #include <libcr51sign/libcr51sign.h>
22 #include <libcr51sign/libcr51sign_internal.h>
23 #include <libcr51sign/libcr51sign_mauv.h>
24 #include <stdint.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 
29 #ifdef __cplusplus
30 extern "C"
31 {
32 #endif
33 
34 // True of x is a power of two
35 #define POWER_OF_TWO(x) ((x) && !((x) & ((x)-1)))
36 
37 // Maximum version supported. Major revisions are not backwards compatible.
38 #define MAX_MAJOR_VERSION 1
39 
40 // Descriptor alignment on the external EEPROM.
41 #define DESCRIPTOR_ALIGNMENT (64 * 1024)
42 
43 // SPS EEPROM sector size is 4KiB, since this is the smallest erasable size.
44 #define IMAGE_REGION_ALIGNMENT 4096
45 
46 #define MAX_READ_SIZE 1024
47 
48 #ifndef ARRAY_SIZE
49 #define ARRAY_SIZE(t) (sizeof(t) / sizeof(t[0]))
50 #endif
51 
52 // Values of SIGNATURE_OFFSET shuold be same for all sig types (2048,3072,4096)
53 #define SIGNATURE_OFFSET offsetof(struct signature_rsa3072_pkcs15, modulus)
54 
55 #ifndef BUILD_ASSERT
56 #define BUILD_ASSERT(cond) ((void)sizeof(char[1 - 2 * !(cond)]))
57 #endif
58 
59 // Returns the bytes size of keys used in the given signature_scheme.
60 // Return error if signature_scheme is invalid.
61 //
62 static failure_reason get_key_size(enum signature_scheme signature_scheme,
63                                    uint16_t* key_size)
64 {
65     switch (signature_scheme)
66     {
67         case SIGNATURE_RSA2048_PKCS15:
68             *key_size = 256;
69             return LIBCR51SIGN_SUCCESS;
70         case SIGNATURE_RSA3072_PKCS15:
71             *key_size = 384;
72             return LIBCR51SIGN_SUCCESS;
73         case SIGNATURE_RSA4096_PKCS15:
74         case SIGNATURE_RSA4096_PKCS15_SHA512:
75             *key_size = 512;
76             return LIBCR51SIGN_SUCCESS;
77         default:
78             return LIBCR51SIGN_ERROR_INVALID_SIG_SCHEME;
79     }
80 }
81 
82 // Returns the hash_type for a given signature scheme
83 // Returns error if scheme is invalid.
84 failure_reason get_hash_type_from_signature(enum signature_scheme scheme,
85                                             enum hash_type* type)
86 {
87     switch (scheme)
88     {
89         case SIGNATURE_RSA2048_PKCS15:
90         case SIGNATURE_RSA3072_PKCS15:
91         case SIGNATURE_RSA4096_PKCS15:
92             *type = HASH_SHA2_256;
93             return LIBCR51SIGN_SUCCESS;
94         case SIGNATURE_RSA4096_PKCS15_SHA512:
95             *type = HASH_SHA2_512;
96             return LIBCR51SIGN_SUCCESS;
97         default:
98             return LIBCR51SIGN_ERROR_INVALID_SIG_SCHEME;
99     }
100 }
101 
102 // Check if the given hash_type is supported.
103 // Returns error if hash_type is not supported.
104 static failure_reason is_hash_type_supported(enum hash_type type)
105 {
106     switch (type)
107     {
108         case HASH_SHA2_256:
109         case HASH_SHA2_512:
110             return LIBCR51SIGN_SUCCESS;
111         default:
112             return LIBCR51SIGN_ERROR_INVALID_HASH_TYPE;
113     }
114 }
115 
116 // Determines digest size for a given hash_type.
117 // Returns error if hash_type is not supported.
118 static failure_reason get_hash_digest_size(enum hash_type type, uint32_t* size)
119 {
120     switch (type)
121     {
122         case HASH_SHA2_256:
123             *size = LIBCR51SIGN_SHA256_DIGEST_SIZE;
124             return LIBCR51SIGN_SUCCESS;
125         case HASH_SHA2_512:
126             *size = LIBCR51SIGN_SHA512_DIGEST_SIZE;
127             return LIBCR51SIGN_SUCCESS;
128         default:
129             return LIBCR51SIGN_ERROR_INVALID_HASH_TYPE;
130     }
131 }
132 
133 // Determines hash struct size for a given hash_type.
134 // Returns error if hash_type is not supported.
135 static failure_reason get_hash_struct_size(enum hash_type type, uint32_t* size)
136 {
137     switch (type)
138     {
139         case HASH_SHA2_256:
140             *size = sizeof(struct hash_sha256);
141             return LIBCR51SIGN_SUCCESS;
142         case HASH_SHA2_512:
143             *size = sizeof(struct hash_sha512);
144             return LIBCR51SIGN_SUCCESS;
145         default:
146             return LIBCR51SIGN_ERROR_INVALID_HASH_TYPE;
147     }
148 }
149 
150 // Checks that:
151 //  - The signing key is trusted
152 //  - The target version is not denylisted
153 // If validating a staged update, also checks that:
154 //  - The target image family matches the current image family
155 //  - The image type transition is legal (i.e. dev -> *|| prod -> prod) or
156 //    alternatively that the hardware ID is allowlisted
157 // Assuming the caller has performed following:
158 // board_get_base_key_index();
159 // board_get_key_array
160 // Possible return codes:
161 // LIBCR51SIGN_SUCCESS = 0,
162 // LIBCR51SIGN_ERROR_RUNTIME_FAILURE = 1,
163 // LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR = 3,
164 // LIBCR51SIGN_ERROR_INVALID_IMAGE_FAMILY = 4,
165 // LIBCR51SIGN_ERROR_IMAGE_TYPE_DISALLOWED = 5,
166 
167 static failure_reason validate_transition(const struct libcr51sign_ctx* ctx,
168                                           const struct libcr51sign_intf* intf,
169                                           uint32_t signature_struct_offset)
170 {
171     BUILD_ASSERT((offsetof(struct signature_rsa2048_pkcs15, modulus) ==
172                       SIGNATURE_OFFSET &&
173                   offsetof(struct signature_rsa3072_pkcs15, modulus) ==
174                       SIGNATURE_OFFSET &&
175                   offsetof(struct signature_rsa4096_pkcs15, modulus) ==
176                       SIGNATURE_OFFSET));
177 
178     // Read up to the modulus.
179     enum
180     {
181         read_len = SIGNATURE_OFFSET
182     };
183     uint8_t buffer[read_len];
184     int rv;
185     rv = intf->read(ctx, signature_struct_offset, read_len, buffer);
186     if (rv != LIBCR51SIGN_SUCCESS)
187     {
188         CPRINTS(ctx, "%s: failed to read signature struct\n", __FUNCTION__);
189         return LIBCR51SIGN_ERROR_RUNTIME_FAILURE;
190     }
191     if (*(uint32_t*)buffer != SIGNATURE_MAGIC)
192     {
193         CPRINTS(ctx, "%s: bad signature magic\n", __FUNCTION__);
194         return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
195     }
196 
197     if (ctx->descriptor.image_family != ctx->current_image_family &&
198         ctx->descriptor.image_family != IMAGE_FAMILY_ALL &&
199         ctx->current_image_family != IMAGE_FAMILY_ALL)
200     {
201         CPRINTS(ctx, "%s: invalid image family\n", __FUNCTION__);
202         return LIBCR51SIGN_ERROR_INVALID_IMAGE_FAMILY;
203     }
204 
205     if (intf->is_production_mode == NULL)
206     {
207         CPRINTS(ctx, "%s: missing is_production_mode\n", __FUNCTION__);
208         return LIBCR51SIGN_ERROR_INVALID_INTERFACE;
209     }
210     if (intf->is_production_mode() && (ctx->descriptor.image_type == IMAGE_DEV))
211     {
212         CPRINTS(ctx, "%s: checking exemption allowlist\n", __FUNCTION__);
213 
214         // If function is NULL or if the function call return false, return
215         // error
216         if (intf->prod_to_dev_downgrade_allowed == NULL ||
217             !intf->prod_to_dev_downgrade_allowed())
218         {
219             CPRINTS(ctx, "%s: illegal image type\n", __FUNCTION__);
220             return LIBCR51SIGN_ERROR_DEV_DOWNGRADE_DISALLOWED;
221         }
222     }
223     return LIBCR51SIGN_SUCCESS;
224 }
225 
226 // If caller had provided read_and_hash_update call that, otherwise call read
227 // and then update.
228 
229 static failure_reason read_and_hash_update(const struct libcr51sign_ctx* ctx,
230                                            const struct libcr51sign_intf* intf,
231                                            uint32_t offset, uint32_t size)
232 {
233     uint8_t read_buffer[MAX_READ_SIZE];
234     int rv;
235     int read_size;
236 
237     if (intf->read_and_hash_update)
238     {
239         rv = intf->read_and_hash_update((void*)ctx, offset, size);
240     }
241     else
242     {
243         if (!intf->hash_update)
244         {
245             CPRINTS(ctx, "%s: missing hash_update\n", __FUNCTION__);
246             return LIBCR51SIGN_ERROR_INVALID_INTERFACE;
247         }
248         do
249         {
250             read_size = size < MAX_READ_SIZE ? size : MAX_READ_SIZE;
251             rv = intf->read((void*)ctx, offset, read_size, read_buffer);
252             if (rv != LIBCR51SIGN_SUCCESS)
253             {
254                 return LIBCR51SIGN_ERROR_RUNTIME_FAILURE;
255             }
256             rv = intf->hash_update((void*)ctx, read_buffer, read_size);
257             if (rv != LIBCR51SIGN_SUCCESS)
258             {
259                 return LIBCR51SIGN_ERROR_RUNTIME_FAILURE;
260             }
261             offset += read_size;
262             size -= read_size;
263         } while (size > 0);
264     }
265     return rv;
266 }
267 
268 // Validates the image_region array, namely that:
269 //  - The regions are aligned, contiguous & exhaustive
270 //  - That the image descriptor resides in a static region
271 //
272 // If the array is consistent, proceeds to hash the static regions and
273 // validates the hash. d_offset is the absolute image descriptor offset
274 
275 static failure_reason validate_payload_regions(
276     const struct libcr51sign_ctx* ctx, struct libcr51sign_intf* intf,
277     uint32_t d_offset, struct libcr51sign_validated_regions* image_regions)
278 {
279     // Allocate buffer to accomodate largest supported hash-type(SHA512)
280     uint8_t magic_and_digest[MEMBER_SIZE(struct hash_sha512, hash_magic) +
281                              LIBCR51SIGN_SHA512_DIGEST_SIZE];
282     uint8_t dcrypto_digest[LIBCR51SIGN_SHA512_DIGEST_SIZE];
283     uint32_t byte_count, region_count, image_size, hash_offset, digest_size;
284     uint32_t i;
285     uint8_t d_region_num = 0;
286     int rv;
287     struct image_region const* region;
288 
289     if (image_regions == NULL)
290     {
291         CPRINTS(ctx, "%s: Missing image region input\n", __FUNCTION__);
292         return LIBCR51SIGN_ERROR_INVALID_REGION_INPUT;
293     }
294 
295     BUILD_ASSERT((MEMBER_SIZE(struct hash_sha256, hash_magic) ==
296                   MEMBER_SIZE(struct hash_sha512, hash_magic)));
297     image_size = ctx->descriptor.image_size;
298     region_count = ctx->descriptor.region_count;
299     hash_offset = d_offset + sizeof(struct image_descriptor) +
300                   region_count * sizeof(struct image_region);
301     // Read the image_region array.
302 
303     if (region_count > ARRAY_SIZE(image_regions->image_regions))
304     {
305         CPRINTS(ctx,
306                 "%s: ctx->descriptor.region_count is greater "
307                 "than LIBCR51SIGN_MAX_REGION_COUNT\n",
308                 __FUNCTION__);
309         return LIBCR51SIGN_ERROR_INVALID_REGION_SIZE;
310     }
311 
312     rv = intf->read(ctx, d_offset + sizeof(struct image_descriptor),
313                     region_count * sizeof(struct image_region),
314                     (uint8_t*)&image_regions->image_regions);
315 
316     image_regions->region_count = region_count;
317 
318     if (rv != LIBCR51SIGN_SUCCESS)
319     {
320         CPRINTS(ctx, "%s: failed to read region array\n", __FUNCTION__);
321         return LIBCR51SIGN_ERROR_RUNTIME_FAILURE;
322     }
323 
324     // Validate that the regions are contiguous & exhaustive.
325     for (i = 0, byte_count = 0; i < region_count; i++)
326     {
327         region = image_regions->image_regions + i;
328 
329         CPRINTS(ctx, "%s: region #%d \"%s\" (%x - %x)\n", __FUNCTION__, i,
330                 (const char*)region->region_name, region->region_offset,
331                 region->region_offset + region->region_size);
332         if ((region->region_offset % IMAGE_REGION_ALIGNMENT) != 0 ||
333             (region->region_size % IMAGE_REGION_ALIGNMENT) != 0)
334         {
335             CPRINTS(ctx, "%s: regions must be sector aligned\n", __FUNCTION__);
336             return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
337         }
338         if (region->region_offset != byte_count ||
339             region->region_size > image_size - byte_count)
340         {
341             CPRINTS(ctx, "%s: invalid region array\n", __FUNCTION__);
342             return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
343         }
344         byte_count += region->region_size;
345         // The image descriptor must be part of a static region.
346         if (d_offset >= region->region_offset && d_offset < byte_count)
347         {
348             d_region_num = i;
349             CPRINTS(ctx, "%s: image descriptor in region %d\n", __FUNCTION__,
350                     i);
351             // The descriptor can't span regions.
352             if ((ctx->descriptor.descriptor_area_size >
353                  (byte_count - d_offset)) ||
354                 !(region->region_attributes & IMAGE_REGION_STATIC))
355             {
356                 CPRINTS(ctx,
357                         "%s: descriptor must reside in "
358                         "static region\n",
359                         __FUNCTION__);
360                 return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
361             }
362         }
363     }
364     if (byte_count != image_size)
365     {
366         CPRINTS(ctx, "%s: invalid image size\n", __FUNCTION__);
367         return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
368     }
369 
370     rv = get_hash_digest_size(ctx->descriptor.hash_type, &digest_size);
371     if (rv != LIBCR51SIGN_SUCCESS)
372     {
373         return rv;
374     }
375 
376     rv = intf->read(ctx, hash_offset,
377                     MEMBER_SIZE(struct hash_sha256, hash_magic) + digest_size,
378                     magic_and_digest);
379     if (rv != LIBCR51SIGN_SUCCESS)
380     {
381         CPRINTS(ctx, "%s: failed to read hash from flash\n", __FUNCTION__);
382         return LIBCR51SIGN_ERROR_RUNTIME_FAILURE;
383     }
384     if (*(uint32_t*)magic_and_digest != HASH_MAGIC)
385     {
386         CPRINTS(ctx, "%s: bad hash magic\n", __FUNCTION__);
387         return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
388     }
389     rv = intf->hash_init(ctx, ctx->descriptor.hash_type);
390     if (rv != LIBCR51SIGN_SUCCESS)
391     {
392         CPRINTS(ctx, "%s: hash_init failed\n", __FUNCTION__);
393         return LIBCR51SIGN_ERROR_RUNTIME_FAILURE;
394     }
395     for (i = 0; i < region_count; i++)
396     {
397         uint32_t hash_start, hash_size;
398         region = image_regions->image_regions + i;
399 
400         if (!(region->region_attributes & IMAGE_REGION_STATIC))
401         {
402             continue;
403         }
404         hash_start = region->region_offset;
405         hash_size = region->region_size;
406 
407         // Skip the descriptor.
408         do
409         {
410             if (i == d_region_num)
411             {
412                 hash_size = d_offset - hash_start;
413                 if (!hash_size)
414                 {
415                     hash_start += ctx->descriptor.descriptor_area_size;
416                     hash_size = (region->region_offset + region->region_size -
417                                  hash_start);
418                 }
419             }
420 
421             CPRINTS(ctx, "%s: hashing %s (%x - %x)\n", __FUNCTION__,
422                     (const char*)region->region_name, hash_start,
423                     hash_start + hash_size);
424             // Read the image_region array.
425             rv = read_and_hash_update(ctx, intf, hash_start, hash_size);
426             if (rv != LIBCR51SIGN_SUCCESS)
427             {
428                 return rv;
429             }
430             hash_start += hash_size;
431         } while (hash_start != region->region_offset + region->region_size);
432     }
433     rv = intf->hash_final((void*)ctx, (uint8_t*)dcrypto_digest);
434 
435     if (rv != LIBCR51SIGN_SUCCESS)
436     {
437         return LIBCR51SIGN_ERROR_RUNTIME_FAILURE;
438     }
439 
440     if (memcmp(magic_and_digest + MEMBER_SIZE(struct hash_sha256, hash_magic),
441                dcrypto_digest, digest_size))
442     {
443         CPRINTS(ctx, "%s: invalid hash\n", __FUNCTION__);
444         return LIBCR51SIGN_ERROR_INVALID_HASH;
445     }
446     // Image is valid.
447     return LIBCR51SIGN_SUCCESS;
448 }
449 
450 // Create empty image_regions to pass to validate_payload_regions
451 // Support validate_payload_regions_helper to remove image_regions as a required
452 // input.
453 
454 static failure_reason
455     allocate_and_validate_payload_regions(const struct libcr51sign_ctx* ctx,
456                                           struct libcr51sign_intf* intf,
457                                           uint32_t d_offset)
458 {
459     struct libcr51sign_validated_regions image_regions;
460     return validate_payload_regions(ctx, intf, d_offset, &image_regions);
461 }
462 
463 // Wrapper around validate_payload_regions to allow nullptr for image_regions.
464 // Calls allocate_and_validate_payload_regions when image_regions is nullptr to
465 // create placer holder image_regions.
466 
467 static failure_reason validate_payload_regions_helper(
468     const struct libcr51sign_ctx* ctx, struct libcr51sign_intf* intf,
469     uint32_t d_offset, struct libcr51sign_validated_regions* image_regions)
470 {
471     if (image_regions)
472     {
473         return validate_payload_regions(ctx, intf, d_offset, image_regions);
474     }
475 
476     return allocate_and_validate_payload_regions(ctx, intf, d_offset);
477 }
478 
479 // Check if the given signature_scheme is supported.
480 // Returns nonzero on error, zero on success
481 
482 static failure_reason
483     is_signature_scheme_supported(enum signature_scheme scheme)
484 {
485     switch (scheme)
486     {
487         case SIGNATURE_RSA2048_PKCS15:
488         case SIGNATURE_RSA3072_PKCS15:
489         case SIGNATURE_RSA4096_PKCS15:
490         case SIGNATURE_RSA4096_PKCS15_SHA512:
491             return LIBCR51SIGN_SUCCESS;
492         default:
493             return LIBCR51SIGN_ERROR_INVALID_SIG_SCHEME;
494     }
495 }
496 
497 // Returns size of signature struct size in |size|
498 // Returns nonzero on error, zero on success
499 
500 static failure_reason get_signature_struct_size(enum signature_scheme scheme,
501                                                 uint32_t* size)
502 {
503     switch (scheme)
504     {
505         case SIGNATURE_RSA2048_PKCS15:
506             *size = sizeof(struct signature_rsa2048_pkcs15);
507             return LIBCR51SIGN_SUCCESS;
508         case SIGNATURE_RSA3072_PKCS15:
509             *size = sizeof(struct signature_rsa3072_pkcs15);
510             return LIBCR51SIGN_SUCCESS;
511         case SIGNATURE_RSA4096_PKCS15:
512         case SIGNATURE_RSA4096_PKCS15_SHA512:
513             *size = sizeof(struct signature_rsa4096_pkcs15);
514             return LIBCR51SIGN_SUCCESS;
515         default:
516             return LIBCR51SIGN_ERROR_INVALID_SIG_SCHEME;
517     }
518 }
519 
520 static failure_reason get_signature_field_offset(enum signature_scheme scheme,
521                                                  uint32_t* offset)
522 {
523     switch (scheme)
524     {
525         case SIGNATURE_RSA2048_PKCS15:
526             *offset = offsetof(struct signature_rsa2048_pkcs15, signature);
527             return LIBCR51SIGN_SUCCESS;
528         case SIGNATURE_RSA3072_PKCS15:
529             *offset = offsetof(struct signature_rsa3072_pkcs15, signature);
530             return LIBCR51SIGN_SUCCESS;
531         case SIGNATURE_RSA4096_PKCS15:
532         case SIGNATURE_RSA4096_PKCS15_SHA512:
533             *offset = offsetof(struct signature_rsa4096_pkcs15, signature);
534             return LIBCR51SIGN_SUCCESS;
535         default:
536             return LIBCR51SIGN_ERROR_INVALID_SIG_SCHEME;
537     }
538 }
539 
540 // Validates the signature (of type scheme) read from "device" at
541 //"raw_signature_offset" with "public_key" over a SHA256/SHA512 digest of
542 // EEPROM area "data_offset:data_size".
543 
544 static failure_reason validate_signature(const struct libcr51sign_ctx* ctx,
545                                          const struct libcr51sign_intf* intf,
546                                          uint32_t data_offset,
547                                          uint32_t data_size,
548                                          enum signature_scheme scheme,
549                                          uint32_t raw_signature_offset)
550 {
551     uint8_t signature[LIBCR51SIGN_MAX_SIGNATURE_SIZE];
552     uint16_t key_size;
553     uint32_t digest_size;
554     uint8_t dcrypto_digest[LIBCR51SIGN_SHA512_DIGEST_SIZE];
555     int rv;
556     enum hash_type hash_type;
557 
558     if (!intf->hash_init)
559     {
560         CPRINTS(ctx, "%s: missing hash_init\n", __FUNCTION__);
561         return LIBCR51SIGN_ERROR_INVALID_INTERFACE;
562     }
563     rv = get_hash_type_from_signature(scheme, &hash_type);
564     if (rv != LIBCR51SIGN_SUCCESS)
565     {
566         CPRINTS(ctx, "%s: hash_type from signature failed\n", __FUNCTION__);
567         return rv;
568     }
569     rv = intf->hash_init(ctx, hash_type);
570     if (rv != LIBCR51SIGN_SUCCESS)
571     {
572         CPRINTS(ctx, "%s: hash_init failed\n", __FUNCTION__);
573         return LIBCR51SIGN_ERROR_RUNTIME_FAILURE;
574     }
575     rv = read_and_hash_update(ctx, intf, data_offset, data_size);
576     if (rv != LIBCR51SIGN_SUCCESS)
577     {
578         CPRINTS(ctx, "%s: hash_update failed\n", __FUNCTION__);
579         return rv;
580     }
581     if (!intf->hash_final)
582     {
583         CPRINTS(ctx, "%s: missing hash_final\n", __FUNCTION__);
584         return LIBCR51SIGN_ERROR_INVALID_INTERFACE;
585     }
586     rv = intf->hash_final((void*)ctx, dcrypto_digest);
587     if (rv != LIBCR51SIGN_SUCCESS)
588     {
589         CPRINTS(ctx, "%s: hash_final failed (status = %d)\n", __FUNCTION__, rv);
590         return LIBCR51SIGN_ERROR_RUNTIME_FAILURE;
591     }
592     rv = get_key_size(scheme, &key_size);
593     if (rv != LIBCR51SIGN_SUCCESS)
594     {
595         return rv;
596     }
597 
598     rv = intf->read(ctx, raw_signature_offset, key_size, signature);
599     if (rv != LIBCR51SIGN_SUCCESS)
600     {
601         CPRINTS(ctx, "%s: failed to read signature (status = %d)\n",
602                 __FUNCTION__, rv);
603         return LIBCR51SIGN_ERROR_RUNTIME_FAILURE;
604     }
605     if (!intf->verify_signature)
606     {
607         CPRINTS(ctx, "%s: missing verify_signature\n", __FUNCTION__);
608         return LIBCR51SIGN_ERROR_INVALID_INTERFACE;
609     }
610     rv = get_hash_digest_size(hash_type, &digest_size);
611     if (rv != LIBCR51SIGN_SUCCESS)
612     {
613         return rv;
614     }
615     rv = intf->verify_signature(ctx, scheme, signature, key_size,
616                                 dcrypto_digest, digest_size);
617     if (rv != LIBCR51SIGN_SUCCESS)
618     {
619         CPRINTS(ctx, "%s: verification failed (status = %d)\n", __FUNCTION__,
620                 rv);
621         return LIBCR51SIGN_ERROR_INVALID_SIGNATURE;
622     }
623     CPRINTS(ctx, "%s: verification succeeded\n", __FUNCTION__);
624     return LIBCR51SIGN_SUCCESS;
625 }
626 
627 // Sanity checks the image descriptor & validates its signature.
628 // This function does not validate the image_region array or image hash.
629 //
630 //@param[in] ctx  context which describes the image and holds opaque private
631 //                 data for the user of the library
632 //@param[in] intf  function pointers which interface to the current system
633 // and environment
634 //@param offset  Absolute image descriptor flash offset.
635 //@param relative_offset  Image descriptor offset relative to image start.
636 //@param max_size Maximum size of the flash space in bytes.
637 //@param[out] payload_blob_offset  Absolute offset of BLOB data in image
638 //                                 descriptor (if BLOB data is present)
639 static failure_reason
640     validate_descriptor(const struct libcr51sign_ctx* ctx,
641                         const struct libcr51sign_intf* intf, uint32_t offset,
642                         uint32_t relative_offset, uint32_t max_size,
643                         uint32_t* const restrict payload_blob_offset)
644 {
645     uint32_t max_descriptor_size, signed_size, signature_scheme,
646         signature_offset;
647     uint32_t signature_struct_offset, signature_struct_size, hash_struct_size;
648     int rv;
649 
650     max_descriptor_size = max_size - relative_offset;
651     if (max_size < relative_offset ||
652         max_descriptor_size < sizeof(struct image_descriptor))
653     {
654         CPRINTS(ctx, "%s: invalid arguments\n", __FUNCTION__);
655         return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
656     }
657 
658     rv = intf->read(ctx, offset, sizeof(ctx->descriptor),
659                     (uint8_t*)&ctx->descriptor);
660     if (rv != LIBCR51SIGN_SUCCESS)
661     {
662         CPRINTS(ctx, "%s: failed to read descriptor\n", __FUNCTION__);
663         return LIBCR51SIGN_ERROR_RUNTIME_FAILURE;
664     }
665     if (ctx->descriptor.descriptor_magic != DESCRIPTOR_MAGIC ||
666         ctx->descriptor.descriptor_offset != relative_offset ||
667         ctx->descriptor.region_count == 0 ||
668         ctx->descriptor.descriptor_area_size > max_descriptor_size ||
669         ctx->descriptor.image_size > max_size)
670     {
671         CPRINTS(ctx, "%s: invalid descriptor\n", __FUNCTION__);
672         return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
673     }
674     if (intf->image_size_valid == NULL)
675     {
676         // Preserve original behavior of requiring exact image_size match if no
677         // operator is provided.
678         if (ctx->descriptor.image_size != max_size)
679         {
680             CPRINTS(ctx, "%s: invalid image size\n", __FUNCTION__);
681             return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
682         }
683     }
684     else if (!intf->image_size_valid(ctx->descriptor.image_size))
685     {
686         CPRINTS(ctx, "%s: invalid image size\n", __FUNCTION__);
687         return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
688     }
689     if (ctx->descriptor.image_type != IMAGE_DEV &&
690         ctx->descriptor.image_type != IMAGE_PROD &&
691         ctx->descriptor.image_type != IMAGE_BREAKOUT &&
692         ctx->descriptor.image_type != IMAGE_TEST &&
693         ctx->descriptor.image_type != IMAGE_UNSIGNED_INTEGRITY)
694     {
695         CPRINTS(ctx, "%s: bad image type\n", __FUNCTION__);
696         return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
697     }
698     // Although the image_descriptor struct supports unauthenticated
699     // images, Haven will not allow it.
700     // Haven only supports SHA256 + RSA2048/RSA3072_PKCS15 currently.
701 
702     signature_scheme = ctx->descriptor.signature_scheme;
703 
704     rv = is_signature_scheme_supported(signature_scheme);
705     if (rv != LIBCR51SIGN_SUCCESS)
706     {
707         return rv;
708     }
709     rv = is_hash_type_supported(ctx->descriptor.hash_type);
710     if (rv != LIBCR51SIGN_SUCCESS)
711     {
712         CPRINTS(ctx, "%s: invalid hash type\n", __FUNCTION__);
713         return rv;
714     }
715     if (ctx->descriptor.descriptor_major > MAX_MAJOR_VERSION ||
716         ctx->descriptor.region_count > LIBCR51SIGN_MAX_REGION_COUNT)
717     {
718         CPRINTS(ctx, "%s: unsupported descriptor\n", __FUNCTION__);
719         return LIBCR51SIGN_ERROR_UNSUPPORTED_DESCRIPTOR;
720     }
721     rv = get_signature_struct_size(signature_scheme, &signature_struct_size);
722     if (rv != LIBCR51SIGN_SUCCESS)
723     {
724         return rv;
725     }
726 
727     // Compute the size of the signed portion of the image descriptor.
728     signed_size = sizeof(struct image_descriptor) +
729                   ctx->descriptor.region_count * sizeof(struct image_region);
730     rv = get_hash_struct_size(ctx->descriptor.hash_type, &hash_struct_size);
731     if (rv != LIBCR51SIGN_SUCCESS)
732     {
733         return rv;
734     }
735     signed_size += hash_struct_size;
736     if (ctx->descriptor.denylist_size)
737     {
738         signed_size += sizeof(struct denylist);
739         signed_size += ctx->descriptor.denylist_size *
740                        sizeof(struct denylist_record);
741     }
742     if (ctx->descriptor.blob_size)
743     {
744         *payload_blob_offset = offset + signed_size;
745         signed_size += sizeof(struct blob);
746         // Previous additions are guaranteed not to overflow.
747         if ((ctx->descriptor.blob_size >
748              ctx->descriptor.descriptor_area_size - signed_size) ||
749             // Sanity check blob size
750             (ctx->descriptor.blob_size < sizeof(struct blob_data)))
751         {
752             CPRINTS(ctx, "%s: invalid blob size (0x%x)\n", __FUNCTION__,
753                     ctx->descriptor.blob_size);
754             return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
755         }
756         signed_size += ctx->descriptor.blob_size;
757     }
758     if (signature_struct_size >
759         ctx->descriptor.descriptor_area_size - signed_size)
760     {
761         CPRINTS(ctx,
762                 "%s: invalid descriptor area size "
763                 "(expected = 0x%x, actual = 0x%x)\n",
764                 __FUNCTION__, ctx->descriptor.descriptor_area_size,
765                 signed_size + signature_struct_size);
766         return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
767     }
768     signature_struct_offset = signed_size;
769     // Omit the actual signature.
770     rv = get_signature_field_offset(signature_scheme, &signature_offset);
771     if (rv != LIBCR51SIGN_SUCCESS)
772     {
773         return rv;
774     }
775     signed_size += signature_offset;
776 
777     // Lookup key & validate transition.
778     rv = validate_transition(ctx, intf, offset + signature_struct_offset);
779 
780     if (rv != LIBCR51SIGN_SUCCESS)
781     {
782         return rv;
783     }
784     return validate_signature(ctx, intf, offset, signed_size, signature_scheme,
785                               offset + signed_size);
786 }
787 
788 // Scans the external EEPROM for a magic value at "alignment" boundaries.
789 //
790 //@param device  Handle to the external EEPROM.
791 //@param magic   8-byte pattern to search for.
792 //@param start_offset  Offset to begin searching at.
793 //@param limit   Exclusive address (e.g. EEPROM size).
794 //@param alignment   Alignment boundaries (POW2) to search on.
795 //@param header_offset   Location to place the new header offset.
796 //@return LIBCR51SIGN_SUCCESS (or non-zero on error).
797 
798 int scan_for_magic_8(const struct libcr51sign_ctx* ctx,
799                      const struct libcr51sign_intf* intf, uint64_t magic,
800                      uint32_t start_offset, uint32_t limit, uint32_t alignment,
801                      uint32_t* header_offset)
802 {
803     uint64_t read_data;
804     uint32_t offset;
805     int rv;
806 
807     if (limit <= start_offset || limit > ctx->end_offset ||
808         limit < sizeof(magic) || !POWER_OF_TWO(alignment))
809     {
810         return LIBCR51SIGN_ERROR_INVALID_ARGUMENT;
811     }
812 
813     if (!intf->read)
814     {
815         CPRINTS(ctx, "%s: missing intf->read\n", __FUNCTION__);
816         return LIBCR51SIGN_ERROR_INVALID_INTERFACE;
817     }
818     // Align start_offset to the next valid boundary.
819     start_offset = ((start_offset - 1) & ~(alignment - 1)) + alignment;
820     for (offset = start_offset; offset < limit - sizeof(magic);
821          offset += alignment)
822     {
823         rv = intf->read((void*)ctx, offset, sizeof(read_data),
824                         (uint8_t*)&read_data);
825         if (rv != LIBCR51SIGN_SUCCESS)
826         {
827             return rv;
828         }
829         if (read_data == magic)
830         {
831             if (header_offset)
832             {
833                 *header_offset = offset;
834             }
835             return LIBCR51SIGN_SUCCESS;
836         }
837     }
838     // Failed to locate magic.
839     return LIBCR51SIGN_ERROR_FAILED_TO_LOCATE_MAGIC;
840 }
841 
842 // Check whether the signature on the image is valid.
843 // Validates the authenticity of an EEPROM image. Scans for & validates the
844 // signature on the image descriptor. If the descriptor validates, hashes the
845 // rest of the image to verify its integrity.
846 //
847 // @param[in] ctx - context which describes the image and holds opaque private
848 //                 data for the user of the library
849 // @param[in] intf - function pointers which interface to the current system
850 //                  and environment
851 // @param[out] image_regions - image_region pointer to an array for the output
852 //
853 // TODO(aranika) return valid key
854 //
855 // @return nonzero on error, zero on success
856 
857 failure_reason
858     libcr51sign_validate(const struct libcr51sign_ctx* ctx,
859                          struct libcr51sign_intf* intf,
860                          struct libcr51sign_validated_regions* image_regions)
861 {
862     int rv, rv_first_desc = LIBCR51SIGN_SUCCESS;
863     uint32_t descriptor_offset;
864     uint32_t payload_blob_offset = 0;
865 
866     if (!ctx)
867     {
868         CPRINTS(ctx, "%s: Missing context\n", __FUNCTION__);
869         return LIBCR51SIGN_ERROR_INVALID_CONTEXT;
870     }
871     else if (!intf)
872     {
873         CPRINTS(ctx, "%s: Missing interface\n", __FUNCTION__);
874         return LIBCR51SIGN_ERROR_INVALID_INTERFACE;
875     }
876 
877     rv = scan_for_magic_8(ctx, intf, DESCRIPTOR_MAGIC, ctx->start_offset,
878                           ctx->end_offset, DESCRIPTOR_ALIGNMENT,
879                           &descriptor_offset);
880     while (rv == LIBCR51SIGN_SUCCESS)
881     {
882         CPRINTS(ctx, "%s: potential image descriptor found @%x\n", __FUNCTION__,
883                 descriptor_offset);
884         // Validation is split into 3 functions to minimize stack usage.
885 
886         rv = validate_descriptor(
887             ctx, intf, descriptor_offset, descriptor_offset - ctx->start_offset,
888             ctx->end_offset - ctx->start_offset, &payload_blob_offset);
889         if (rv != LIBCR51SIGN_SUCCESS)
890         {
891             CPRINTS(ctx, "%s: validate_descriptor() failed ec%d\n",
892                     __FUNCTION__, rv);
893         }
894         else
895         {
896             rv = validate_payload_regions_helper(ctx, intf, descriptor_offset,
897                                                  image_regions);
898             if (rv != LIBCR51SIGN_SUCCESS)
899             {
900                 CPRINTS(ctx, "%s: validate_payload_regions() failed ec%d\n",
901                         __FUNCTION__, rv);
902             }
903             else if (ctx->descriptor.image_type == IMAGE_PROD)
904             {
905                 // Lookup and validate payload Image MAUV against Image MAUV
906                 // stored in the system after checking signature to ensure
907                 // offsets and sizes are not tampered with. Also, do this after
908                 // hash calculation for payload regions to ensure that stored
909                 // Image MAUV is updated (if necessary) as close to the end of
910                 // payload validation as possible
911                 rv = validate_payload_image_mauv(ctx, intf, payload_blob_offset,
912                                                  ctx->descriptor.blob_size);
913                 if (rv == LIBCR51SIGN_SUCCESS)
914                 {
915                     CPRINTS(ctx,
916                             "%s: Payload Image MAUV validation successful\n",
917                             __FUNCTION__);
918                     return rv;
919                 }
920                 if (rv == LIBCR51SIGN_ERROR_STORING_NEW_IMAGE_MAUV_DATA)
921                 {
922                     CPRINTS(
923                         ctx,
924                         "%s: Payload validation succeeded, but Image MAUV validation "
925                         "failed\n",
926                         __FUNCTION__);
927                     return LIBCR51SIGN_ERROR_VALID_IMAGE_BUT_NEW_IMAGE_MAUV_DATA_NOT_STORED;
928                 }
929                 CPRINTS(ctx, "%s: Payload Image MAUV validation failed\n",
930                         __FUNCTION__);
931                 // In practice, we expect only 1 valid image descriptor in
932                 // payload. If Image MAUV check fails for the payload after
933                 // validating the image descriptor, do not try validating other
934                 // image descriptors
935                 return rv;
936             }
937             else
938             {
939                 return rv;
940             }
941         }
942 
943         // Store the first desc fail reason if any
944         if (rv != LIBCR51SIGN_SUCCESS && rv_first_desc == LIBCR51SIGN_SUCCESS)
945             rv_first_desc = rv;
946 
947         // scan_for_magic_8() will round up to the next aligned boundary.
948         descriptor_offset++;
949         rv = scan_for_magic_8(ctx, intf, DESCRIPTOR_MAGIC, descriptor_offset,
950                               ctx->end_offset, DESCRIPTOR_ALIGNMENT,
951                               &descriptor_offset);
952     }
953     CPRINTS(ctx, "%s: failed to validate image ec%d\n", __FUNCTION__, rv);
954     // If desc validation failed for some reason then return that reason
955     if (rv_first_desc != LIBCR51SIGN_SUCCESS)
956         return rv_first_desc;
957     else
958         return rv;
959 }
960 
961 // @func to returns the libcr51sign error code as a string
962 // @param[in] ec - Error code
963 // @return error code in string format
964 
965 const char* libcr51sign_errorcode_to_string(failure_reason ec)
966 {
967     switch (ec)
968     {
969         case LIBCR51SIGN_SUCCESS:
970             return "Success";
971         case LIBCR51SIGN_ERROR_RUNTIME_FAILURE:
972             return "Runtime Error Failure";
973         case LIBCR51SIGN_ERROR_UNSUPPORTED_DESCRIPTOR:
974             return "Unsupported descriptor";
975         case LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR:
976             return "Invalid descriptor";
977         case LIBCR51SIGN_ERROR_INVALID_IMAGE_FAMILY:
978             return "Invalid image family";
979         case LIBCR51SIGN_ERROR_IMAGE_TYPE_DISALLOWED:
980             return "Image type disallowed";
981         case LIBCR51SIGN_ERROR_DEV_DOWNGRADE_DISALLOWED:
982             return "Dev downgrade disallowed";
983         case LIBCR51SIGN_ERROR_UNTRUSTED_KEY:
984             return "Untrusted key";
985         case LIBCR51SIGN_ERROR_INVALID_SIGNATURE:
986             return "Invalid signature";
987         case LIBCR51SIGN_ERROR_INVALID_HASH:
988             return "Invalid hash";
989         case LIBCR51SIGN_ERROR_INVALID_HASH_TYPE:
990             return "Invalid hash type";
991         case LIBCR51SIGN_ERROR_INVALID_ARGUMENT:
992             return "Invalid Argument";
993         case LIBCR51SIGN_ERROR_FAILED_TO_LOCATE_MAGIC:
994             return "Failed to locate descriptor";
995         case LIBCR51SIGN_ERROR_INVALID_CONTEXT:
996             return "Invalid context";
997         case LIBCR51SIGN_ERROR_INVALID_INTERFACE:
998             return "Invalid interface";
999         case LIBCR51SIGN_ERROR_INVALID_SIG_SCHEME:
1000             return "Invalid signature scheme";
1001         case LIBCR51SIGN_ERROR_INVALID_REGION_INPUT:
1002             return "Invalid image region input";
1003         case LIBCR51SIGN_ERROR_INVALID_REGION_SIZE:
1004             return "Invalid image region size";
1005         case LIBCR51SIGN_ERROR_INVALID_IMAGE_MAUV_DATA:
1006             return "Invalid Image MAUV data";
1007         case LIBCR51SIGN_ERROR_RETRIEVING_STORED_IMAGE_MAUV_DATA:
1008             return "Failed to retrieve Image MAUV data stored in system";
1009         case LIBCR51SIGN_ERROR_STORING_NEW_IMAGE_MAUV_DATA:
1010             return "Failed to store Image MAUV data from payload image into system";
1011         case LIBCR51SIGN_ERROR_STORED_IMAGE_MAUV_DOES_NOT_ALLOW_UPDATE_TO_PAYLOAD:
1012             return "Image MAUV stored in system does not allow payload "
1013                    "update";
1014         case LIBCR51SIGN_ERROR_VALID_IMAGE_BUT_NEW_IMAGE_MAUV_DATA_NOT_STORED:
1015             return "Payload image is valid for update but failed to store new Image "
1016                    "MAUV in system";
1017         case LIBCR51SIGN_ERROR_STORED_IMAGE_MAUV_EXPECTS_PAYLOAD_IMAGE_MAUV:
1018             return "Image MAUV is expected to be present in payload when stored "
1019                    "Image MAUV is present in the system";
1020         case LIBCR51SIGN_NO_STORED_MAUV_FOUND:
1021             return "Client did not find any MAUV data stored in the system";
1022         default:
1023             return "Unknown error";
1024     }
1025 }
1026 
1027 #ifdef __cplusplus
1028 } //  extern "C"
1029 #endif
1030