-
Notifications
You must be signed in to change notification settings - Fork 970
Expand file tree
/
Copy pathpk.c
More file actions
7345 lines (6494 loc) · 213 KB
/
pk.c
File metadata and controls
7345 lines (6494 loc) · 213 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
/* pk.c
*
* Copyright (C) 2006-2026 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL 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.
*
* wolfSSL 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 this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
*/
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
#include <wolfssl/internal.h>
#ifndef WC_NO_RNG
#include <wolfssl/wolfcrypt/random.h>
#endif
#if !defined(WOLFSSL_PK_INCLUDED)
#ifndef WOLFSSL_IGNORE_FILE_WARN
#warning pk.c does not need to be compiled separately from ssl.c
#endif
#else
#ifndef NO_RSA
#include <wolfssl/wolfcrypt/rsa.h>
#endif
/*******************************************************************************
* COMMON FUNCTIONS
******************************************************************************/
/* Calculate the number of bytes require to represent a length value in ASN.
*
* @param [in] l Length value to use.
* @return Number of bytes required to represent length value.
*/
#define ASN_LEN_SIZE(l) \
(((l) < 128) ? 1 : (((l) < 256) ? 2 : 3))
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
#ifndef NO_ASN
#if (!defined(NO_FILESYSTEM) && (defined(OPENSSL_EXTRA) || \
defined(OPENSSL_ALL))) || (!defined(NO_BIO) && defined(OPENSSL_EXTRA))
/* Convert the PEM encoding in the buffer to DER.
*
* @param [in] pem Buffer containing PEM encoded data.
* @param [in] pemSz Size of data in buffer in bytes.
* @param [in] cb Password callback when PEM encrypted.
* @param [in] pass NUL terminated string for passphrase when PEM
* encrypted.
* @param [in] keyType Type of key to match against PEM header/footer.
* @param [out] keyFormat Format of key.
* @param [out] der Buffer holding DER encoding.
* @return Negative on failure.
* @return Number of bytes consumed on success.
*/
static int pem_mem_to_der(const char* pem, int pemSz, wc_pem_password_cb* cb,
void* pass, int keyType, int* keyFormat, DerBuffer** der)
{
WC_DECLARE_VAR(info, EncryptedInfo, 1, 0);
wc_pem_password_cb* localCb = NULL;
int ret = 0;
if (cb != NULL) {
localCb = cb;
}
else if (pass != NULL) {
localCb = wolfSSL_PEM_def_callback;
}
#ifdef WOLFSSL_SMALL_STACK
info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
DYNAMIC_TYPE_ENCRYPTEDINFO);
if (info == NULL) {
WOLFSSL_ERROR_MSG("Error getting memory for EncryptedInfo structure");
ret = MEMORY_E;
}
#endif /* WOLFSSL_SMALL_STACK */
if (ret == 0) {
XMEMSET(info, 0, sizeof(EncryptedInfo));
info->passwd_cb = localCb;
info->passwd_userdata = pass;
/* Do not strip PKCS8 header */
ret = PemToDer((const unsigned char *)pem, pemSz, keyType, der, NULL,
info, keyFormat);
if (ret < 0) {
WOLFSSL_ERROR_MSG("Bad PEM To DER");
}
}
if (ret >= 0) {
ret = (int)info->consumed;
}
WC_FREE_VAR_EX(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
return ret;
}
#endif
#if defined(OPENSSL_EXTRA) && (!defined(NO_RSA) || !defined(WOLFCRYPT_ONLY))
#ifndef NO_BIO
/* Read PEM data from a BIO and decode to DER in a new buffer.
*
* @param [in, out] bio BIO object to read with.
* @param [in] cb Password callback when PEM encrypted.
* @param [in] pass NUL terminated string for passphrase when PEM
* encrypted.
* @param [in] keyType Type of key to match against PEM header/footer.
* @param [out] keyFormat Format of key.
* @param [out] der Buffer holding DER encoding.
* @return Negative on failure.
* @return Number of bytes consumed on success.
*/
static int pem_read_bio_key(WOLFSSL_BIO* bio, wc_pem_password_cb* cb,
void* pass, int keyType, int* keyFormat, DerBuffer** der)
{
int ret;
char* mem = NULL;
int memSz;
int alloced = 0;
ret = wolfssl_read_bio(bio, &mem, &memSz, &alloced);
if (ret == 0) {
ret = pem_mem_to_der(mem, memSz, cb, pass, keyType, keyFormat, der);
/* Write left over data back to BIO if not a file BIO */
if ((ret > 0) && ((memSz - ret) > 0) &&
(bio->type != WOLFSSL_BIO_FILE)) {
int res;
if (!alloced) {
/* If wolfssl_read_bio() points mem at the buffer internal to
* bio, we need to dup it before calling wolfSSL_BIO_write(),
* because the latter may reallocate the bio, invalidating the
* mem pointer before reading from it.
*/
char *mem_dup = (char *)XMALLOC((size_t)(memSz - ret),
NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (mem_dup != NULL) {
XMEMCPY(mem_dup, mem + ret, (size_t)(memSz - ret));
res = wolfSSL_BIO_write(bio, mem_dup, memSz - ret);
mem = mem_dup;
alloced = 1;
}
else
res = MEMORY_E;
}
else
res = wolfSSL_BIO_write(bio, mem + ret, memSz - ret);
if (res != memSz - ret) {
WOLFSSL_ERROR_MSG("Unable to write back excess data");
if (res < 0) {
ret = res;
}
else {
ret = MEMORY_E;
}
}
}
if (alloced) {
XFREE(mem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
}
}
return ret;
}
#endif /* !NO_BIO */
#if !defined(NO_FILESYSTEM)
/* Read PEM data from a file and decode to DER in a new buffer.
*
* @param [in] fp File pointer to read with.
* @param [in] cb Password callback when PEM encrypted.
* @param [in] pass NUL terminated string for passphrase when PEM
* encrypted.
* @param [in] keyType Type of key to match against PEM header/footer.
* @param [out] keyFormat Format of key.
* @param [out] der Buffer holding DER encoding.
* @return Negative on failure.
* @return Number of bytes consumed on success.
*/
static int pem_read_file_key(XFILE fp, wc_pem_password_cb* cb, void* pass,
int keyType, int* keyFormat, DerBuffer** der)
{
int ret;
char* mem = NULL;
int memSz;
ret = wolfssl_read_file(fp, &mem, &memSz);
if (ret == 0) {
ret = pem_mem_to_der(mem, memSz, cb, pass, keyType, keyFormat, der);
XFREE(mem, NULL, DYNAMIC_TYPE_OPENSSL);
}
return ret;
}
#endif /* !NO_FILESYSTEM */
#endif
#if defined(OPENSSL_EXTRA) && ((!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) \
|| !defined(WOLFCRYPT_ONLY))
/* Convert DER data to PEM in an allocated buffer.
*
* @param [in] der Buffer containing DER data.
* @param [in] derSz Size of DER data in bytes.
* @param [in] type Type of key being encoded.
* @param [in] heap Heap hint for dynamic memory allocation.
* @param [out] out Allocated buffer containing PEM.
* @param [out] outSz Size of PEM encoding.
* @return 1 on success.
* @return 0 on error.
*/
static int der_to_pem_alloc(const unsigned char* der, int derSz, int type,
void* heap, byte** out, int* outSz)
{
int ret = 1;
int pemSz;
byte* pem = NULL;
(void)heap;
/* Convert DER to PEM - to get size. */
pemSz = wc_DerToPem(der, (word32)derSz, NULL, 0, type);
if (pemSz < 0) {
ret = 0;
}
if (ret == 1) {
/* Allocate memory for PEM to be encoded into. */
pem = (byte*)XMALLOC((size_t)pemSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
if (pem == NULL) {
ret = 0;
}
}
/* Convert DER to PEM. */
if ((ret == 1) && (wc_DerToPem(der, (word32)derSz, pem, (word32)pemSz,
type) < 0)) {
ret = 0;
XFREE(pem, heap, DYNAMIC_TYPE_TMP_BUFFER);
pem = NULL;
}
*out = pem;
*outSz = pemSz;
return ret;
}
#ifndef NO_BIO
/* Write the DER data as PEM into BIO.
*
* @param [in] der Buffer containing DER data.
* @param [in] derSz Size of DER data in bytes.
* @param [in, out] bio BIO object to write with.
* @param [in] type Type of key being encoded.
* @return 1 on success.
* @return 0 on error.
*/
static int der_write_to_bio_as_pem(const unsigned char* der, int derSz,
WOLFSSL_BIO* bio, int type)
{
int ret;
int pemSz;
byte* pem = NULL;
ret = der_to_pem_alloc(der, derSz, type, bio->heap, &pem, &pemSz);
if (ret == 1) {
int len = wolfSSL_BIO_write(bio, pem, pemSz);
if (len != pemSz) {
WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO");
ret = 0;
}
}
XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
return ret;
}
#endif
#endif
#if defined(OPENSSL_EXTRA) && \
((!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) || \
(!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)) || \
(defined(HAVE_ECC) && defined(WOLFSSL_KEY_GEN)))
#if !defined(NO_FILESYSTEM)
/* Write the DER data as PEM into file pointer.
*
* @param [in] der Buffer containing DER data.
* @param [in] derSz Size of DER data in bytes.
* @param [in] fp File pointer to write with.
* @param [in] type Type of key being encoded.
* @param [in] heap Heap hint for dynamic memory allocation.
* @return 1 on success.
* @return 0 on error.
*/
static int der_write_to_file_as_pem(const unsigned char* der, int derSz,
XFILE fp, int type, void* heap)
{
int ret;
int pemSz;
byte* pem = NULL;
ret = der_to_pem_alloc(der, derSz, type, heap, &pem, &pemSz);
if (ret == 1) {
int len = (int)XFWRITE(pem, 1, (size_t)pemSz, fp);
if (len != pemSz) {
WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO");
ret = 0;
}
}
XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
return ret;
}
#endif
#endif
#if defined(OPENSSL_EXTRA) && defined(WOLFSSL_KEY_GEN) && \
defined(WOLFSSL_PEM_TO_DER)
/* Encrypt private key into PEM format.
*
* DER is encrypted in place.
*
* @param [in] der DER encoding of private key.
* @param [in] derSz Size of DER in bytes.
* @param [in] cipher EVP cipher.
* @param [in] passwd Password to use with encryption.
* @param [in] passedSz Size of password in bytes.
* @param [out] cipherInfo PEM cipher information lines.
* @param [in] maxDerSz Maximum size of DER buffer.
* @param [in] hashType Hash algorithm
* @return 1 on success.
* @return 0 on error.
*/
int EncryptDerKey(byte *der, int *derSz, const WOLFSSL_EVP_CIPHER* cipher,
unsigned char* passwd, int passwdSz, byte **cipherInfo, int maxDerSz,
int hashType)
{
int ret = 0;
int paddingSz = 0;
word32 idx;
word32 cipherInfoSz = 0;
WC_DECLARE_VAR(info, EncryptedInfo, 1, 0);
WOLFSSL_ENTER("EncryptDerKey");
/* Validate parameters. */
if ((der == NULL) || (derSz == NULL) || (cipher == NULL) ||
(passwd == NULL) || (cipherInfo == NULL)) {
ret = BAD_FUNC_ARG;
}
#ifdef WOLFSSL_SMALL_STACK
if (ret == 0) {
/* Allocate encrypted info. */
info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
DYNAMIC_TYPE_ENCRYPTEDINFO);
if (info == NULL) {
WOLFSSL_MSG("malloc failed");
ret = MEMORY_E;
}
}
#endif
if (ret == 0) {
/* Clear the encrypted info and set name. */
XMEMSET(info, 0, sizeof(EncryptedInfo));
XSTRNCPY(info->name, cipher, NAME_SZ - 1);
info->name[NAME_SZ - 1] = '\0'; /* null term */
/* Get encrypted info from name. */
ret = wc_EncryptedInfoGet(info, info->name);
if (ret != 0) {
WOLFSSL_MSG("unsupported cipher");
}
}
if (ret == 0) {
/* Generate a random salt. */
if (wolfSSL_RAND_bytes(info->iv, (int)info->ivSz) != 1) {
WOLFSSL_MSG("generate iv failed");
ret = WOLFSSL_FATAL_ERROR;
}
}
if (ret == 0) {
/* Calculate padding size - always a padding block. */
paddingSz = (int)info->ivSz - ((*derSz) % (int)info->ivSz);
/* Check der is big enough. */
if (maxDerSz < (*derSz) + paddingSz) {
WOLFSSL_MSG("not enough DER buffer allocated");
ret = BAD_FUNC_ARG;
}
}
if (ret == 0) {
/* Set padding bytes to padding length. */
XMEMSET(der + (*derSz), (byte)paddingSz, (size_t)paddingSz);
/* Add padding to DER size. */
(*derSz) += (int)paddingSz;
/* Encrypt DER buffer. */
ret = wc_BufferKeyEncrypt(info, der, (word32)*derSz, passwd, passwdSz,
hashType);
if (ret != 0) {
WOLFSSL_MSG("encrypt key failed");
}
}
if (ret == 0) {
/* Create cipher info : 'cipher_name,Salt(hex)' */
cipherInfoSz = (word32)(2 * info->ivSz + XSTRLEN(info->name) + 2);
/* Allocate memory for PEM encryption lines. */
*cipherInfo = (byte*)XMALLOC(cipherInfoSz, NULL, DYNAMIC_TYPE_STRING);
if (*cipherInfo == NULL) {
WOLFSSL_MSG("malloc failed");
ret = MEMORY_E;
}
}
if (ret == 0) {
/* Copy in name and add on comma. */
XSTRLCPY((char*)*cipherInfo, info->name, cipherInfoSz);
XSTRLCAT((char*)*cipherInfo, ",", cipherInfoSz);
/* Find end of string. */
idx = (word32)XSTRLEN((char*)*cipherInfo);
/* Calculate remaining bytes. */
cipherInfoSz -= idx;
/* Encode IV into PEM encryption lines. */
ret = Base16_Encode(info->iv, info->ivSz, *cipherInfo + idx,
&cipherInfoSz);
if (ret != 0) {
WOLFSSL_MSG("Base16_Encode failed");
XFREE(*cipherInfo, NULL, DYNAMIC_TYPE_STRING);
*cipherInfo = NULL;
}
}
WC_FREE_VAR_EX(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
return ret == 0;
}
#endif /* OPENSSL_EXTRA && WOLFSSL_KEY_GEN && WOLFSSL_PEM_TO_DER */
#if defined(OPENSSL_EXTRA) && defined(WOLFSSL_KEY_GEN) && \
(defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)) && \
(!defined(NO_RSA) || defined(HAVE_ECC))
/* Encrypt the DER in PEM format.
*
* @param [in] der DER encoded private key.
* @param [in] derSz Size of DER in bytes.
* @param [in] cipher EVP cipher.
* @param [in] passwd Password to use in encryption.
* @param [in] passwdSz Size of password in bytes.
* @param [in] type PEM type of write out.
* @param [in] heap Dynamic memory hint.
* @param [out] out Allocated buffer containing PEM encoding.
* heap was NULL and dynamic type is DYNAMIC_TYPE_KEY.
* @param [out] outSz Size of PEM encoding in bytes.
* @return 1 on success.
* @return 0 on failure.
*/
static int der_to_enc_pem_alloc(unsigned char* der, int derSz,
const WOLFSSL_EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz,
int type, void* heap, byte** out, int* outSz)
{
int ret = 1;
byte* tmp = NULL;
byte* cipherInfo = NULL;
int pemSz = 0;
int derAllocSz = derSz;
int hashType = WC_HASH_TYPE_NONE;
#if !defined(NO_MD5)
hashType = WC_MD5;
#elif !defined(NO_SHA)
hashType = WC_SHA;
#endif
/* Macro doesn't always use it. */
(void)heap;
/* Encrypt DER buffer if required. */
if ((ret == 1) && (passwd != NULL) && (passwdSz > 0) && (cipher != NULL)) {
int blockSz = wolfSSL_EVP_CIPHER_block_size(cipher);
byte *tmpBuf;
/* Add space for padding. */
#ifdef WOLFSSL_NO_REALLOC
tmpBuf = (byte*)XMALLOC((size_t)(derSz + blockSz), heap,
DYNAMIC_TYPE_TMP_BUFFER);
if (tmpBuf != NULL && der != NULL)
{
XMEMCPY(tmpBuf, der, (size_t)(derSz));
XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER);
der = NULL;
}
#else
tmpBuf = (byte*)XREALLOC(der, (size_t)(derSz + blockSz), heap,
DYNAMIC_TYPE_TMP_BUFFER);
#endif
if (tmpBuf == NULL) {
WOLFSSL_ERROR_MSG("Extending DER buffer failed");
ret = 0; /* der buffer is free'd at the end of the function */
}
else {
der = tmpBuf;
derAllocSz = derSz + blockSz;
/* Encrypt DER inline. */
ret = EncryptDerKey(der, &derSz, cipher, passwd, passwdSz,
&cipherInfo, derSz + blockSz, hashType);
if (ret != 1) {
WOLFSSL_ERROR_MSG("EncryptDerKey failed");
}
}
}
if (ret == 1) {
/* Calculate PEM encoding size. */
pemSz = wc_DerToPemEx(der, (word32)derSz, NULL, 0, cipherInfo, type);
if (pemSz <= 0) {
WOLFSSL_ERROR_MSG("wc_DerToPemEx failed");
ret = 0;
}
}
if (ret == 1) {
/* Allocate space for PEM encoding plus a NUL terminator. */
tmp = (byte*)XMALLOC((size_t)(pemSz + 1), NULL, DYNAMIC_TYPE_KEY);
if (tmp == NULL) {
WOLFSSL_ERROR_MSG("malloc failed");
ret = 0;
}
}
if (ret == 1) {
/* DER to PEM */
pemSz = wc_DerToPemEx(der, (word32)derSz, tmp, (word32)pemSz,
cipherInfo, type);
if (pemSz <= 0) {
WOLFSSL_ERROR_MSG("wc_DerToPemEx failed");
ret = 0;
}
}
if (ret == 1) {
/* NUL terminate string - PEM. */
tmp[pemSz] = 0x00;
/* Return allocated buffer and size. */
*out = tmp;
*outSz = pemSz;
/* Don't free returning buffer. */
tmp = NULL;
}
XFREE(tmp, NULL, DYNAMIC_TYPE_KEY);
XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
if (der != NULL) {
ForceZero(der, (word32)derAllocSz);
XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER);
}
return ret;
}
#endif
#endif /* !NO_ASN */
#if !defined(NO_CERTS) && defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
!defined(NO_STDIO_FILESYSTEM) && (!defined(NO_RSA) || !defined(NO_DSA) || \
defined(HAVE_ECC)) && defined(OPENSSL_EXTRA)
/* Print the number bn in hex with name field and indentation indent to file fp.
*
* Used by wolfSSL_DSA_print_fp, wolfSSL_RSA_print_fp and
* wolfSSL_EC_KEY_print_fp to print DSA, RSA and ECC keys and parameters.
*
* @param [in] fp File pointer to write to.
* @param [in] indent Number of spaces to prepend to each line.
* @param [in] field Name of field.
* @param [in] bn Big number to print.
* @return 1 on success.
* @return 0 on failure.
* @return BAD_FUNC_ARG when fp is invalid, indent is less than 0, or field or
* bn or NULL.
*/
static int pk_bn_field_print_fp(XFILE fp, int indent, const char* field,
const WOLFSSL_BIGNUM* bn)
{
static const int HEX_INDENT = 4;
static const int MAX_DIGITS_PER_LINE = 30;
int ret = 1;
int i = 0;
char* buf = NULL;
/* Internal function - assume parameters are valid. */
/* Convert BN to hexadecimal character array (allocates buffer). */
buf = wolfSSL_BN_bn2hex(bn);
if (buf == NULL) {
ret = 0;
}
if (ret == 1) {
/* Print leading spaces, name and spaces before data. */
if (indent > 0) {
if (XFPRINTF(fp, "%*s", indent, "") < 0)
ret = 0;
}
}
if (ret == 1) {
if (XFPRINTF(fp, "%s:\n", field) < 0)
ret = 0;
}
if (ret == 1) {
if (indent > 0) {
if (XFPRINTF(fp, "%*s", indent, "") < 0)
ret = 0;
}
}
if (ret == 1) {
if (XFPRINTF(fp, "%*s", HEX_INDENT, "") < 0)
ret = 0;
}
if (ret == 1) {
/* Print first byte - should always exist. */
if ((buf[i] != '\0') && (buf[i+1] != '\0')) {
if (XFPRINTF(fp, "%c", buf[i++]) < 0)
ret = 0;
else if (XFPRINTF(fp, "%c", buf[i++]) < 0)
ret = 0;
}
}
if (ret == 1) {
/* Print each hexadecimal character with byte separator. */
while ((buf[i] != '\0') && (buf[i+1] != '\0')) {
/* Byte separator every two nibbles - one byte. */
if (XFPRINTF(fp, ":") < 0) {
ret = 0;
break;
}
/* New line after every 15 bytes - 30 nibbles. */
if (i % MAX_DIGITS_PER_LINE == 0) {
if (XFPRINTF(fp, "\n") < 0) {
ret = 0;
break;
}
if (indent > 0) {
if (XFPRINTF(fp, "%*s", indent, "") < 0) {
ret = 0;
break;
}
}
if (XFPRINTF(fp, "%*s", HEX_INDENT, "") < 0) {
ret = 0;
break;
}
}
/* Print two nibbles - one byte. */
if (XFPRINTF(fp, "%c", buf[i++]) < 0) {
ret = 0;
break;
}
if (XFPRINTF(fp, "%c", buf[i++]) < 0) {
ret = 0;
break;
}
}
/* Ensure on new line after data. */
if (XFPRINTF(fp, "\n") < 0) {
ret = 0;
}
}
/* Dispose of any allocated character array. */
XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
return ret;
}
#endif /* !NO_CERTS && XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM &&
* (!NO_DSA || !NO_RSA || HAVE_ECC) */
#if defined(OPENSSL_EXTRA) && defined(XSNPRINTF) && !defined(NO_BIO) && \
!defined(NO_RSA)
/* snprintf() must be available */
/* Maximum number of extra indent spaces on each line. */
#define PRINT_NUM_MAX_INDENT 48
/* Maximum size of a line containing a value. */
#define PRINT_NUM_MAX_VALUE_LINE PRINT_NUM_MAX_INDENT
/* Number of leading spaces on each line. */
#define PRINT_NUM_INDENT_CNT 4
/* Indent spaces for number lines. */
#define PRINT_NUM_INDENT " "
/* 4 leading spaces and 15 bytes with colons is a complete line. */
#define PRINT_NUM_MAX_DIGIT_LINE (PRINT_NUM_INDENT_CNT + 3 * 15)
/* Print indent to BIO.
*
* @param [in] bio BIO object to write to.
* @param [in] line Buffer to put characters to before writing to BIO.
* @param [in] lineLen Length of buffer.
* @return 1 on success.
* @return 0 on failure.
*/
static int wolfssl_print_indent(WOLFSSL_BIO* bio, char* line, int lineLen,
int indent)
{
int ret = 1;
if (indent > 0) {
int len_wanted;
/* Cap indent to buffer size to avoid format truncation warning */
if (indent >= lineLen) {
indent = lineLen - 1;
}
/* Print indent spaces. */
len_wanted = XSNPRINTF(line, (size_t)lineLen, "%*s", indent, " ");
if ((len_wanted < 0) || (len_wanted >= lineLen)) {
WOLFSSL_ERROR_MSG("Buffer overflow formatting indentation");
ret = 0;
}
else {
/* Write indents string to BIO */
if (wolfSSL_BIO_write(bio, line, len_wanted) <= 0) {
ret = 0;
}
}
}
return ret;
}
/* Print out name, and value in decimal and hex to BIO.
*
* @param [in] bio BIO object to write to.
* @param [in] value MP integer to write.
* @param [in] name Name of value.
* @param [in] indent Number of leading spaces before line.
* @return 1 on success.
* @return 0 on failure.
*/
static int wolfssl_print_value(WOLFSSL_BIO* bio, mp_int* value,
const char* name, int indent)
{
int ret = 1;
int len;
char line[PRINT_NUM_MAX_VALUE_LINE + 1];
/* Get the length of hex encoded value. */
len = mp_unsigned_bin_size(value);
/* Value must no more than 32-bits - 4 bytes. */
if ((len < 0) || (len > 4)) {
WOLFSSL_ERROR_MSG("Error getting exponent size");
ret = 0;
}
if (ret == 1) {
/* Print any indent spaces. */
ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
}
if (ret == 1) {
/* Get 32-bits of value. */
word32 v = (word32)value->dp[0];
/* Print the line to the string. */
len = (int)XSNPRINTF(line, sizeof(line), "%s %u (0x%x)\n", name, v,
v);
if (len >= (int)sizeof(line)) {
WOLFSSL_ERROR_MSG("Buffer overflow while formatting value");
ret = 0;
} else {
/* Write string to BIO */
if (wolfSSL_BIO_write(bio, line, len) <= 0) {
ret = 0;
}
}
}
return ret;
}
/* Print out name and multi-precision number to BIO.
*
* @param [in] bio BIO object to write to.
* @param [in] num MP integer to write.
* @param [in] name Name of value.
* @param [in] indent Number of leading spaces before each line.
* @return 1 on success.
* @return 0 on failure.
*/
static int wolfssl_print_number(WOLFSSL_BIO* bio, mp_int* num, const char* name,
int indent)
{
int ret = 1;
int rawLen = 0;
byte* rawKey = NULL;
char line[PRINT_NUM_MAX_DIGIT_LINE + 1];
int li = 0; /* Line index. */
int i;
/* Allocate a buffer to hold binary encoded data. */
rawLen = mp_unsigned_bin_size(num);
if (rawLen == 0) {
WOLFSSL_ERROR_MSG("Invalid number");
ret = 0;
}
if (ret == 1) {
rawKey = (byte*)XMALLOC((size_t)rawLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (rawKey == NULL) {
WOLFSSL_ERROR_MSG("Memory allocation error");
ret = 0;
}
}
/* Encode number as big-endian byte array. */
if ((ret == 1) && (mp_to_unsigned_bin(num, rawKey) < 0)) {
ret = 0;
}
if (ret == 1) {
/* Print any indent spaces. */
ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
}
if (ret == 1) {
/* Print header string line to string. */
li = XSNPRINTF(line, sizeof(line), "%s\n", name);
if (li >= (int)sizeof(line)) {
WOLFSSL_ERROR_MSG("Buffer overflow formatting name");
ret = 0;
}
else {
if (wolfSSL_BIO_write(bio, line, li) <= 0) {
ret = 0;
}
}
}
if (ret == 1) {
/* Print any indent spaces. */
ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
}
if (ret == 1) {
/* Start first digit line with spaces.
* Writing out zeros ensures number is a positive value. */
li = XSNPRINTF(line, sizeof(line), PRINT_NUM_INDENT "%s",
mp_leading_bit(num) ? "00:" : "");
if (li >= (int)sizeof(line)) {
WOLFSSL_ERROR_MSG("Buffer overflow formatting spaces");
ret = 0;
}
}
/* Put out each line of numbers. */
for (i = 0; (ret == 1) && (i < rawLen); i++) {
/* Encode another byte as 2 hex digits and append colon. */
int len_wanted = XSNPRINTF(line + li, sizeof(line) - (size_t)li,
"%02x:", rawKey[i]);
/* Check if there was room -- if not, print the current line, not
* including the newest octet.
*/
if (len_wanted >= (int)sizeof(line) - li) {
/* bump current octet to the next line. */
--i;
/* More bytes coming so add a line break. */
line[li++] = '\n';
/* Write out the line. */
if (wolfSSL_BIO_write(bio, line, li) <= 0) {
ret = 0;
}
if (ret == 1) {
/* Print any indent spaces. */
ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
}
/* Put the leading spaces on new line. */
XSTRNCPY(line, PRINT_NUM_INDENT, PRINT_NUM_INDENT_CNT + 1);
li = PRINT_NUM_INDENT_CNT;
}
else {
li += len_wanted;
}
}
if (ret == 1) {
/* Put out last line - replace last colon with carriage return. */
line[li-1] = '\n';
if (wolfSSL_BIO_write(bio, line, li) <= 0) {
ret = 0;
}
}
/* Dispose of any allocated data. */
XFREE(rawKey, NULL, DYNAMIC_TYPE_TMP_BUFFER);
return ret;
}
#endif /* OPENSSL_EXTRA && XSNPRINTF && !NO_BIO && !NO_RSA */
#endif /* OPENSSL_EXTRA */
#if !defined(NO_CERTS) || (defined(OPENSSL_EXTRA) && (!defined(NO_RSA) || \
(!defined(NO_DH) && defined(HAVE_FIPS) && !FIPS_VERSION_GT(2,0)) || \
defined(HAVE_ECC)))
/* Uses the DER SEQUENCE to determine size of DER data.
*
* Outer SEQUENCE encapsulates all the DER encoding.
* Add the length of the SEQUENCE data to the length of the SEQUENCE header.
*
* @param [in] seq Buffer holding DER encoded sequence.
* @param [in] len Length of data in buffer (may be larger than SEQ).
* @return Size of complete DER encoding on success.
* @return 0 on failure.
*/
static int wolfssl_der_length(const unsigned char* seq, int len)
{
int ret = 0;
word32 i = 0;
/* Check it is a SEQUENCE and get the length of the underlying data.
* i is updated to be after SEQUENCE header bytes.
*/
if (GetSequence_ex(seq, &i, &ret, (word32)len, 0) >= 0) {
/* Add SEQUENCE header length to underlying data length. */
ret += (int)i;
}
return ret;
}
#endif
#define WOLFSSL_PK_RSA_INCLUDED
#include "src/pk_rsa.c"
/*******************************************************************************
* START OF DSA API
******************************************************************************/
#ifndef NO_DSA
#if defined(OPENSSL_EXTRA) && defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
!defined(NO_STDIO_FILESYSTEM)
/* return code compliant with OpenSSL :
* 1 if success, 0 if error
*/
int wolfSSL_DSA_print_fp(XFILE fp, WOLFSSL_DSA* dsa, int indent)
{
int ret = 1;
WOLFSSL_ENTER("wolfSSL_DSA_print_fp");
if (fp == XBADFILE || dsa == NULL) {
ret = 0;
}
if (ret == 1 && dsa->p != NULL) {
int pBits = wolfSSL_BN_num_bits(dsa->p);
if (pBits == 0) {
ret = 0;
}
else {
if (XFPRINTF(fp, "%*s", indent, "") < 0)
ret = 0;
else if (XFPRINTF(fp, "Private-Key: (%d bit)\n", pBits) < 0)
ret = 0;
}
}
if (ret == 1 && dsa->priv_key != NULL) {
ret = pk_bn_field_print_fp(fp, indent, "priv", dsa->priv_key);
}
if (ret == 1 && dsa->pub_key != NULL) {
ret = pk_bn_field_print_fp(fp, indent, "pub", dsa->pub_key);
}
if (ret == 1 && dsa->p != NULL) {
ret = pk_bn_field_print_fp(fp, indent, "P", dsa->p);
}
if (ret == 1 && dsa->q != NULL) {
ret = pk_bn_field_print_fp(fp, indent, "Q", dsa->q);
}
if (ret == 1 && dsa->g != NULL) {
ret = pk_bn_field_print_fp(fp, indent, "G", dsa->g);
}
WOLFSSL_LEAVE("wolfSSL_DSA_print_fp", ret);
return ret;
}
#endif /* OPENSSL_EXTRA && XSNPRINTF && !NO_FILESYSTEM && NO_STDIO_FILESYSTEM */
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
static void InitwolfSSL_DSA(WOLFSSL_DSA* dsa)
{
if (dsa) {