-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathiot_pkcs11_psa.c
3649 lines (3212 loc) · 128 KB
/
iot_pkcs11_psa.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
/*
* Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Copyright (c) 2019-2021 Arm Limited. All Rights Reserved.
*
* 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.
*
*/
/*
* This file is derivative of amazon-freertos\libraries\abstractions\pkcs11\mbedtls
* \iot_pkcs11_mbedtls.c(amazon-freertos commit 74875b1d2)
*/
/**
* @file iot_pkcs11_psa.c
* @brief PSA based PKCS#11 implementation.
*/
/* C runtime includes. */
#include <stdio.h>
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#define MBEDTLS_ALLOW_PRIVATE_ACCESS
/* PKCS#11 includes. */
#include "core_pkcs11_config.h"
#include "core_pkcs11.h"
#include "iot_pkcs11_psa_object_management.h"
#include "iot_pkcs11_psa_input_format.h"
/* mbedTLS includes. */
#include "mbedtls/pk.h"
#define PKCS11_PRINT( X ) vLoggingPrintf X
#define PKCS11_WARNING_PRINT( X ) /* vLoggingPrintf X */
#define pkcs11NO_OPERATION ( ( CK_MECHANISM_TYPE ) 0xFFFFFFFFUL )
/*
* The length of the content of an ECPoint n uncompressed
* representation format defined by SEC1 §2.3.3.
*/
#define pkcs11KEY_ECPOINT_LENGTH ( 65 )
/**
* @brief Cryptoki module attribute definitions.
*/
#define pkcs11SLOT_ID ( 1 )
/* Private defines for checking that attribute templates are complete. */
#define LABEL_IN_TEMPLATE ( 1U )
#define PRIVATE_IN_TEMPLATE ( 1U << 1 )
#define SIGN_IN_TEMPLATE ( 1U << 2 )
#define EC_PARAMS_IN_TEMPLATE ( 1U << 3 )
#define VERIFY_IN_TEMPLATE ( 1U << 4 )
/**
* @brief Helper definitions.
*/
#define PKCS11_MODULE_IS_INITIALIZED ( ( xP11Context.xIsInitialized == CK_TRUE ) ? CK_TRUE : CK_FALSE )
#define PKCS11_SESSION_IS_OPEN( xSessionHandle ) ( ( ( ( P11SessionPtr_t ) xSessionHandle )->xOpened ) == CK_TRUE ? CKR_OK : CKR_SESSION_CLOSED )
#define PKCS11_SESSION_IS_VALID( xSessionHandle ) ( ( ( P11SessionPtr_t ) xSessionHandle != NULL ) ? PKCS11_SESSION_IS_OPEN( xSessionHandle ) : CKR_SESSION_HANDLE_INVALID )
#define PKCS11_SESSION_VALID_AND_MODULE_INITIALIZED( xSessionHandle ) ( PKCS11_MODULE_IS_INITIALIZED ? PKCS11_SESSION_IS_VALID( xSessionHandle ) : CKR_CRYPTOKI_NOT_INITIALIZED )
typedef struct P11Object_t
{
CK_OBJECT_HANDLE xHandle; /* The "PSA Handle". */
CK_BYTE xLabel[ pkcs11configMAX_LABEL_LENGTH + 1 ]; /* Plus 1 for the null terminator. */
} P11Object_t;
/* This structure helps the aws_pkcs11_psa.c maintain a mapping of all objects in one place.
* The ObjectList maintains a list of what object handles are available.
*/
typedef struct P11ObjectList_t
{
SemaphoreHandle_t xMutex; /* Mutex that protects write operations to the xObjects array. */
P11Object_t xObjects[ pkcs11configMAX_NUM_OBJECTS ];
} P11ObjectList_t;
/* PKCS #11 Module Object */
typedef struct P11Struct_t
{
CK_BBOOL xIsInitialized; /* Indicates whether PKCS #11 module has been initialized with a call to C_Initialize. */
P11ObjectList_t xObjectList; /* List of PKCS #11 objects that have been found/created since module initialization.
* The array position indicates the "App Handle" */
} P11Struct_t, * P11Context_t;
/* The global PKCS #11 module object.
* Entropy/randomness and object lists are shared across PKCS #11 sessions. */
static P11Struct_t xP11Context;
/**
* @brief Session structure.
*/
typedef struct P11Session
{
CK_ULONG ulState;
CK_BBOOL xOpened;
CK_MECHANISM_TYPE xOperationInProgress;
CK_BBOOL xFindObjectInit;
CK_BYTE * pxFindObjectLabel;
uint8_t xFindObjectLabelLength;
SemaphoreHandle_t xVerifyMutex; /* Protects the verification key from being modified while in use. */
psa_key_handle_t uxVerifyKey;
CK_MECHANISM_TYPE xVerifyMechanism; /* The mechanism of verify operation in progress. Set during C_VerifyInit. */
psa_algorithm_t xVerifyAlgorithm; /* Verify algorithm that is compatible with the type of key. */
SemaphoreHandle_t xSignMutex; /* Protects the signing key from being modified while in use. */
psa_key_handle_t uxSignKey;
CK_MECHANISM_TYPE xSignMechanism; /* Mechanism of the sign operation in progress. Set during C_SignInit. */
psa_algorithm_t xSignAlgorithm; /* Signature algorithm that is compatible with the type of key. */
psa_hash_operation_t *pxHashOperationHandle; /* hash operation handle in PSA crypto service. */
} P11Session_t, * P11SessionPtr_t;
/*
* PKCS#11 module implementation.
*/
/**
* @brief PKCS#11 interface functions implemented by this Cryptoki module.
*/
static CK_FUNCTION_LIST prvP11FunctionList =
{
{ CRYPTOKI_VERSION_MAJOR, CRYPTOKI_VERSION_MINOR },
C_Initialize,
C_Finalize,
NULL, /*C_GetInfo */
C_GetFunctionList,
C_GetSlotList,
NULL, /*C_GetSlotInfo*/
C_GetTokenInfo,
NULL, /*C_GetMechanismList*/
C_GetMechanismInfo,
C_InitToken,
NULL, /*C_InitPIN*/
NULL, /*C_SetPIN*/
C_OpenSession,
C_CloseSession,
NULL, /*C_CloseAllSessions*/
NULL, /*C_GetSessionInfo*/
NULL, /*C_GetOperationState*/
NULL, /*C_SetOperationState*/
C_Login, /*C_Login*/
NULL, /*C_Logout*/
C_CreateObject,
NULL, /*C_CopyObject*/
C_DestroyObject,
NULL, /*C_GetObjectSize*/
C_GetAttributeValue,
NULL, /*C_SetAttributeValue*/
C_FindObjectsInit,
C_FindObjects,
C_FindObjectsFinal,
NULL, /*C_EncryptInit*/
NULL, /*C_Encrypt*/
NULL, /*C_EncryptUpdate*/
NULL, /*C_EncryptFinal*/
NULL, /*C_DecryptInit*/
NULL, /*C_Decrypt*/
NULL, /*C_DecryptUpdate*/
NULL, /*C_DecryptFinal*/
C_DigestInit,
NULL, /*C_Digest*/
C_DigestUpdate,
NULL, /* C_DigestKey*/
C_DigestFinal,
C_SignInit,
C_Sign,
NULL, /*C_SignUpdate*/
NULL, /*C_SignFinal*/
NULL, /*C_SignRecoverInit*/
NULL, /*C_SignRecover*/
C_VerifyInit,
C_Verify,
NULL, /*C_VerifyUpdate*/
NULL, /*C_VerifyFinal*/
NULL, /*C_VerifyRecoverInit*/
NULL, /*C_VerifyRecover*/
NULL, /*C_DigestEncryptUpdate*/
NULL, /*C_DecryptDigestUpdate*/
NULL, /*C_SignEncryptUpdate*/
NULL, /*C_DecryptVerifyUpdate*/
NULL, /*C_GenerateKey*/
C_GenerateKeyPair,
NULL, /*C_WrapKey*/
NULL, /*C_UnwrapKey*/
NULL, /*C_DeriveKey*/
NULL, /*C_SeedRandom*/
C_GenerateRandom,
NULL, /*C_GetFunctionStatus*/
NULL, /*C_CancelFunction*/
NULL /*C_WaitForSlotEvent*/
};
/*-----------------------------------------------------------*/
/**
* @brief Maps an opaque caller session handle into its internal state structure.
*/
P11SessionPtr_t prvSessionPointerFromHandle( CK_SESSION_HANDLE xSession )
{
return ( P11SessionPtr_t ) xSession; /*lint !e923 Allow casting integer type to pointer for handle. */
}
/**
* @brief Add an object that exists in NVM to the application object array.
*
* @param[in[ xPalHandle The handle used by the PKCS #11 PAL for object.
* @param[out] pxAppHandle Updated to contain the application handle corresponding to xPalHandle.
* @param[in] pcLabel Pointer to object label.
* @param[in] xLabelLength Length of the PKCS #11 label.
*
*/
CK_RV prvAddObjectToList( CK_OBJECT_HANDLE xPalHandle,
CK_OBJECT_HANDLE_PTR pxAppHandle,
uint8_t * pcLabel,
size_t xLabelLength )
{
CK_RV xResult = CKR_OK;
BaseType_t xGotSemaphore;
CK_BBOOL xObjectFound = CK_FALSE;
int lInsertIndex = -1;
int lSearchIndex = pkcs11configMAX_NUM_OBJECTS - 1;
xGotSemaphore = xSemaphoreTake( xP11Context.xObjectList.xMutex, portMAX_DELAY );
if( xGotSemaphore == pdTRUE )
{
for( lSearchIndex = pkcs11configMAX_NUM_OBJECTS - 1; lSearchIndex >= 0; lSearchIndex-- )
{
if( xP11Context.xObjectList.xObjects[ lSearchIndex ].xHandle == xPalHandle )
{
/* Object already exists in list. */
xObjectFound = CK_TRUE;
/* Assign the object handle. */
*pxAppHandle = lSearchIndex + 1;
break;
}
else if( xP11Context.xObjectList.xObjects[ lSearchIndex ].xHandle == CK_INVALID_HANDLE )
{
lInsertIndex = lSearchIndex;
}
}
if( xObjectFound == CK_FALSE )
{
if( lInsertIndex != -1 )
{
if( xLabelLength < pkcs11configMAX_LABEL_LENGTH )
{
xP11Context.xObjectList.xObjects[ lInsertIndex ].xHandle = xPalHandle;
memcpy( xP11Context.xObjectList.xObjects[ lInsertIndex ].xLabel, pcLabel, xLabelLength );
*pxAppHandle = lInsertIndex + 1;
}
else
{
xResult = CKR_DATA_LEN_RANGE;
}
}
else
{
xResult = CKR_BUFFER_TOO_SMALL;
}
}
xSemaphoreGive( xP11Context.xObjectList.xMutex );
}
else
{
xResult = CKR_CANT_LOCK;
}
return xResult;
}
/**
* @brief Looks up a PKCS #11 object's label and PAL handle given an application handle.
*
* @param[in] xAppHandle The handle of the object being lookedup for, used by the application.
* @param[out] xPalHandle Pointer to the handle corresponding to xPalHandle being used by the PAL.
* @param[out] ppcLabel Pointer to an array containing label. NULL if object not found.
* @param[out] pxLabelLength Pointer to label length (includes a string null terminator).
* 0 if no object found.
*/
void prvFindObjectInListByHandle( CK_OBJECT_HANDLE xAppHandle,
CK_OBJECT_HANDLE_PTR pxPalHandle,
uint8_t ** ppcLabel,
size_t * pxLabelLength )
{
int lIndex = xAppHandle - 1;
*ppcLabel = NULL;
*pxLabelLength = 0;
*pxPalHandle = CK_INVALID_HANDLE;
if( lIndex < pkcs11configMAX_NUM_OBJECTS ) /* Check that handle is in bounds. */
{
if( xP11Context.xObjectList.xObjects[ lIndex ].xHandle != CK_INVALID_HANDLE )
{
*ppcLabel = xP11Context.xObjectList.xObjects[ lIndex ].xLabel;
*pxLabelLength = strlen( ( const char * ) xP11Context.xObjectList.xObjects[ lIndex ].xLabel ) + 1;
*pxPalHandle = xP11Context.xObjectList.xObjects[ lIndex ].xHandle;
}
}
}
/**
* @brief Searches the PKCS #11 module's object list for label and provides handle.
*
* @param[in] pcLabel Array containing label.
* @param[in] xLableLength Length of the label, in bytes.
* @param[out] pxPalHandle Pointer to the PAL handle to be provided.
* CK_INVALID_HANDLE if no object found.
* @param[out] pxAppHandle Pointer to the application handle to be provided.
* CK_INVALID_HANDLE if no object found.
*/
void prvFindObjectInListByLabel( uint8_t * pcLabel,
size_t xLabelLength,
CK_OBJECT_HANDLE_PTR pxPalHandle,
CK_OBJECT_HANDLE_PTR pxAppHandle )
{
uint8_t ucIndex;
*pxPalHandle = CK_INVALID_HANDLE;
*pxAppHandle = CK_INVALID_HANDLE;
for( ucIndex = 0; ucIndex < pkcs11configMAX_NUM_OBJECTS; ucIndex++ )
{
if( 0 == memcmp( pcLabel, xP11Context.xObjectList.xObjects[ ucIndex ].xLabel, xLabelLength ) )
{
*pxPalHandle = xP11Context.xObjectList.xObjects[ ucIndex ].xHandle;
*pxAppHandle = ucIndex + 1; /* Zero is not a valid handle, so let's offset by 1. */
break;
}
}
}
/**
* @brief This function is not implemented for this port.
*
* C_Login() is only implemented for compatibility with other ports.
* All inputs to this function are ignored, and calling this
* function on this port does not add any security.
*
* @return CKR_OK.
*/
CK_DECLARE_FUNCTION( CK_RV, C_Login )( CK_SESSION_HANDLE hSession,
CK_USER_TYPE userType,
CK_UTF8CHAR_PTR pPin,
CK_ULONG ulPinLen )
{
/* Avoid warnings about unused parameters. */
( void ) hSession;
( void ) userType;
( void ) pPin;
( void ) ulPinLen;
return CKR_OK;
}
/* Helper function for parsing the templates of device certificates for
* C_CreateObject. */
CK_RV prvCreateCertificate( CK_ATTRIBUTE_PTR pxTemplate,
CK_ULONG ulCount,
CK_OBJECT_HANDLE_PTR pxObject )
{
CK_RV xResult = CKR_OK;
CK_BYTE_PTR pxCertificateValue = NULL;
CK_ULONG xCertificateLength = 0;
CK_ATTRIBUTE_PTR pxLabel = NULL;
CK_ATTRIBUTE_PTR pxClass = NULL;
CK_OBJECT_HANDLE xPalHandle = CK_INVALID_HANDLE;
CK_CERTIFICATE_TYPE xCertificateType = 0; /* = CKC_X_509; */
uint32_t ulIndex = 0;
CK_BBOOL xBool = CK_FALSE;
CK_ATTRIBUTE xAttribute;
/* Search for the pointer to the certificate VALUE. */
for( ulIndex = 0; ulIndex < ulCount; ulIndex++ )
{
xAttribute = pxTemplate[ ulIndex ];
switch( xAttribute.type )
{
case ( CKA_VALUE ):
pxCertificateValue = xAttribute.pValue;
xCertificateLength = xAttribute.ulValueLen;
break;
case ( CKA_LABEL ):
if( xAttribute.ulValueLen <= pkcs11configMAX_LABEL_LENGTH )
{
pxLabel = &pxTemplate[ ulIndex ];
}
else
{
xResult = CKR_DATA_LEN_RANGE;
}
break;
case ( CKA_CERTIFICATE_TYPE ):
memcpy( &xCertificateType, xAttribute.pValue, sizeof( CK_CERTIFICATE_TYPE ) );
if( xCertificateType != CKC_X_509 )
{
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
}
break;
case ( CKA_TOKEN ):
memcpy( &xBool, xAttribute.pValue, sizeof( CK_BBOOL ) );
if( xBool != CK_TRUE )
{
PKCS11_PRINT( ( "ERROR: Only token key object is supported. \r\n" ) );
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
}
break;
case ( CKA_CLASS ):
pxClass = &pxTemplate[ ulIndex ];
break;
case ( CKA_SUBJECT ):
/* Do nothing. This was already parsed out of the template previously. */
break;
default:
xResult = CKR_TEMPLATE_INCONSISTENT;
break;
}
}
if( ( pxCertificateValue == NULL ) || ( pxLabel == NULL ) )
{
xResult = CKR_TEMPLATE_INCOMPLETE;
}
if( xResult == CKR_OK )
{
xPalHandle = PKCS11PSASaveObject( pxClass, pxLabel, pxCertificateValue, xCertificateLength, NULL );
if( xPalHandle == 0 ) /*Invalid handle. */
{
xResult = CKR_DEVICE_MEMORY;
}
}
if( xResult == CKR_OK )
{
/* If adding the object to the list fails, an error will be returned. In this case, remain the
* saved object in PSA as the object list as well as the PSA secure storage will be searched when
* finding an object in C_findobjects.
*/
xResult = prvAddObjectToList( xPalHandle, pxObject, pxLabel->pValue, pxLabel->ulValueLen );
}
return xResult;
}
#define PKCS11_INVALID_KEY_TYPE ( ( CK_KEY_TYPE ) 0xFFFFFFFF )
/* Helper to search an attribute for the key type attribute. */
void prvGetKeyType( CK_KEY_TYPE * pxKeyType,
CK_ATTRIBUTE_PTR pxTemplate,
CK_ULONG ulCount )
{
uint32_t ulIndex;
CK_ATTRIBUTE xAttribute;
*pxKeyType = PKCS11_INVALID_KEY_TYPE;
for( ulIndex = 0; ulIndex < ulCount; ulIndex++ )
{
xAttribute = pxTemplate[ ulIndex ];
if( xAttribute.type == CKA_KEY_TYPE )
{
memcpy( pxKeyType, xAttribute.pValue, sizeof( CK_KEY_TYPE ) );
break;
}
}
}
/* Helper to search a template for the label attribute. */
void prvGetLabel( CK_ATTRIBUTE_PTR * ppxLabel,
CK_ATTRIBUTE_PTR pxTemplate,
CK_ULONG ulCount )
{
CK_ATTRIBUTE xAttribute;
uint32_t ulIndex;
*ppxLabel = NULL;
for( ulIndex = 0; ulIndex < ulCount; ulIndex++ )
{
xAttribute = pxTemplate[ ulIndex ];
if( xAttribute.type == CKA_LABEL )
{
*ppxLabel = &pxTemplate[ ulIndex ];
break;
}
}
}
/* Helper function for checking attribute templates of elliptic curve
* private keys before import with C_CreateObject. */
CK_RV prvCreateEcPrivateKey( mbedtls_pk_context * pxMbedContext,
CK_ATTRIBUTE_PTR * ppxLabel,
CK_ATTRIBUTE_PTR * ppxClass,
CK_ATTRIBUTE_PTR pxTemplate,
CK_ULONG ulCount,
CK_OBJECT_HANDLE_PTR pxObject )
{
CK_RV xResult = CKR_OK;
int lMbedReturn;
CK_BBOOL xBool;
uint32_t ulIndex;
CK_ATTRIBUTE xAttribute;
*ppxLabel = NULL;
*ppxClass = NULL;
/* Key will be assembled in the mbedTLS key context and then exported to DER for storage. */
mbedtls_ecp_keypair * pxKeyPair = ( mbedtls_ecp_keypair * ) pxMbedContext->pk_ctx;
for( ulIndex = 0; ulIndex < ulCount; ulIndex++ )
{
xAttribute = pxTemplate[ ulIndex ];
switch( xAttribute.type )
{
case ( CKA_CLASS ):
*ppxClass = &pxTemplate[ ulIndex ];
break;
case ( CKA_KEY_TYPE ):
/* Do nothing.
* Key type and object type were checked previously. */
break;
case ( CKA_TOKEN ):
memcpy( &xBool, xAttribute.pValue, sizeof( CK_BBOOL ) );
if( xBool != CK_TRUE )
{
PKCS11_PRINT( ( "ERROR: Only token key creation is supported. \r\n" ) );
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
}
break;
case ( CKA_SIGN ):
memcpy( &xBool, xAttribute.pValue, sizeof( CK_BBOOL ) );
if( xBool != CK_TRUE )
{
PKCS11_PRINT( ( "ERROR: Only keys with signing priveledges are supported. \r\n" ) );
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
}
break;
case ( CKA_LABEL ):
if( xAttribute.ulValueLen <= pkcs11configMAX_LABEL_LENGTH )
{
*ppxLabel = &pxTemplate[ ulIndex ];
}
else
{
xResult = CKR_DATA_LEN_RANGE;
}
break;
case ( CKA_EC_PARAMS ):
if( memcmp( ( CK_BYTE[] ) pkcs11DER_ENCODED_OID_P256, xAttribute.pValue, xAttribute.ulValueLen ) )
{
PKCS11_PRINT( ( "ERROR: Only elliptic curve P-256 is supported.\r\n" ) );
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
}
break;
case ( CKA_VALUE ):
lMbedReturn = mbedtls_mpi_read_binary( &pxKeyPair->d,
xAttribute.pValue,
xAttribute.ulValueLen );
if( lMbedReturn != 0 )
{
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
}
break;
default:
xResult = CKR_TEMPLATE_INCONSISTENT;
break;
}
}
return xResult;
}
/* Helper function for parsing RSA Private Key attribute templates
* for C_CreateObject. */
CK_RV prvCreateRsaPrivateKey( mbedtls_pk_context * pxMbedContext,
CK_ATTRIBUTE_PTR * ppxLabel,
CK_ATTRIBUTE_PTR * ppxClass,
CK_ATTRIBUTE_PTR pxTemplate,
CK_ULONG ulCount,
CK_OBJECT_HANDLE_PTR pxObject )
{
CK_RV xResult = CKR_OK;
mbedtls_rsa_context * pxRsaContext;
int lMbedReturn = 0;
CK_BBOOL xBool;
uint32_t ulIndex;
CK_ATTRIBUTE xAttribute;
*ppxLabel = NULL;
*ppxClass = NULL;
pxRsaContext = pxMbedContext->pk_ctx;
mbedtls_rsa_init( pxRsaContext );
/* Parse template and collect the relevant parts. */
for( ulIndex = 0; ulIndex < ulCount; ulIndex++ )
{
xAttribute = pxTemplate[ ulIndex ];
switch( xAttribute.type )
{
case ( CKA_CLASS ):
*ppxClass = &pxTemplate[ ulIndex ];
break;
case ( CKA_KEY_TYPE ):
/* Do nothing.
* Key type & object type were checked previously.
*/
break;
case ( CKA_TOKEN ):
memcpy( &xBool, xAttribute.pValue, sizeof( CK_BBOOL ) );
if( xBool != CK_TRUE )
{
PKCS11_PRINT( ( "ERROR: Only token key creation is supported. \r\n" ) );
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
}
break;
case ( CKA_LABEL ):
if( xAttribute.ulValueLen <= pkcs11configMAX_LABEL_LENGTH )
{
*ppxLabel = &pxTemplate[ ulIndex ];
}
else
{
xResult = CKR_DATA_LEN_RANGE;
}
break;
case ( CKA_SIGN ):
memcpy( &xBool, xAttribute.pValue, xAttribute.ulValueLen );
if( xBool != CK_TRUE )
{
PKCS11_PRINT( ( "Only RSA private keys with signing permissions supported. \r\n" ) );
xResult = CKR_TEMPLATE_INCONSISTENT;
}
break;
case ( CKA_MODULUS ):
lMbedReturn = mbedtls_rsa_import_raw( pxRsaContext,
xAttribute.pValue, xAttribute.ulValueLen, /* N */
NULL, 0, /* P */
NULL, 0, /* Q */
NULL, 0, /* D */
NULL, 0 ); /* E */
break;
case ( CKA_PUBLIC_EXPONENT ):
lMbedReturn = mbedtls_rsa_import_raw( pxRsaContext,
NULL, 0, /* N */
NULL, 0, /* P */
NULL, 0, /* Q */
NULL, 0, /* D */
xAttribute.pValue, xAttribute.ulValueLen ); /* E */
break;
case ( CKA_PRIME_1 ):
lMbedReturn = mbedtls_rsa_import_raw( pxRsaContext,
NULL, 0, /* N */
xAttribute.pValue, xAttribute.ulValueLen, /* P */
NULL, 0, /* Q */
NULL, 0, /* D */
NULL, 0 ); /* E */
break;
case ( CKA_PRIME_2 ):
lMbedReturn = mbedtls_rsa_import_raw( pxRsaContext,
NULL, 0, /* N */
NULL, 0, /* P */
xAttribute.pValue, xAttribute.ulValueLen, /* Q */
NULL, 0, /* D */
NULL, 0 ); /* E */
break;
case ( CKA_PRIVATE_EXPONENT ):
lMbedReturn = mbedtls_rsa_import_raw( pxRsaContext,
NULL, 0, /* N */
NULL, 0, /* P */
NULL, 0, /* Q */
xAttribute.pValue, xAttribute.ulValueLen, /* D */
NULL, 0 ); /* E */
break;
case ( CKA_EXPONENT_1 ):
lMbedReturn = mbedtls_mpi_read_binary( &pxRsaContext->DP, xAttribute.pValue, xAttribute.ulValueLen );
break;
case ( CKA_EXPONENT_2 ):
lMbedReturn = mbedtls_mpi_read_binary( &pxRsaContext->DQ, xAttribute.pValue, xAttribute.ulValueLen );
break;
case ( CKA_COEFFICIENT ):
lMbedReturn = mbedtls_mpi_read_binary( &pxRsaContext->QP, xAttribute.pValue, xAttribute.ulValueLen );
break;
default:
PKCS11_PRINT( ( "Unknown attribute found for RSA private key. %d \r\n", xAttribute.type ) );
xResult = CKR_TEMPLATE_INCONSISTENT;
break;
}
if( lMbedReturn != 0 )
{
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
break;
}
}
return xResult;
}
/* Helper function for importing private keys using template
* C_CreateObject. */
CK_RV prvCreatePrivateKey( CK_ATTRIBUTE_PTR pxTemplate,
CK_ULONG ulCount,
CK_OBJECT_HANDLE_PTR pxObject )
{
/*
* RSAPrivateKey ::= SEQUENCE {
* version Version,
* modulus INTEGER, -- n (256 bytes for RSA-2048)
* publicExponent INTEGER, -- e (3 or 4 bytes for RSA-2048)
* privateExponent INTEGER, -- d (about 256 bytes for RSA-2048)
* prime1 INTEGER, -- p (128 bytes for RSA-2048)
* prime2 INTEGER, -- q (128 bytes for RSA-2048)
* exponent1 INTEGER, -- d mod (p-1) (128 bytes for RSA-2048)
* exponent2 INTEGER, -- d mod (q-1) (128 bytes for RSA-2048)
* coefficient INTEGER, -- (inverse of q) mod p (128 bytes for RSA-2048)
* otherPrimeInfos OtherPrimeInfos OPTIONAL
* }
* Besides, when encode the key, some ASN tags are also introduced.
* For RSA-2048, the encoded length should be around 1232 bytes.
*/
#define MAX_PRIVATE_KEY_SIZE 1300
mbedtls_pk_context xMbedContext;
int lDerKeyLength = 0;
int compare = 0;
CK_BYTE_PTR pxDerKey = NULL;
CK_RV xResult = CKR_OK;
CK_KEY_TYPE xKeyType;
CK_ATTRIBUTE_PTR pxLabel = NULL;
CK_ATTRIBUTE_PTR pxClass = NULL;
CK_OBJECT_HANDLE xPalHandle = CK_INVALID_HANDLE;
mbedtls_rsa_context * pxRsaCtx = NULL;
mbedtls_ecp_keypair * pxKeyPair = NULL;
prvGetKeyType( &xKeyType, pxTemplate, ulCount );
mbedtls_pk_init( &xMbedContext );
if( xKeyType == CKK_RSA )
{
/* mbedtls_rsa_context must be malloc'ed to use with mbedtls_pk_free function. */
pxRsaCtx = pvPortMalloc( sizeof( mbedtls_rsa_context ) );
if( pxRsaCtx != NULL )
{
xMbedContext.pk_ctx = pxRsaCtx;
xMbedContext.pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA);
xResult = prvCreateRsaPrivateKey( &xMbedContext,
&pxLabel,
&pxClass,
pxTemplate,
ulCount,
pxObject );
}
else
{
xResult = CKR_HOST_MEMORY;
}
}
#if ( pkcs11configSUPPRESS_ECDSA_MECHANISM != 1 )
else if( xKeyType == CKK_EC ) /* CKK_EC = CKK_ECDSA. */
{
/* Key will be assembled in the mbedTLS key context and then exported to DER for storage. */
prvGetLabel( &pxLabel, pxTemplate, ulCount );
/* An mbedTLS key is comprised of 2 pieces of data- an "info" and a "context".
* Since a valid key was not found by prvGetExistingKeyComponent, we are going to initialize
* the structure so that the mbedTLS structures will look the same as they would if a key
* had been found, minus the public key component. */
/* If a key had been found by prvGetExistingKeyComponent, the keypair context
* would have been malloc'ed. */
pxKeyPair = pvPortMalloc( sizeof( mbedtls_ecp_keypair ) );
if( pxKeyPair != NULL )
{
/* Initialize the info. */
xMbedContext.pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY);
/* Initialize the context. */
xMbedContext.pk_ctx = pxKeyPair;
mbedtls_ecp_keypair_init( pxKeyPair );
mbedtls_ecp_group_init( &pxKeyPair->grp );
/*/ * At this time, only P-256 curves are supported. * / */
mbedtls_ecp_group_load( &pxKeyPair->grp, MBEDTLS_ECP_DP_SECP256R1 );
}
else
{
xResult = CKR_HOST_MEMORY;
}
xResult = prvCreateEcPrivateKey( &xMbedContext,
&pxLabel,
&pxClass,
pxTemplate,
ulCount,
pxObject );
}
#endif /* if ( pkcs11configSUPPRESS_ECDSA_MECHANISM != 1 ) */
else
{
xResult = CKR_MECHANISM_INVALID;
}
/* Convert back to DER and save to memory. */
if( xResult == CKR_OK )
{
pxDerKey = pvPortMalloc( MAX_PRIVATE_KEY_SIZE );
if( pxDerKey == NULL )
{
xResult = CKR_HOST_MEMORY;
}
}
if( xResult == CKR_OK )
{
lDerKeyLength = mbedtls_pk_write_key_der( &xMbedContext, pxDerKey, MAX_PRIVATE_KEY_SIZE );
if( lDerKeyLength < 0 )
{
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
}
/* Do not clean up the mbedTLS key context here as it will be used in psa_save_object. */
}
/* Save the object to device NVM. */
if( xResult == CKR_OK )
{
xPalHandle = PKCS11PSASaveObject( pxClass,
pxLabel,
pxDerKey + ( MAX_PRIVATE_KEY_SIZE - lDerKeyLength ),
lDerKeyLength,
&xMbedContext );
if( xPalHandle == 0 )
{
xResult = CKR_DEVICE_MEMORY;
}
mbedtls_pk_free( &xMbedContext );
}
/* Store the PAL handle/label/application handle in lookup. */
if( xResult == CKR_OK )
{
xResult = prvAddObjectToList( xPalHandle, pxObject, pxLabel->pValue, pxLabel->ulValueLen );
}
if( pxDerKey != NULL )
{
vPortFree( pxDerKey );
}
return xResult;
}
/* Helper function for importing elliptic curve public keys from
* template using C_CreateObject. */
CK_RV prvCreateECPublicKey( mbedtls_pk_context * pxMbedContext,
CK_ATTRIBUTE_PTR * ppxLabel,
CK_ATTRIBUTE_PTR *ppxClass,
CK_ATTRIBUTE_PTR pxTemplate,
CK_ULONG ulCount,
CK_OBJECT_HANDLE_PTR pxObject )
{
CK_RV xResult = CKR_OK;
int lMbedReturn;
CK_BBOOL xBool;
uint32_t ulIndex;
CK_ATTRIBUTE xAttribute;
*ppxLabel = NULL;
*ppxClass = NULL;
/* Key will be assembled in the mbedTLS key context and then exported to DER for storage. */
mbedtls_ecp_keypair * pxKeyPair = ( mbedtls_ecp_keypair * ) pxMbedContext->pk_ctx;
for( ulIndex = 0; ulIndex < ulCount; ulIndex++ )
{
xAttribute = pxTemplate[ ulIndex ];
switch( xAttribute.type )
{
case ( CKA_CLASS ):
*ppxClass = &pxTemplate[ ulIndex ];
case ( CKA_KEY_TYPE ):
/* Do nothing.
* Key type and class were checked previously. */
break;
case ( CKA_TOKEN ):
memcpy( &xBool, xAttribute.pValue, sizeof( CK_BBOOL ) );
if( xBool != CK_TRUE )
{
PKCS11_PRINT( ( "ERROR: Only token key creation is supported. \r\n" ) );
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
}
break;
case ( CKA_LABEL ):
if( xAttribute.ulValueLen < pkcs11configMAX_LABEL_LENGTH )
{
*ppxLabel = &pxTemplate[ ulIndex ];
}
else
{
xResult = CKR_DATA_LEN_RANGE;
}
break;
case ( CKA_VERIFY ):
memcpy( &xBool, xAttribute.pValue, xAttribute.ulValueLen );
if( xBool != CK_TRUE )
{
PKCS11_PRINT( ( "Only EC Public Keys with verify permissions supported. \r\n" ) );