-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathwh_server_crypto.c
More file actions
8861 lines (7915 loc) · 318 KB
/
Copy pathwh_server_crypto.c
File metadata and controls
8861 lines (7915 loc) · 318 KB
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) 2024 wolfSSL Inc.
*
* This file is part of wolfHSM.
*
* wolfHSM is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* wolfHSM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with wolfHSM. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* src/wh_server/cryptocb.c
*
*/
/* Pick up compile-time configuration */
#include "wolfhsm/wh_settings.h"
#if !defined(WOLFHSM_CFG_NO_CRYPTO) && defined(WOLFHSM_CFG_ENABLE_SERVER)
/* System libraries */
#include <stdint.h>
#include <stddef.h> /* For NULL */
#include <string.h> /* For memset, memcpy */
#include "wolfssl/wolfcrypt/settings.h"
#include "wolfssl/wolfcrypt/types.h"
#include "wolfssl/wolfcrypt/error-crypt.h"
#include "wolfssl/wolfcrypt/asn.h"
#include "wolfssl/wolfcrypt/rsa.h"
#include "wolfssl/wolfcrypt/curve25519.h"
#include "wolfssl/wolfcrypt/ecc.h"
#include "wolfssl/wolfcrypt/ed25519.h"
#include "wolfssl/wolfcrypt/aes.h"
#include "wolfssl/wolfcrypt/sha256.h"
#include "wolfssl/wolfcrypt/sha512.h"
#ifdef WOLFSSL_SHA3
#include "wolfssl/wolfcrypt/sha3.h"
#endif
#include "wolfssl/wolfcrypt/cmac.h"
#include "wolfssl/wolfcrypt/wc_mldsa.h"
#if defined(WOLFSSL_HAVE_LMS)
#include "wolfssl/wolfcrypt/wc_lms.h"
#endif
#if defined(WOLFSSL_HAVE_XMSS)
#include "wolfssl/wolfcrypt/wc_xmss.h"
#endif
#include "wolfssl/wolfcrypt/wc_mlkem.h"
#include "wolfssl/wolfcrypt/hmac.h"
#include "wolfssl/wolfcrypt/kdf.h"
#include "wolfhsm/wh_error.h"
#include "wolfhsm/wh_crypto.h"
#include "wolfhsm/wh_utils.h"
#include "wolfhsm/wh_server_keystore.h"
#include "wolfhsm/wh_server_crypto.h"
#include "wolfhsm/wh_server.h"
#include "wolfhsm/wh_message_crypto.h"
/** Forward declarations */
#ifndef NO_RSA
#ifdef WOLFSSL_KEY_GEN
/* Process a Generate RsaKey request packet and produce a response packet */
static int _HandleRsaKeyGen(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
#endif /* WOLFSSL_KEY_GEN */
/* Process a Rng request packet and produce a response packet */
static int _HandleRng(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
/* Process a Rsa Function request packet and produce a response packet */
static int _HandleRsaFunction(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
/* Process a Rsa Get Size request packet and produce a response packet */
static int _HandleRsaGetSize(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
#endif /* !NO_RSA */
#ifdef HAVE_HKDF
/* Process an HKDF request packet and produce a response packet */
static int _HandleHkdf(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
#endif /* HAVE_HKDF */
#ifndef NO_AES
#ifdef WOLFSSL_AES_COUNTER
/* Process a AES CBC request packet and produce a response packet */
static int _HandleAesCtr(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
#endif /* WOLFSSL_AES_COUNTER */
#ifdef HAVE_AES_ECB
static int _HandleAesEcb(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
#endif /* HAVE_AES_ECB */
#ifdef HAVE_AES_CBC
static int _HandleAesCbc(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
#endif /* HAVE_AES_CBC */
#ifdef HAVE_AESGCM
static int _HandleAesGcm(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
#endif /* HAVE_AESGCM */
#endif /* !NO_AES */
#ifdef HAVE_ECC
static int _HandleEccKeyGen(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
#ifdef HAVE_ECC_DHE
static int _HandleEccSharedSecret(whServerContext* ctx, uint16_t magic,
int devId, const void* cryptoDataIn,
uint16_t inSize, void* cryptoDataOut,
uint16_t* outSize);
#endif /* HAVE_ECC_DHE */
#ifdef HAVE_ECC_SIGN
static int _HandleEccSign(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
#endif /* HAVE_ECC_SIGN */
#ifdef HAVE_ECC_VERIFY
static int _HandleEccVerify(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
#endif /* HAVE_ECC_VERIFY */
#endif /* HAVE_ECC */
#ifdef HAVE_CURVE25519
/* Process a Generate curve25519_key request packet and produce a response */
static int _HandleCurve25519KeyGen(whServerContext* ctx, uint16_t magic,
int devId, const void* cryptoDataIn,
uint16_t inSize, void* cryptoDataOut,
uint16_t* outSize);
/* Process a curve25519_key Function request packet and produce a response */
static int _HandleCurve25519SharedSecret(whServerContext* ctx, uint16_t magic,
int devId, const void* cryptoDataIn,
uint16_t inSize, void* cryptoDataOut,
uint16_t* outSize);
#endif /* HAVE_CURVE25519 */
#ifdef HAVE_ED25519
static int _HandleEd25519KeyGen(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
static int _HandleEd25519Sign(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
static int _HandleEd25519Verify(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
#ifdef WOLFHSM_CFG_DMA
static int _HandleEd25519SignDma(whServerContext* ctx, uint16_t magic,
int devId, const void* cryptoDataIn,
uint16_t inSize, void* cryptoDataOut,
uint16_t* outSize);
static int _HandleEd25519VerifyDma(whServerContext* ctx, uint16_t magic,
int devId, const void* cryptoDataIn,
uint16_t inSize, void* cryptoDataOut,
uint16_t* outSize);
#endif /* WOLFHSM_CFG_DMA */
#endif /* HAVE_ED25519 */
#ifdef WOLFSSL_HAVE_MLDSA
/* Process an ML-DSA KeyGen request packet and produce a response packet */
static int _HandleMlDsaKeyGen(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
/* Process an ML-DSA Sign request packet and produce a response packet */
static int _HandleMlDsaSign(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
/* Process an ML-DSA Verify request packet and produce a response packet */
static int _HandleMlDsaVerify(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
/* Process an ML-DSA Check PrivKey request packet and produce a response
* packet */
static int _HandleMlDsaCheckPrivKey(whServerContext* ctx, uint16_t magic,
int devId, const void* cryptoDataIn,
uint16_t inSize, void* cryptoDataOut,
uint16_t* outSize);
#endif /* WOLFSSL_HAVE_MLDSA */
#ifdef WOLFSSL_HAVE_MLKEM
static int _HandleMlKemKeyGen(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
static int _HandleMlKemEncaps(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
static int _HandleMlKemDecaps(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize);
#ifdef WOLFHSM_CFG_DMA
static int _HandleMlKemKeyGenDma(whServerContext* ctx, uint16_t magic,
int devId, const void* cryptoDataIn,
uint16_t inSize, void* cryptoDataOut,
uint16_t* outSize);
static int _HandleMlKemEncapsDma(whServerContext* ctx, uint16_t magic,
int devId, const void* cryptoDataIn,
uint16_t inSize, void* cryptoDataOut,
uint16_t* outSize);
static int _HandleMlKemDecapsDma(whServerContext* ctx, uint16_t magic,
int devId, const void* cryptoDataIn,
uint16_t inSize, void* cryptoDataOut,
uint16_t* outSize);
#endif /* WOLFHSM_CFG_DMA */
#endif /* WOLFSSL_HAVE_MLKEM */
/** Public server crypto functions */
#ifndef NO_RSA
int wh_Server_CacheImportRsaKey(whServerContext* ctx, RsaKey* key,
whKeyId keyId, whNvmFlags flags, uint32_t label_len, uint8_t* label)
{
int ret = 0;
uint8_t* cacheBuf;
whNvmMetadata* cacheMeta;
uint16_t max_size;
uint16_t der_size;
if ( (ctx == NULL) ||
(key == NULL) ||
(WH_KEYID_ISERASED(keyId)) ||
((label != NULL) && (label_len > sizeof(cacheMeta->label)))) {
return WH_ERROR_BADARGS;
}
/* wc_RsaKeyToDer doesn't have a length check option so we need to just pass
* the big key size if compiled */
/* TODO: Change this to use an estimate of the DER size based on key len */
if(WOLFHSM_CFG_SERVER_KEYCACHE_BIG_COUNT > 0) {
max_size = WOLFHSM_CFG_SERVER_KEYCACHE_BIG_BUFSIZE;
} else {
max_size = WOLFHSM_CFG_SERVER_KEYCACHE_BUFSIZE;
}
/* get a free slot */
ret = wh_Server_KeystoreGetCacheSlotChecked(ctx, keyId, max_size, &cacheBuf,
&cacheMeta);
if (ret == 0) {
ret = wh_Crypto_RsaSerializeKeyDer(key, max_size, cacheBuf, &der_size);
}
if (ret == 0) {
/* set meta */
cacheMeta->id = keyId;
cacheMeta->len = der_size;
/* clients can't set server-only flags (e.g. trusted KEK) */
cacheMeta->flags = flags & ~WH_NVM_FLAGS_SERVER_ONLY;
cacheMeta->access = WH_NVM_ACCESS_ANY;
if ( (label != NULL) &&
(label_len > 0) ) {
memcpy(cacheMeta->label, label, label_len);
}
}
return ret;
}
int wh_Server_CacheExportRsaKey(whServerContext* ctx, whKeyId keyId,
RsaKey* key)
{
uint8_t* cacheBuf;
whNvmMetadata* cacheMeta;
int ret = 0;
if ( (ctx == NULL) ||
(key == NULL) ||
(WH_KEYID_ISERASED(keyId))) {
return WH_ERROR_BADARGS;
}
/* Load key from NVM into a cache slot if necessary */
ret = wh_Server_KeystoreFreshenKey(ctx, keyId, &cacheBuf, &cacheMeta);
if (ret == 0) {
ret = wh_Crypto_RsaDeserializeKeyDer(cacheMeta->len, cacheBuf, key);
}
return ret;
}
#ifdef WOLFSSL_KEY_GEN
static int _HandleRsaKeyGen(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize)
{
int ret = 0;
RsaKey rsa[1] = {0};
whMessageCrypto_RsaKeyGenRequest req;
whMessageCrypto_RsaKeyGenResponse res;
if (inSize < sizeof(whMessageCrypto_RsaKeyGenRequest)) {
return WH_ERROR_BADARGS;
}
/* Translate request */
ret = wh_MessageCrypto_TranslateRsaKeyGenRequest(
magic, (const whMessageCrypto_RsaKeyGenRequest*)cryptoDataIn, &req);
if (ret != 0) {
return ret;
}
/* Extract parameters from translated request */
int key_size = req.size;
long e = req.e;
/* Force incoming key_id to have current user/type */
whKeyId key_id = wh_KeyId_TranslateFromClient(
WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId);
whNvmFlags flags = req.flags;
uint8_t* label = req.label;
uint32_t label_size = WH_NVM_LABEL_LEN;
/* Get pointer to where key data would be stored (after response struct) */
uint8_t* out =
(uint8_t*)cryptoDataOut + sizeof(whMessageCrypto_RsaKeyGenResponse);
uint16_t max_size = (uint16_t)(WOLFHSM_CFG_COMM_DATA_LEN -
((uint8_t*)out - (uint8_t*)cryptoDataOut));
uint16_t der_size = 0;
/* init the rsa key */
ret = wc_InitRsaKey_ex(rsa, NULL, devId);
if (ret == 0) {
/* make the rsa key with the given params */
ret = wc_MakeRsaKey(rsa, key_size, e, ctx->crypto->rng);
WH_DEBUG_SERVER_VERBOSE("MakeRsaKey: size:%d, e:%ld, ret:%d\n", key_size, e, ret);
if (ret == 0) {
/* Check incoming flags */
if (flags & WH_NVM_FLAGS_EPHEMERAL) {
/* Must serialize the key into the response packet */
ret =
wh_Crypto_RsaSerializeKeyDer(rsa, max_size, out, &der_size);
if (ret == 0) {
res.keyId = 0;
res.len = der_size;
}
}
else {
/* Must import the key into the cache and return keyid */
if (WH_KEYID_ISERASED(key_id)) {
/* Generate a new id */
ret = wh_Server_KeystoreGetUniqueId(ctx, &key_id);
WH_DEBUG_SERVER_VERBOSE("RsaKeyGen UniqueId: keyId:%u, ret:%d\n", key_id, ret);
if (ret != WH_ERROR_OK) {
/* Early return on unique ID generation failure */
wc_FreeRsaKey(rsa);
return ret;
}
}
if (ret == 0) {
ret = wh_Server_CacheImportRsaKey(ctx, rsa, key_id, flags,
label_size, label);
}
WH_DEBUG_SERVER_VERBOSE("RsaKeyGen CacheKeyRsa: keyId:%u, ret:%d\n", key_id, ret);
if (ret == 0) {
res.keyId = wh_KeyId_TranslateToClient(key_id);
res.len = 0;
}
}
}
wc_FreeRsaKey(rsa);
}
if (ret == 0) {
wh_MessageCrypto_TranslateRsaKeyGenResponse(
magic, &res, (whMessageCrypto_RsaKeyGenResponse*)cryptoDataOut);
*outSize = sizeof(whMessageCrypto_RsaKeyGenResponse) + res.len;
}
return ret;
}
#endif /* WOLFSSL_KEY_GEN */
static int _HandleRsaFunction(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize)
{
int ret;
RsaKey rsa[1];
whMessageCrypto_RsaRequest req;
/* Validate minimum size */
if (inSize < sizeof(whMessageCrypto_RsaRequest)) {
return WH_ERROR_BADARGS;
}
/* Translate request */
ret = wh_MessageCrypto_TranslateRsaRequest(
magic, (const whMessageCrypto_RsaRequest*)cryptoDataIn, &req);
if (ret != 0) {
return ret;
}
/* Extract parameters from translated request */
int op_type = (int)(req.opType);
uint32_t options = req.options;
int evict = !!(options & WH_MESSAGE_CRYPTO_RSA_OPTIONS_EVICT);
whKeyId key_id = wh_KeyId_TranslateFromClient(
WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId);
word32 in_len = (word32)(req.inLen);
word32 out_len = (word32)(req.outLen);
/* Ensure input data fits within request payload */
uint32_t available = inSize - sizeof(whMessageCrypto_RsaRequest);
if (in_len > available) {
return WH_ERROR_BADARGS;
}
/* in and out are after the fixed size fields */
const byte* in = (const byte*)cryptoDataIn + sizeof(whMessageCrypto_RsaRequest);
byte* out = (byte*)cryptoDataOut + sizeof(whMessageCrypto_RsaResponse);
WH_DEBUG_SERVER_VERBOSE("HandleRsaFunction opType:%d inLen:%u keyId:%u outLen:%u\n",
op_type, in_len, key_id, out_len);
switch (op_type)
{
case RSA_PUBLIC_ENCRYPT:
case RSA_PUBLIC_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
case RSA_PRIVATE_DECRYPT:
/* Valid op_types */
break;
default:
/* Invalid opType */
WH_DEBUG_SERVER_VERBOSE("Unknown opType:%d\n", op_type);
return BAD_FUNC_ARG;
}
/* Validate key usage policy based on RSA operation type */
if (!WH_KEYID_ISERASED(key_id)) {
whNvmFlags requiredUsage = WH_NVM_FLAGS_NONE;
switch (op_type) {
case RSA_PUBLIC_ENCRYPT:
case RSA_PRIVATE_ENCRYPT:
requiredUsage = WH_NVM_FLAGS_USAGE_ENCRYPT;
break;
case RSA_PUBLIC_DECRYPT:
case RSA_PRIVATE_DECRYPT:
requiredUsage = WH_NVM_FLAGS_USAGE_DECRYPT;
break;
}
ret = wh_Server_KeystoreFindEnforceKeyUsage(ctx, key_id, requiredUsage);
if (ret != WH_ERROR_OK) {
/* Currently wolfCrypt doesn't have a way for crypto callbacks to
distinguish if a low level RSA operation (like encrypt/decrypt) is
being performed as part of a higher level operation like
sign/verify. Until that information is propagated to the
callback, the usage flags are treated as equivalent. */
if (ret == WH_ERROR_USAGE) {
if (op_type == RSA_PUBLIC_DECRYPT) {
/* Decrypt usage flag wasn't set so this might be a verify
* operation. Attempt to enforce against the verify flag */
ret = wh_Server_KeystoreFindEnforceKeyUsage(
ctx, key_id, WH_NVM_FLAGS_USAGE_VERIFY);
}
else if (op_type == RSA_PRIVATE_ENCRYPT) {
/* Encrypt usage flag wasn't set so this might be a sign
* operation. Attempt to enforce against the sign flag */
ret = wh_Server_KeystoreFindEnforceKeyUsage(
ctx, key_id, WH_NVM_FLAGS_USAGE_SIGN);
}
}
if (ret != WH_ERROR_OK) {
goto cleanup;
}
}
}
/* init rsa key */
ret = wc_InitRsaKey_ex(rsa, NULL, devId);
/* load the key from the keystore */
if (ret == 0) {
ret = wh_Server_CacheExportRsaKey(ctx, key_id, rsa);
WH_DEBUG_SERVER_VERBOSE("CacheExportRsaKey keyid:%u, ret:%d\n", key_id, ret);
if (ret == 0) {
/* do the rsa operation */
ret = wc_RsaFunction(in, in_len, out, &out_len,
op_type, rsa, ctx->crypto->rng);
WH_DEBUG_SERVER_VERBOSE("RsaFunction in:%p %u, out:%p, opType:%d, outLen:%d, ret:%d\n",
in, in_len, out, op_type, out_len, ret);
}
/* free the key */
wc_FreeRsaKey(rsa);
}
cleanup:
if (evict != 0) {
/* User requested to evict from cache, even if the call failed */
(void)wh_Server_KeystoreEvictKey(ctx, key_id);
}
if (ret == 0) {
whMessageCrypto_RsaResponse res;
/*set outLen and outgoing message size */
res.outLen = out_len;
wh_MessageCrypto_TranslateRsaResponse(
magic, &res, (whMessageCrypto_RsaResponse*)cryptoDataOut);
*outSize = sizeof(whMessageCrypto_RsaResponse) + out_len;
}
return ret;
}
static int _HandleRsaGetSize(whServerContext* ctx, uint16_t magic, int devId,
const void* cryptoDataIn, uint16_t inSize,
void* cryptoDataOut, uint16_t* outSize)
{
int ret;
RsaKey rsa[1];
whMessageCrypto_RsaGetSizeRequest req;
whMessageCrypto_RsaGetSizeResponse res;
int key_size = 0;
if (inSize < sizeof(whMessageCrypto_RsaGetSizeRequest)) {
return WH_ERROR_BADARGS;
}
/* Translate request */
ret = wh_MessageCrypto_TranslateRsaGetSizeRequest(
magic, (const whMessageCrypto_RsaGetSizeRequest*)cryptoDataIn, &req);
if (ret != 0) {
return ret;
}
/* Extract parameters from translated request */
whKeyId key_id = wh_KeyId_TranslateFromClient(
WH_KEYTYPE_CRYPTO, ctx->comm->client_id, req.keyId);
uint32_t options = req.options;
int evict = !!(options & WH_MESSAGE_CRYPTO_RSA_GET_SIZE_OPTIONS_EVICT);
/* init rsa key */
ret = wc_InitRsaKey_ex(rsa, NULL, devId);
/* load the key from the keystore */
if (ret == 0) {
ret = wh_Server_CacheExportRsaKey(ctx, key_id, rsa);
/* get the size */
if (ret == 0) {
key_size = wc_RsaEncryptSize(rsa);
if (key_size < 0) {
ret = key_size;
}
}
wc_FreeRsaKey(rsa);
}
if (evict != 0) {
WH_DEBUG_SERVER_VERBOSE("evicting temp key:%x options:%u evict:%u\n",
key_id, options, evict);
/* User requested to evict from cache, even if the call failed */
(void)wh_Server_KeystoreEvictKey(ctx, key_id);
}
if (ret == 0) {
res.keySize = key_size;
wh_MessageCrypto_TranslateRsaGetSizeResponse(
magic, &res, (whMessageCrypto_RsaGetSizeResponse*)cryptoDataOut);
*outSize = sizeof(whMessageCrypto_RsaGetSizeResponse);
}
WH_DEBUG_SERVER_VERBOSE("keyId:%d, key_size:%d, ret:%d\n", key_id,
key_size, ret);
return ret;
}
#endif /* !NO_RSA */
#ifdef HAVE_ECC
int wh_Server_EccKeyCacheImport(whServerContext* ctx, ecc_key* key,
whKeyId keyId, whNvmFlags flags, uint16_t label_len, uint8_t* label)
{
int ret = WH_ERROR_OK;
uint8_t* cacheBuf;
whNvmMetadata* cacheMeta;
/* Maximum size of an ecc key der file */
uint16_t max_size = ECC_BUFSIZE;
uint16_t der_size;
if ( (ctx == NULL) ||
(key == NULL) ||
WH_KEYID_ISERASED(keyId) ||
((label != NULL) && (label_len > sizeof(cacheMeta->label))) ) {
return WH_ERROR_BADARGS;
}
/* get a free slot */
ret = wh_Server_KeystoreGetCacheSlotChecked(ctx, keyId, max_size, &cacheBuf,
&cacheMeta);
if (ret == WH_ERROR_OK) {
ret = wh_Crypto_EccSerializeKeyDer(key, max_size, cacheBuf, &der_size);
}
if (ret == WH_ERROR_OK) {
/* set meta */
cacheMeta->id = keyId;
cacheMeta->len = der_size;
/* clients can't set server-only flags (e.g. trusted KEK) */
cacheMeta->flags = flags & ~WH_NVM_FLAGS_SERVER_ONLY;
cacheMeta->access = WH_NVM_ACCESS_ANY;
if ( (label != NULL) &&
(label_len > 0) ) {
memcpy(cacheMeta->label, label, label_len);
}
}
return ret;
}
int wh_Server_EccKeyCacheExport(whServerContext* ctx, whKeyId keyId,
ecc_key* key)
{
uint8_t* cacheBuf;
whNvmMetadata* cacheMeta;
int ret = WH_ERROR_OK;
if ( (ctx == NULL) ||
(key == NULL) ||
WH_KEYID_ISERASED(keyId) ) {
return WH_ERROR_BADARGS;
}
/* Load key from NVM into a cache slot if necessary */
ret = wh_Server_KeystoreFreshenKey(ctx, keyId, &cacheBuf, &cacheMeta);
if (ret == WH_ERROR_OK) {
ret = wh_Crypto_EccDeserializeKeyDer(cacheBuf, cacheMeta->len, key);
}
return ret;
}
#endif /* HAVE_ECC */
#ifdef HAVE_ED25519
int wh_Server_CacheImportEd25519Key(whServerContext* ctx, ed25519_key* key,
whKeyId keyId, whNvmFlags flags,
uint16_t label_len, uint8_t* label)
{
int ret = WH_ERROR_OK;
uint8_t* cacheBuf = NULL;
whNvmMetadata* cacheMeta;
/* Ed25519 DER (private key) is small; 128 bytes is ample headroom */
uint16_t max_size = 128;
uint16_t der_size = 0;
if ((ctx == NULL) || (key == NULL) || WH_KEYID_ISERASED(keyId) ||
((label != NULL) && (label_len > sizeof(cacheMeta->label)))) {
return WH_ERROR_BADARGS;
}
ret = wh_Server_KeystoreGetCacheSlotChecked(ctx, keyId, max_size, &cacheBuf,
&cacheMeta);
if (ret == WH_ERROR_OK) {
ret = wh_Crypto_Ed25519SerializeKeyDer(key, max_size, cacheBuf,
&der_size);
}
if (ret == WH_ERROR_OK) {
cacheMeta->id = keyId;
cacheMeta->len = der_size;
/* clients can't set server-only flags (e.g. trusted KEK) */
cacheMeta->flags = flags & ~WH_NVM_FLAGS_SERVER_ONLY;
cacheMeta->access = WH_NVM_ACCESS_ANY;
if ((label != NULL) && (label_len > 0)) {
memcpy(cacheMeta->label, label, label_len);
}
}
return ret;
}
int wh_Server_CacheExportEd25519Key(whServerContext* ctx, whKeyId keyId,
ed25519_key* key)
{
uint8_t* cacheBuf = NULL;
whNvmMetadata* cacheMeta;
int ret = WH_ERROR_OK;
if ((ctx == NULL) || (key == NULL) || WH_KEYID_ISERASED(keyId)) {
return WH_ERROR_BADARGS;
}
ret = wh_Server_KeystoreFreshenKey(ctx, keyId, &cacheBuf, &cacheMeta);
if (ret == WH_ERROR_OK) {
ret = wh_Crypto_Ed25519DeserializeKeyDer(cacheBuf, cacheMeta->len, key);
}
return ret;
}
#endif /* HAVE_ED25519 */
#ifdef HAVE_CURVE25519
int wh_Server_CacheImportCurve25519Key(whServerContext* server,
curve25519_key* key, whKeyId keyId,
whNvmFlags flags, uint16_t label_len,
uint8_t* label)
{
uint8_t* cacheBuf;
whNvmMetadata* cacheMeta;
int ret;
uint8_t der_buf[CURVE25519_MAX_KEY_TO_DER_SZ];
uint16_t keySz = sizeof(der_buf);
if ((server == NULL) || (key == NULL) || (WH_KEYID_ISERASED(keyId)) ||
((label != NULL) && (label_len > sizeof(cacheMeta->label)))) {
return WH_ERROR_BADARGS;
}
/* Serialize the key into the temporary buffer so we can get the size */
ret = wh_Crypto_Curve25519SerializeKey(key, der_buf, &keySz);
/* if successful, find a free cache slot and copy in the key data */
if (ret == 0) {
ret = wh_Server_KeystoreGetCacheSlotChecked(server, keyId, keySz,
&cacheBuf, &cacheMeta);
if (ret == 0) {
memcpy(cacheBuf, der_buf, keySz);
/* Update metadata to cache the key */
cacheMeta->id = keyId;
cacheMeta->len = keySz;
/* clients can't set server-only flags (e.g. trusted KEK) */
cacheMeta->flags = flags & ~WH_NVM_FLAGS_SERVER_ONLY;
cacheMeta->access = WH_NVM_ACCESS_ANY;
if ((label != NULL) && (label_len > 0)) {
memcpy(cacheMeta->label, label, label_len);
}
}
}
return ret;
}
int wh_Server_CacheExportCurve25519Key(whServerContext* server, whKeyId keyId,
curve25519_key* key)
{
uint8_t* cacheBuf;
whNvmMetadata* cacheMeta;
int ret = 0;
if ( (server == NULL) ||
(key == NULL) ||
(WH_KEYID_ISERASED(keyId))) {
return WH_ERROR_BADARGS;
}
/* Load key from NVM into a cache slot if necessary */
ret = wh_Server_KeystoreFreshenKey(server, keyId, &cacheBuf, &cacheMeta);
if (ret == 0) {
ret = wh_Crypto_Curve25519DeserializeKey(cacheBuf, cacheMeta->len, key);
WH_DEBUG_SERVER_VERBOSE("Export25519Key id:%u ret:%d\n", keyId, ret);
WH_DEBUG_SERVER_VERBOSE("export key:\n");
WH_DEBUG_VERBOSE_HEXDUMP("[server] export key:", cacheBuf, cacheMeta->len);
}
return ret;
}
#endif /* HAVE_CURVE25519 */
#ifdef WOLFSSL_HAVE_MLDSA
/* The big key cache buffer must be able to hold a full ML-DSA keypair DER,
* otherwise wh_Server_MlDsaKeyCacheImport() can never succeed. */
WH_UTILS_STATIC_ASSERT(
WOLFHSM_CFG_SERVER_KEYCACHE_BIG_BUFSIZE >= MLDSA_MAX_BOTH_KEY_DER_SIZE,
"WOLFHSM_CFG_SERVER_KEYCACHE_BIG_BUFSIZE too small for ML-DSA keypair DER");
int wh_Server_MlDsaKeyCacheImport(whServerContext* ctx, wc_MlDsaKey* key,
whKeyId keyId, whNvmFlags flags,
uint16_t label_len, uint8_t* label)
{
int ret = WH_ERROR_OK;
uint8_t* cacheBuf;
whNvmMetadata* cacheMeta;
uint16_t der_size;
if ((ctx == NULL) || (key == NULL) || (WH_KEYID_ISERASED(keyId)) ||
((label != NULL) && (label_len > sizeof(cacheMeta->label)))) {
return WH_ERROR_BADARGS;
}
/* The key may hold a full keypair, in which case
* wh_Crypto_MlDsaSerializeKeyDer() encodes both the public and private key
* (wc_MlDsaKey_KeyToDer()), so size for both keys, not just the private key. */
ret = wh_Server_KeystoreGetCacheSlotChecked(
ctx, keyId, MLDSA_MAX_BOTH_KEY_DER_SIZE, &cacheBuf, &cacheMeta);
if (ret == WH_ERROR_OK) {
ret = wh_Crypto_MlDsaSerializeKeyDer(key, MLDSA_MAX_BOTH_KEY_DER_SIZE,
cacheBuf, &der_size);
WH_DEBUG_SERVER_VERBOSE("keyId:%u, ret:%d\n", keyId, ret);
}
if (ret == WH_ERROR_OK) {
cacheMeta->id = keyId;
cacheMeta->len = der_size;
/* clients can't set server-only flags (e.g. trusted KEK) */
cacheMeta->flags = flags & ~WH_NVM_FLAGS_SERVER_ONLY;
cacheMeta->access = WH_NVM_ACCESS_ANY;
if ((label != NULL) && (label_len > 0)) {
memcpy(cacheMeta->label, label, label_len);
}
}
return ret;
}
int wh_Server_MlDsaKeyCacheExport(whServerContext* ctx, whKeyId keyId,
wc_MlDsaKey* key)
{
uint8_t* cacheBuf;
whNvmMetadata* cacheMeta;
int ret = WH_ERROR_OK;
if ((ctx == NULL) || (key == NULL) || (WH_KEYID_ISERASED(keyId))) {
return WH_ERROR_BADARGS;
}
ret = wh_Server_KeystoreFreshenKey(ctx, keyId, &cacheBuf, &cacheMeta);
if (ret == WH_ERROR_OK) {
ret = wh_Crypto_MlDsaDeserializeKeyDer(cacheBuf, cacheMeta->len, key);
WH_DEBUG_SERVER_VERBOSE("keyId:%u, ret:%d\n", keyId, ret);
}
return ret;
}
#endif /* WOLFSSL_HAVE_MLDSA */
#ifdef WOLFSSL_HAVE_MLKEM
int wh_Server_MlKemKeyCacheImport(whServerContext* ctx, MlKemKey* key,
whKeyId keyId, whNvmFlags flags,
uint16_t label_len, uint8_t* label)
{
int ret = WH_ERROR_OK;
uint8_t* cacheBuf;
whNvmMetadata* cacheMeta;
uint16_t keySize = WC_ML_KEM_MAX_PRIVATE_KEY_SIZE;
if ((ctx == NULL) || (key == NULL) || (WH_KEYID_ISERASED(keyId)) ||
((label != NULL) && (label_len > sizeof(cacheMeta->label)))) {
return WH_ERROR_BADARGS;
}
ret = wh_Server_KeystoreGetCacheSlotChecked(ctx, keyId, keySize, &cacheBuf,
&cacheMeta);
if (ret == WH_ERROR_OK) {
ret = wh_Crypto_MlKemSerializeKey(key, keySize, cacheBuf, &keySize);
}
if (ret == WH_ERROR_OK) {
cacheMeta->id = keyId;
cacheMeta->len = keySize;
/* clients can't set server-only flags (e.g. trusted KEK) */
cacheMeta->flags = flags & ~WH_NVM_FLAGS_SERVER_ONLY;
cacheMeta->access = WH_NVM_ACCESS_ANY;
if ((label != NULL) && (label_len > 0)) {
memcpy(cacheMeta->label, label, label_len);
}
}
return ret;
}
int wh_Server_MlKemKeyCacheExport(whServerContext* ctx, whKeyId keyId,
MlKemKey* key)
{
uint8_t* cacheBuf;
whNvmMetadata* cacheMeta;
int ret = WH_ERROR_OK;
if ((ctx == NULL) || (key == NULL) || (WH_KEYID_ISERASED(keyId))) {
return WH_ERROR_BADARGS;
}
ret = wh_Server_KeystoreFreshenKey(ctx, keyId, &cacheBuf, &cacheMeta);
if (ret == WH_ERROR_OK) {
ret = wh_Crypto_MlKemDeserializeKey(cacheBuf, cacheMeta->len, key);
WH_DEBUG_SERVER_VERBOSE("keyId:%u, ret:%d\n", keyId, ret);
}
return ret;
}
#endif /* WOLFSSL_HAVE_MLKEM */
/* The sign path (and its slot callbacks) is unavailable in verify-only builds;
* gate on at least one non-verify-only stateful algorithm being enabled. */
#if ((defined(WOLFSSL_HAVE_LMS) && !defined(WOLFSSL_LMS_VERIFY_ONLY)) || \
(defined(WOLFSSL_HAVE_XMSS) && !defined(WOLFSSL_XMSS_VERIFY_ONLY))) && \
defined(WOLFHSM_CFG_DMA)
/* Stateful-key persistence context.
*
* wolfCrypt's wc_LmsKey_Sign and wc_XmssKey_Sign require write/read callbacks
* for the software path. We wire write_private_key directly to atomic NVM
* commit (wh_Nvm_AddObjectWithReclaim): wolfCrypt's contract is to advance
* the index, call write_cb, and only emit the signature if write_cb returned
* success. That gives us pre-commit-then-emit ordering for free.
*
* This context keeps a pointer into the server's cache slot blob (laid out by
* wh_Crypto_{Lms,Xmss}SerializeKey). Each write_cb invocation overwrites the
* priv region of the slot in place and re-commits the entire slot. */
typedef struct whServerStatefulSigCtx {
whServerContext* server;
whKeyId keyId;
whNvmMetadata* meta; /* points at the cache slot's metadata */
uint8_t* slotBuf; /* points at the cache slot's data buffer */
uint16_t hdrSz; /* fixed header size (offset to params) */
uint16_t pubLen; /* priv begins at hdrSz + paramLen + pubLen */
uint16_t paramLen;
uint16_t slotCapacity;
} whServerStatefulSigCtx;
/* Compute the priv-region offset inside the slot blob from the context. */
static uint16_t _StatefulSigPrivOffset(const whServerStatefulSigCtx* b)
{
return (uint16_t)(b->hdrSz + b->paramLen + b->pubLen);
}
/* Update the slot blob's privLen header field in place. */
static void _StatefulSigWritePrivLen(uint8_t* slotBuf, uint16_t privLen)
{
uint8_t* p = slotBuf + offsetof(whCryptoStatefulSigHeader, privLen);
memcpy(p, &privLen, sizeof(privLen));
}
#if defined(WOLFSSL_HAVE_LMS) && defined(WOLFHSM_CFG_DMA) && \
!defined(WOLFSSL_LMS_VERIFY_ONLY)
static int _LmsSlotWriteCb(const byte* priv, word32 privSz, void* context)
{
whServerStatefulSigCtx* b = (whServerStatefulSigCtx*)context;
uint16_t privOff;
uint32_t newLen;
int rc;
if ((b == NULL) || (priv == NULL) || (b->slotBuf == NULL) ||
(b->meta == NULL)) {
return WC_LMS_RC_BAD_ARG;
}
privOff = _StatefulSigPrivOffset(b);
newLen = (uint32_t)privOff + privSz;
if (newLen > b->slotCapacity) {
return WC_LMS_RC_WRITE_FAIL;
}
memcpy(b->slotBuf + privOff, priv, privSz);
_StatefulSigWritePrivLen(b->slotBuf, (uint16_t)privSz);
b->meta->len = (whNvmSize)newLen;
/* Atomic dual-partition commit. Wolfcrypt aborts the sign if this
* returns anything other than _SAVED_TO_NV_MEMORY, so the signature
* never escapes for an un-persisted index. */
rc = wh_Nvm_AddObjectWithReclaim(b->server->nvm, b->meta, b->meta->len,
b->slotBuf);
return (rc == WH_ERROR_OK) ? WC_LMS_RC_SAVED_TO_NV_MEMORY
: WC_LMS_RC_WRITE_FAIL;
}
static int _LmsSlotReadCb(byte* priv, word32 privSz, void* context)
{
whServerStatefulSigCtx* b = (whServerStatefulSigCtx*)context;
uint16_t privOff;
if ((b == NULL) || (priv == NULL) || (b->slotBuf == NULL)) {
return WC_LMS_RC_BAD_ARG;
}
privOff = _StatefulSigPrivOffset(b);
if ((uint32_t)privOff + privSz > b->meta->len) {
return WC_LMS_RC_READ_FAIL;
}
memcpy(priv, b->slotBuf + privOff, privSz);
return WC_LMS_RC_READ_TO_MEMORY;
}
#endif /* WOLFSSL_HAVE_LMS && WOLFHSM_CFG_DMA && !WOLFSSL_LMS_VERIFY_ONLY */
#if defined(WOLFSSL_HAVE_XMSS) && defined(WOLFHSM_CFG_DMA) && \
!defined(WOLFSSL_XMSS_VERIFY_ONLY)
static enum wc_XmssRc _XmssSlotWriteCb(const byte* priv, word32 privSz,
void* context)
{
whServerStatefulSigCtx* b = (whServerStatefulSigCtx*)context;
uint16_t privOff;
uint32_t newLen;
int rc;
if ((b == NULL) || (priv == NULL) || (b->slotBuf == NULL) ||
(b->meta == NULL)) {