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 //
get_key_size(enum signature_scheme signature_scheme,uint16_t * key_size)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.
get_hash_type_from_signature(enum signature_scheme scheme,enum hash_type * type)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.
is_hash_type_supported(enum hash_type type)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.
get_hash_digest_size(enum hash_type type,uint32_t * size)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.
get_hash_struct_size(enum hash_type type,uint32_t * size)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 
validate_transition(const struct libcr51sign_ctx * ctx,const struct libcr51sign_intf * intf,uint32_t signature_struct_offset)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 
read_and_hash_update(const struct libcr51sign_ctx * ctx,const struct libcr51sign_intf * intf,uint32_t offset,uint32_t size)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 
validate_payload_regions(const struct libcr51sign_ctx * ctx,struct libcr51sign_intf * intf,uint32_t d_offset,struct libcr51sign_validated_regions * image_regions)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 
allocate_and_validate_payload_regions(const struct libcr51sign_ctx * ctx,struct libcr51sign_intf * intf,uint32_t d_offset)454 static failure_reason allocate_and_validate_payload_regions(
455     const struct libcr51sign_ctx* ctx, struct libcr51sign_intf* intf,
456     uint32_t d_offset)
457 {
458     struct libcr51sign_validated_regions image_regions;
459     return validate_payload_regions(ctx, intf, d_offset, &image_regions);
460 }
461 
462 // Wrapper around validate_payload_regions to allow nullptr for image_regions.
463 // Calls allocate_and_validate_payload_regions when image_regions is nullptr to
464 // create placer holder image_regions.
465 
validate_payload_regions_helper(const struct libcr51sign_ctx * ctx,struct libcr51sign_intf * intf,uint32_t d_offset,struct libcr51sign_validated_regions * image_regions)466 static failure_reason validate_payload_regions_helper(
467     const struct libcr51sign_ctx* ctx, struct libcr51sign_intf* intf,
468     uint32_t d_offset, struct libcr51sign_validated_regions* image_regions)
469 {
470     if (image_regions)
471     {
472         return validate_payload_regions(ctx, intf, d_offset, image_regions);
473     }
474 
475     return allocate_and_validate_payload_regions(ctx, intf, d_offset);
476 }
477 
478 // Check if the given signature_scheme is supported.
479 // Returns nonzero on error, zero on success
480 
481 static failure_reason
is_signature_scheme_supported(enum signature_scheme scheme)482     is_signature_scheme_supported(enum signature_scheme scheme)
483 {
484     switch (scheme)
485     {
486         case SIGNATURE_RSA2048_PKCS15:
487         case SIGNATURE_RSA3072_PKCS15:
488         case SIGNATURE_RSA4096_PKCS15:
489         case SIGNATURE_RSA4096_PKCS15_SHA512:
490             return LIBCR51SIGN_SUCCESS;
491         default:
492             return LIBCR51SIGN_ERROR_INVALID_SIG_SCHEME;
493     }
494 }
495 
496 // Returns size of signature struct size in |size|
497 // Returns nonzero on error, zero on success
498 
499 static failure_reason
get_signature_struct_size(enum signature_scheme scheme,uint32_t * size)500     get_signature_struct_size(enum signature_scheme scheme, uint32_t* size)
501 {
502     switch (scheme)
503     {
504         case SIGNATURE_RSA2048_PKCS15:
505             *size = sizeof(struct signature_rsa2048_pkcs15);
506             return LIBCR51SIGN_SUCCESS;
507         case SIGNATURE_RSA3072_PKCS15:
508             *size = sizeof(struct signature_rsa3072_pkcs15);
509             return LIBCR51SIGN_SUCCESS;
510         case SIGNATURE_RSA4096_PKCS15:
511         case SIGNATURE_RSA4096_PKCS15_SHA512:
512             *size = sizeof(struct signature_rsa4096_pkcs15);
513             return LIBCR51SIGN_SUCCESS;
514         default:
515             return LIBCR51SIGN_ERROR_INVALID_SIG_SCHEME;
516     }
517 }
518 
519 static failure_reason
get_signature_field_offset(enum signature_scheme scheme,uint32_t * offset)520     get_signature_field_offset(enum signature_scheme scheme, uint32_t* offset)
521 {
522     switch (scheme)
523     {
524         case SIGNATURE_RSA2048_PKCS15:
525             *offset = offsetof(struct signature_rsa2048_pkcs15, signature);
526             return LIBCR51SIGN_SUCCESS;
527         case SIGNATURE_RSA3072_PKCS15:
528             *offset = offsetof(struct signature_rsa3072_pkcs15, signature);
529             return LIBCR51SIGN_SUCCESS;
530         case SIGNATURE_RSA4096_PKCS15:
531         case SIGNATURE_RSA4096_PKCS15_SHA512:
532             *offset = offsetof(struct signature_rsa4096_pkcs15, signature);
533             return LIBCR51SIGN_SUCCESS;
534         default:
535             return LIBCR51SIGN_ERROR_INVALID_SIG_SCHEME;
536     }
537 }
538 
539 // Validates the signature (of type scheme) read from "device" at
540 //"raw_signature_offset" with "public_key" over a SHA256/SHA512 digest of
541 // EEPROM area "data_offset:data_size".
542 
validate_signature(const struct libcr51sign_ctx * ctx,const struct libcr51sign_intf * intf,uint32_t data_offset,uint32_t data_size,enum signature_scheme scheme,uint32_t raw_signature_offset)543 static failure_reason validate_signature(
544     const struct libcr51sign_ctx* ctx, const struct libcr51sign_intf* intf,
545     uint32_t data_offset, uint32_t data_size, enum signature_scheme scheme,
546     uint32_t raw_signature_offset)
547 {
548     uint8_t signature[LIBCR51SIGN_MAX_SIGNATURE_SIZE];
549     uint16_t key_size;
550     uint32_t digest_size;
551     uint8_t dcrypto_digest[LIBCR51SIGN_SHA512_DIGEST_SIZE];
552     int rv;
553     enum hash_type hash_type;
554 
555     if (!intf->hash_init)
556     {
557         CPRINTS(ctx, "%s: missing hash_init\n", __FUNCTION__);
558         return LIBCR51SIGN_ERROR_INVALID_INTERFACE;
559     }
560     rv = get_hash_type_from_signature(scheme, &hash_type);
561     if (rv != LIBCR51SIGN_SUCCESS)
562     {
563         CPRINTS(ctx, "%s: hash_type from signature failed\n", __FUNCTION__);
564         return rv;
565     }
566     rv = intf->hash_init(ctx, hash_type);
567     if (rv != LIBCR51SIGN_SUCCESS)
568     {
569         CPRINTS(ctx, "%s: hash_init failed\n", __FUNCTION__);
570         return LIBCR51SIGN_ERROR_RUNTIME_FAILURE;
571     }
572     rv = read_and_hash_update(ctx, intf, data_offset, data_size);
573     if (rv != LIBCR51SIGN_SUCCESS)
574     {
575         CPRINTS(ctx, "%s: hash_update failed\n", __FUNCTION__);
576         return rv;
577     }
578     if (!intf->hash_final)
579     {
580         CPRINTS(ctx, "%s: missing hash_final\n", __FUNCTION__);
581         return LIBCR51SIGN_ERROR_INVALID_INTERFACE;
582     }
583     rv = intf->hash_final((void*)ctx, dcrypto_digest);
584     if (rv != LIBCR51SIGN_SUCCESS)
585     {
586         CPRINTS(ctx, "%s: hash_final failed (status = %d)\n", __FUNCTION__, rv);
587         return LIBCR51SIGN_ERROR_RUNTIME_FAILURE;
588     }
589     rv = get_key_size(scheme, &key_size);
590     if (rv != LIBCR51SIGN_SUCCESS)
591     {
592         return rv;
593     }
594 
595     rv = intf->read(ctx, raw_signature_offset, key_size, signature);
596     if (rv != LIBCR51SIGN_SUCCESS)
597     {
598         CPRINTS(ctx, "%s: failed to read signature (status = %d)\n",
599                 __FUNCTION__, rv);
600         return LIBCR51SIGN_ERROR_RUNTIME_FAILURE;
601     }
602     if (!intf->verify_signature)
603     {
604         CPRINTS(ctx, "%s: missing verify_signature\n", __FUNCTION__);
605         return LIBCR51SIGN_ERROR_INVALID_INTERFACE;
606     }
607     rv = get_hash_digest_size(hash_type, &digest_size);
608     if (rv != LIBCR51SIGN_SUCCESS)
609     {
610         return rv;
611     }
612     rv = intf->verify_signature(ctx, scheme, signature, key_size,
613                                 dcrypto_digest, digest_size);
614     if (rv != LIBCR51SIGN_SUCCESS)
615     {
616         CPRINTS(ctx, "%s: verification failed (status = %d)\n", __FUNCTION__,
617                 rv);
618         return LIBCR51SIGN_ERROR_INVALID_SIGNATURE;
619     }
620     CPRINTS(ctx, "%s: verification succeeded\n", __FUNCTION__);
621     return LIBCR51SIGN_SUCCESS;
622 }
623 
624 // Sanity checks the image descriptor & validates its signature.
625 // This function does not validate the image_region array or image hash.
626 //
627 //@param[in] ctx  context which describes the image and holds opaque private
628 //                 data for the user of the library
629 //@param[in] intf  function pointers which interface to the current system
630 // and environment
631 //@param offset  Absolute image descriptor flash offset.
632 //@param relative_offset  Image descriptor offset relative to image start.
633 //@param max_size Maximum size of the flash space in bytes.
634 //@param[out] payload_blob_offset  Absolute offset of BLOB data in image
635 //                                 descriptor (if BLOB data is present)
validate_descriptor(const struct libcr51sign_ctx * ctx,const struct libcr51sign_intf * intf,uint32_t offset,uint32_t relative_offset,uint32_t max_size,uint32_t * const restrict payload_blob_offset)636 static failure_reason validate_descriptor(
637     const struct libcr51sign_ctx* ctx, const struct libcr51sign_intf* intf,
638     uint32_t offset, uint32_t relative_offset, uint32_t max_size,
639     uint32_t* const restrict payload_blob_offset)
640 {
641     uint32_t max_descriptor_size, signed_size, signature_scheme,
642         signature_offset;
643     uint32_t signature_struct_offset, signature_struct_size, hash_struct_size;
644     int rv;
645 
646     max_descriptor_size = max_size - relative_offset;
647     if (max_size < relative_offset ||
648         max_descriptor_size < sizeof(struct image_descriptor))
649     {
650         CPRINTS(ctx, "%s: invalid arguments\n", __FUNCTION__);
651         return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
652     }
653 
654     rv = intf->read(ctx, offset, sizeof(ctx->descriptor),
655                     (uint8_t*)&ctx->descriptor);
656     if (rv != LIBCR51SIGN_SUCCESS)
657     {
658         CPRINTS(ctx, "%s: failed to read descriptor\n", __FUNCTION__);
659         return LIBCR51SIGN_ERROR_RUNTIME_FAILURE;
660     }
661     if (ctx->descriptor.descriptor_magic != DESCRIPTOR_MAGIC ||
662         ctx->descriptor.descriptor_offset != relative_offset ||
663         ctx->descriptor.region_count == 0 ||
664         ctx->descriptor.descriptor_area_size > max_descriptor_size ||
665         ctx->descriptor.image_size > max_size)
666     {
667         CPRINTS(ctx, "%s: invalid descriptor\n", __FUNCTION__);
668         return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
669     }
670     if (intf->image_size_valid == NULL)
671     {
672         // Preserve original behavior of requiring exact image_size match if no
673         // operator is provided.
674         if (ctx->descriptor.image_size != max_size)
675         {
676             CPRINTS(ctx, "%s: invalid image size\n", __FUNCTION__);
677             return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
678         }
679     }
680     else if (!intf->image_size_valid(ctx->descriptor.image_size))
681     {
682         CPRINTS(ctx, "%s: invalid image size\n", __FUNCTION__);
683         return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
684     }
685     if (ctx->descriptor.image_type != IMAGE_DEV &&
686         ctx->descriptor.image_type != IMAGE_PROD &&
687         ctx->descriptor.image_type != IMAGE_BREAKOUT &&
688         ctx->descriptor.image_type != IMAGE_TEST &&
689         ctx->descriptor.image_type != IMAGE_UNSIGNED_INTEGRITY)
690     {
691         CPRINTS(ctx, "%s: bad image type\n", __FUNCTION__);
692         return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
693     }
694     // Although the image_descriptor struct supports unauthenticated
695     // images, Haven will not allow it.
696     // Haven only supports SHA256 + RSA2048/RSA3072_PKCS15 currently.
697 
698     signature_scheme = ctx->descriptor.signature_scheme;
699 
700     rv = is_signature_scheme_supported(signature_scheme);
701     if (rv != LIBCR51SIGN_SUCCESS)
702     {
703         return rv;
704     }
705     rv = is_hash_type_supported(ctx->descriptor.hash_type);
706     if (rv != LIBCR51SIGN_SUCCESS)
707     {
708         CPRINTS(ctx, "%s: invalid hash type\n", __FUNCTION__);
709         return rv;
710     }
711     if (ctx->descriptor.descriptor_major > MAX_MAJOR_VERSION ||
712         ctx->descriptor.region_count > LIBCR51SIGN_MAX_REGION_COUNT)
713     {
714         CPRINTS(ctx, "%s: unsupported descriptor\n", __FUNCTION__);
715         return LIBCR51SIGN_ERROR_UNSUPPORTED_DESCRIPTOR;
716     }
717     rv = get_signature_struct_size(signature_scheme, &signature_struct_size);
718     if (rv != LIBCR51SIGN_SUCCESS)
719     {
720         return rv;
721     }
722 
723     // Compute the size of the signed portion of the image descriptor.
724     signed_size = sizeof(struct image_descriptor) +
725                   ctx->descriptor.region_count * sizeof(struct image_region);
726     rv = get_hash_struct_size(ctx->descriptor.hash_type, &hash_struct_size);
727     if (rv != LIBCR51SIGN_SUCCESS)
728     {
729         return rv;
730     }
731     signed_size += hash_struct_size;
732     if (ctx->descriptor.denylist_size)
733     {
734         signed_size += sizeof(struct denylist);
735         signed_size += ctx->descriptor.denylist_size *
736                        sizeof(struct denylist_record);
737     }
738     if (ctx->descriptor.blob_size)
739     {
740         *payload_blob_offset = offset + signed_size;
741         signed_size += sizeof(struct blob);
742         // Previous additions are guaranteed not to overflow.
743         if ((ctx->descriptor.blob_size >
744              ctx->descriptor.descriptor_area_size - signed_size) ||
745             // Sanity check blob size
746             (ctx->descriptor.blob_size < sizeof(struct blob_data)))
747         {
748             CPRINTS(ctx, "%s: invalid blob size (0x%x)\n", __FUNCTION__,
749                     ctx->descriptor.blob_size);
750             return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
751         }
752         signed_size += ctx->descriptor.blob_size;
753     }
754     if (signature_struct_size >
755         ctx->descriptor.descriptor_area_size - signed_size)
756     {
757         CPRINTS(ctx,
758                 "%s: invalid descriptor area size "
759                 "(expected = 0x%x, actual = 0x%x)\n",
760                 __FUNCTION__, ctx->descriptor.descriptor_area_size,
761                 signed_size + signature_struct_size);
762         return LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR;
763     }
764     signature_struct_offset = signed_size;
765     // Omit the actual signature.
766     rv = get_signature_field_offset(signature_scheme, &signature_offset);
767     if (rv != LIBCR51SIGN_SUCCESS)
768     {
769         return rv;
770     }
771     signed_size += signature_offset;
772 
773     // Lookup key & validate transition.
774     rv = validate_transition(ctx, intf, offset + signature_struct_offset);
775 
776     if (rv != LIBCR51SIGN_SUCCESS)
777     {
778         return rv;
779     }
780     return validate_signature(ctx, intf, offset, signed_size, signature_scheme,
781                               offset + signed_size);
782 }
783 
784 // Scans the external EEPROM for a magic value at "alignment" boundaries.
785 //
786 //@param device  Handle to the external EEPROM.
787 //@param magic   8-byte pattern to search for.
788 //@param start_offset  Offset to begin searching at.
789 //@param limit   Exclusive address (e.g. EEPROM size).
790 //@param alignment   Alignment boundaries (POW2) to search on.
791 //@param header_offset   Location to place the new header offset.
792 //@return LIBCR51SIGN_SUCCESS (or non-zero on error).
793 
scan_for_magic_8(const struct libcr51sign_ctx * ctx,const struct libcr51sign_intf * intf,uint64_t magic,uint32_t start_offset,uint32_t limit,uint32_t alignment,uint32_t * header_offset)794 int scan_for_magic_8(const struct libcr51sign_ctx* ctx,
795                      const struct libcr51sign_intf* intf, uint64_t magic,
796                      uint32_t start_offset, uint32_t limit, uint32_t alignment,
797                      uint32_t* header_offset)
798 {
799     uint64_t read_data;
800     uint32_t offset;
801     int rv;
802 
803     if (limit <= start_offset || limit > ctx->end_offset ||
804         limit < sizeof(magic) || !POWER_OF_TWO(alignment))
805     {
806         return LIBCR51SIGN_ERROR_INVALID_ARGUMENT;
807     }
808 
809     if (!intf->read)
810     {
811         CPRINTS(ctx, "%s: missing intf->read\n", __FUNCTION__);
812         return LIBCR51SIGN_ERROR_INVALID_INTERFACE;
813     }
814     // Align start_offset to the next valid boundary.
815     start_offset = ((start_offset - 1) & ~(alignment - 1)) + alignment;
816     for (offset = start_offset; offset < limit - sizeof(magic);
817          offset += alignment)
818     {
819         rv = intf->read((void*)ctx, offset, sizeof(read_data),
820                         (uint8_t*)&read_data);
821         if (rv != LIBCR51SIGN_SUCCESS)
822         {
823             return rv;
824         }
825         if (read_data == magic)
826         {
827             if (header_offset)
828             {
829                 *header_offset = offset;
830             }
831             return LIBCR51SIGN_SUCCESS;
832         }
833     }
834     // Failed to locate magic.
835     return LIBCR51SIGN_ERROR_FAILED_TO_LOCATE_MAGIC;
836 }
837 
838 // Check whether the signature on the image is valid.
839 // Validates the authenticity of an EEPROM image. Scans for & validates the
840 // signature on the image descriptor. If the descriptor validates, hashes the
841 // rest of the image to verify its integrity.
842 //
843 // @param[in] ctx - context which describes the image and holds opaque private
844 //                 data for the user of the library
845 // @param[in] intf - function pointers which interface to the current system
846 //                  and environment
847 // @param[out] image_regions - image_region pointer to an array for the output
848 //
849 // TODO(aranika) return valid key
850 //
851 // @return nonzero on error, zero on success
852 
libcr51sign_validate(const struct libcr51sign_ctx * ctx,struct libcr51sign_intf * intf,struct libcr51sign_validated_regions * image_regions)853 failure_reason libcr51sign_validate(
854     const struct libcr51sign_ctx* ctx, struct libcr51sign_intf* intf,
855     struct libcr51sign_validated_regions* image_regions)
856 {
857     int rv, rv_first_desc = LIBCR51SIGN_SUCCESS;
858     uint32_t descriptor_offset;
859     uint32_t payload_blob_offset = 0;
860 
861     if (!ctx)
862     {
863         CPRINTS(ctx, "%s: Missing context\n", __FUNCTION__);
864         return LIBCR51SIGN_ERROR_INVALID_CONTEXT;
865     }
866     else if (!intf)
867     {
868         CPRINTS(ctx, "%s: Missing interface\n", __FUNCTION__);
869         return LIBCR51SIGN_ERROR_INVALID_INTERFACE;
870     }
871 
872     rv = scan_for_magic_8(ctx, intf, DESCRIPTOR_MAGIC, ctx->start_offset,
873                           ctx->end_offset, DESCRIPTOR_ALIGNMENT,
874                           &descriptor_offset);
875     while (rv == LIBCR51SIGN_SUCCESS)
876     {
877         CPRINTS(ctx, "%s: potential image descriptor found @%x\n", __FUNCTION__,
878                 descriptor_offset);
879         // Validation is split into 3 functions to minimize stack usage.
880 
881         rv = validate_descriptor(
882             ctx, intf, descriptor_offset, descriptor_offset - ctx->start_offset,
883             ctx->end_offset - ctx->start_offset, &payload_blob_offset);
884         if (rv != LIBCR51SIGN_SUCCESS)
885         {
886             CPRINTS(ctx, "%s: validate_descriptor() failed ec%d\n",
887                     __FUNCTION__, rv);
888         }
889         else
890         {
891             rv = validate_payload_regions_helper(ctx, intf, descriptor_offset,
892                                                  image_regions);
893             if (rv != LIBCR51SIGN_SUCCESS)
894             {
895                 CPRINTS(ctx, "%s: validate_payload_regions() failed ec%d\n",
896                         __FUNCTION__, rv);
897             }
898             else if (ctx->descriptor.image_type == IMAGE_PROD)
899             {
900                 // Lookup and validate payload Image MAUV against Image MAUV
901                 // stored in the system after checking signature to ensure
902                 // offsets and sizes are not tampered with. Also, do this after
903                 // hash calculation for payload regions to ensure that stored
904                 // Image MAUV is updated (if necessary) as close to the end of
905                 // payload validation as possible
906                 rv = validate_payload_image_mauv(ctx, intf, payload_blob_offset,
907                                                  ctx->descriptor.blob_size);
908                 if (rv == LIBCR51SIGN_SUCCESS)
909                 {
910                     CPRINTS(ctx,
911                             "%s: Payload Image MAUV validation successful\n",
912                             __FUNCTION__);
913                     return rv;
914                 }
915                 if (rv == LIBCR51SIGN_ERROR_STORING_NEW_IMAGE_MAUV_DATA)
916                 {
917                     CPRINTS(
918                         ctx,
919                         "%s: Payload validation succeeded, but Image MAUV validation "
920                         "failed\n",
921                         __FUNCTION__);
922                     return LIBCR51SIGN_ERROR_VALID_IMAGE_BUT_NEW_IMAGE_MAUV_DATA_NOT_STORED;
923                 }
924                 CPRINTS(ctx, "%s: Payload Image MAUV validation failed\n",
925                         __FUNCTION__);
926                 // In practice, we expect only 1 valid image descriptor in
927                 // payload. If Image MAUV check fails for the payload after
928                 // validating the image descriptor, do not try validating other
929                 // image descriptors
930                 return rv;
931             }
932             else
933             {
934                 return rv;
935             }
936         }
937 
938         // Store the first desc fail reason if any
939         if (rv != LIBCR51SIGN_SUCCESS && rv_first_desc == LIBCR51SIGN_SUCCESS)
940             rv_first_desc = rv;
941 
942         // scan_for_magic_8() will round up to the next aligned boundary.
943         descriptor_offset++;
944         rv = scan_for_magic_8(ctx, intf, DESCRIPTOR_MAGIC, descriptor_offset,
945                               ctx->end_offset, DESCRIPTOR_ALIGNMENT,
946                               &descriptor_offset);
947     }
948     CPRINTS(ctx, "%s: failed to validate image ec%d\n", __FUNCTION__, rv);
949     // If desc validation failed for some reason then return that reason
950     if (rv_first_desc != LIBCR51SIGN_SUCCESS)
951         return rv_first_desc;
952     else
953         return rv;
954 }
955 
956 // @func to returns the libcr51sign error code as a string
957 // @param[in] ec - Error code
958 // @return error code in string format
959 
libcr51sign_errorcode_to_string(failure_reason ec)960 const char* libcr51sign_errorcode_to_string(failure_reason ec)
961 {
962     switch (ec)
963     {
964         case LIBCR51SIGN_SUCCESS:
965             return "Success";
966         case LIBCR51SIGN_ERROR_RUNTIME_FAILURE:
967             return "Runtime Error Failure";
968         case LIBCR51SIGN_ERROR_UNSUPPORTED_DESCRIPTOR:
969             return "Unsupported descriptor";
970         case LIBCR51SIGN_ERROR_INVALID_DESCRIPTOR:
971             return "Invalid descriptor";
972         case LIBCR51SIGN_ERROR_INVALID_IMAGE_FAMILY:
973             return "Invalid image family";
974         case LIBCR51SIGN_ERROR_IMAGE_TYPE_DISALLOWED:
975             return "Image type disallowed";
976         case LIBCR51SIGN_ERROR_DEV_DOWNGRADE_DISALLOWED:
977             return "Dev downgrade disallowed";
978         case LIBCR51SIGN_ERROR_UNTRUSTED_KEY:
979             return "Untrusted key";
980         case LIBCR51SIGN_ERROR_INVALID_SIGNATURE:
981             return "Invalid signature";
982         case LIBCR51SIGN_ERROR_INVALID_HASH:
983             return "Invalid hash";
984         case LIBCR51SIGN_ERROR_INVALID_HASH_TYPE:
985             return "Invalid hash type";
986         case LIBCR51SIGN_ERROR_INVALID_ARGUMENT:
987             return "Invalid Argument";
988         case LIBCR51SIGN_ERROR_FAILED_TO_LOCATE_MAGIC:
989             return "Failed to locate descriptor";
990         case LIBCR51SIGN_ERROR_INVALID_CONTEXT:
991             return "Invalid context";
992         case LIBCR51SIGN_ERROR_INVALID_INTERFACE:
993             return "Invalid interface";
994         case LIBCR51SIGN_ERROR_INVALID_SIG_SCHEME:
995             return "Invalid signature scheme";
996         case LIBCR51SIGN_ERROR_INVALID_REGION_INPUT:
997             return "Invalid image region input";
998         case LIBCR51SIGN_ERROR_INVALID_REGION_SIZE:
999             return "Invalid image region size";
1000         case LIBCR51SIGN_ERROR_INVALID_IMAGE_MAUV_DATA:
1001             return "Invalid Image MAUV data";
1002         case LIBCR51SIGN_ERROR_RETRIEVING_STORED_IMAGE_MAUV_DATA:
1003             return "Failed to retrieve Image MAUV data stored in system";
1004         case LIBCR51SIGN_ERROR_STORING_NEW_IMAGE_MAUV_DATA:
1005             return "Failed to store Image MAUV data from payload image into system";
1006         case LIBCR51SIGN_ERROR_STORED_IMAGE_MAUV_DOES_NOT_ALLOW_UPDATE_TO_PAYLOAD:
1007             return "Image MAUV stored in system does not allow payload "
1008                    "update";
1009         case LIBCR51SIGN_ERROR_VALID_IMAGE_BUT_NEW_IMAGE_MAUV_DATA_NOT_STORED:
1010             return "Payload image is valid for update but failed to store new Image "
1011                    "MAUV in system";
1012         case LIBCR51SIGN_ERROR_STORED_IMAGE_MAUV_EXPECTS_PAYLOAD_IMAGE_MAUV:
1013             return "Image MAUV is expected to be present in payload when stored "
1014                    "Image MAUV is present in the system";
1015         case LIBCR51SIGN_NO_STORED_MAUV_FOUND:
1016             return "Client did not find any MAUV data stored in the system";
1017         default:
1018             return "Unknown error";
1019     }
1020 }
1021 
1022 #ifdef __cplusplus
1023 } //  extern "C"
1024 #endif
1025