/
pkcs11c.c
8106 lines (7357 loc) · 277 KB
/
pkcs11c.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* This file implements PKCS 11 on top of our existing security modules
*
* For more information about PKCS 11 See PKCS 11 Token Inteface Standard.
* This implementation has two slots:
* slot 1 is our generic crypto support. It does not require login.
* It supports Public Key ops, and all they bulk ciphers and hashes.
* It can also support Private Key ops for imported Private keys. It does
* not have any token storage.
* slot 2 is our private key support. It requires a login before use. It
* can store Private Keys and Certs as token objects. Currently only private
* keys and their associated Certificates are saved on the token.
*
* In this implementation, session objects are only visible to the session
* that created or generated them.
*/
#include "seccomon.h"
#include "secitem.h"
#include "secport.h"
#include "blapi.h"
#include "pkcs11.h"
#include "pkcs11i.h"
#include "pkcs1sig.h"
#include "lowkeyi.h"
#include "secder.h"
#include "secdig.h"
#include "lowpbe.h" /* We do PBE below */
#include "pkcs11t.h"
#include "secoid.h"
#include "alghmac.h"
#include "softoken.h"
#include "secasn1.h"
#include "secerr.h"
#include "prprf.h"
#include "prenv.h"
#define __PASTE(x, y) x##y
/*
* we renamed all our internal functions, get the correct
* definitions for them...
*/
#undef CK_PKCS11_FUNCTION_INFO
#undef CK_NEED_ARG_LIST
#define CK_EXTERN extern
#define CK_PKCS11_FUNCTION_INFO(func) \
CK_RV __PASTE(NS, func)
#define CK_NEED_ARG_LIST 1
#include "pkcs11f.h"
typedef struct {
PRUint8 client_version[2];
PRUint8 random[46];
} SSL3RSAPreMasterSecret;
static void
sftk_Null(void *data, PRBool freeit)
{
return;
}
#ifdef EC_DEBUG
#define SEC_PRINT(str1, str2, num, sitem) \
printf("pkcs11c.c:%s:%s (keytype=%d) [len=%d]\n", \
str1, str2, num, sitem->len); \
for (i = 0; i < sitem->len; i++) { \
printf("%02x:", sitem->data[i]); \
} \
printf("\n")
#else
#undef EC_DEBUG
#define SEC_PRINT(a, b, c, d)
#endif
/*
* free routines.... Free local type allocated data, and convert
* other free routines to the destroy signature.
*/
static void
sftk_FreePrivKey(NSSLOWKEYPrivateKey *key, PRBool freeit)
{
nsslowkey_DestroyPrivateKey(key);
}
static void
sftk_Space(void *data, PRBool freeit)
{
PORT_Free(data);
}
/*
* map all the SEC_ERROR_xxx error codes that may be returned by freebl
* functions to CKR_xxx. return CKR_DEVICE_ERROR by default for backward
* compatibility.
*/
static CK_RV
sftk_MapCryptError(int error)
{
switch (error) {
case SEC_ERROR_INVALID_ARGS:
case SEC_ERROR_BAD_DATA: /* MP_RANGE gets mapped to this */
return CKR_ARGUMENTS_BAD;
case SEC_ERROR_INPUT_LEN:
return CKR_DATA_LEN_RANGE;
case SEC_ERROR_OUTPUT_LEN:
return CKR_BUFFER_TOO_SMALL;
case SEC_ERROR_LIBRARY_FAILURE:
return CKR_GENERAL_ERROR;
case SEC_ERROR_NO_MEMORY:
return CKR_HOST_MEMORY;
case SEC_ERROR_BAD_SIGNATURE:
return CKR_SIGNATURE_INVALID;
case SEC_ERROR_INVALID_KEY:
return CKR_KEY_SIZE_RANGE;
case SEC_ERROR_BAD_KEY: /* an EC public key that fails validation */
return CKR_KEY_SIZE_RANGE; /* the closest error code */
case SEC_ERROR_UNSUPPORTED_EC_POINT_FORM:
return CKR_TEMPLATE_INCONSISTENT;
case SEC_ERROR_UNSUPPORTED_KEYALG:
return CKR_MECHANISM_INVALID;
case SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE:
return CKR_DOMAIN_PARAMS_INVALID;
/* key pair generation failed after max number of attempts */
case SEC_ERROR_NEED_RANDOM:
return CKR_FUNCTION_FAILED;
}
return CKR_DEVICE_ERROR;
}
/* used by Decrypt and UnwrapKey (indirectly) */
static CK_RV
sftk_MapDecryptError(int error)
{
switch (error) {
case SEC_ERROR_BAD_DATA:
return CKR_ENCRYPTED_DATA_INVALID;
default:
return sftk_MapCryptError(error);
}
}
/*
* return CKR_SIGNATURE_INVALID instead of CKR_DEVICE_ERROR by default for
* backward compatibilty.
*/
static CK_RV
sftk_MapVerifyError(int error)
{
CK_RV crv = sftk_MapCryptError(error);
if (crv == CKR_DEVICE_ERROR)
crv = CKR_SIGNATURE_INVALID;
return crv;
}
/*
* turn a CDMF key into a des key. CDMF is an old IBM scheme to export DES by
* Deprecating a full des key to 40 bit key strenth.
*/
static CK_RV
sftk_cdmf2des(unsigned char *cdmfkey, unsigned char *deskey)
{
unsigned char key1[8] = { 0xc4, 0x08, 0xb0, 0x54, 0x0b, 0xa1, 0xe0, 0xae };
unsigned char key2[8] = { 0xef, 0x2c, 0x04, 0x1c, 0xe6, 0x38, 0x2f, 0xe6 };
unsigned char enc_src[8];
unsigned char enc_dest[8];
unsigned int leng, i;
DESContext *descx;
SECStatus rv;
/* zero the parity bits */
for (i = 0; i < 8; i++) {
enc_src[i] = cdmfkey[i] & 0xfe;
}
/* encrypt with key 1 */
descx = DES_CreateContext(key1, NULL, NSS_DES, PR_TRUE);
if (descx == NULL)
return CKR_HOST_MEMORY;
rv = DES_Encrypt(descx, enc_dest, &leng, 8, enc_src, 8);
DES_DestroyContext(descx, PR_TRUE);
if (rv != SECSuccess)
return sftk_MapCryptError(PORT_GetError());
/* xor source with des, zero the parity bits and deprecate the key*/
for (i = 0; i < 8; i++) {
if (i & 1) {
enc_src[i] = (enc_src[i] ^ enc_dest[i]) & 0xfe;
} else {
enc_src[i] = (enc_src[i] ^ enc_dest[i]) & 0x0e;
}
}
/* encrypt with key 2 */
descx = DES_CreateContext(key2, NULL, NSS_DES, PR_TRUE);
if (descx == NULL)
return CKR_HOST_MEMORY;
rv = DES_Encrypt(descx, deskey, &leng, 8, enc_src, 8);
DES_DestroyContext(descx, PR_TRUE);
if (rv != SECSuccess)
return sftk_MapCryptError(PORT_GetError());
/* set the corret parity on our new des key */
sftk_FormatDESKey(deskey, 8);
return CKR_OK;
}
/* NSC_DestroyObject destroys an object. */
CK_RV
NSC_DestroyObject(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject)
{
SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession);
SFTKSession *session;
SFTKObject *object;
SFTKFreeStatus status;
CHECK_FORK();
if (slot == NULL) {
return CKR_SESSION_HANDLE_INVALID;
}
/*
* This whole block just makes sure we really can destroy the
* requested object.
*/
session = sftk_SessionFromHandle(hSession);
if (session == NULL) {
return CKR_SESSION_HANDLE_INVALID;
}
object = sftk_ObjectFromHandle(hObject, session);
if (object == NULL) {
sftk_FreeSession(session);
return CKR_OBJECT_HANDLE_INVALID;
}
/* don't destroy a private object if we aren't logged in */
if ((!slot->isLoggedIn) && (slot->needLogin) &&
(sftk_isTrue(object, CKA_PRIVATE))) {
sftk_FreeSession(session);
sftk_FreeObject(object);
return CKR_USER_NOT_LOGGED_IN;
}
/* don't destroy a token object if we aren't in a rw session */
if (((session->info.flags & CKF_RW_SESSION) == 0) &&
(sftk_isTrue(object, CKA_TOKEN))) {
sftk_FreeSession(session);
sftk_FreeObject(object);
return CKR_SESSION_READ_ONLY;
}
sftk_DeleteObject(session, object);
sftk_FreeSession(session);
/*
* get some indication if the object is destroyed. Note: this is not
* 100%. Someone may have an object reference outstanding (though that
* should not be the case by here. Also note that the object is "half"
* destroyed. Our internal representation is destroyed, but it may still
* be in the data base.
*/
status = sftk_FreeObject(object);
return (status != SFTK_DestroyFailure) ? CKR_OK : CKR_DEVICE_ERROR;
}
/*
************** Crypto Functions: Utilities ************************
*/
/*
* Utility function for converting PSS/OAEP parameter types into
* HASH_HashTypes. Note: Only SHA family functions are defined in RFC 3447.
*/
static HASH_HashType
GetHashTypeFromMechanism(CK_MECHANISM_TYPE mech)
{
switch (mech) {
case CKM_SHA_1:
case CKG_MGF1_SHA1:
return HASH_AlgSHA1;
case CKM_SHA224:
case CKG_MGF1_SHA224:
return HASH_AlgSHA224;
case CKM_SHA256:
case CKG_MGF1_SHA256:
return HASH_AlgSHA256;
case CKM_SHA384:
case CKG_MGF1_SHA384:
return HASH_AlgSHA384;
case CKM_SHA512:
case CKG_MGF1_SHA512:
return HASH_AlgSHA512;
default:
return HASH_AlgNULL;
}
}
/*
* Returns true if "params" contains a valid set of PSS parameters
*/
static PRBool
sftk_ValidatePssParams(const CK_RSA_PKCS_PSS_PARAMS *params)
{
if (!params) {
return PR_FALSE;
}
if (GetHashTypeFromMechanism(params->hashAlg) == HASH_AlgNULL ||
GetHashTypeFromMechanism(params->mgf) == HASH_AlgNULL) {
return PR_FALSE;
}
return PR_TRUE;
}
/*
* Returns true if "params" contains a valid set of OAEP parameters
*/
static PRBool
sftk_ValidateOaepParams(const CK_RSA_PKCS_OAEP_PARAMS *params)
{
if (!params) {
return PR_FALSE;
}
/* The requirements of ulSourceLen/pSourceData come from PKCS #11, which
* state:
* If the parameter is empty, pSourceData must be NULL and
* ulSourceDataLen must be zero.
*/
if (params->source != CKZ_DATA_SPECIFIED ||
(GetHashTypeFromMechanism(params->hashAlg) == HASH_AlgNULL) ||
(GetHashTypeFromMechanism(params->mgf) == HASH_AlgNULL) ||
(params->ulSourceDataLen == 0 && params->pSourceData != NULL) ||
(params->ulSourceDataLen != 0 && params->pSourceData == NULL)) {
return PR_FALSE;
}
return PR_TRUE;
}
/*
* return a context based on the SFTKContext type.
*/
SFTKSessionContext *
sftk_ReturnContextByType(SFTKSession *session, SFTKContextType type)
{
switch (type) {
case SFTK_ENCRYPT:
case SFTK_DECRYPT:
return session->enc_context;
case SFTK_HASH:
return session->hash_context;
case SFTK_SIGN:
case SFTK_SIGN_RECOVER:
case SFTK_VERIFY:
case SFTK_VERIFY_RECOVER:
return session->hash_context;
}
return NULL;
}
/*
* change a context based on the SFTKContext type.
*/
void
sftk_SetContextByType(SFTKSession *session, SFTKContextType type,
SFTKSessionContext *context)
{
switch (type) {
case SFTK_ENCRYPT:
case SFTK_DECRYPT:
session->enc_context = context;
break;
case SFTK_HASH:
session->hash_context = context;
break;
case SFTK_SIGN:
case SFTK_SIGN_RECOVER:
case SFTK_VERIFY:
case SFTK_VERIFY_RECOVER:
session->hash_context = context;
break;
}
return;
}
/*
* code to grab the context. Needed by every C_XXXUpdate, C_XXXFinal,
* and C_XXX function. The function takes a session handle, the context type,
* and wether or not the session needs to be multipart. It returns the context,
* and optionally returns the session pointer (if sessionPtr != NULL) if session
* pointer is returned, the caller is responsible for freeing it.
*/
static CK_RV
sftk_GetContext(CK_SESSION_HANDLE handle, SFTKSessionContext **contextPtr,
SFTKContextType type, PRBool needMulti, SFTKSession **sessionPtr)
{
SFTKSession *session;
SFTKSessionContext *context;
session = sftk_SessionFromHandle(handle);
if (session == NULL)
return CKR_SESSION_HANDLE_INVALID;
context = sftk_ReturnContextByType(session, type);
/* make sure the context is valid */
if ((context == NULL) || (context->type != type) || (needMulti && !(context->multi))) {
sftk_FreeSession(session);
return CKR_OPERATION_NOT_INITIALIZED;
}
*contextPtr = context;
if (sessionPtr != NULL) {
*sessionPtr = session;
} else {
sftk_FreeSession(session);
}
return CKR_OK;
}
/** Terminate operation (in the PKCS#11 spec sense).
* Intuitive name for FreeContext/SetNullContext pair.
*/
static void
sftk_TerminateOp(SFTKSession *session, SFTKContextType ctype,
SFTKSessionContext *context)
{
sftk_FreeContext(context);
sftk_SetContextByType(session, ctype, NULL);
}
/*
************** Crypto Functions: Encrypt ************************
*/
/*
* All the NSC_InitXXX functions have a set of common checks and processing they
* all need to do at the beginning. This is done here.
*/
static CK_RV
sftk_InitGeneric(SFTKSession *session, SFTKSessionContext **contextPtr,
SFTKContextType ctype, SFTKObject **keyPtr,
CK_OBJECT_HANDLE hKey, CK_KEY_TYPE *keyTypePtr,
CK_OBJECT_CLASS pubKeyType, CK_ATTRIBUTE_TYPE operation)
{
SFTKObject *key = NULL;
SFTKAttribute *att;
SFTKSessionContext *context;
/* We can only init if there is not current context active */
if (sftk_ReturnContextByType(session, ctype) != NULL) {
return CKR_OPERATION_ACTIVE;
}
/* find the key */
if (keyPtr) {
key = sftk_ObjectFromHandle(hKey, session);
if (key == NULL) {
return CKR_KEY_HANDLE_INVALID;
}
/* make sure it's a valid key for this operation */
if (((key->objclass != CKO_SECRET_KEY) && (key->objclass != pubKeyType)) || !sftk_isTrue(key, operation)) {
sftk_FreeObject(key);
return CKR_KEY_TYPE_INCONSISTENT;
}
/* get the key type */
att = sftk_FindAttribute(key, CKA_KEY_TYPE);
if (att == NULL) {
sftk_FreeObject(key);
return CKR_KEY_TYPE_INCONSISTENT;
}
PORT_Assert(att->attrib.ulValueLen == sizeof(CK_KEY_TYPE));
if (att->attrib.ulValueLen != sizeof(CK_KEY_TYPE)) {
sftk_FreeAttribute(att);
sftk_FreeObject(key);
return CKR_ATTRIBUTE_VALUE_INVALID;
}
PORT_Memcpy(keyTypePtr, att->attrib.pValue, sizeof(CK_KEY_TYPE));
sftk_FreeAttribute(att);
*keyPtr = key;
}
/* allocate the context structure */
context = (SFTKSessionContext *)PORT_Alloc(sizeof(SFTKSessionContext));
if (context == NULL) {
if (key)
sftk_FreeObject(key);
return CKR_HOST_MEMORY;
}
context->type = ctype;
context->multi = PR_TRUE;
context->rsa = PR_FALSE;
context->cipherInfo = NULL;
context->hashInfo = NULL;
context->doPad = PR_FALSE;
context->padDataLength = 0;
context->key = key;
context->blockSize = 0;
context->maxLen = 0;
*contextPtr = context;
return CKR_OK;
}
static int
sftk_aes_mode(CK_MECHANISM_TYPE mechanism)
{
switch (mechanism) {
case CKM_AES_CBC_PAD:
case CKM_AES_CBC:
return NSS_AES_CBC;
case CKM_AES_ECB:
return NSS_AES;
case CKM_AES_CTS:
return NSS_AES_CTS;
case CKM_AES_CTR:
return NSS_AES_CTR;
case CKM_AES_GCM:
return NSS_AES_GCM;
}
return -1;
}
static SECStatus
sftk_RSAEncryptRaw(NSSLOWKEYPublicKey *key, unsigned char *output,
unsigned int *outputLen, unsigned int maxLen,
const unsigned char *input, unsigned int inputLen)
{
SECStatus rv = SECFailure;
PORT_Assert(key->keyType == NSSLOWKEYRSAKey);
if (key->keyType != NSSLOWKEYRSAKey) {
PORT_SetError(SEC_ERROR_INVALID_KEY);
return SECFailure;
}
rv = RSA_EncryptRaw(&key->u.rsa, output, outputLen, maxLen, input,
inputLen);
if (rv != SECSuccess && PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) {
sftk_fatalError = PR_TRUE;
}
return rv;
}
static SECStatus
sftk_RSADecryptRaw(NSSLOWKEYPrivateKey *key, unsigned char *output,
unsigned int *outputLen, unsigned int maxLen,
const unsigned char *input, unsigned int inputLen)
{
SECStatus rv = SECFailure;
PORT_Assert(key->keyType == NSSLOWKEYRSAKey);
if (key->keyType != NSSLOWKEYRSAKey) {
PORT_SetError(SEC_ERROR_INVALID_KEY);
return SECFailure;
}
rv = RSA_DecryptRaw(&key->u.rsa, output, outputLen, maxLen, input,
inputLen);
if (rv != SECSuccess && PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) {
sftk_fatalError = PR_TRUE;
}
return rv;
}
static SECStatus
sftk_RSAEncrypt(NSSLOWKEYPublicKey *key, unsigned char *output,
unsigned int *outputLen, unsigned int maxLen,
const unsigned char *input, unsigned int inputLen)
{
SECStatus rv = SECFailure;
PORT_Assert(key->keyType == NSSLOWKEYRSAKey);
if (key->keyType != NSSLOWKEYRSAKey) {
PORT_SetError(SEC_ERROR_INVALID_KEY);
return SECFailure;
}
rv = RSA_EncryptBlock(&key->u.rsa, output, outputLen, maxLen, input,
inputLen);
if (rv != SECSuccess && PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) {
sftk_fatalError = PR_TRUE;
}
return rv;
}
static SECStatus
sftk_RSADecrypt(NSSLOWKEYPrivateKey *key, unsigned char *output,
unsigned int *outputLen, unsigned int maxLen,
const unsigned char *input, unsigned int inputLen)
{
SECStatus rv = SECFailure;
PORT_Assert(key->keyType == NSSLOWKEYRSAKey);
if (key->keyType != NSSLOWKEYRSAKey) {
PORT_SetError(SEC_ERROR_INVALID_KEY);
return SECFailure;
}
rv = RSA_DecryptBlock(&key->u.rsa, output, outputLen, maxLen, input,
inputLen);
if (rv != SECSuccess && PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) {
sftk_fatalError = PR_TRUE;
}
return rv;
}
static SECStatus
sftk_RSAEncryptOAEP(SFTKOAEPEncryptInfo *info, unsigned char *output,
unsigned int *outputLen, unsigned int maxLen,
const unsigned char *input, unsigned int inputLen)
{
HASH_HashType hashAlg;
HASH_HashType maskHashAlg;
PORT_Assert(info->key->keyType == NSSLOWKEYRSAKey);
if (info->key->keyType != NSSLOWKEYRSAKey) {
PORT_SetError(SEC_ERROR_INVALID_KEY);
return SECFailure;
}
hashAlg = GetHashTypeFromMechanism(info->params->hashAlg);
maskHashAlg = GetHashTypeFromMechanism(info->params->mgf);
return RSA_EncryptOAEP(&info->key->u.rsa, hashAlg, maskHashAlg,
(const unsigned char *)info->params->pSourceData,
info->params->ulSourceDataLen, NULL, 0,
output, outputLen, maxLen, input, inputLen);
}
static SECStatus
sftk_RSADecryptOAEP(SFTKOAEPDecryptInfo *info, unsigned char *output,
unsigned int *outputLen, unsigned int maxLen,
const unsigned char *input, unsigned int inputLen)
{
SECStatus rv = SECFailure;
HASH_HashType hashAlg;
HASH_HashType maskHashAlg;
PORT_Assert(info->key->keyType == NSSLOWKEYRSAKey);
if (info->key->keyType != NSSLOWKEYRSAKey) {
PORT_SetError(SEC_ERROR_INVALID_KEY);
return SECFailure;
}
hashAlg = GetHashTypeFromMechanism(info->params->hashAlg);
maskHashAlg = GetHashTypeFromMechanism(info->params->mgf);
rv = RSA_DecryptOAEP(&info->key->u.rsa, hashAlg, maskHashAlg,
(const unsigned char *)info->params->pSourceData,
info->params->ulSourceDataLen,
output, outputLen, maxLen, input, inputLen);
if (rv != SECSuccess && PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) {
sftk_fatalError = PR_TRUE;
}
return rv;
}
static SFTKChaCha20Poly1305Info *
sftk_ChaCha20Poly1305_CreateContext(const unsigned char *key,
unsigned int keyLen,
const CK_NSS_AEAD_PARAMS *params)
{
SFTKChaCha20Poly1305Info *ctx;
if (params->ulNonceLen != sizeof(ctx->nonce)) {
PORT_SetError(SEC_ERROR_INPUT_LEN);
return NULL;
}
ctx = PORT_New(SFTKChaCha20Poly1305Info);
if (ctx == NULL) {
return NULL;
}
if (ChaCha20Poly1305_InitContext(&ctx->freeblCtx, key, keyLen,
params->ulTagLen) != SECSuccess) {
PORT_Free(ctx);
return NULL;
}
PORT_Memcpy(ctx->nonce, params->pNonce, sizeof(ctx->nonce));
/* AAD data and length must both be null, or both non-null. */
PORT_Assert((params->pAAD == NULL) == (params->ulAADLen == 0));
if (params->ulAADLen > sizeof(ctx->ad)) {
/* Need to allocate an overflow buffer for the additional data. */
ctx->adOverflow = (unsigned char *)PORT_Alloc(params->ulAADLen);
if (!ctx->adOverflow) {
PORT_Free(ctx);
return NULL;
}
PORT_Memcpy(ctx->adOverflow, params->pAAD, params->ulAADLen);
} else {
ctx->adOverflow = NULL;
if (params->pAAD) {
PORT_Memcpy(ctx->ad, params->pAAD, params->ulAADLen);
}
}
ctx->adLen = params->ulAADLen;
return ctx;
}
static void
sftk_ChaCha20Poly1305_DestroyContext(SFTKChaCha20Poly1305Info *ctx,
PRBool freeit)
{
ChaCha20Poly1305_DestroyContext(&ctx->freeblCtx, PR_FALSE);
if (ctx->adOverflow != NULL) {
PORT_Free(ctx->adOverflow);
ctx->adOverflow = NULL;
}
ctx->adLen = 0;
if (freeit) {
PORT_Free(ctx);
}
}
static SECStatus
sftk_ChaCha20Poly1305_Encrypt(const SFTKChaCha20Poly1305Info *ctx,
unsigned char *output, unsigned int *outputLen,
unsigned int maxOutputLen,
const unsigned char *input, unsigned int inputLen)
{
const unsigned char *ad = ctx->adOverflow;
if (ad == NULL) {
ad = ctx->ad;
}
return ChaCha20Poly1305_Seal(&ctx->freeblCtx, output, outputLen,
maxOutputLen, input, inputLen, ctx->nonce,
sizeof(ctx->nonce), ad, ctx->adLen);
}
static SECStatus
sftk_ChaCha20Poly1305_Decrypt(const SFTKChaCha20Poly1305Info *ctx,
unsigned char *output, unsigned int *outputLen,
unsigned int maxOutputLen,
const unsigned char *input, unsigned int inputLen)
{
const unsigned char *ad = ctx->adOverflow;
if (ad == NULL) {
ad = ctx->ad;
}
return ChaCha20Poly1305_Open(&ctx->freeblCtx, output, outputLen,
maxOutputLen, input, inputLen, ctx->nonce,
sizeof(ctx->nonce), ad, ctx->adLen);
}
/** NSC_CryptInit initializes an encryption/Decryption operation.
*
* Always called by NSC_EncryptInit, NSC_DecryptInit, NSC_WrapKey,NSC_UnwrapKey.
* Called by NSC_SignInit, NSC_VerifyInit (via sftk_InitCBCMac) only for block
* ciphers MAC'ing.
*/
static CK_RV
sftk_CryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism,
CK_OBJECT_HANDLE hKey,
CK_ATTRIBUTE_TYPE mechUsage, CK_ATTRIBUTE_TYPE keyUsage,
SFTKContextType contextType, PRBool isEncrypt)
{
SFTKSession *session;
SFTKObject *key;
SFTKSessionContext *context;
SFTKAttribute *att;
CK_RC2_CBC_PARAMS *rc2_param;
#if NSS_SOFTOKEN_DOES_RC5
CK_RC5_CBC_PARAMS *rc5_param;
SECItem rc5Key;
#endif
CK_KEY_TYPE key_type;
CK_RV crv = CKR_OK;
unsigned effectiveKeyLength;
unsigned char newdeskey[24];
PRBool useNewKey = PR_FALSE;
int t;
crv = sftk_MechAllowsOperation(pMechanism->mechanism, mechUsage);
if (crv != CKR_OK)
return crv;
session = sftk_SessionFromHandle(hSession);
if (session == NULL)
return CKR_SESSION_HANDLE_INVALID;
crv = sftk_InitGeneric(session, &context, contextType, &key, hKey, &key_type,
isEncrypt ? CKO_PUBLIC_KEY : CKO_PRIVATE_KEY, keyUsage);
if (crv != CKR_OK) {
sftk_FreeSession(session);
return crv;
}
context->doPad = PR_FALSE;
switch (pMechanism->mechanism) {
case CKM_RSA_PKCS:
case CKM_RSA_X_509:
if (key_type != CKK_RSA) {
crv = CKR_KEY_TYPE_INCONSISTENT;
break;
}
context->multi = PR_FALSE;
context->rsa = PR_TRUE;
if (isEncrypt) {
NSSLOWKEYPublicKey *pubKey = sftk_GetPubKey(key, CKK_RSA, &crv);
if (pubKey == NULL) {
crv = CKR_KEY_HANDLE_INVALID;
break;
}
context->maxLen = nsslowkey_PublicModulusLen(pubKey);
context->cipherInfo = (void *)pubKey;
context->update = (SFTKCipher)(pMechanism->mechanism == CKM_RSA_X_509
? sftk_RSAEncryptRaw
: sftk_RSAEncrypt);
} else {
NSSLOWKEYPrivateKey *privKey = sftk_GetPrivKey(key, CKK_RSA, &crv);
if (privKey == NULL) {
crv = CKR_KEY_HANDLE_INVALID;
break;
}
context->maxLen = nsslowkey_PrivateModulusLen(privKey);
context->cipherInfo = (void *)privKey;
context->update = (SFTKCipher)(pMechanism->mechanism == CKM_RSA_X_509
? sftk_RSADecryptRaw
: sftk_RSADecrypt);
}
context->destroy = sftk_Null;
break;
case CKM_RSA_PKCS_OAEP:
if (key_type != CKK_RSA) {
crv = CKR_KEY_TYPE_INCONSISTENT;
break;
}
if (pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_OAEP_PARAMS) ||
!sftk_ValidateOaepParams((CK_RSA_PKCS_OAEP_PARAMS *)pMechanism->pParameter)) {
crv = CKR_MECHANISM_PARAM_INVALID;
break;
}
context->multi = PR_FALSE;
context->rsa = PR_TRUE;
if (isEncrypt) {
SFTKOAEPEncryptInfo *info = PORT_New(SFTKOAEPEncryptInfo);
if (info == NULL) {
crv = CKR_HOST_MEMORY;
break;
}
info->params = pMechanism->pParameter;
info->key = sftk_GetPubKey(key, CKK_RSA, &crv);
if (info->key == NULL) {
PORT_Free(info);
crv = CKR_KEY_HANDLE_INVALID;
break;
}
context->update = (SFTKCipher)sftk_RSAEncryptOAEP;
context->maxLen = nsslowkey_PublicModulusLen(info->key);
context->cipherInfo = info;
} else {
SFTKOAEPDecryptInfo *info = PORT_New(SFTKOAEPDecryptInfo);
if (info == NULL) {
crv = CKR_HOST_MEMORY;
break;
}
info->params = pMechanism->pParameter;
info->key = sftk_GetPrivKey(key, CKK_RSA, &crv);
if (info->key == NULL) {
PORT_Free(info);
crv = CKR_KEY_HANDLE_INVALID;
break;
}
context->update = (SFTKCipher)sftk_RSADecryptOAEP;
context->maxLen = nsslowkey_PrivateModulusLen(info->key);
context->cipherInfo = info;
}
context->destroy = (SFTKDestroy)sftk_Space;
break;
case CKM_RC2_CBC_PAD:
context->doPad = PR_TRUE;
/* fall thru */
case CKM_RC2_ECB:
case CKM_RC2_CBC:
context->blockSize = 8;
if (key_type != CKK_RC2) {
crv = CKR_KEY_TYPE_INCONSISTENT;
break;
}
att = sftk_FindAttribute(key, CKA_VALUE);
if (att == NULL) {
crv = CKR_KEY_HANDLE_INVALID;
break;
}
rc2_param = (CK_RC2_CBC_PARAMS *)pMechanism->pParameter;
effectiveKeyLength = (rc2_param->ulEffectiveBits + 7) / 8;
context->cipherInfo =
RC2_CreateContext((unsigned char *)att->attrib.pValue,
att->attrib.ulValueLen, rc2_param->iv,
pMechanism->mechanism == CKM_RC2_ECB ? NSS_RC2 : NSS_RC2_CBC, effectiveKeyLength);
sftk_FreeAttribute(att);
if (context->cipherInfo == NULL) {
crv = CKR_HOST_MEMORY;
break;
}
context->update = (SFTKCipher)(isEncrypt ? RC2_Encrypt : RC2_Decrypt);
context->destroy = (SFTKDestroy)RC2_DestroyContext;
break;
#if NSS_SOFTOKEN_DOES_RC5
case CKM_RC5_CBC_PAD:
context->doPad = PR_TRUE;
/* fall thru */
case CKM_RC5_ECB:
case CKM_RC5_CBC:
if (key_type != CKK_RC5) {
crv = CKR_KEY_TYPE_INCONSISTENT;
break;
}
att = sftk_FindAttribute(key, CKA_VALUE);
if (att == NULL) {
crv = CKR_KEY_HANDLE_INVALID;
break;
}
rc5_param = (CK_RC5_CBC_PARAMS *)pMechanism->pParameter;
context->blockSize = rc5_param->ulWordsize * 2;
rc5Key.data = (unsigned char *)att->attrib.pValue;
rc5Key.len = att->attrib.ulValueLen;
context->cipherInfo = RC5_CreateContext(&rc5Key, rc5_param->ulRounds,
rc5_param->ulWordsize, rc5_param->pIv,
pMechanism->mechanism == CKM_RC5_ECB ? NSS_RC5 : NSS_RC5_CBC);
sftk_FreeAttribute(att);
if (context->cipherInfo == NULL) {
crv = CKR_HOST_MEMORY;
break;
}
context->update = (SFTKCipher)(isEncrypt ? RC5_Encrypt : RC5_Decrypt);
context->destroy = (SFTKDestroy)RC5_DestroyContext;
break;
#endif
case CKM_RC4:
if (key_type != CKK_RC4) {
crv = CKR_KEY_TYPE_INCONSISTENT;
break;
}
att = sftk_FindAttribute(key, CKA_VALUE);
if (att == NULL) {
crv = CKR_KEY_HANDLE_INVALID;
break;
}
context->cipherInfo =
RC4_CreateContext((unsigned char *)att->attrib.pValue,
att->attrib.ulValueLen);
sftk_FreeAttribute(att);
if (context->cipherInfo == NULL) {
crv = CKR_HOST_MEMORY; /* WRONG !!! */
break;
}
context->update = (SFTKCipher)(isEncrypt ? RC4_Encrypt : RC4_Decrypt);
context->destroy = (SFTKDestroy)RC4_DestroyContext;
break;
case CKM_CDMF_CBC_PAD:
context->doPad = PR_TRUE;
/* fall thru */
case CKM_CDMF_ECB:
case CKM_CDMF_CBC:
if (key_type != CKK_CDMF) {
crv = CKR_KEY_TYPE_INCONSISTENT;
break;
}
t = (pMechanism->mechanism == CKM_CDMF_ECB) ? NSS_DES : NSS_DES_CBC;
goto finish_des;
case CKM_DES_ECB:
if (key_type != CKK_DES) {
crv = CKR_KEY_TYPE_INCONSISTENT;
break;
}
t = NSS_DES;
goto finish_des;
case CKM_DES_CBC_PAD:
context->doPad = PR_TRUE;
/* fall thru */
case CKM_DES_CBC:
if (key_type != CKK_DES) {
crv = CKR_KEY_TYPE_INCONSISTENT;
break;
}
t = NSS_DES_CBC;
goto finish_des;
case CKM_DES3_ECB:
if ((key_type != CKK_DES2) && (key_type != CKK_DES3)) {
crv = CKR_KEY_TYPE_INCONSISTENT;