-
Notifications
You must be signed in to change notification settings - Fork 43
/
core_pkcs11_mbedtls.c
5805 lines (5119 loc) · 220 KB
/
core_pkcs11_mbedtls.c
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
/*
* corePKCS11 v3.5.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @file core_pkcs11_mbedtls.c
* @brief mbedTLS-based PKCS#11 implementation for software keys. This
* file deviates from the FreeRTOS style standard for some function names and
* data types in order to maintain compliance with the PKCS #11 standard.
*/
/* PKCS #11 includes. */
#include "core_pkcs11_config.h"
#include "core_pkcs11_config_defaults.h"
#include "core_pkcs11.h"
#include "core_pkcs11_pal.h"
#include "core_pki_utils.h"
/**
* @brief Declaring MBEDTLS_ALLOW_PRIVATE_ACCESS allows access to mbedtls "private" fields.
*/
#define MBEDTLS_ALLOW_PRIVATE_ACCESS
/* mbedTLS includes. */
#include "mbedtls/pk.h"
#include "mbedtls/x509_crt.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/entropy.h"
#include "mbedtls/sha256.h"
#include "mbedtls/cmac.h"
#include "mbedtls/platform.h"
#include "mbedtls/threading.h"
#include "mbedtls/error.h"
/* C runtime includes. */
#include <string.h>
/*-----------------------------------------------------------*/
/**
* @defgroup pkcs11_macros PKCS #11 Implementation Macros
* @brief Macros for PKCS #11 software implementation.
*/
/**
* @defgroup pkcs11_datatypes PKCS #11 Datatypes
* @brief Internal datatypes for PKCS #11 software implementation.
*/
#ifndef DISABLE_LOGGING
/**
* @brief Represents string to be logged when mbedTLS returned error
* does not contain a high-level code.
*/
static const char * pNoHighLevelMbedTlsCodeStr = "<No-High-Level-Code>";
/**
* @brief Represents string to be logged when mbedTLS returned error
* does not contain a low-level code.
*/
static const char * pNoLowLevelMbedTlsCodeStr = "<No-Low-Level-Code>";
/**
* @brief Utility for converting the high-level code in an mbedTLS error to string,
* if the code-contains a high-level code; otherwise, using a default string.
*/
#define mbedtlsHighLevelCodeOrDefault( mbedTlsCode ) \
( mbedtls_high_level_strerr( mbedTlsCode ) != NULL ) ? \
mbedtls_high_level_strerr( mbedTlsCode ) : pNoHighLevelMbedTlsCodeStr
/**
* @brief Utility for converting the level-level code in an mbedTLS error to string,
* if the code-contains a level-level code; otherwise, using a default string.
*/
#define mbedtlsLowLevelCodeOrDefault( mbedTlsCode ) \
( mbedtls_low_level_strerr( mbedTlsCode ) != NULL ) ? \
mbedtls_low_level_strerr( mbedTlsCode ) : pNoLowLevelMbedTlsCodeStr
#endif /* ifndef DISABLE_LOGGING */
/**
* @ingroup pkcs11_macros
* @brief Delay to wait on acquiring a mutex, in ms.
*/
#define pkcs11MUTEX_WAIT_MS ( pdMS_TO_TICKS( 5000U ) )
/**
* @ingroup pkcs11_macros
* @brief Indicates that no PKCS #11 operation is underway for given session.
*/
#define pkcs11NO_OPERATION ( ( CK_MECHANISM_TYPE ) 0xFFFFFFFFUL )
/**
* @ingroup pkcs11_macros
* @brief size of a prime256v1 EC private key in bytes, when encoded in DER.
*/
#define pkcs11_PRIVATE_EC_PRIME_256_DER_SIZE 160
/**
* @ingroup pkcs11_macros
* @brief size of a prime256v1 EC public key in bytes, when encoded in DER.
*/
#define pkcs11_PUBLIC_EC_PRIME_256_DER_SIZE 100
/**
* @ingroup pkcs11_macros
* @brief size of a 2048 bit RSA public key in bytes, when encoded in DER.
*/
#define pkcs11_PUBLIC_RSA_2048_DER_SIZE 300
/**
* @ingroup pkcs11_macros
* @brief size of a 2048 bit RSA private key in bytes, in DER encoding.
*/
#define pkcs11_PRIVATE_RSA_2048_DER_SIZE 1200
/**
* @ingroup pkcs11_macros
* @brief Max size of an EC public key in bytes, in DER encoding.
*/
#define pkcs11_MAX_EC_PUBLIC_KEY_DER_SIZE pkcs11_PUBLIC_EC_PRIME_256_DER_SIZE
/**
* @ingroup pkcs11_macros
* @brief Max size of an EC private key in bytes, in DER encoding.
*/
#define pkcs11_MAX_EC_PRIVATE_KEY_DER_SIZE pkcs11_PRIVATE_EC_PRIME_256_DER_SIZE
/**
* @ingroup pkcs11_macros
* @brief Length of bytes to contain an EC point.
*
* This port currently only uses prime256v1, in which the fields are 32 bytes in
* length. The public EC point is as long as the curve's fields * 2 + 1.
* so the EC point for this port is (32 * 2) + 1 bytes in length.
*
* mbed TLS encodes the length of the point in the first byte of the buffer it
* receives, so an additional 1 byte in length is added to account for this.
*
* In addition to this, an additional 1 byte is added to store information
* indicating that the point is uncompressed.
*
* @note This length needs to be updated if using a different curve.
*
* To summarize:
* 32 points of 2 bytes each + 1 point length byte, 1 length byte, and
* 1 type (uncompressed) byte
*/
#define pkcs11EC_POINT_LENGTH ( ( 32UL * 2UL ) + 1UL + 1UL + 1UL )
/**
* @ingroup pkcs11_macros
* @brief Max size of a public key.
* This macro defines the size of a key in bytes, in DER encoding.
*
* @note The largest RSA public key is used because EC keys are smaller.
*/
#define pkcs11_MAX_PUBLIC_KEY_DER_SIZE pkcs11_PUBLIC_RSA_2048_DER_SIZE
/**
* @ingroup pkcs11_macros
* @brief Max key length of a key.
* This macro defines the size of a key in bytes, in DER format.
*
* Currently the largest key type supported by this port is a 2048 bit
* RSA private key.
*
* @note The largest RSA private key is used because EC keys are smaller and
* the RSA public key is smaller.
*/
#define pkcs11_MAX_PRIVATE_KEY_DER_SIZE pkcs11_PRIVATE_RSA_2048_DER_SIZE
/**
* @ingroup pkcs11_macros
* @brief The size of the buffer malloc'ed for the exported public key in C_GenerateKeyPair.
*/
#define pkcs11KEY_GEN_MAX_DER_SIZE 200
/**
* @ingroup pkcs11_macros
* @brief The slot ID to be returned by this PKCS #11 implementation.
*
* @note that this implementation does not have a concept of "slots" so this number is arbitrary.
*/
#define pkcs11SLOT_ID 1
/**
* @ingroup pkcs11_macros
* @brief Private defines for checking that attribute templates are complete.
*/
#define LABEL_IN_TEMPLATE ( 1U ) /**< Bit set for label in template. */
#define PRIVATE_IN_TEMPLATE ( 1U << 1 ) /**< Bit set for private key in in template. */
#define SIGN_IN_TEMPLATE ( 1U << 2 ) /**< Bit set for sign in template. */
#define EC_PARAMS_IN_TEMPLATE ( 1U << 3 ) /**< Bit set for EC params in template. */
#define VERIFY_IN_TEMPLATE ( 1U << 4 ) /**< Bit set for verify in template. */
/**
* @ingroup pkcs11_macros
* @brief Macro to signify an invalid PKCS #11 key type.
*/
#define PKCS11_INVALID_KEY_TYPE ( ( CK_KEY_TYPE ) 0xFFFFFFFFUL )
/**
* @ingroup pkcs11_macros
* @brief Private define for minimum SHA256-HMAC key size.
*/
#define PKCS11_SHA256_HMAC_MIN_SIZE ( 32UL )
/**
* @ingroup pkcs11_macros
* @brief Private define for minimum AES-CMAC key size, in bytes.
*/
#define PKCS11_AES_CMAC_MIN_SIZE ( 16UL )
/**
* @ingroup pkcs11_macros
* @brief Private define to inform mbedtls MD module to use an HMAC for the MD context.
*/
#define PKCS11_USING_HMAC ( 1 )
/**
* @brief Define the MBEDTLS_VERSION_NUMBER as 0 if it is not defined, done for MISRA rule 20.9
*/
#ifndef MBEDTLS_VERSION_NUMBER
#define MBEDTLS_VERSION_NUMBER 0
#endif
/**
* @ingroup pkcs11_datatypes
* @brief PKCS #11 object container.
*
* Maps a PKCS #11 object handle to it's label.
*/
typedef struct P11Object_t
{
CK_OBJECT_HANDLE xHandle; /**< @brief The "PAL Handle". */
CK_ULONG xLabelSize; /**< @brief Size of label. */
CK_BYTE xLabel[ pkcs11configMAX_LABEL_LENGTH + 1 ]; /**< @brief Plus 1 for the null terminator. */
} P11Object_t;
/**
* @ingroup pkcs11_datatypes
* @brief PKCS #11 object container list.
*
* This structure helps the core_pkcs11_mbedtls.c maintain a mapping of all objects in one place.
* Because some objects exist in device NVM and must be called by their "PAL Handles", and other
* objects do not have designated NVM storage locations, the ObjectList maintains a list
* of what object handles are available.
*/
typedef struct P11ObjectList_t
{
mbedtls_threading_mutex_t xMutex; /**< @brief Mutex that protects write operations to the xObjects array. */
P11Object_t xObjects[ pkcs11configMAX_NUM_OBJECTS ]; /**< @brief List of PKCS #11 objects. */
} P11ObjectList_t;
/**
* @ingroup pkcs11_datatypes
* @brief PKCS #11 Module Object
*/
typedef struct P11Struct_t
{
CK_BBOOL xIsInitialized; /**< @brief Indicates whether PKCS #11 module has been initialized with a call to C_Initialize. */
mbedtls_ctr_drbg_context xMbedDrbgCtx; /**< @brief CTR-DRBG context for PKCS #11 module - used to generate pseudo-random numbers. */
mbedtls_entropy_context xMbedEntropyContext; /**< @brief Entropy context for PKCS #11 module - used to collect entropy for RNG. */
mbedtls_threading_mutex_t xSessionMutex; /**< @brief Mutex that protects write operations to the pxSession array. */
P11ObjectList_t xObjectList; /**< @brief List of PKCS #11 objects that have been found/created since module initialization.
* The array position indicates the "App Handle" */
} P11Struct_t;
/**
* @ingroup pkcs11_datatypes
* @brief Session structure.
*/
typedef struct P11Session
{
CK_ULONG ulState; /**< @brief Stores the session flags. */
CK_BBOOL xOpened; /**< @brief Set to CK_TRUE upon opening PKCS #11 session. */
CK_MECHANISM_TYPE xOperationDigestMechanism; /**< @brief Indicates if a digest operation is in progress. */
CK_BYTE * pxFindObjectLabel; /**< @brief Pointer to the label for the search in progress. Should be NULL if no search in progress. */
CK_ULONG xFindObjectLabelLen; /**< @brief Size of current search label. */
CK_MECHANISM_TYPE xOperationVerifyMechanism; /**< @brief The mechanism of verify operation in progress. Set during C_VerifyInit. */
mbedtls_threading_mutex_t xVerifyMutex; /**< @brief Protects the verification key from being modified while in use. */
CK_OBJECT_HANDLE xVerifyKeyHandle; /**< @brief Object handle to the verification key. */
mbedtls_pk_context xVerifyKey; /**< @brief Verification key. Set during C_VerifyInit. */
CK_MECHANISM_TYPE xOperationSignMechanism; /**< @brief Mechanism of the sign operation in progress. Set during C_SignInit. */
mbedtls_threading_mutex_t xSignMutex; /**< @brief Protects the signing key from being modified while in use. */
CK_OBJECT_HANDLE xSignKeyHandle; /**< @brief Object handle to the signing key. */
mbedtls_pk_context xSignKey; /**< @brief Signing key. Set during C_SignInit. */
mbedtls_sha256_context xSHA256Context; /**< @brief Context for in progress digest operation. */
CK_OBJECT_HANDLE xHMACKeyHandle; /**< @brief Object handle to the HMAC key. */
mbedtls_md_context_t xHMACSecretContext; /**< @brief Context for in progress HMAC operation. Set during C_SignInit or C_VerifyInit. */
CK_OBJECT_HANDLE xCMACKeyHandle; /**< @brief Object handle to the CMAC key. */
mbedtls_cipher_context_t xCMACSecretContext; /**< @brief Context for in progress CMAC operation. Set during C_SignInit or C_VerifyInit. */
} P11Session_t;
/*-----------------------------------------------------------*/
/**
* @brief The global PKCS #11 module object.
* Entropy/randomness and object lists are shared across PKCS #11 sessions.
*/
static P11Struct_t xP11Context;
/**
* @brief The global PKCS #11 session list.
*/
static P11Session_t pxP11Sessions[ pkcs11configMAX_SESSIONS ] = { 0 };
/**
* @brief Helper to check if the current session is initialized and valid.
*/
static CK_RV prvCheckValidSessionAndModule( const P11Session_t * pxSession )
{
CK_RV xResult = CKR_OK;
/** MISRA Rule 10.5 - Cannot cast from unsigned to signed.
* The rule 10.5 is violated because type of the boolean macros defined by PKCS #11
* are 0 and 1, which results in a signed integer, meanwhile the underlying
* type of CK_BBOOL is an unsigned char.
*
* This means that our implementation conforms to the exception provided by MISRA
* To quote MISRA: "An integer constant expression with the value 0 or 1 of either signedness
* may be cast to a type which is defined as essentially Boolean.
* This allows the implementation of non-C99 Boolean models."
*/
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
if( xP11Context.xIsInitialized == ( CK_BBOOL ) CK_FALSE )
{
LogDebug( ( "Could not get a valid session. PKCS #11 was not initialized since xP11Context.xIsInitialized was CK_FALSE." ) );
xResult = CKR_CRYPTOKI_NOT_INITIALIZED;
}
else if( pxSession == NULL )
{
LogDebug( ( "Could not get a valid session. PKCS #11 session handle pSession was NULL." ) );
xResult = CKR_SESSION_HANDLE_INVALID;
}
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
else if( pxSession->xOpened == ( CK_BBOOL ) CK_FALSE )
{
LogDebug( ( "Could not get a valid session. PKCS #11 session handle was not initialized with a previous call to C_OpenSession." ) );
xResult = CKR_SESSION_HANDLE_INVALID;
}
else
{
/* Session is initialized and valid. */
}
return xResult;
}
/**
* @brief Maps an opaque caller session handle into its internal state structure.
*/
static P11Session_t * prvSessionPointerFromHandle( CK_SESSION_HANDLE xSession )
{
P11Session_t * pxSession = NULL;
if( ( xSession >= 1UL ) && ( xSession <= pkcs11configMAX_SESSIONS ) )
{
/* Decrement by 1, invalid handles in PKCS #11 are defined to be 0. */
pxSession = &pxP11Sessions[ xSession - 1UL ];
}
else
{
LogDebug( ( "Could not convert from CK_SESSION_HANDLE to P11Session_t pointer. Session handle was out of the valid range. Session handle was: %lu.", ( unsigned long int ) xSession ) );
}
return pxSession;
}
/**
* @brief Determines if an operation is in progress.
*/
static CK_BBOOL prvOperationActive( const P11Session_t * pxSession )
{
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
CK_BBOOL xResult = ( CK_BBOOL ) CK_FALSE;
if( ( pxSession->xOperationDigestMechanism < pkcs11NO_OPERATION ) == CK_TRUE )
{
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
xResult = ( CK_BBOOL ) CK_TRUE;
}
else if( ( pxSession->xOperationSignMechanism < pkcs11NO_OPERATION ) == CK_TRUE )
{
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
xResult = ( CK_BBOOL ) CK_TRUE;
}
else if( ( pxSession->xOperationVerifyMechanism < pkcs11NO_OPERATION ) == CK_TRUE )
{
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
xResult = ( CK_BBOOL ) CK_TRUE;
}
else if( pxSession->pxFindObjectLabel != NULL )
{
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
xResult = ( CK_BBOOL ) CK_TRUE;
}
else
{
/* MISRA */
}
return xResult;
}
/**
* @brief Initialize mbedTLS.
*/
static CK_RV prvMbedTLS_Initialize( void )
{
CK_RV xResult = CKR_OK;
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
int32_t lMbedTLSResult = 0;
( void ) memset( &xP11Context, 0, sizeof( xP11Context ) );
mbedtls_mutex_init( &xP11Context.xObjectList.xMutex );
mbedtls_mutex_init( &xP11Context.xSessionMutex );
/* Initialize the entropy source and DRBG for the PKCS#11 module */
mbedtls_entropy_init( &xP11Context.xMbedEntropyContext );
mbedtls_ctr_drbg_init( &xP11Context.xMbedDrbgCtx );
lMbedTLSResult = mbedtls_ctr_drbg_seed( &xP11Context.xMbedDrbgCtx,
mbedtls_entropy_func,
&xP11Context.xMbedEntropyContext,
NULL,
0 );
if( 0 != lMbedTLSResult )
{
LogError( ( "Could not initialize PKCS #11. Failed to seed the DRBG: mbed TLS error = %s : %s.",
mbedtlsHighLevelCodeOrDefault( lMbedTLSResult ),
mbedtlsLowLevelCodeOrDefault( lMbedTLSResult ) ) );
xResult = CKR_FUNCTION_FAILED;
}
else
{
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
xP11Context.xIsInitialized = ( CK_BBOOL ) CK_TRUE;
LogDebug( ( "PKCS #11 module was successfully initialized." ) );
}
return xResult;
}
/**
* @brief Searches a template for the CKA_CLASS attribute.
*/
static CK_RV prvGetObjectClass( const CK_ATTRIBUTE * pxTemplate,
CK_ULONG ulCount,
CK_OBJECT_CLASS * pxClass )
{
CK_RV xResult = CKR_TEMPLATE_INCOMPLETE;
CK_ULONG ulIndex = 0;
/* Search template for class attribute. */
for( ulIndex = 0; ulIndex < ulCount; ulIndex++ )
{
if( ( pxTemplate[ ulIndex ].type == CKA_CLASS ) &&
( pxTemplate[ ulIndex ].ulValueLen == sizeof( CK_OBJECT_CLASS ) ) )
{
LogDebug( ( "Successfully found object class attribute." ) );
( void ) memcpy( pxClass, pxTemplate[ ulIndex ].pValue,
sizeof( CK_OBJECT_CLASS ) );
xResult = CKR_OK;
break;
}
}
return xResult;
}
/**
* @brief Parses attribute values for a certificate.
*/
static CK_RV prvCertAttParse( CK_ATTRIBUTE * pxAttribute,
CK_CERTIFICATE_TYPE * pxCertificateType,
CK_BYTE_PTR * ppxCertificateValue,
CK_ULONG * pxCertificateLength,
CK_ATTRIBUTE ** ppxLabel )
{
CK_RV xResult = CKR_OK;
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
CK_BBOOL xBool = ( CK_BBOOL ) CK_FALSE;
switch( pxAttribute->type )
{
case ( CKA_VALUE ):
*ppxCertificateValue = pxAttribute->pValue;
*pxCertificateLength = pxAttribute->ulValueLen;
break;
case ( CKA_LABEL ):
if( pxAttribute->ulValueLen <= pkcs11configMAX_LABEL_LENGTH )
{
*ppxLabel = pxAttribute;
}
else
{
LogError( ( "Failed parsing certificate template. Label length "
"was not in the valid range. Found %lu and expected %lu. "
"Consider updating pkcs11configMAX_LABEL_LENGTH.",
( unsigned long int ) pxAttribute->ulValueLen,
( unsigned long int ) pkcs11configMAX_LABEL_LENGTH ) );
xResult = CKR_DATA_LEN_RANGE;
}
break;
case ( CKA_CERTIFICATE_TYPE ):
if( pxAttribute->ulValueLen == sizeof( CK_CERTIFICATE_TYPE ) )
{
( void ) memcpy( pxCertificateType, pxAttribute->pValue, sizeof( CK_CERTIFICATE_TYPE ) );
}
if( *pxCertificateType != CKC_X_509 )
{
LogError( ( "Failed parsing certificate template. Certificate type was invalid. "
"Expected CKC_X_509, but found 0x%0lX.", ( unsigned long int ) *pxCertificateType ) );
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
}
break;
case ( CKA_TOKEN ):
if( pxAttribute->ulValueLen == sizeof( CK_BBOOL ) )
{
( void ) memcpy( &xBool, pxAttribute->pValue, sizeof( CK_BBOOL ) );
}
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
if( xBool != ( CK_BBOOL ) CK_TRUE )
{
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
}
break;
case ( CKA_CLASS ):
case ( CKA_SUBJECT ):
/* Do nothing. This was already parsed out of the template previously. */
break;
default:
LogError( ( "Failed parsing certificate template. Received an unknown "
"template type with value 0x%0lX.", ( unsigned long int ) pxAttribute->type ) );
xResult = CKR_ATTRIBUTE_TYPE_INVALID;
break;
}
return xResult;
}
/**
* @brief Parses attribute values for an RSA public Key.
*/
static CK_RV prvRsaPrivKeyAttParse( const CK_ATTRIBUTE * pxAttribute )
{
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
CK_BBOOL xBool = ( CK_BBOOL ) CK_FALSE;
CK_RV xResult = CKR_OK;
if( pxAttribute->type == CKA_SIGN )
{
if( pxAttribute->ulValueLen == sizeof( CK_BBOOL ) )
{
( void ) memcpy( &xBool, pxAttribute->pValue, pxAttribute->ulValueLen );
}
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
if( xBool == ( CK_BBOOL ) CK_FALSE )
{
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
LogError( ( "Failed to parse RSA private key. Expected sign permissions to be supported." ) );
}
}
return xResult;
}
/**
* @brief Parses attribute values for an RSA public Key.
*/
static CK_RV prvRsaPubKeyAttParse( const CK_ATTRIBUTE * pxAttribute )
{
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
CK_BBOOL xBool = ( CK_BBOOL ) CK_FALSE;
CK_RV xResult = CKR_OK;
if( pxAttribute->type == CKA_VERIFY )
{
if( pxAttribute->ulValueLen == sizeof( CK_BBOOL ) )
{
( void ) memcpy( &xBool, pxAttribute->pValue, pxAttribute->ulValueLen );
}
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
if( xBool == ( CK_BBOOL ) CK_FALSE )
{
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
LogError( ( "Failed to parse RSA public key. Expected verify permissions to be supported." ) );
}
}
return xResult;
}
/**
* @brief Parses attribute values for an RSA key an puts them in the mbed TLS context.
*/
static CK_RV prvRsaContextParse( const CK_ATTRIBUTE * pxAttribute,
mbedtls_rsa_context * pxRsaContext )
{
CK_RV xResult = CKR_OK;
int32_t lMbedTLSResult = 0;
switch( pxAttribute->type )
{
case ( CKA_MODULUS ):
lMbedTLSResult = mbedtls_rsa_import_raw( pxRsaContext,
pxAttribute->pValue, pxAttribute->ulValueLen, /* N */
NULL, 0, /* P */
NULL, 0, /* Q */
NULL, 0, /* D */
NULL, 0 ); /* E */
break;
case ( CKA_PUBLIC_EXPONENT ):
lMbedTLSResult = mbedtls_rsa_import_raw( pxRsaContext,
NULL, 0, /* N */
NULL, 0, /* P */
NULL, 0, /* Q */
NULL, 0, /* D */
pxAttribute->pValue, pxAttribute->ulValueLen ); /* E */
break;
case ( CKA_PRIME_1 ):
lMbedTLSResult = mbedtls_rsa_import_raw( pxRsaContext,
NULL, 0, /* N */
pxAttribute->pValue, pxAttribute->ulValueLen, /* P */
NULL, 0, /* Q */
NULL, 0, /* D */
NULL, 0 ); /* E */
break;
case ( CKA_PRIME_2 ):
lMbedTLSResult = mbedtls_rsa_import_raw( pxRsaContext,
NULL, 0, /* N */
NULL, 0, /* P */
pxAttribute->pValue, pxAttribute->ulValueLen, /* Q */
NULL, 0, /* D */
NULL, 0 ); /* E */
break;
case ( CKA_PRIVATE_EXPONENT ):
lMbedTLSResult = mbedtls_rsa_import_raw( pxRsaContext,
NULL, 0, /* N */
NULL, 0, /* P */
NULL, 0, /* Q */
pxAttribute->pValue, pxAttribute->ulValueLen, /* D */
NULL, 0 ); /* E */
break;
case ( CKA_EXPONENT_1 ):
lMbedTLSResult = mbedtls_mpi_read_binary( &pxRsaContext->DP, pxAttribute->pValue, pxAttribute->ulValueLen );
break;
case ( CKA_EXPONENT_2 ):
lMbedTLSResult = mbedtls_mpi_read_binary( &pxRsaContext->DQ, pxAttribute->pValue, pxAttribute->ulValueLen );
break;
case ( CKA_COEFFICIENT ):
lMbedTLSResult = mbedtls_mpi_read_binary( &pxRsaContext->QP, pxAttribute->pValue, pxAttribute->ulValueLen );
break;
default:
/* This should never be reached, as the above types are what gets this function called.
* Nevertheless this is an error case, and MISRA requires a default statement. */
xResult = CKR_ATTRIBUTE_TYPE_INVALID;
break;
}
if( lMbedTLSResult != 0 )
{
LogError( ( "Failed to parse RSA private key template: mbed TLS error = %s : %s.",
mbedtlsHighLevelCodeOrDefault( lMbedTLSResult ),
mbedtlsLowLevelCodeOrDefault( lMbedTLSResult ) ) );
xResult = CKR_FUNCTION_FAILED;
}
return xResult;
}
/**
* @brief Parses attribute values for a RSA Key.
*/
static CK_RV prvRsaKeyAttParse( const CK_ATTRIBUTE * pxAttribute,
mbedtls_rsa_context * pxRsaContext,
CK_BBOOL xIsPrivate )
{
CK_RV xResult = CKR_OK;
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
CK_BBOOL xBool = ( CK_BBOOL ) CK_FALSE;
switch( pxAttribute->type )
{
case ( CKA_CLASS ):
case ( CKA_KEY_TYPE ):
case ( CKA_LABEL ):
/* Do nothing. These values were parsed previously. */
break;
case ( CKA_TOKEN ):
if( pxAttribute->ulValueLen == sizeof( CK_BBOOL ) )
{
( void ) memcpy( &xBool, pxAttribute->pValue, sizeof( CK_BBOOL ) );
}
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
if( xBool != ( CK_BBOOL ) CK_TRUE )
{
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
}
break;
case ( CKA_VERIFY ):
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
if( xIsPrivate == ( CK_BBOOL ) CK_FALSE )
{
xResult = prvRsaPubKeyAttParse( pxAttribute );
}
else
{
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
}
break;
case ( CKA_SIGN ):
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
if( xIsPrivate == ( CK_BBOOL ) CK_TRUE )
{
xResult = prvRsaPrivKeyAttParse( pxAttribute );
}
else
{
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
}
break;
case ( CKA_MODULUS ):
case ( CKA_PUBLIC_EXPONENT ):
case ( CKA_PRIME_1 ):
case ( CKA_PRIME_2 ):
case ( CKA_PRIVATE_EXPONENT ):
case ( CKA_EXPONENT_1 ):
case ( CKA_EXPONENT_2 ):
case ( CKA_COEFFICIENT ):
xResult = prvRsaContextParse( pxAttribute, pxRsaContext );
break;
default:
xResult = CKR_ATTRIBUTE_TYPE_INVALID;
break;
}
return xResult;
}
/**
* @brief Parses attribute values for a private EC Key.
*/
#ifndef pkcs11configSUPPRESS_ECDSA_MECHANISM
static CK_RV prvEcPrivKeyAttParse( const CK_ATTRIBUTE * pxAttribute,
const mbedtls_pk_context * pxMbedContext )
{
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
CK_BBOOL xBool = ( CK_BBOOL ) CK_FALSE;
int32_t lMbedTLSResult = 0;
CK_RV xResult = CKR_OK;
mbedtls_ecp_keypair * pxKeyPair = ( mbedtls_ecp_keypair * ) pxMbedContext->pk_ctx;
if( pxAttribute->type == CKA_SIGN )
{
if( pxAttribute->ulValueLen == sizeof( CK_BBOOL ) )
{
( void ) memcpy( &xBool, pxAttribute->pValue, sizeof( CK_BBOOL ) );
}
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
if( xBool == ( CK_BBOOL ) CK_FALSE )
{
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
LogError( ( "Failed to parse EC private key. Only private keys with signing privileges are supported." ) );
}
}
else
{
lMbedTLSResult = mbedtls_mpi_read_binary( &pxKeyPair->d,
pxAttribute->pValue,
pxAttribute->ulValueLen );
if( lMbedTLSResult != 0 )
{
xResult = CKR_FUNCTION_FAILED;
LogError( ( "Failed to parse EC private key. MPI read binary failed: mbed TLS error = %s : %s.",
mbedtlsHighLevelCodeOrDefault( lMbedTLSResult ),
mbedtlsLowLevelCodeOrDefault( lMbedTLSResult ) ) );
}
}
return xResult;
}
#endif /* ifndef pkcs11configSUPPRESS_ECDSA_MECHANISM */
/**
* @brief Parses attribute values for a public EC Key.
*/
#ifndef pkcs11configSUPPRESS_ECDSA_MECHANISM
static CK_RV prvEcPubKeyAttParse( const CK_ATTRIBUTE * pxAttribute,
const mbedtls_pk_context * pxMbedContext )
{
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
CK_BBOOL xBool = ( CK_BBOOL ) CK_FALSE;
int32_t lMbedTLSResult = 0;
CK_RV xResult = CKR_OK;
mbedtls_ecp_keypair * pxKeyPair = ( mbedtls_ecp_keypair * ) pxMbedContext->pk_ctx;
if( pxAttribute->type == CKA_VERIFY )
{
if( pxAttribute->ulValueLen == sizeof( CK_BBOOL ) )
{
( void ) memcpy( &xBool, pxAttribute->pValue, pxAttribute->ulValueLen );
}
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
if( xBool == ( CK_BBOOL ) CK_FALSE )
{
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
LogError( ( "Failed to parse EC public key. Expected verify permissions to be supported." ) );
}
}
else
{
/* Strip the ANS.1 Encoding of type and length. Otherwise mbed TLS
* won't be able to parse the binary EC point. */
if( pxAttribute->ulValueLen >= 2UL )
{
lMbedTLSResult = mbedtls_ecp_point_read_binary( &pxKeyPair->grp,
&pxKeyPair->Q,
( ( uint8_t * ) ( pxAttribute->pValue ) + 2U ),
( pxAttribute->ulValueLen - 2U ) );
if( lMbedTLSResult != 0 )
{
xResult = CKR_FUNCTION_FAILED;
LogError( ( "Failed to parse EC public key. mbedtls_ecp_point_read_binary failed: mbed TLS error = %s : %s.",
mbedtlsHighLevelCodeOrDefault( lMbedTLSResult ),
mbedtlsLowLevelCodeOrDefault( lMbedTLSResult ) ) );
}
}
else
{
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
}
}
return xResult;
}
#endif /* ifndef pkcs11configSUPPRESS_ECDSA_MECHANISM */
/**
* @brief Parses attribute values for an EC Key.
*/
#ifndef pkcs11configSUPPRESS_ECDSA_MECHANISM
static CK_RV prvEcKeyAttParse( const CK_ATTRIBUTE * pxAttribute,
const mbedtls_pk_context * pxMbedContext,
CK_BBOOL xIsPrivate )
{
CK_RV xResult = CKR_OK;
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
CK_BBOOL xBool = ( CK_BBOOL ) CK_FALSE;
const CK_BYTE pxEcCurve[] = pkcs11DER_ENCODED_OID_P256;
const CK_BYTE * pxEcAttVal = NULL;
const CK_BBOOL * pxEcBoolAtt = NULL;
/* Common EC key attributes. */
switch( pxAttribute->type )
{
case ( CKA_CLASS ):
case ( CKA_KEY_TYPE ):
case ( CKA_LABEL ):
break;
case ( CKA_TOKEN ):
pxEcBoolAtt = ( CK_BBOOL * ) pxAttribute->pValue;
if( pxAttribute->ulValueLen == sizeof( CK_BBOOL ) )
{
( void ) memcpy( &xBool, pxEcBoolAtt, sizeof( CK_BBOOL ) );
}
/* MISRA Ref 10.5.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/corePKCS11/blob/main/MISRA.md#rule-105 */
/* coverity[misra_c_2012_rule_10_5_violation] */
if( xBool != ( CK_BBOOL ) CK_TRUE )
{
LogError( ( "Failed parsing EC key template. Expected token type to be true, but it was false." ) );
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
}
break;