aboutsummaryrefslogtreecommitdiff
path: root/secure_fw/services/initial_attestation/attestation_core.c
blob: 052107c02e3cbfb5c0323c09a5a012deca773dec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
/*
 * Copyright (c) 2018-2020, Arm Limited. All rights reserved.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 *
 */

#include <stdint.h>
#include <string.h>
#include <stddef.h>
#include "tfm_client.h"
#include "attestation.h"
#include "attestation_key.h"
#include "tfm_boot_status.h"
#include "tfm_plat_defs.h"
#include "tfm_plat_device_id.h"
#include "tfm_plat_boot_seed.h"
#include "tfm_attest_hal.h"
#include "attest_token.h"
#include "attest_eat_defines.h"
#include "t_cose_common.h"
#include "tfm_memory_utils.h"
#include "platform/include/tfm_plat_crypto_keys.h"

#define MAX_BOOT_STATUS 512

/* Indicates how to encode SW components' measurements in the CBOR map */
#define EAT_SW_COMPONENT_NESTED     1  /* Nested map */
#define EAT_SW_COMPONENT_NOT_NESTED 0  /* Flat structure */

/*!
 * \struct attest_boot_data
 *
 * \brief Contains the received boot status information from bootloader
 *
 * \details This is a redefinition of \ref tfm_boot_data to allocate the
 *          appropriate, service dependent size of \ref boot_data.
 */
struct attest_boot_data {
    struct shared_data_tlv_header header;
    uint8_t data[MAX_BOOT_STATUS];
};

/*!
 * \var boot_data
 *
 * \brief Store the boot status in service's memory.
 *
 * \details Boot status comes from the secure bootloader and primarily stored
 *          on a memory area which is shared between bootloader and SPM.
 *          SPM provides the \ref tfm_core_get_boot_data() API to retrieve
 *          the service related data from shared area.
 */
__attribute__ ((aligned(4)))
static struct attest_boot_data boot_data;

enum psa_attest_err_t attest_init(void)
{
    enum psa_attest_err_t res;

    res = attest_get_boot_data(TLV_MAJOR_IAS,
                               (struct tfm_boot_data *)&boot_data,
                               MAX_BOOT_STATUS);

    return res;
}

/*!
 * \brief Static function to map return values between \ref attest_token_err_t
 *        and \ref psa_attest_err_t
 *
 * \param[in]  token_err  Token encoding return value
 *
 * \return Returns error code as specified in \ref psa_attest_err_t
 */
static inline enum psa_attest_err_t
error_mapping(enum attest_token_err_t token_err)
{
    switch (token_err) {
    case ATTEST_TOKEN_ERR_SUCCESS:
        return PSA_ATTEST_ERR_SUCCESS;
        break;
    case ATTEST_TOKEN_ERR_TOO_SMALL:
        return PSA_ATTEST_ERR_TOKEN_BUFFER_OVERFLOW;
        break;
    default:
        return PSA_ATTEST_ERR_GENERAL;
    }
}

/*!
 * \brief Static function to convert a pointer and size info to unsigned
 *        integer number. Max 32bits unsigned integers are supported.
 *
 * This implementation assumes that the endianness of the sender and receiver
 * of the data is the same because they are actually running on the same CPU
 * instance. If this assumption is not true than this function must be
 * refactored accordingly.
 *
 * \param[in]  int_ptr  Pointer to the unsigned integer
 * \param[in]  len      Size of the unsigned integers in bytes
 * \param[in]  value    Pointer where to store the converted value
 *
 * \return Returns 0 on success and -1 on error.
 */
static inline int32_t get_uint(const void *int_ptr,
                               size_t len,
                               uint32_t *value)
{
    uint16_t uint16;

    switch (len) {
    case 1:
        *value = (uint32_t)(*(uint8_t  *)(int_ptr));
        break;
    case 2:
        /* Avoid unaligned access */
        (void)tfm_memcpy(&uint16, int_ptr, sizeof(uint16));
        *value = (uint32_t)uint16;
        break;
    case 4:
        /* Avoid unaligned access */
        (void)tfm_memcpy(value, int_ptr, sizeof(uint32_t));
        break;
    default:
        return -1;
    }

    return 0;
}
/*!
 * \brief Static function to look up all entires in the shared data area
 *       (boot status) which belong to a specific module.
 *
 * \param[in]     module  The identifier of SW module to look up based on this
 * \param[out]    claim   The type of SW module's attribute
 * \param[out]    tlv_len Length of the shared data entry
 * \param[in/out] tlv_ptr Pointer to the shared data entry. If its value NULL as
 *                        input then it will starts the look up from the
 *                        beginning of the shared data section. If not NULL then
 *                        it continue look up from the next entry. It returns
 *                        the address of next found entry which belongs to
 *                        module.
 *
 * \retval    -1          Error, boot status is malformed
 * \retval     0          Entry not found
 * \retval     1          Entry found
 */
static int32_t attest_get_tlv_by_module(uint8_t    module,
                                        uint8_t   *claim,
                                        uint16_t  *tlv_len,
                                        uint8_t  **tlv_ptr)
{
    struct shared_data_tlv_entry tlv_entry;
    uint8_t *tlv_end;
    uint8_t *tlv_curr;

    if (boot_data.header.tlv_magic != SHARED_DATA_TLV_INFO_MAGIC) {
        return -1;
    }

    /* Get the boundaries of TLV section where to lookup*/
    tlv_end = (uint8_t *)&boot_data + boot_data.header.tlv_tot_len;
    if (*tlv_ptr == NULL) {
        /* At first call set to the beginning of the TLV section */
        tlv_curr = boot_data.data;
    } else {
        /* Any subsequent call set to the next TLV entry */
        (void)tfm_memcpy(&tlv_entry, *tlv_ptr, SHARED_DATA_ENTRY_HEADER_SIZE);
        tlv_curr  = (*tlv_ptr) + tlv_entry.tlv_len;
    }

    /* Iterates over the TLV section and returns the address and size of TLVs
     * with requested module identifier
     */
    for (; tlv_curr < tlv_end; tlv_curr += tlv_entry.tlv_len) {
        /* Create local copy to avoid unaligned access */
        (void)tfm_memcpy(&tlv_entry, tlv_curr, SHARED_DATA_ENTRY_HEADER_SIZE);
        if (GET_IAS_MODULE(tlv_entry.tlv_type) == module) {
            *claim   = GET_IAS_CLAIM(tlv_entry.tlv_type);
            *tlv_ptr = tlv_curr;
            *tlv_len = tlv_entry.tlv_len;
            return 1;
        }
    }

    return 0;
}

/*!
 * \brief Static function to look up specific claim belongs to SW_GENERAL module
 *
 * \param[in]   claim    The claim ID to look for
 * \param[out]  tlv_len  Length of the shared data entry
 * \param[out]  tlv_ptr  Pointer to a shared data entry which belongs to the
 *                       SW_GENERAL module.
 *
 * \retval    -1          Error, boot status is malformed
 * \retval     0          Entry not found
 * \retval     1          Entry found
 */
static int32_t attest_get_tlv_by_id(uint8_t    claim,
                                    uint16_t  *tlv_len,
                                    uint8_t  **tlv_ptr)
{
    uint8_t tlv_id;
    uint8_t module = SW_GENERAL;
    int32_t found;

    /* Ensure that look up starting from the beginning of the boot status */
    *tlv_ptr = NULL;

    /* Look up specific TLV entry which belongs to SW_GENERAL module */
    do {
        /* Look up next entry */
        found = attest_get_tlv_by_module(module, &tlv_id,
                                         tlv_len, tlv_ptr);
        if (found != 1) {
            break;
        }
        /* At least one entry was found which belongs to SW_GENERAL,
         * check whether this one is looked for
         */
        if (claim == tlv_id) {
            break;
        }
    } while (found == 1);

    return found;
}

#ifdef INDIVIDUAL_SW_COMPONENTS /* DEPRECATED */
/*!
 * \brief Static function to add SW component related claims to attestation
 *        token in CBOR format.
 *
 *  This function translates between TLV  and CBOR encoding.
 *
 * \param[in]  token_ctx    Attestation token encoding context
 * \param[in]  tlv_id       The ID of claim
 * \param[in]  claim_value  A structure which carries a pointer and size about
 *                          the data item to be added to the token
 *
 * \deprecated This function is deprecated and will probably be removed
 *             in the future.
 *
 * \return Returns error code as specified in \ref psa_attest_err_t
 */
static enum psa_attest_err_t
attest_add_sw_component_claim(struct attest_token_ctx *token_ctx,
                              uint8_t tlv_id,
                              const struct q_useful_buf_c *claim_value)
{
    switch (tlv_id) {
    case SW_MEASURE_VALUE:
        attest_token_add_bstr(token_ctx,
                              EAT_CBOR_SW_COMPONENT_MEASUREMENT_VALUE,
                              claim_value);
        break;
    case SW_MEASURE_TYPE:
        attest_token_add_tstr(token_ctx,
                              EAT_CBOR_SW_COMPONENT_MEASUREMENT_DESC,
                              claim_value);
        break;
    case SW_VERSION:
        attest_token_add_tstr(token_ctx,
                              EAT_CBOR_SW_COMPONENT_VERSION,
                              claim_value);
        break;
    case SW_SIGNER_ID:
        attest_token_add_bstr(token_ctx,
                              EAT_CBOR_SW_COMPONENT_SIGNER_ID,
                              claim_value);
        break;
    case SW_TYPE:
        attest_token_add_tstr(token_ctx,
                              EAT_CBOR_SW_COMPONENT_MEASUREMENT_TYPE,
                              claim_value);
        break;
    default:
        return PSA_ATTEST_ERR_GENERAL;
    }

    return PSA_ATTEST_ERR_SUCCESS;
}

/*!
 * \brief Static function to add the measurement data of a single SW components
 *        to the attestation token.
 *
 * \param[in]  token_ctx    Token encoding context
 * \param[in]  module       SW component identifier
 * \param[in]  tlv_address  Address of the first TLV entry in the boot status,
 *                          which belongs to this SW component.
 * \param[in]  nested_map   Flag to indicate that how to encode the SW component
 *                          measurement data: nested map or non-nested map.
 * \deprecated This function is deprecated and will probably be removed
 *             in the future.
 *
 * \return Returns error code as specified in \ref psa_attest_err_t
 */
static enum psa_attest_err_t
attest_add_single_sw_measurment(struct attest_token_ctx *token_ctx,
                                uint32_t module,
                                uint8_t *tlv_address,
                                uint32_t nested_map)
{
    struct shared_data_tlv_entry tlv_entry;
    uint16_t tlv_len;
    uint8_t  tlv_id;
    uint8_t *tlv_ptr = tlv_address;
    int32_t found = 1;
    struct q_useful_buf_c claim_value;
    enum psa_attest_err_t res;
    QCBOREncodeContext *cbor_encode_ctx;

    /* Create local copy to avoid unaligned access */
    (void)tfm_memcpy(&tlv_entry, tlv_address, SHARED_DATA_ENTRY_HEADER_SIZE);
    tlv_len = tlv_entry.tlv_len;
    tlv_id = GET_IAS_CLAIM(tlv_entry.tlv_type);

    cbor_encode_ctx = attest_token_borrow_cbor_cntxt(token_ctx);

    /* Open nested map for SW component measurement claims */
    if (nested_map) {
        QCBOREncode_OpenMapInMapN(cbor_encode_ctx,
                                 EAT_CBOR_SW_COMPONENT_MEASUREMENT_VALUE);
    }

    /* Look up all measurement TLV entry which belongs to the SW component */
    while (found) {
        /* Here only measurement claims are added to the token */
        if (GET_IAS_MEASUREMENT_CLAIM(tlv_id)) {
            claim_value.ptr = tlv_ptr + SHARED_DATA_ENTRY_HEADER_SIZE;
            claim_value.len = tlv_len - SHARED_DATA_ENTRY_HEADER_SIZE;
            res = attest_add_sw_component_claim(token_ctx,
                                                tlv_id,
                                                &claim_value);
            if (res != PSA_ATTEST_ERR_SUCCESS) {
                return res;
            }
        }

        /* Look up next entry it can be non-measurement claim*/
        found = attest_get_tlv_by_module(module, &tlv_id,
                                         &tlv_len, &tlv_ptr);
        if (found == -1) {
            return PSA_ATTEST_ERR_CLAIM_UNAVAILABLE;
        }
    }

    if (nested_map) {
        QCBOREncode_CloseMap(cbor_encode_ctx);
    }

    return PSA_ATTEST_ERR_SUCCESS;
}

/*!
 * \brief Static function to add the claims of a single SW components to the
 *        attestation token.
 *
 * \param[in]  token_ctx    Token encoding context
 * \param[in]  module       SW component identifier
 * \param[in]  tlv_address  Address of the first TLV entry in the boot status,
 *                          which belongs to this SW component.
 *
 * \deprecated This function is deprecated and will probably be removed
 *             in the future.
 *
 * \return Returns error code as specified in \ref psa_attest_err_t
 */
static enum psa_attest_err_t
attest_add_single_sw_component(struct attest_token_ctx *token_ctx,
                               uint32_t module,
                               uint8_t *tlv_address)
{
    struct shared_data_tlv_entry tlv_entry;
    uint16_t tlv_len;
    uint8_t  tlv_id;
    uint8_t *tlv_ptr = tlv_address;
    int32_t found = 1;
    uint32_t measurement_claim_cnt = 0;
    struct q_useful_buf_c claim_value;
    QCBOREncodeContext *cbor_encode_ctx;
    enum psa_attest_err_t res;

    /* Create local copy to avoid unaligned access */
    (void)tfm_memcpy(&tlv_entry, tlv_address, SHARED_DATA_ENTRY_HEADER_SIZE);
    tlv_len = tlv_entry.tlv_len;
    tlv_id = GET_IAS_CLAIM(tlv_entry.tlv_type);

    /* Open map which stores claims belong to a SW component */
    cbor_encode_ctx = attest_token_borrow_cbor_cntxt(token_ctx);
    QCBOREncode_OpenMap(cbor_encode_ctx);

    /* Look up all TLV entry which belongs to the same SW component */
    while (found) {
        /* Check whether claim is measurement claim */
        if (GET_IAS_MEASUREMENT_CLAIM(tlv_id)) {
            if (measurement_claim_cnt == 0) {
                /* Call only once when first measurement claim found */
                measurement_claim_cnt++;
                res = attest_add_single_sw_measurment(
                                                   token_ctx,
                                                   module,
                                                   tlv_ptr,
                                                   EAT_SW_COMPONENT_NOT_NESTED);
                if (res != PSA_ATTEST_ERR_SUCCESS) {
                    return res;
                }
            }
        } else {
            /* Adding top level claims */
            claim_value.ptr = tlv_ptr + SHARED_DATA_ENTRY_HEADER_SIZE;
            claim_value.len = tlv_len - SHARED_DATA_ENTRY_HEADER_SIZE;
            res = attest_add_sw_component_claim(token_ctx,
                                                tlv_id,
                                                &claim_value);
            if (res != PSA_ATTEST_ERR_SUCCESS) {
                return res;
            }
        }

        /* Look up next entry which belongs to SW component */
        found = attest_get_tlv_by_module(module, &tlv_id,
                                         &tlv_len, &tlv_ptr);
        if (found == -1) {
            return PSA_ATTEST_ERR_CLAIM_UNAVAILABLE;
        }
    }

    /* Close map which stores claims belong to a SW component */
    QCBOREncode_CloseMap(cbor_encode_ctx);

    return PSA_ATTEST_ERR_SUCCESS;
}
#endif /* INDIVIDUAL_SW_COMPONENTS */

/*!
 * \brief Static function to add the claims of all SW components to the
 *        attestation token.
 *
 * \param[in]  token_ctx  Token encoding context
 *
 * \return Returns error code as specified in \ref psa_attest_err_t
 */
static enum psa_attest_err_t
attest_add_all_sw_components(struct attest_token_ctx *token_ctx)
{
    uint16_t tlv_len;
    uint8_t *tlv_ptr;
    uint8_t  tlv_id;
    int32_t found;
    uint32_t cnt = 0;
    uint32_t module;
    QCBOREncodeContext *cbor_encode_ctx = NULL;
#ifdef INDIVIDUAL_SW_COMPONENTS
    enum psa_attest_err_t res;
#else
    UsefulBufC encoded = NULLUsefulBufC;
#endif

    /* Starting from module 1, because module 0 contains general claims which
     * are not related to SW module(i.e: boot_seed, etc.)
     */
    for (module = 1; module < SW_MAX; ++module) {
        /* Indicates to restart the look up from the beginning of the shared
         * data section
         */
        tlv_ptr = NULL;

        /* Look up the first TLV entry which belongs to the SW module */
        found = attest_get_tlv_by_module(module, &tlv_id,
                                         &tlv_len, &tlv_ptr);
        if (found == -1) {
            return PSA_ATTEST_ERR_CLAIM_UNAVAILABLE;
        }

        if (found == 1) {
            cnt++;
            if (cnt == 1) {
                /* Open array which stores SW components claims */
                cbor_encode_ctx = attest_token_borrow_cbor_cntxt(token_ctx);
                QCBOREncode_OpenArrayInMapN(cbor_encode_ctx,
                                            EAT_CBOR_ARM_LABEL_SW_COMPONENTS);
            }

#ifdef INDIVIDUAL_SW_COMPONENTS
            res = attest_add_single_sw_component(token_ctx, module, tlv_ptr);
            if (res != PSA_ATTEST_ERR_SUCCESS) {
                return res;
            }
#else
            encoded.ptr = tlv_ptr + SHARED_DATA_ENTRY_HEADER_SIZE;
            encoded.len = tlv_len - SHARED_DATA_ENTRY_HEADER_SIZE;
            QCBOREncode_AddEncoded(cbor_encode_ctx, encoded);
#endif /* INDIVIDUAL_SW_COMPONENTS */
        }
    }

    if (cnt != 0) {
        /* Close array which stores SW components claims*/
        QCBOREncode_CloseArray(cbor_encode_ctx);
    } else {
        /* If there is not any SW components' measurement in the boot status
         * then include this claim to indicate that this state is intentional
         */
        attest_token_add_integer(token_ctx,
                                 EAT_CBOR_ARM_LABEL_NO_SW_COMPONENTS,
                                 (int64_t)NO_SW_COMPONENT_FIXED_VALUE);
    }

    return PSA_ATTEST_ERR_SUCCESS;
}

/*!
 * \brief Static function to add boot seed claim to attestation token.
 *
 * \param[in]  token_ctx  Token encoding context
 *
 * \return Returns error code as specified in \ref psa_attest_err_t
 */
static enum psa_attest_err_t
attest_add_boot_seed_claim(struct attest_token_ctx *token_ctx)
{
    uint8_t boot_seed[BOOT_SEED_SIZE];
    enum tfm_plat_err_t res;
    struct q_useful_buf_c claim_value = {0};
    uint16_t tlv_len;
    uint8_t *tlv_ptr = NULL;
    int32_t found = 0;

    /* First look up BOOT_SEED in boot status, it might comes from bootloader */
    found = attest_get_tlv_by_id(BOOT_SEED, &tlv_len, &tlv_ptr);
    if (found == 1) {
        claim_value.ptr = tlv_ptr + SHARED_DATA_ENTRY_HEADER_SIZE;
        claim_value.len = tlv_len - SHARED_DATA_ENTRY_HEADER_SIZE;
    } else {
        /* If not found in boot status then use callback function to get it
         * from runtime SW
         */
        res = tfm_plat_get_boot_seed(sizeof(boot_seed), boot_seed);
        if (res != TFM_PLAT_ERR_SUCCESS) {
            return PSA_ATTEST_ERR_CLAIM_UNAVAILABLE;
        }
        claim_value.ptr = boot_seed;
        claim_value.len = BOOT_SEED_SIZE;
    }

    attest_token_add_bstr(token_ctx,
                          EAT_CBOR_ARM_LABEL_BOOT_SEED,
                          &claim_value);

    return PSA_ATTEST_ERR_SUCCESS;
}

/*!
 * \brief Static function to add instance id claim to attestation token.
 *
 * \param[in]  token_ctx  Token encoding context
 *
 * \note This mandatory claim represents the unique identifier of the instance.
 *       In the PSA definition it is a hash of the public attestation key of the
 *       instance. The claim will be represented by the EAT standard claim UEID
 *       of type GUID. The EAT definition of a GUID type is that it will be
 *       between 128 & 256 bits but this implementation will use the full 256
 *       bits to accommodate a hash result.
 *
 * \return Returns error code as specified in \ref psa_attest_err_t
 */
static enum psa_attest_err_t
attest_add_instance_id_claim(struct attest_token_ctx *token_ctx)
{
    psa_status_t crypto_res;
    enum psa_attest_err_t attest_res;
    uint8_t instance_id[INSTANCE_ID_MAX_SIZE];
    size_t instance_id_len;
    struct q_useful_buf_c claim_value;
    uint8_t *public_key;
    size_t key_len;
    psa_ecc_curve_t psa_curve;
    psa_hash_operation_t hash = psa_hash_operation_init();

    attest_res = attest_get_initial_attestation_public_key(&public_key,
                                                           &key_len,
                                                           &psa_curve);
    if (attest_res != PSA_ATTEST_ERR_SUCCESS) {
        return PSA_ATTEST_ERR_CLAIM_UNAVAILABLE;
    }

    crypto_res = psa_hash_setup(&hash, PSA_ALG_SHA_256);
    if (crypto_res != PSA_SUCCESS) {
        return PSA_ATTEST_ERR_CLAIM_UNAVAILABLE;
    }

    crypto_res = psa_hash_update(&hash, public_key, key_len);
    if (crypto_res != PSA_SUCCESS) {
        return PSA_ATTEST_ERR_CLAIM_UNAVAILABLE;
    }

    /* The hash starts from the second byte, leaving the first free. */
    crypto_res = psa_hash_finish(&hash, instance_id + 1,
                                 INSTANCE_ID_MAX_SIZE - 1,
                                 &instance_id_len);
    if (crypto_res != PSA_SUCCESS) {
        return PSA_ATTEST_ERR_CLAIM_UNAVAILABLE;
    }

    /* First byte indicates the type: 0x01 indicates GUID */
    instance_id[0] = 0x01;
    instance_id_len += 1;

    claim_value.ptr = instance_id;
    claim_value.len = instance_id_len;
    attest_token_add_bstr(token_ctx,
                          EAT_CBOR_ARM_LABEL_UEID,
                          &claim_value);

    return PSA_ATTEST_ERR_SUCCESS;
}

/*!
 * \brief Static function to add implementation id claim to attestation token.
 *
 * \param[in]  token_ctx  Token encoding context
 *
 * \return Returns error code as specified in \ref psa_attest_err_t
 */
static enum psa_attest_err_t
attest_add_implementation_id_claim(struct attest_token_ctx *token_ctx)
{
    uint8_t implementation_id[IMPLEMENTATION_ID_MAX_SIZE];
    enum tfm_plat_err_t res_plat;
    uint32_t size = sizeof(implementation_id);
    struct q_useful_buf_c claim_value;

    res_plat = tfm_plat_get_implementation_id(&size, implementation_id);
    if (res_plat != TFM_PLAT_ERR_SUCCESS) {
        return PSA_ATTEST_ERR_CLAIM_UNAVAILABLE;
    }

    claim_value.ptr = implementation_id;
    claim_value.len  = size;
    attest_token_add_bstr(token_ctx,
                          EAT_CBOR_ARM_LABEL_IMPLEMENTATION_ID,
                          &claim_value);

    return PSA_ATTEST_ERR_SUCCESS;
}

/*!
 * \brief Static function to add caller id claim to attestation token.
 *
 * \param[in]  token_ctx  Token encoding context
 *
 * \return Returns error code as specified in \ref psa_attest_err_t
 */
static enum psa_attest_err_t
attest_add_caller_id_claim(struct attest_token_ctx *token_ctx)
{
    enum psa_attest_err_t res;
    int32_t caller_id;

    res = attest_get_caller_client_id(&caller_id);
    if (res != PSA_ATTEST_ERR_SUCCESS) {
        return res;
    }

    attest_token_add_integer(token_ctx,
                             EAT_CBOR_ARM_LABEL_CLIENT_ID,
                             (int64_t)caller_id);

    return PSA_ATTEST_ERR_SUCCESS;
}

/*!
 * \brief Static function to add security lifecycle claim to attestation token.
 *
 * \param[in]  token_ctx  Token encoding context
 *
 * \return Returns error code as specified in \ref psa_attest_err_t
 */
static enum psa_attest_err_t
attest_add_security_lifecycle_claim(struct attest_token_ctx *token_ctx)
{
    enum tfm_security_lifecycle_t security_lifecycle;
    uint32_t slc_value;
    int32_t res;
    struct q_useful_buf_c claim_value = {0};
    uint16_t tlv_len;
    uint8_t *tlv_ptr = NULL;
    int32_t found = 0;

    /* First look up lifecycle state in boot status, it might comes
     * from bootloader
     */
    found = attest_get_tlv_by_id(SECURITY_LIFECYCLE, &tlv_len, &tlv_ptr);
    if (found == 1) {
        claim_value.ptr = tlv_ptr + SHARED_DATA_ENTRY_HEADER_SIZE;
        claim_value.len = tlv_len - SHARED_DATA_ENTRY_HEADER_SIZE;
        res = get_uint(claim_value.ptr, claim_value.len, &slc_value);
        if (res) {
            return PSA_ATTEST_ERR_GENERAL;
        }
        security_lifecycle = (enum tfm_security_lifecycle_t)slc_value;
    } else {
        /* If not found in boot status then use callback function to get it
         * from runtime SW
         */
        security_lifecycle = tfm_attest_hal_get_security_lifecycle();
    }

    /* Sanity check */
    if (security_lifecycle < TFM_SLC_UNKNOWN ||
        security_lifecycle > TFM_SLC_DECOMMISSIONED) {
        return PSA_ATTEST_ERR_GENERAL;
    }

    attest_token_add_integer(token_ctx,
                             EAT_CBOR_ARM_LABEL_SECURITY_LIFECYCLE,
                             (int64_t)security_lifecycle);

    return PSA_ATTEST_ERR_SUCCESS;
}

/*!
 * \brief Static function to add challenge claim to attestation token.
 *
 * \param[in]  token_ctx  Token encoding context
 * \param[in]  challenge  Pointer to buffer which stores the challenge
 *
 * \return Returns error code as specified in \ref psa_attest_err_t
 */
static enum psa_attest_err_t
attest_add_challenge_claim(struct attest_token_ctx   *token_ctx,
                           const struct q_useful_buf_c *challenge)
{
    attest_token_add_bstr(token_ctx, EAT_CBOR_ARM_LABEL_CHALLENGE, challenge);

    return PSA_ATTEST_ERR_SUCCESS;
}

#ifdef INCLUDE_OPTIONAL_CLAIMS /* Remove them from release build */
/*!
 * \brief Static function to add the verification service indicator claim
 *        to the attestation token.
 *
 * \param[in]  token_ctx  Token encoding context
 *
 * \return Returns error code as specified in \ref psa_attest_err_t
 */
static enum psa_attest_err_t
attest_add_verification_service(struct attest_token_ctx *token_ctx)
{
    struct q_useful_buf_c service;
    uint32_t size;

    service.ptr = tfm_attest_hal_get_verification_service(&size);

    if (service.ptr) {
        service.len = size;
        attest_token_add_tstr(token_ctx,
                              EAT_CBOR_ARM_LABEL_ORIGINATION,
                              &service);
    }

    return PSA_ATTEST_ERR_SUCCESS;
}

/*!
 * \brief Static function to add the name of the profile definition document
 *
 * \param[in]  token_ctx  Token encoding context
 *
 * \return Returns error code as specified in \ref psa_attest_err_t
 */
static enum psa_attest_err_t
attest_add_profile_definition(struct attest_token_ctx *token_ctx)
{
    struct q_useful_buf_c profile;
    uint32_t size;

    profile.ptr = tfm_attest_hal_get_profile_definition(&size);

    if (profile.ptr) {
        profile.len = size;
        attest_token_add_tstr(token_ctx,
                              EAT_CBOR_ARM_LABEL_PROFILE_DEFINITION,
                              &profile);
    }

    return PSA_ATTEST_ERR_SUCCESS;
}

/*!
 * \brief Static function to add hardware version claim to attestation token.
 *
 * \param[in]  token_ctx  Token encoding context
 *
 * \return Returns error code as specified in \ref psa_attest_err_t
 */
static enum psa_attest_err_t
attest_add_hw_version_claim(struct attest_token_ctx *token_ctx)
{
    uint8_t hw_version[HW_VERSION_MAX_SIZE];
    enum tfm_plat_err_t res_plat;
    uint32_t size = sizeof(hw_version);
    struct q_useful_buf_c claim_value = {0};
    uint16_t tlv_len;
    uint8_t *tlv_ptr = NULL;
    int32_t found = 0;

    /* First look up HW version in boot status, it might comes
     * from bootloader
     */
    found = attest_get_tlv_by_id(HW_VERSION, &tlv_len, &tlv_ptr);
    if (found == 1) {
        claim_value.ptr = tlv_ptr + SHARED_DATA_ENTRY_HEADER_SIZE;
        claim_value.len = tlv_len - SHARED_DATA_ENTRY_HEADER_SIZE;
    } else {
        /* If not found in boot status then use callback function to get it
         * from runtime SW
         */
        res_plat = tfm_plat_get_hw_version(&size, hw_version);
        if (res_plat != TFM_PLAT_ERR_SUCCESS) {
            return PSA_ATTEST_ERR_CLAIM_UNAVAILABLE;
        }
        claim_value.ptr = hw_version;
        claim_value.len = size;
    }

    attest_token_add_tstr(token_ctx,
                          EAT_CBOR_ARM_LABEL_HW_VERSION,
                          &claim_value);

    return PSA_ATTEST_ERR_SUCCESS;
}
#endif /* INCLUDE_OPTIONAL_CLAIMS */

/*!
 * \brief Static function to verify the input challenge size
 *
 *  Only discrete sizes are accepted.
 *
 * \param[in] challenge_size  Size of challenge object in bytes.
 *
 * \retval  PSA_ATTEST_ERR_SUCCESS
 * \retval  PSA_ATTEST_ERR_INVALID_INPUT
 */
static enum psa_attest_err_t attest_verify_challenge_size(size_t challenge_size)
{
    switch (challenge_size) {
    /* Intentional fall through */
    case PSA_INITIAL_ATTEST_CHALLENGE_SIZE_32:
    case PSA_INITIAL_ATTEST_CHALLENGE_SIZE_48:
    case PSA_INITIAL_ATTEST_CHALLENGE_SIZE_64:
        return PSA_ATTEST_ERR_SUCCESS;
    }

    return PSA_ATTEST_ERR_INVALID_INPUT;
}

#ifdef INCLUDE_TEST_CODE_AND_KEY_ID /* Remove them from release build */
/*!
 * \brief Static function to get the option flags from challenge object
 *
 * Option flags are passed in if the challenge is 64 bytes long and the last
 * 60 bytes are all 0. In this case the first 4 bytes of the challenge is
 * the option flags for test.
 *
 * See flag definition in attest_token.h
 *
 * \param[in]  challenge     Structure to carry the challenge value:
 *                           pointer + challeng's length.
 * \param[out] option_flags  Flags to select different custom options,
 *                           for example \ref TOKEN_OPT_OMIT_CLAIMS.
 * \param[out] key_select    Selects which attestation key to sign with.
 */
static void attest_get_option_flags(struct q_useful_buf_c *challenge,
                                    uint32_t *option_flags,
                                    int32_t  *key_select)
{
    uint32_t found_option_flags = 1;
    uint32_t option_flags_size = sizeof(uint32_t);
    uint8_t *challenge_end;
    uint8_t *challenge_data;

    /* Get option flags if there is encoded in the challenge object */
    if (challenge->len == PSA_INITIAL_ATTEST_CHALLENGE_SIZE_64) {
        challenge_end  = ((uint8_t *)challenge->ptr) + challenge->len;
        challenge_data = ((uint8_t *)challenge->ptr) + option_flags_size;

        /* Compare bytes(4-63) with 0 */
        while (challenge_data < challenge_end) {
            if (*challenge_data++ != 0) {
                found_option_flags = 0;
                break;
            }
        }
    } else {
        found_option_flags = 0;
    }

    if (found_option_flags) {
        (void)tfm_memcpy(option_flags, challenge->ptr, option_flags_size);

        /* Lower three bits are the key select */
        *key_select = *option_flags & 0x7;
    } else {
        *option_flags = 0;
        *key_select = 0;
    }
}
#endif /* INCLUDE_TEST_CODE_AND_KEY_ID */

/*!
 * \brief Static function to create the initial attestation token
 *
 * \param[in]  challenge        Structure to carry the challenge value:
 *                              pointer + challeng's length
 * \param[in]  token            Structure to carry the token info, where to
 *                              create it: pointer + buffer's length
 * \param[out] completed_token  Structure to carry the info about the created
 *                              token: pointer + final token's length
 *
 * \return Returns error code as specified in \ref psa_attest_err_t
 */
static enum psa_attest_err_t
attest_create_token(struct q_useful_buf_c *challenge,
                    struct q_useful_buf   *token,
                    struct q_useful_buf_c *completed_token)
{
    enum psa_attest_err_t attest_err = PSA_ATTEST_ERR_SUCCESS;
    enum attest_token_err_t token_err;
    struct attest_token_ctx attest_token_ctx;
    int32_t key_select = 0;
    uint32_t option_flags = 0;

    attest_err = attest_register_initial_attestation_key();
    if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
        goto error;
    }

#ifdef INCLUDE_TEST_CODE_AND_KEY_ID /* Remove them from release build */
    attest_get_option_flags(challenge, &option_flags, &key_select);
#endif

    /* Get started creating the token. This sets up the CBOR and COSE contexts
     * which causes the COSE headers to be constructed.
     */
    token_err = attest_token_start(&attest_token_ctx,
                                   option_flags,            /* option_flags */
                                   key_select,              /* key_select   */
                                   T_COSE_ALGORITHM_ES256,  /* alg_select   */
                                   token);

    if (token_err != ATTEST_TOKEN_ERR_SUCCESS) {
        attest_err = error_mapping(token_err);
        goto error;
    }

    attest_err = attest_add_challenge_claim(&attest_token_ctx,
                                            challenge);
    if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
        goto error;
    }

    if (!(option_flags & TOKEN_OPT_OMIT_CLAIMS)) {
        /* Mandatory claims in IAT token */
        attest_err = attest_add_boot_seed_claim(&attest_token_ctx);
        if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
            goto error;
        }

        attest_err = attest_add_instance_id_claim(&attest_token_ctx);
        if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
            goto error;
        }

        attest_err = attest_add_implementation_id_claim(&attest_token_ctx);
        if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
            goto error;
        }

        attest_err = attest_add_caller_id_claim(&attest_token_ctx);
        if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
            goto error;
        }

        attest_err = attest_add_security_lifecycle_claim(&attest_token_ctx);
        if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
            goto error;
        }

        attest_err = attest_add_all_sw_components(&attest_token_ctx);
        if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
            goto error;
        }

#ifdef INCLUDE_OPTIONAL_CLAIMS
        /* Optional claims in IAT token, remove them from release build */
        attest_err = attest_add_verification_service(&attest_token_ctx);
        if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
            goto error;
        }

        attest_err = attest_add_profile_definition(&attest_token_ctx);
        if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
            goto error;
        }

        attest_err = attest_add_hw_version_claim(&attest_token_ctx);
        if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
            goto error;
        }
#endif /* INCLUDE_OPTIONAL_CLAIMS */
    }

    /* Finish up creating the token. This is where the actual signature
     * is generated. This finishes up the CBOR encoding too.
     */
    token_err = attest_token_finish(&attest_token_ctx, completed_token);
    if (token_err) {
        attest_err = error_mapping(token_err);
        goto error;
    }

error:
    if (attest_err == PSA_ATTEST_ERR_SUCCESS) {
        /* We got here normally and therefore care about error codes. */
        attest_err = attest_unregister_initial_attestation_key();
    }
    else {
        /* Error handler: just remove they key and preserve error. */
        (void)attest_unregister_initial_attestation_key();
    }
    return attest_err;
}

/* Limitations of the current implementation:
 *  - Token is not signed yet properly, just a fake signature is added to the
 *    token due to lack of psa_asymmetric_sign() implementation in crypto
 *    service.
 */
enum psa_attest_err_t
initial_attest_get_token(const psa_invec  *in_vec,  uint32_t num_invec,
                               psa_outvec *out_vec, uint32_t num_outvec)
{
    enum psa_attest_err_t attest_err = PSA_ATTEST_ERR_SUCCESS;
    struct q_useful_buf_c challenge;
    struct q_useful_buf token;
    struct q_useful_buf_c completed_token;

    challenge.ptr = in_vec[0].base;
    challenge.len = in_vec[0].len;
    token.ptr = out_vec[0].base;
    token.len = out_vec[0].len;

    attest_err = attest_verify_challenge_size(challenge.len);
    if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
        goto error;
    }

    attest_err = attest_check_memory_access((void *)challenge.ptr,
                                            challenge.len,
                                            TFM_ATTEST_ACCESS_RO);
    if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
        goto error;
    }

    if (token.len == 0) {
        attest_err = PSA_ATTEST_ERR_INVALID_INPUT;
        goto error;
    }

    attest_err = attest_check_memory_access(token.ptr,
                                            token.len,
                                            TFM_ATTEST_ACCESS_RW);
    if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
        goto error;
    }

    attest_err = attest_create_token(&challenge, &token, &completed_token);
    if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
        goto error;
    }

    out_vec[0].base = (void *)completed_token.ptr;
    out_vec[0].len  = completed_token.len;

error:
    return attest_err;
}

/* Initial implementation, just returns with hard coded value */
enum psa_attest_err_t
initial_attest_get_token_size(const psa_invec  *in_vec,  uint32_t num_invec,
                                    psa_outvec *out_vec, uint32_t num_outvec)
{
    enum psa_attest_err_t attest_err = PSA_ATTEST_ERR_SUCCESS;
    uint32_t  challenge_size = *(uint32_t *)in_vec[0].base;
    uint32_t *token_buf_size = (uint32_t *)out_vec[0].base;
    struct q_useful_buf_c challenge;
    struct q_useful_buf token;
    struct q_useful_buf_c completed_token;

    /* Only the size of the challenge is needed */
    challenge.ptr = NULL;
    challenge.len = challenge_size;

    /* Special value to get the size of the token, but token is not created */
    token.ptr = NULL;
    token.len = INT32_MAX;

    if (out_vec[0].len < sizeof(uint32_t)) {
        attest_err = PSA_ATTEST_ERR_INVALID_INPUT;
        goto error;
    }

    attest_err = attest_verify_challenge_size(challenge_size);
    if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
        goto error;
    }

    attest_err = attest_create_token(&challenge, &token, &completed_token);
    if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
        goto error;
    }

    *token_buf_size = completed_token.len;

error:
    return attest_err;
}

enum psa_attest_err_t
initial_attest_get_public_key(const psa_invec  *in_vec,  uint32_t num_invec,
                                    psa_outvec *out_vec, uint32_t num_outvec)
{
    enum psa_attest_err_t attest_err = PSA_ATTEST_ERR_SUCCESS;
    struct q_useful_buf key_buffer;
    uint8_t *key_source;
    size_t key_len;
    psa_ecc_curve_t curve_type;

    (void)in_vec;

    if (num_invec != 0 || num_outvec != 3) {
        attest_err = PSA_ATTEST_ERR_INVALID_INPUT;
        goto error;
    }

    key_buffer.ptr = out_vec[0].base;
    key_buffer.len = out_vec[0].len;

    if (out_vec[1].len != sizeof(curve_type) ||
        out_vec[2].len != sizeof(key_len)) {
        attest_err = PSA_ATTEST_ERR_INVALID_INPUT;
        goto error;
    }

    attest_err = attest_check_memory_access(key_buffer.ptr,
                                            key_buffer.len,
                                            TFM_ATTEST_ACCESS_RW);
    if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
        goto error;
    }

    attest_err = attest_check_memory_access(out_vec[1].base,
                                            out_vec[1].len,
                                            TFM_ATTEST_ACCESS_RW);
    if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
        goto error;
    }

    attest_err = attest_get_initial_attestation_public_key(&key_source,
                                                           &key_len,
                                                           &curve_type);
    if (attest_err != PSA_ATTEST_ERR_SUCCESS) {
        goto error;
    }

    if (key_buffer.len < key_len) {
        attest_err = PSA_ATTEST_ERR_KEY_BUFFER_OVERFLOW;
        goto error;
    }

    (void)tfm_memcpy(key_buffer.ptr, key_source, key_len);

    *(psa_ecc_curve_t *)out_vec[1].base = curve_type;

    *(size_t *)out_vec[2].base = key_len;

error:
    return attest_err;
}