source: UsbWattMeter/trunk/wolfssl-3.7.0/wolfcrypt/src/asn.c

Last change on this file was 167, checked in by coas-nagasima, 6 years ago

MIMEにSJISを設定

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
  • Property svn:mime-type set to text/x-csrc; charset=SHIFT_JIS
File size: 254.1 KB
RevLine 
[164]1/* asn.c
2 *
3 * Copyright (C) 2006-2015 wolfSSL Inc.
4 *
5 * This file is part of wolfSSL. (formerly known as CyaSSL)
6 *
7 * wolfSSL is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * wolfSSL is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
20 */
21
22#ifdef HAVE_CONFIG_H
23 #include <config.h>
24#endif
25
26#include <wolfssl/wolfcrypt/settings.h>
27
28#ifndef NO_ASN
29
30#ifdef HAVE_RTP_SYS
31 #include "os.h" /* dc_rtc_api needs */
32 #include "dc_rtc_api.h" /* to get current time */
33#endif
34
35#include <wolfssl/wolfcrypt/asn.h>
36#include <wolfssl/wolfcrypt/coding.h>
37//#include <wolfssl/wolfcrypt/md2.h>
38#include <wolfssl/wolfcrypt/hmac.h>
39#include <wolfssl/wolfcrypt/error-crypt.h>
40#include <wolfssl/wolfcrypt/pwdbased.h>
41#include <wolfssl/wolfcrypt/des3.h>
42#include <wolfssl/wolfcrypt/logging.h>
43
44#include <wolfssl/wolfcrypt/random.h>
45#include <wolfssl/wolfcrypt/hash.h>
46
47
48#ifndef NO_RC4
49 #include <wolfssl/wolfcrypt/arc4.h>
50#endif
51
52#ifdef HAVE_NTRU
53 #include "libntruencrypt/ntru_crypto.h"
54#endif
55
56#if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
57 #include <wolfssl/wolfcrypt/sha512.h>
58#endif
59
60#ifndef NO_SHA256
61 #include <wolfssl/wolfcrypt/sha256.h>
62#endif
63
64#ifdef HAVE_ECC
65 #include <wolfssl/wolfcrypt/ecc.h>
66#endif
67
68#ifdef WOLFSSL_DEBUG_ENCODING
69 #if defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
70 #if MQX_USE_IO_OLD
71 #include <fio.h>
72 #else
73 #include <nio.h>
74 #endif
75 #else
76 #include <stdio.h>
77 #endif
78#endif
79
80#ifdef _MSC_VER
81 /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
82 #pragma warning(disable: 4996)
83#endif
84
85
86#ifndef TRUE
87 #define TRUE 1
88#endif
89#ifndef FALSE
90 #define FALSE 0
91#endif
92
93
94#ifdef HAVE_RTP_SYS
95 /* uses parital <time.h> structures */
96 #define XTIME(tl) (0)
97 #define XGMTIME(c, t) my_gmtime((c))
98 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
99#elif defined(MICRIUM)
100 #if (NET_SECURE_MGR_CFG_EN == DEF_ENABLED)
101 #define XVALIDATE_DATE(d,f,t) NetSecure_ValidateDateHandler((d),(f),(t))
102 #else
103 #define XVALIDATE_DATE(d, f, t) (0)
104 #endif
105 #define NO_TIME_H
106 /* since Micrium not defining XTIME or XGMTIME, CERT_GEN not available */
107#elif defined(MICROCHIP_TCPIP_V5) || defined(MICROCHIP_TCPIP)
108 #include <time.h>
109 #define XTIME(t1) pic32_time((t1))
110 #define XGMTIME(c, t) gmtime((c))
111 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
112#elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
113 #define XTIME(t1) mqx_time((t1))
114 #define XGMTIME(c, t) mqx_gmtime((c), (t))
115 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
116#elif defined(FREESCALE_KSDK_BM)
117 #include <time.h>
118 #define XTIME(t1) ksdk_time((t1))
119 #define XGMTIME(c, t) gmtime((c))
120 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
121
122#elif defined(USER_TIME)
123 /* user time, and gmtime compatible functions, there is a gmtime
124 implementation here that WINCE uses, so really just need some ticks
125 since the EPOCH
126 */
127
128 struct tm {
129 int tm_sec; /* seconds after the minute [0-60] */
130 int tm_min; /* minutes after the hour [0-59] */
131 int tm_hour; /* hours since midnight [0-23] */
132 int tm_mday; /* day of the month [1-31] */
133 int tm_mon; /* months since January [0-11] */
134 int tm_year; /* years since 1900 */
135 int tm_wday; /* days since Sunday [0-6] */
136 int tm_yday; /* days since January 1 [0-365] */
137 int tm_isdst; /* Daylight Savings Time flag */
138 long tm_gmtoff; /* offset from CUT in seconds */
139 char *tm_zone; /* timezone abbreviation */
140 };
141 typedef long time_t;
142
143 /* forward declaration */
144 struct tm* gmtime(const time_t* timer);
145 extern time_t XTIME(time_t * timer);
146
147 #define XGMTIME(c, t) gmtime((c))
148 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
149
150 #ifdef STACK_TRAP
151 /* for stack trap tracking, don't call os gmtime on OS X/linux,
152 uses a lot of stack spce */
153 extern time_t time(time_t * timer);
154 #define XTIME(tl) time((tl))
155 #endif /* STACK_TRAP */
156
157#elif defined(TIME_OVERRIDES)
158 /* user would like to override time() and gmtime() functionality */
159
160 #ifndef HAVE_TIME_T_TYPE
161 typedef long time_t;
162 #endif
163 extern time_t XTIME(time_t * timer);
164
165 #ifndef HAVE_TM_TYPE
166 struct tm {
167 int tm_sec; /* seconds after the minute [0-60] */
168 int tm_min; /* minutes after the hour [0-59] */
169 int tm_hour; /* hours since midnight [0-23] */
170 int tm_mday; /* day of the month [1-31] */
171 int tm_mon; /* months since January [0-11] */
172 int tm_year; /* years since 1900 */
173 int tm_wday; /* days since Sunday [0-6] */
174 int tm_yday; /* days since January 1 [0-365] */
175 int tm_isdst; /* Daylight Savings Time flag */
176 long tm_gmtoff; /* offset from CUT in seconds */
177 char *tm_zone; /* timezone abbreviation */
178 };
179 #endif
180 extern struct tm* XGMTIME(const time_t* timer, struct tm* tmp);
181
182 #ifndef HAVE_VALIDATE_DATE
183 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
184 #endif
185
186#elif defined(IDIRECT_DEV_TIME)
187 /*Gets the timestamp from cloak software owned by VT iDirect
188 in place of time() from <time.h> */
189 #include <time.h>
190 #define XTIME(t1) idirect_time((t1))
191 #define XGMTIME(c) gmtime((c))
192 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
193
194#else
195 /* default */
196 /* uses complete <time.h> facility */
197 #include <time.h>
198 #define XTIME(tl) time((tl))
199 #define XGMTIME(c, t) gmtime((c))
200 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
201#endif
202
203
204#ifdef _WIN32_WCE
205/* no time() or gmtime() even though in time.h header?? */
206
207#include <windows.h>
208
209
210time_t time(time_t* timer)
211{
212 SYSTEMTIME sysTime;
213 FILETIME fTime;
214 ULARGE_INTEGER intTime;
215 time_t localTime;
216
217 if (timer == NULL)
218 timer = &localTime;
219
220 GetSystemTime(&sysTime);
221 SystemTimeToFileTime(&sysTime, &fTime);
222
223 XMEMCPY(&intTime, &fTime, sizeof(FILETIME));
224 /* subtract EPOCH */
225 intTime.QuadPart -= 0x19db1ded53e8000;
226 /* to secs */
227 intTime.QuadPart /= 10000000;
228 *timer = (time_t)intTime.QuadPart;
229
230 return *timer;
231}
232
233#endif /* _WIN32_WCE */
234#if defined( _WIN32_WCE ) || defined( USER_TIME )
235
236struct tm* gmtime(const time_t* timer)
237{
238 #define YEAR0 1900
239 #define EPOCH_YEAR 1970
240 #define SECS_DAY (24L * 60L * 60L)
241 #define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) %400)))
242 #define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365)
243
244 static const int _ytab[2][12] =
245 {
246 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
247 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
248 };
249
250 static struct tm st_time;
251 struct tm* ret = &st_time;
252 time_t secs = *timer;
253 unsigned long dayclock, dayno;
254 int year = EPOCH_YEAR;
255
256 dayclock = (unsigned long)secs % SECS_DAY;
257 dayno = (unsigned long)secs / SECS_DAY;
258
259 ret->tm_sec = (int) dayclock % 60;
260 ret->tm_min = (int)(dayclock % 3600) / 60;
261 ret->tm_hour = (int) dayclock / 3600;
262 ret->tm_wday = (int) (dayno + 4) % 7; /* day 0 a Thursday */
263
264 while(dayno >= (unsigned long)YEARSIZE(year)) {
265 dayno -= YEARSIZE(year);
266 year++;
267 }
268
269 ret->tm_year = year - YEAR0;
270 ret->tm_yday = (int)dayno;
271 ret->tm_mon = 0;
272
273 while(dayno >= (unsigned long)_ytab[LEAPYEAR(year)][ret->tm_mon]) {
274 dayno -= _ytab[LEAPYEAR(year)][ret->tm_mon];
275 ret->tm_mon++;
276 }
277
278 ret->tm_mday = (int)++dayno;
279 ret->tm_isdst = 0;
280
281 return ret;
282}
283
284#endif /* _WIN32_WCE || USER_TIME */
285
286
287#ifdef HAVE_RTP_SYS
288
289#define YEAR0 1900
290
291struct tm* my_gmtime(const time_t* timer) /* has a gmtime() but hangs */
292{
293 static struct tm st_time;
294 struct tm* ret = &st_time;
295
296 DC_RTC_CALENDAR cal;
297 dc_rtc_time_get(&cal, TRUE);
298
299 ret->tm_year = cal.year - YEAR0; /* gm starts at 1900 */
300 ret->tm_mon = cal.month - 1; /* gm starts at 0 */
301 ret->tm_mday = cal.day;
302 ret->tm_hour = cal.hour;
303 ret->tm_min = cal.minute;
304 ret->tm_sec = cal.second;
305
306 return ret;
307}
308
309#endif /* HAVE_RTP_SYS */
310
311
312#if defined(MICROCHIP_TCPIP_V5) || defined(MICROCHIP_TCPIP)
313
314/*
315 * time() is just a stub in Microchip libraries. We need our own
316 * implementation. Use SNTP client to get seconds since epoch.
317 */
318time_t pic32_time(time_t* timer)
319{
320#ifdef MICROCHIP_TCPIP_V5
321 DWORD sec = 0;
322#else
323 uint32_t sec = 0;
324#endif
325 time_t localTime;
326
327 if (timer == NULL)
328 timer = &localTime;
329
330#ifdef MICROCHIP_MPLAB_HARMONY
331 sec = TCPIP_SNTP_UTCSecondsGet();
332#else
333 sec = SNTPGetUTCSeconds();
334#endif
335 *timer = (time_t) sec;
336
337 return *timer;
338}
339
340#endif /* MICROCHIP_TCPIP */
341
342
343#if defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
344
345time_t mqx_time(time_t* timer)
346{
347 time_t localTime;
348 TIME_STRUCT time_s;
349
350 if (timer == NULL)
351 timer = &localTime;
352
353 _time_get(&time_s);
354 *timer = (time_t) time_s.SECONDS;
355
356 return *timer;
357}
358
359/* CodeWarrior GCC toolchain only has gmtime_r(), no gmtime() */
360struct tm* mqx_gmtime(const time_t* clock, struct tm* tmpTime)
361{
362 return gmtime_r(clock, tmpTime);
363}
364
365#endif /* FREESCALE_MQX */
366
367#ifdef FREESCALE_KSDK_BM
368
369/* setting for PIT timer */
370#define PIT_INSTANCE 0
371#define PIT_CHANNEL 0
372
373#include "fsl_pit_driver.h"
374
375time_t ksdk_time(time_t* timer)
376{
377 time_t localTime;
378
379 if (timer == NULL)
380 timer = &localTime;
381
382 *timer = (PIT_DRV_ReadTimerUs(PIT_INSTANCE, PIT_CHANNEL)) / 1000000;
383 return *timer;
384}
385
386#endif /* FREESCALE_KSDK_BM */
387
388#ifdef WOLFSSL_TIRTOS
389
390time_t XTIME(time_t * timer)
391{
392 time_t sec = 0;
393
394 sec = (time_t) Seconds_get();
395
396 if (timer != NULL)
397 *timer = sec;
398
399 return sec;
400}
401
402#endif /* WOLFSSL_TIRTOS */
403
404static INLINE word32 btoi(byte b)
405{
406 return b - 0x30;
407}
408
409
410/* two byte date/time, add to value */
411static INLINE void GetTime(int* value, const byte* date, int* idx)
412{
413 int i = *idx;
414
415 *value += btoi(date[i++]) * 10;
416 *value += btoi(date[i++]);
417
418 *idx = i;
419}
420
421
422#if defined(MICRIUM)
423
424CPU_INT32S NetSecure_ValidateDateHandler(CPU_INT08U *date, CPU_INT08U format,
425 CPU_INT08U dateType)
426{
427 CPU_BOOLEAN rtn_code;
428 CPU_INT32S i;
429 CPU_INT32S val;
430 CPU_INT16U year;
431 CPU_INT08U month;
432 CPU_INT16U day;
433 CPU_INT08U hour;
434 CPU_INT08U min;
435 CPU_INT08U sec;
436
437 i = 0;
438 year = 0u;
439
440 if (format == ASN_UTC_TIME) {
441 if (btoi(date[0]) >= 5)
442 year = 1900;
443 else
444 year = 2000;
445 }
446 else { /* format == GENERALIZED_TIME */
447 year += btoi(date[i++]) * 1000;
448 year += btoi(date[i++]) * 100;
449 }
450
451 val = year;
452 GetTime(&val, date, &i);
453 year = (CPU_INT16U)val;
454
455 val = 0;
456 GetTime(&val, date, &i);
457 month = (CPU_INT08U)val;
458
459 val = 0;
460 GetTime(&val, date, &i);
461 day = (CPU_INT16U)val;
462
463 val = 0;
464 GetTime(&val, date, &i);
465 hour = (CPU_INT08U)val;
466
467 val = 0;
468 GetTime(&val, date, &i);
469 min = (CPU_INT08U)val;
470
471 val = 0;
472 GetTime(&val, date, &i);
473 sec = (CPU_INT08U)val;
474
475 return NetSecure_ValidateDate(year, month, day, hour, min, sec, dateType);
476}
477
478#endif /* MICRIUM */
479
480#if defined(IDIRECT_DEV_TIME)
481
482extern time_t getTimestamp();
483
484time_t idirect_time(time_t * timer)
485{
486 time_t sec = getTimestamp();
487
488 if (timer != NULL)
489 *timer = sec;
490
491 return sec;
492}
493
494#endif
495
496
497WOLFSSL_LOCAL int GetLength(const byte* input, word32* inOutIdx, int* len,
498 word32 maxIdx)
499{
500 int length = 0;
501 word32 i = *inOutIdx;
502 byte b;
503
504 *len = 0; /* default length */
505
506 if ( (i+1) > maxIdx) { /* for first read */
507 WOLFSSL_MSG("GetLength bad index on input");
508 return BUFFER_E;
509 }
510
511 b = input[i++];
512 if (b >= ASN_LONG_LENGTH) {
513 word32 bytes = b & 0x7F;
514
515 if ( (i+bytes) > maxIdx) { /* for reading bytes */
516 WOLFSSL_MSG("GetLength bad long length");
517 return BUFFER_E;
518 }
519
520 while (bytes--) {
521 b = input[i++];
522 length = (length << 8) | b;
523 }
524 }
525 else
526 length = b;
527
528 if ( (i+length) > maxIdx) { /* for user of length */
529 WOLFSSL_MSG("GetLength value exceeds buffer length");
530 return BUFFER_E;
531 }
532
533 *inOutIdx = i;
534 if (length > 0)
535 *len = length;
536
537 return length;
538}
539
540
541WOLFSSL_LOCAL int GetSequence(const byte* input, word32* inOutIdx, int* len,
542 word32 maxIdx)
543{
544 int length = -1;
545 word32 idx = *inOutIdx;
546
547 if (input[idx++] != (ASN_SEQUENCE | ASN_CONSTRUCTED) ||
548 GetLength(input, &idx, &length, maxIdx) < 0)
549 return ASN_PARSE_E;
550
551 *len = length;
552 *inOutIdx = idx;
553
554 return length;
555}
556
557
558WOLFSSL_LOCAL int GetSet(const byte* input, word32* inOutIdx, int* len,
559 word32 maxIdx)
560{
561 int length = -1;
562 word32 idx = *inOutIdx;
563
564 if (input[idx++] != (ASN_SET | ASN_CONSTRUCTED) ||
565 GetLength(input, &idx, &length, maxIdx) < 0)
566 return ASN_PARSE_E;
567
568 *len = length;
569 *inOutIdx = idx;
570
571 return length;
572}
573
574
575/* winodws header clash for WinCE using GetVersion */
576WOLFSSL_LOCAL int GetMyVersion(const byte* input, word32* inOutIdx,
577 int* version)
578{
579 word32 idx = *inOutIdx;
580
581 WOLFSSL_ENTER("GetMyVersion");
582
583 if (input[idx++] != ASN_INTEGER)
584 return ASN_PARSE_E;
585
586 if (input[idx++] != 0x01)
587 return ASN_VERSION_E;
588
589 *version = input[idx++];
590 *inOutIdx = idx;
591
592 return *version;
593}
594
595
596#ifndef NO_PWDBASED
597/* Get small count integer, 32 bits or less */
598static int GetShortInt(const byte* input, word32* inOutIdx, int* number)
599{
600 word32 idx = *inOutIdx;
601 word32 len;
602
603 *number = 0;
604
605 if (input[idx++] != ASN_INTEGER)
606 return ASN_PARSE_E;
607
608 len = input[idx++];
609 if (len > 4)
610 return ASN_PARSE_E;
611
612 while (len--) {
613 *number = *number << 8 | input[idx++];
614 }
615
616 *inOutIdx = idx;
617
618 return *number;
619}
620#endif /* !NO_PWDBASED */
621
622
623/* May not have one, not an error */
624static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version)
625{
626 word32 idx = *inOutIdx;
627
628 WOLFSSL_ENTER("GetExplicitVersion");
629 if (input[idx++] == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
630 *inOutIdx = ++idx; /* eat header */
631 return GetMyVersion(input, inOutIdx, version);
632 }
633
634 /* go back as is */
635 *version = 0;
636
637 return 0;
638}
639
640
641WOLFSSL_LOCAL int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx,
642 word32 maxIdx)
643{
644 word32 i = *inOutIdx;
645 byte b = input[i++];
646 int length;
647
648 if (b != ASN_INTEGER)
649 return ASN_PARSE_E;
650
651 if (GetLength(input, &i, &length, maxIdx) < 0)
652 return ASN_PARSE_E;
653
654 if ( (b = input[i++]) == 0x00)
655 length--;
656 else
657 i--;
658
659 if (mp_init(mpi) != MP_OKAY)
660 return MP_INIT_E;
661
662 if (mp_read_unsigned_bin(mpi, (byte*)input + i, length) != 0) {
663 mp_clear(mpi);
664 return ASN_GETINT_E;
665 }
666
667 *inOutIdx = i + length;
668 return 0;
669}
670
671
672static int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
673 word32 maxIdx)
674{
675 int length;
676 word32 i = *inOutIdx;
677 byte b;
678 *oid = 0;
679
680 b = input[i++];
681 if (b != ASN_OBJECT_ID)
682 return ASN_OBJECT_ID_E;
683
684 if (GetLength(input, &i, &length, maxIdx) < 0)
685 return ASN_PARSE_E;
686
687 while(length--)
688 *oid += input[i++];
689 /* just sum it up for now */
690
691 *inOutIdx = i;
692
693 return 0;
694}
695
696
697WOLFSSL_LOCAL int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
698 word32 maxIdx)
699{
700 int length;
701 word32 i = *inOutIdx;
702 byte b;
703 *oid = 0;
704
705 WOLFSSL_ENTER("GetAlgoId");
706
707 if (GetSequence(input, &i, &length, maxIdx) < 0)
708 return ASN_PARSE_E;
709
710 b = input[i++];
711 if (b != ASN_OBJECT_ID)
712 return ASN_OBJECT_ID_E;
713
714 if (GetLength(input, &i, &length, maxIdx) < 0)
715 return ASN_PARSE_E;
716
717 while(length--) {
718 /* odd HC08 compiler behavior here when input[i++] */
719 *oid += input[i];
720 i++;
721 }
722 /* just sum it up for now */
723
724 /* could have NULL tag and 0 terminator, but may not */
725 b = input[i++];
726
727 if (b == ASN_TAG_NULL) {
728 b = input[i++];
729 if (b != 0)
730 return ASN_EXPECT_0_E;
731 }
732 else
733 /* go back, didn't have it */
734 i--;
735
736 *inOutIdx = i;
737
738 return 0;
739}
740
741#ifndef NO_RSA
742
743
744#ifdef HAVE_CAVIUM
745
746static int GetCaviumInt(byte** buff, word16* buffSz, const byte* input,
747 word32* inOutIdx, word32 maxIdx, void* heap)
748{
749 word32 i = *inOutIdx;
750 byte b = input[i++];
751 int length;
752
753 if (b != ASN_INTEGER)
754 return ASN_PARSE_E;
755
756 if (GetLength(input, &i, &length, maxIdx) < 0)
757 return ASN_PARSE_E;
758
759 if ( (b = input[i++]) == 0x00)
760 length--;
761 else
762 i--;
763
764 *buffSz = (word16)length;
765 *buff = XMALLOC(*buffSz, heap, DYNAMIC_TYPE_CAVIUM_RSA);
766 if (*buff == NULL)
767 return MEMORY_E;
768
769 XMEMCPY(*buff, input + i, *buffSz);
770
771 *inOutIdx = i + length;
772 return 0;
773}
774
775static int CaviumRsaPrivateKeyDecode(const byte* input, word32* inOutIdx,
776 RsaKey* key, word32 inSz)
777{
778 int version, length;
779 void* h = key->heap;
780
781 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
782 return ASN_PARSE_E;
783
784 if (GetMyVersion(input, inOutIdx, &version) < 0)
785 return ASN_PARSE_E;
786
787 key->type = RSA_PRIVATE;
788
789 if (GetCaviumInt(&key->c_n, &key->c_nSz, input, inOutIdx, inSz, h) < 0 ||
790 GetCaviumInt(&key->c_e, &key->c_eSz, input, inOutIdx, inSz, h) < 0 ||
791 GetCaviumInt(&key->c_d, &key->c_dSz, input, inOutIdx, inSz, h) < 0 ||
792 GetCaviumInt(&key->c_p, &key->c_pSz, input, inOutIdx, inSz, h) < 0 ||
793 GetCaviumInt(&key->c_q, &key->c_qSz, input, inOutIdx, inSz, h) < 0 ||
794 GetCaviumInt(&key->c_dP, &key->c_dP_Sz, input, inOutIdx, inSz, h) < 0 ||
795 GetCaviumInt(&key->c_dQ, &key->c_dQ_Sz, input, inOutIdx, inSz, h) < 0 ||
796 GetCaviumInt(&key->c_u, &key->c_uSz, input, inOutIdx, inSz, h) < 0 )
797 return ASN_RSA_KEY_E;
798
799 return 0;
800}
801
802
803#endif /* HAVE_CAVIUM */
804
805#ifndef HAVE_USER_RSA
806int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
807 word32 inSz)
808{
809 int version, length;
810
811#ifdef HAVE_CAVIUM
812 if (key->magic == WOLFSSL_RSA_CAVIUM_MAGIC)
813 return CaviumRsaPrivateKeyDecode(input, inOutIdx, key, inSz);
814#endif
815
816 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
817 return ASN_PARSE_E;
818
819 if (GetMyVersion(input, inOutIdx, &version) < 0)
820 return ASN_PARSE_E;
821
822 key->type = RSA_PRIVATE;
823
824 if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
825 GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
826 GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
827 GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
828 GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
829 GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
830 GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
831 GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
832
833 return 0;
834}
835#endif /* HAVE_USER_RSA */
836#endif /* NO_RSA */
837
838/* Remove PKCS8 header, move beginning of traditional to beginning of input */
839int ToTraditional(byte* input, word32 sz)
840{
841 word32 inOutIdx = 0, oid;
842 int version, length;
843
844 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
845 return ASN_PARSE_E;
846
847 if (GetMyVersion(input, &inOutIdx, &version) < 0)
848 return ASN_PARSE_E;
849
850 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
851 return ASN_PARSE_E;
852
853 if (input[inOutIdx] == ASN_OBJECT_ID) {
854 /* pkcs8 ecc uses slightly different format */
855 inOutIdx++; /* past id */
856 if (GetLength(input, &inOutIdx, &length, sz) < 0)
857 return ASN_PARSE_E;
858 inOutIdx += length; /* over sub id, key input will verify */
859 }
860
861 if (input[inOutIdx++] != ASN_OCTET_STRING)
862 return ASN_PARSE_E;
863
864 if (GetLength(input, &inOutIdx, &length, sz) < 0)
865 return ASN_PARSE_E;
866
867 XMEMMOVE(input, input + inOutIdx, length);
868
869 return length;
870}
871
872
873#ifndef NO_PWDBASED
874
875/* Check To see if PKCS version algo is supported, set id if it is return 0
876 < 0 on error */
877static int CheckAlgo(int first, int second, int* id, int* version)
878{
879 *id = ALGO_ID_E;
880 *version = PKCS5; /* default */
881
882 if (first == 1) {
883 switch (second) {
884 case 1:
885 *id = PBE_SHA1_RC4_128;
886 *version = PKCS12;
887 return 0;
888 case 3:
889 *id = PBE_SHA1_DES3;
890 *version = PKCS12;
891 return 0;
892 default:
893 return ALGO_ID_E;
894 }
895 }
896
897 if (first != PKCS5)
898 return ASN_INPUT_E; /* VERSION ERROR */
899
900 if (second == PBES2) {
901 *version = PKCS5v2;
902 return 0;
903 }
904
905 switch (second) {
906 case 3: /* see RFC 2898 for ids */
907 *id = PBE_MD5_DES;
908 return 0;
909 case 10:
910 *id = PBE_SHA1_DES;
911 return 0;
912 default:
913 return ALGO_ID_E;
914
915 }
916}
917
918
919/* Check To see if PKCS v2 algo is supported, set id if it is return 0
920 < 0 on error */
921static int CheckAlgoV2(int oid, int* id)
922{
923 switch (oid) {
924 case 69:
925 *id = PBE_SHA1_DES;
926 return 0;
927 case 652:
928 *id = PBE_SHA1_DES3;
929 return 0;
930 default:
931 return ALGO_ID_E;
932
933 }
934}
935
936
937/* Decrypt intput in place from parameters based on id */
938static int DecryptKey(const char* password, int passwordSz, byte* salt,
939 int saltSz, int iterations, int id, byte* input,
940 int length, int version, byte* cbcIv)
941{
942 int typeH;
943 int derivedLen;
944 int decryptionType;
945 int ret = 0;
946#ifdef WOLFSSL_SMALL_STACK
947 byte* key;
948#else
949 byte key[MAX_KEY_SIZE];
950#endif
951
952 (void)input;
953 (void)length;
954
955 switch (id) {
956 case PBE_MD5_DES:
957 typeH = MD5;
958 derivedLen = 16; /* may need iv for v1.5 */
959 decryptionType = DES_TYPE;
960 break;
961
962 case PBE_SHA1_DES:
963 typeH = SHA;
964 derivedLen = 16; /* may need iv for v1.5 */
965 decryptionType = DES_TYPE;
966 break;
967
968 case PBE_SHA1_DES3:
969 typeH = SHA;
970 derivedLen = 32; /* may need iv for v1.5 */
971 decryptionType = DES3_TYPE;
972 break;
973
974 case PBE_SHA1_RC4_128:
975 typeH = SHA;
976 derivedLen = 16;
977 decryptionType = RC4_TYPE;
978 break;
979
980 default:
981 return ALGO_ID_E;
982 }
983
984#ifdef WOLFSSL_SMALL_STACK
985 key = (byte*)XMALLOC(MAX_KEY_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
986 if (key == NULL)
987 return MEMORY_E;
988#endif
989
990 if (version == PKCS5v2)
991 ret = wc_PBKDF2(key, (byte*)password, passwordSz,
992 salt, saltSz, iterations, derivedLen, typeH);
993#ifndef NO_SHA
994 else if (version == PKCS5)
995 ret = wc_PBKDF1(key, (byte*)password, passwordSz,
996 salt, saltSz, iterations, derivedLen, typeH);
997#endif
998 else if (version == PKCS12) {
999 int i, idx = 0;
1000 byte unicodePasswd[MAX_UNICODE_SZ];
1001
1002 if ( (passwordSz * 2 + 2) > (int)sizeof(unicodePasswd)) {
1003#ifdef WOLFSSL_SMALL_STACK
1004 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1005#endif
1006 return UNICODE_SIZE_E;
1007 }
1008
1009 for (i = 0; i < passwordSz; i++) {
1010 unicodePasswd[idx++] = 0x00;
1011 unicodePasswd[idx++] = (byte)password[i];
1012 }
1013 /* add trailing NULL */
1014 unicodePasswd[idx++] = 0x00;
1015 unicodePasswd[idx++] = 0x00;
1016
1017 ret = wc_PKCS12_PBKDF(key, unicodePasswd, idx, salt, saltSz,
1018 iterations, derivedLen, typeH, 1);
1019 if (decryptionType != RC4_TYPE)
1020 ret += wc_PKCS12_PBKDF(cbcIv, unicodePasswd, idx, salt, saltSz,
1021 iterations, 8, typeH, 2);
1022 }
1023 else {
1024#ifdef WOLFSSL_SMALL_STACK
1025 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1026#endif
1027 return ALGO_ID_E;
1028 }
1029
1030 if (ret != 0) {
1031#ifdef WOLFSSL_SMALL_STACK
1032 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1033#endif
1034 return ret;
1035 }
1036
1037 switch (decryptionType) {
1038#ifndef NO_DES3
1039 case DES_TYPE:
1040 {
1041 Des dec;
1042 byte* desIv = key + 8;
1043
1044 if (version == PKCS5v2 || version == PKCS12)
1045 desIv = cbcIv;
1046
1047 ret = wc_Des_SetKey(&dec, key, desIv, DES_DECRYPTION);
1048 if (ret != 0) {
1049#ifdef WOLFSSL_SMALL_STACK
1050 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1051#endif
1052 return ret;
1053 }
1054
1055 wc_Des_CbcDecrypt(&dec, input, input, length);
1056 break;
1057 }
1058
1059 case DES3_TYPE:
1060 {
1061 Des3 dec;
1062 byte* desIv = key + 24;
1063
1064 if (version == PKCS5v2 || version == PKCS12)
1065 desIv = cbcIv;
1066 ret = wc_Des3_SetKey(&dec, key, desIv, DES_DECRYPTION);
1067 if (ret != 0) {
1068#ifdef WOLFSSL_SMALL_STACK
1069 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1070#endif
1071 return ret;
1072 }
1073 ret = wc_Des3_CbcDecrypt(&dec, input, input, length);
1074 if (ret != 0) {
1075#ifdef WOLFSSL_SMALL_STACK
1076 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1077#endif
1078 return ret;
1079 }
1080 break;
1081 }
1082#endif
1083#ifndef NO_RC4
1084 case RC4_TYPE:
1085 {
1086 Arc4 dec;
1087
1088 wc_Arc4SetKey(&dec, key, derivedLen);
1089 wc_Arc4Process(&dec, input, input, length);
1090 break;
1091 }
1092#endif
1093
1094 default:
1095#ifdef WOLFSSL_SMALL_STACK
1096 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1097#endif
1098 return ALGO_ID_E;
1099 }
1100
1101#ifdef WOLFSSL_SMALL_STACK
1102 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1103#endif
1104
1105 return 0;
1106}
1107
1108
1109/* Remove Encrypted PKCS8 header, move beginning of traditional to beginning
1110 of input */
1111int ToTraditionalEnc(byte* input, word32 sz,const char* password,int passwordSz)
1112{
1113 word32 inOutIdx = 0, oid;
1114 int first, second, length, version, saltSz, id;
1115 int iterations = 0;
1116#ifdef WOLFSSL_SMALL_STACK
1117 byte* salt = NULL;
1118 byte* cbcIv = NULL;
1119#else
1120 byte salt[MAX_SALT_SIZE];
1121 byte cbcIv[MAX_IV_SIZE];
1122#endif
1123
1124 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
1125 return ASN_PARSE_E;
1126
1127 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
1128 return ASN_PARSE_E;
1129
1130 first = input[inOutIdx - 2]; /* PKCS version alwyas 2nd to last byte */
1131 second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
1132
1133 if (CheckAlgo(first, second, &id, &version) < 0)
1134 return ASN_INPUT_E; /* Algo ID error */
1135
1136 if (version == PKCS5v2) {
1137
1138 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
1139 return ASN_PARSE_E;
1140
1141 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
1142 return ASN_PARSE_E;
1143
1144 if (oid != PBKDF2_OID)
1145 return ASN_PARSE_E;
1146 }
1147
1148 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
1149 return ASN_PARSE_E;
1150
1151 if (input[inOutIdx++] != ASN_OCTET_STRING)
1152 return ASN_PARSE_E;
1153
1154 if (GetLength(input, &inOutIdx, &saltSz, sz) < 0)
1155 return ASN_PARSE_E;
1156
1157 if (saltSz > MAX_SALT_SIZE)
1158 return ASN_PARSE_E;
1159
1160#ifdef WOLFSSL_SMALL_STACK
1161 salt = (byte*)XMALLOC(MAX_SALT_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1162 if (salt == NULL)
1163 return MEMORY_E;
1164#endif
1165
1166 XMEMCPY(salt, &input[inOutIdx], saltSz);
1167 inOutIdx += saltSz;
1168
1169 if (GetShortInt(input, &inOutIdx, &iterations) < 0) {
1170#ifdef WOLFSSL_SMALL_STACK
1171 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1172#endif
1173 return ASN_PARSE_E;
1174 }
1175
1176#ifdef WOLFSSL_SMALL_STACK
1177 cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1178 if (cbcIv == NULL) {
1179 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1180 return MEMORY_E;
1181 }
1182#endif
1183
1184 if (version == PKCS5v2) {
1185 /* get encryption algo */
1186 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0) {
1187#ifdef WOLFSSL_SMALL_STACK
1188 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1189 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1190#endif
1191 return ASN_PARSE_E;
1192 }
1193
1194 if (CheckAlgoV2(oid, &id) < 0) {
1195#ifdef WOLFSSL_SMALL_STACK
1196 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1197 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1198#endif
1199 return ASN_PARSE_E; /* PKCS v2 algo id error */
1200 }
1201
1202 if (input[inOutIdx++] != ASN_OCTET_STRING) {
1203#ifdef WOLFSSL_SMALL_STACK
1204 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1205 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1206#endif
1207 return ASN_PARSE_E;
1208 }
1209
1210 if (GetLength(input, &inOutIdx, &length, sz) < 0) {
1211#ifdef WOLFSSL_SMALL_STACK
1212 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1213 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1214#endif
1215 return ASN_PARSE_E;
1216 }
1217
1218 XMEMCPY(cbcIv, &input[inOutIdx], length);
1219 inOutIdx += length;
1220 }
1221
1222 if (input[inOutIdx++] != ASN_OCTET_STRING) {
1223#ifdef WOLFSSL_SMALL_STACK
1224 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1225 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1226#endif
1227 return ASN_PARSE_E;
1228 }
1229
1230 if (GetLength(input, &inOutIdx, &length, sz) < 0) {
1231#ifdef WOLFSSL_SMALL_STACK
1232 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1233 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1234#endif
1235 return ASN_PARSE_E;
1236 }
1237
1238 if (DecryptKey(password, passwordSz, salt, saltSz, iterations, id,
1239 input + inOutIdx, length, version, cbcIv) < 0) {
1240#ifdef WOLFSSL_SMALL_STACK
1241 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1242 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1243#endif
1244 return ASN_INPUT_E; /* decrypt failure */
1245 }
1246
1247#ifdef WOLFSSL_SMALL_STACK
1248 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1249 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1250#endif
1251
1252 XMEMMOVE(input, input + inOutIdx, length);
1253 return ToTraditional(input, length);
1254}
1255
1256#endif /* NO_PWDBASED */
1257
1258#ifndef NO_RSA
1259
1260#ifndef HAVE_USER_RSA
1261int wc_RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
1262 word32 inSz)
1263{
1264 int length;
1265
1266 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1267 return ASN_PARSE_E;
1268
1269 key->type = RSA_PUBLIC;
1270
1271#if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
1272 {
1273 byte b = input[*inOutIdx];
1274 if (b != ASN_INTEGER) {
1275 /* not from decoded cert, will have algo id, skip past */
1276 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1277 return ASN_PARSE_E;
1278
1279 b = input[(*inOutIdx)++];
1280 if (b != ASN_OBJECT_ID)
1281 return ASN_OBJECT_ID_E;
1282
1283 if (GetLength(input, inOutIdx, &length, inSz) < 0)
1284 return ASN_PARSE_E;
1285
1286 *inOutIdx += length; /* skip past */
1287
1288 /* could have NULL tag and 0 terminator, but may not */
1289 b = input[(*inOutIdx)++];
1290
1291 if (b == ASN_TAG_NULL) {
1292 b = input[(*inOutIdx)++];
1293 if (b != 0)
1294 return ASN_EXPECT_0_E;
1295 }
1296 else
1297 /* go back, didn't have it */
1298 (*inOutIdx)--;
1299
1300 /* should have bit tag length and seq next */
1301 b = input[(*inOutIdx)++];
1302 if (b != ASN_BIT_STRING)
1303 return ASN_BITSTR_E;
1304
1305 if (GetLength(input, inOutIdx, &length, inSz) < 0)
1306 return ASN_PARSE_E;
1307
1308 /* could have 0 */
1309 b = input[(*inOutIdx)++];
1310 if (b != 0)
1311 (*inOutIdx)--;
1312
1313 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1314 return ASN_PARSE_E;
1315 } /* end if */
1316 } /* openssl var block */
1317#endif /* OPENSSL_EXTRA */
1318
1319 if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
1320 GetInt(&key->e, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
1321
1322 return 0;
1323}
1324
1325/* import RSA public key elements (n, e) into RsaKey structure (key) */
1326int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e,
1327 word32 eSz, RsaKey* key)
1328{
1329 if (n == NULL || e == NULL || key == NULL)
1330 return BAD_FUNC_ARG;
1331
1332 key->type = RSA_PUBLIC;
1333
1334 if (mp_init(&key->n) != MP_OKAY)
1335 return MP_INIT_E;
1336
1337 if (mp_read_unsigned_bin(&key->n, n, nSz) != 0) {
1338 mp_clear(&key->n);
1339 return ASN_GETINT_E;
1340 }
1341
1342 if (mp_init(&key->e) != MP_OKAY) {
1343 mp_clear(&key->n);
1344 return MP_INIT_E;
1345 }
1346
1347 if (mp_read_unsigned_bin(&key->e, e, eSz) != 0) {
1348 mp_clear(&key->n);
1349 mp_clear(&key->e);
1350 return ASN_GETINT_E;
1351 }
1352
1353 return 0;
1354}
1355#endif /* HAVE_USER_RSA */
1356#endif
1357
1358#ifndef NO_DH
1359
1360int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
1361{
1362 int length;
1363
1364 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1365 return ASN_PARSE_E;
1366
1367 if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
1368 GetInt(&key->g, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
1369
1370 return 0;
1371}
1372
1373
1374int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
1375 byte* g, word32* gInOutSz)
1376{
1377 word32 i = 0;
1378 byte b;
1379 int length;
1380
1381 if (GetSequence(input, &i, &length, inSz) < 0)
1382 return ASN_PARSE_E;
1383
1384 b = input[i++];
1385 if (b != ASN_INTEGER)
1386 return ASN_PARSE_E;
1387
1388 if (GetLength(input, &i, &length, inSz) < 0)
1389 return ASN_PARSE_E;
1390
1391 if ( (b = input[i++]) == 0x00)
1392 length--;
1393 else
1394 i--;
1395
1396 if (length <= (int)*pInOutSz) {
1397 XMEMCPY(p, &input[i], length);
1398 *pInOutSz = length;
1399 }
1400 else
1401 return BUFFER_E;
1402
1403 i += length;
1404
1405 b = input[i++];
1406 if (b != ASN_INTEGER)
1407 return ASN_PARSE_E;
1408
1409 if (GetLength(input, &i, &length, inSz) < 0)
1410 return ASN_PARSE_E;
1411
1412 if (length <= (int)*gInOutSz) {
1413 XMEMCPY(g, &input[i], length);
1414 *gInOutSz = length;
1415 }
1416 else
1417 return BUFFER_E;
1418
1419 return 0;
1420}
1421
1422#endif /* NO_DH */
1423
1424
1425#ifndef NO_DSA
1426
1427int DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
1428 word32 inSz)
1429{
1430 int length;
1431
1432 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1433 return ASN_PARSE_E;
1434
1435 if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
1436 GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
1437 GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
1438 GetInt(&key->y, input, inOutIdx, inSz) < 0 )
1439 return ASN_DH_KEY_E;
1440
1441 key->type = DSA_PUBLIC;
1442 return 0;
1443}
1444
1445
1446int DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
1447 word32 inSz)
1448{
1449 int length, version;
1450
1451 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1452 return ASN_PARSE_E;
1453
1454 if (GetMyVersion(input, inOutIdx, &version) < 0)
1455 return ASN_PARSE_E;
1456
1457 if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
1458 GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
1459 GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
1460 GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
1461 GetInt(&key->x, input, inOutIdx, inSz) < 0 )
1462 return ASN_DH_KEY_E;
1463
1464 key->type = DSA_PRIVATE;
1465 return 0;
1466}
1467
1468static mp_int* GetDsaInt(DsaKey* key, int idx)
1469{
1470 if (idx == 0)
1471 return &key->p;
1472 if (idx == 1)
1473 return &key->q;
1474 if (idx == 2)
1475 return &key->g;
1476 if (idx == 3)
1477 return &key->y;
1478 if (idx == 4)
1479 return &key->x;
1480
1481 return NULL;
1482}
1483
1484/* Release Tmp DSA resources */
1485static INLINE void FreeTmpDsas(byte** tmps)
1486{
1487 int i;
1488
1489 for (i = 0; i < DSA_INTS; i++)
1490 XFREE(tmps[i], NULL, DYNAMIC_TYPE_DSA);
1491}
1492
1493/* Convert DsaKey key to DER format, write to output (inLen), return bytes
1494 written */
1495int wc_DsaKeyToDer(DsaKey* key, byte* output, word32 inLen)
1496{
1497 word32 seqSz, verSz, rawLen, intTotalLen = 0;
1498 word32 sizes[DSA_INTS];
1499 int i, j, outLen, ret = 0, lbit;
1500
1501 byte seq[MAX_SEQ_SZ];
1502 byte ver[MAX_VERSION_SZ];
1503 byte* tmps[DSA_INTS];
1504
1505 if (!key || !output)
1506 return BAD_FUNC_ARG;
1507
1508 if (key->type != DSA_PRIVATE)
1509 return BAD_FUNC_ARG;
1510
1511 for (i = 0; i < DSA_INTS; i++)
1512 tmps[i] = NULL;
1513
1514 /* write all big ints from key to DER tmps */
1515 for (i = 0; i < DSA_INTS; i++) {
1516 mp_int* keyInt = GetDsaInt(key, i);
1517
1518 /* leading zero */
1519 if ((mp_count_bits(keyInt) & 7) == 0 || mp_iszero(keyInt) == MP_YES)
1520 lbit = 1;
1521 else
1522 lbit = 0;
1523
1524 rawLen = mp_unsigned_bin_size(keyInt) + lbit;
1525
1526 tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, NULL, DYNAMIC_TYPE_DSA);
1527 if (tmps[i] == NULL) {
1528 ret = MEMORY_E;
1529 break;
1530 }
1531
1532 tmps[i][0] = ASN_INTEGER;
1533 sizes[i] = SetLength(rawLen, tmps[i] + 1) + 1 + lbit; /* tag & lbit */
1534
1535 if (sizes[i] <= MAX_SEQ_SZ) {
1536 int err;
1537
1538 /* leading zero */
1539 if (lbit)
1540 tmps[i][sizes[i]-1] = 0x00;
1541
1542 err = mp_to_unsigned_bin(keyInt, tmps[i] + sizes[i]);
1543 if (err == MP_OKAY) {
1544 sizes[i] += (rawLen-lbit); /* lbit included in rawLen */
1545 intTotalLen += sizes[i];
1546 }
1547 else {
1548 ret = err;
1549 break;
1550 }
1551 }
1552 else {
1553 ret = ASN_INPUT_E;
1554 break;
1555 }
1556 }
1557
1558 if (ret != 0) {
1559 FreeTmpDsas(tmps);
1560 return ret;
1561 }
1562
1563 /* make headers */
1564 verSz = SetMyVersion(0, ver, FALSE);
1565 seqSz = SetSequence(verSz + intTotalLen, seq);
1566
1567 outLen = seqSz + verSz + intTotalLen;
1568 if (outLen > (int)inLen)
1569 return BAD_FUNC_ARG;
1570
1571 /* write to output */
1572 XMEMCPY(output, seq, seqSz);
1573 j = seqSz;
1574 XMEMCPY(output + j, ver, verSz);
1575 j += verSz;
1576
1577 for (i = 0; i < DSA_INTS; i++) {
1578 XMEMCPY(output + j, tmps[i], sizes[i]);
1579 j += sizes[i];
1580 }
1581 FreeTmpDsas(tmps);
1582
1583 return outLen;
1584}
1585
1586#endif /* NO_DSA */
1587
1588
1589void InitDecodedCert(DecodedCert* cert, byte* source, word32 inSz, void* heap)
1590{
1591 cert->publicKey = 0;
1592 cert->pubKeySize = 0;
1593 cert->pubKeyStored = 0;
1594 cert->version = 0;
1595 cert->signature = 0;
1596 cert->subjectCN = 0;
1597 cert->subjectCNLen = 0;
1598 cert->subjectCNEnc = CTC_UTF8;
1599 cert->subjectCNStored = 0;
1600 cert->weOwnAltNames = 0;
1601 cert->altNames = NULL;
1602#ifndef IGNORE_NAME_CONSTRAINTS
1603 cert->altEmailNames = NULL;
1604 cert->permittedNames = NULL;
1605 cert->excludedNames = NULL;
1606#endif /* IGNORE_NAME_CONSTRAINTS */
1607 cert->issuer[0] = '\0';
1608 cert->subject[0] = '\0';
1609 cert->source = source; /* don't own */
1610 cert->srcIdx = 0;
1611 cert->maxIdx = inSz; /* can't go over this index */
1612 cert->heap = heap;
1613 XMEMSET(cert->serial, 0, EXTERNAL_SERIAL_SIZE);
1614 cert->serialSz = 0;
1615 cert->extensions = 0;
1616 cert->extensionsSz = 0;
1617 cert->extensionsIdx = 0;
1618 cert->extAuthInfo = NULL;
1619 cert->extAuthInfoSz = 0;
1620 cert->extCrlInfo = NULL;
1621 cert->extCrlInfoSz = 0;
1622 XMEMSET(cert->extSubjKeyId, 0, KEYID_SIZE);
1623 cert->extSubjKeyIdSet = 0;
1624 XMEMSET(cert->extAuthKeyId, 0, KEYID_SIZE);
1625 cert->extAuthKeyIdSet = 0;
1626 cert->extKeyUsageSet = 0;
1627 cert->extKeyUsage = 0;
1628 cert->extExtKeyUsageSet = 0;
1629 cert->extExtKeyUsage = 0;
1630 cert->isCA = 0;
1631#ifdef HAVE_PKCS7
1632 cert->issuerRaw = NULL;
1633 cert->issuerRawLen = 0;
1634#endif
1635#ifdef WOLFSSL_CERT_GEN
1636 cert->subjectSN = 0;
1637 cert->subjectSNLen = 0;
1638 cert->subjectSNEnc = CTC_UTF8;
1639 cert->subjectC = 0;
1640 cert->subjectCLen = 0;
1641 cert->subjectCEnc = CTC_PRINTABLE;
1642 cert->subjectL = 0;
1643 cert->subjectLLen = 0;
1644 cert->subjectLEnc = CTC_UTF8;
1645 cert->subjectST = 0;
1646 cert->subjectSTLen = 0;
1647 cert->subjectSTEnc = CTC_UTF8;
1648 cert->subjectO = 0;
1649 cert->subjectOLen = 0;
1650 cert->subjectOEnc = CTC_UTF8;
1651 cert->subjectOU = 0;
1652 cert->subjectOULen = 0;
1653 cert->subjectOUEnc = CTC_UTF8;
1654 cert->subjectEmail = 0;
1655 cert->subjectEmailLen = 0;
1656#endif /* WOLFSSL_CERT_GEN */
1657 cert->beforeDate = NULL;
1658 cert->beforeDateLen = 0;
1659 cert->afterDate = NULL;
1660 cert->afterDateLen = 0;
1661#ifdef OPENSSL_EXTRA
1662 XMEMSET(&cert->issuerName, 0, sizeof(DecodedName));
1663 XMEMSET(&cert->subjectName, 0, sizeof(DecodedName));
1664 cert->extBasicConstSet = 0;
1665 cert->extBasicConstCrit = 0;
1666 cert->extBasicConstPlSet = 0;
1667 cert->pathLength = 0;
1668 cert->extSubjAltNameSet = 0;
1669 cert->extSubjAltNameCrit = 0;
1670 cert->extAuthKeyIdCrit = 0;
1671 cert->extSubjKeyIdCrit = 0;
1672 cert->extKeyUsageCrit = 0;
1673 cert->extExtKeyUsageCrit = 0;
1674 cert->extExtKeyUsageSrc = NULL;
1675 cert->extExtKeyUsageSz = 0;
1676 cert->extExtKeyUsageCount = 0;
1677 cert->extAuthKeyIdSrc = NULL;
1678 cert->extAuthKeyIdSz = 0;
1679 cert->extSubjKeyIdSrc = NULL;
1680 cert->extSubjKeyIdSz = 0;
1681#endif /* OPENSSL_EXTRA */
1682#if defined(OPENSSL_EXTRA) || !defined(IGNORE_NAME_CONSTRAINTS)
1683 cert->extNameConstraintSet = 0;
1684#endif /* OPENSSL_EXTRA || !IGNORE_NAME_CONSTRAINTS */
1685#ifdef HAVE_ECC
1686 cert->pkCurveOID = 0;
1687#endif /* HAVE_ECC */
1688#ifdef WOLFSSL_SEP
1689 cert->deviceTypeSz = 0;
1690 cert->deviceType = NULL;
1691 cert->hwTypeSz = 0;
1692 cert->hwType = NULL;
1693 cert->hwSerialNumSz = 0;
1694 cert->hwSerialNum = NULL;
1695 #ifdef OPENSSL_EXTRA
1696 cert->extCertPolicySet = 0;
1697 cert->extCertPolicyCrit = 0;
1698 #endif /* OPENSSL_EXTRA */
1699#endif /* WOLFSSL_SEP */
1700#ifdef WOLFSSL_CERT_EXT
1701 XMEMSET(cert->extCertPolicies, 0, MAX_CERTPOL_NB*MAX_CERTPOL_SZ);
1702 cert->extCertPoliciesNb = 0;
1703#endif
1704}
1705
1706
1707void FreeAltNames(DNS_entry* altNames, void* heap)
1708{
1709 (void)heap;
1710
1711 while (altNames) {
1712 DNS_entry* tmp = altNames->next;
1713
1714 XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
1715 XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME);
1716 altNames = tmp;
1717 }
1718}
1719
1720#ifndef IGNORE_NAME_CONSTRAINTS
1721
1722void FreeNameSubtrees(Base_entry* names, void* heap)
1723{
1724 (void)heap;
1725
1726 while (names) {
1727 Base_entry* tmp = names->next;
1728
1729 XFREE(names->name, heap, DYNAMIC_TYPE_ALTNAME);
1730 XFREE(names, heap, DYNAMIC_TYPE_ALTNAME);
1731 names = tmp;
1732 }
1733}
1734
1735#endif /* IGNORE_NAME_CONSTRAINTS */
1736
1737void FreeDecodedCert(DecodedCert* cert)
1738{
1739 if (cert->subjectCNStored == 1)
1740 XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
1741 if (cert->pubKeyStored == 1)
1742 XFREE(cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
1743 if (cert->weOwnAltNames && cert->altNames)
1744 FreeAltNames(cert->altNames, cert->heap);
1745#ifndef IGNORE_NAME_CONSTRAINTS
1746 if (cert->altEmailNames)
1747 FreeAltNames(cert->altEmailNames, cert->heap);
1748 if (cert->permittedNames)
1749 FreeNameSubtrees(cert->permittedNames, cert->heap);
1750 if (cert->excludedNames)
1751 FreeNameSubtrees(cert->excludedNames, cert->heap);
1752#endif /* IGNORE_NAME_CONSTRAINTS */
1753#ifdef WOLFSSL_SEP
1754 XFREE(cert->deviceType, cert->heap, 0);
1755 XFREE(cert->hwType, cert->heap, 0);
1756 XFREE(cert->hwSerialNum, cert->heap, 0);
1757#endif /* WOLFSSL_SEP */
1758#ifdef OPENSSL_EXTRA
1759 if (cert->issuerName.fullName != NULL)
1760 XFREE(cert->issuerName.fullName, NULL, DYNAMIC_TYPE_X509);
1761 if (cert->subjectName.fullName != NULL)
1762 XFREE(cert->subjectName.fullName, NULL, DYNAMIC_TYPE_X509);
1763#endif /* OPENSSL_EXTRA */
1764}
1765
1766
1767static int GetCertHeader(DecodedCert* cert)
1768{
1769 int ret = 0, len;
1770 byte serialTmp[EXTERNAL_SERIAL_SIZE];
1771#if defined(WOLFSSL_SMALL_STACK) && defined(USE_FAST_MATH)
1772 mp_int* mpi = NULL;
1773#else
1774 mp_int stack_mpi;
1775 mp_int* mpi = &stack_mpi;
1776#endif
1777
1778 if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
1779 return ASN_PARSE_E;
1780
1781 cert->certBegin = cert->srcIdx;
1782
1783 if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
1784 return ASN_PARSE_E;
1785 cert->sigIndex = len + cert->srcIdx;
1786
1787 if (GetExplicitVersion(cert->source, &cert->srcIdx, &cert->version) < 0)
1788 return ASN_PARSE_E;
1789
1790#if defined(WOLFSSL_SMALL_STACK) && defined(USE_FAST_MATH)
1791 mpi = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_TMP_BUFFER);
1792 if (mpi == NULL)
1793 return MEMORY_E;
1794#endif
1795
1796 if (GetInt(mpi, cert->source, &cert->srcIdx, cert->maxIdx) < 0) {
1797#if defined(WOLFSSL_SMALL_STACK) && defined(USE_FAST_MATH)
1798 XFREE(mpi, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1799#endif
1800 return ASN_PARSE_E;
1801 }
1802
1803 len = mp_unsigned_bin_size(mpi);
1804 if (len < (int)sizeof(serialTmp)) {
1805 if ( (ret = mp_to_unsigned_bin(mpi, serialTmp)) == MP_OKAY) {
1806 XMEMCPY(cert->serial, serialTmp, len);
1807 cert->serialSz = len;
1808 }
1809 }
1810 mp_clear(mpi);
1811
1812#if defined(WOLFSSL_SMALL_STACK) && defined(USE_FAST_MATH)
1813 XFREE(mpi, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1814#endif
1815
1816 return ret;
1817}
1818
1819#if !defined(NO_RSA)
1820/* Store Rsa Key, may save later, Dsa could use in future */
1821static int StoreRsaKey(DecodedCert* cert)
1822{
1823 int length;
1824 word32 recvd = cert->srcIdx;
1825
1826 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1827 return ASN_PARSE_E;
1828
1829 recvd = cert->srcIdx - recvd;
1830 length += recvd;
1831
1832 while (recvd--)
1833 cert->srcIdx--;
1834
1835 cert->pubKeySize = length;
1836 cert->publicKey = cert->source + cert->srcIdx;
1837 cert->srcIdx += length;
1838
1839 return 0;
1840}
1841#endif
1842
1843
1844#ifdef HAVE_ECC
1845
1846 /* return 0 on sucess if the ECC curve oid sum is supported */
1847 static int CheckCurve(word32 oid)
1848 {
1849 int ret = 0;
1850
1851 switch (oid) {
1852#if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC160)
1853 case ECC_160R1:
1854#endif
1855#if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC192)
1856 case ECC_192R1:
1857#endif
1858#if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC224)
1859 case ECC_224R1:
1860#endif
1861#if defined(HAVE_ALL_CURVES) || !defined(NO_ECC256)
1862 case ECC_256R1:
1863#endif
1864#if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC384)
1865 case ECC_384R1:
1866#endif
1867#if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC521)
1868 case ECC_521R1:
1869#endif
1870 break;
1871
1872 default:
1873 ret = ALGO_ID_E;
1874 }
1875
1876 return ret;
1877 }
1878
1879#endif /* HAVE_ECC */
1880
1881
1882static int GetKey(DecodedCert* cert)
1883{
1884 int length;
1885#ifdef HAVE_NTRU
1886 int tmpIdx = cert->srcIdx;
1887#endif
1888
1889 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1890 return ASN_PARSE_E;
1891
1892 if (GetAlgoId(cert->source, &cert->srcIdx, &cert->keyOID, cert->maxIdx) < 0)
1893 return ASN_PARSE_E;
1894
1895 switch (cert->keyOID) {
1896 #ifndef NO_RSA
1897 case RSAk:
1898 {
1899 byte b = cert->source[cert->srcIdx++];
1900 if (b != ASN_BIT_STRING)
1901 return ASN_BITSTR_E;
1902
1903 if (GetLength(cert->source,&cert->srcIdx,&length,cert->maxIdx) < 0)
1904 return ASN_PARSE_E;
1905 b = cert->source[cert->srcIdx++];
1906 if (b != 0x00)
1907 return ASN_EXPECT_0_E;
1908
1909 return StoreRsaKey(cert);
1910 }
1911
1912 #endif /* NO_RSA */
1913 #ifdef HAVE_NTRU
1914 case NTRUk:
1915 {
1916 const byte* key = &cert->source[tmpIdx];
1917 byte* next = (byte*)key;
1918 word16 keyLen;
1919 word32 rc;
1920 word32 remaining = cert->maxIdx - cert->srcIdx;
1921#ifdef WOLFSSL_SMALL_STACK
1922 byte* keyBlob = NULL;
1923#else
1924 byte keyBlob[MAX_NTRU_KEY_SZ];
1925#endif
1926 rc = ntru_crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key,
1927 &keyLen, NULL, &next, &remaining);
1928 if (rc != NTRU_OK)
1929 return ASN_NTRU_KEY_E;
1930 if (keyLen > MAX_NTRU_KEY_SZ)
1931 return ASN_NTRU_KEY_E;
1932
1933#ifdef WOLFSSL_SMALL_STACK
1934 keyBlob = (byte*)XMALLOC(MAX_NTRU_KEY_SZ, NULL,
1935 DYNAMIC_TYPE_TMP_BUFFER);
1936 if (keyBlob == NULL)
1937 return MEMORY_E;
1938#endif
1939
1940 rc = ntru_crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key,
1941 &keyLen, keyBlob, &next, &remaining);
1942 if (rc != NTRU_OK) {
1943#ifdef WOLFSSL_SMALL_STACK
1944 XFREE(keyBlob, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1945#endif
1946 return ASN_NTRU_KEY_E;
1947 }
1948
1949 if ( (next - key) < 0) {
1950#ifdef WOLFSSL_SMALL_STACK
1951 XFREE(keyBlob, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1952#endif
1953 return ASN_NTRU_KEY_E;
1954 }
1955
1956 cert->srcIdx = tmpIdx + (int)(next - key);
1957
1958 cert->publicKey = (byte*) XMALLOC(keyLen, cert->heap,
1959 DYNAMIC_TYPE_PUBLIC_KEY);
1960 if (cert->publicKey == NULL) {
1961#ifdef WOLFSSL_SMALL_STACK
1962 XFREE(keyBlob, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1963#endif
1964 return MEMORY_E;
1965 }
1966 XMEMCPY(cert->publicKey, keyBlob, keyLen);
1967 cert->pubKeyStored = 1;
1968 cert->pubKeySize = keyLen;
1969
1970#ifdef WOLFSSL_SMALL_STACK
1971 XFREE(keyBlob, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1972#endif
1973
1974 return 0;
1975 }
1976 #endif /* HAVE_NTRU */
1977 #ifdef HAVE_ECC
1978 case ECDSAk:
1979 {
1980 int oidSz = 0;
1981 byte b = cert->source[cert->srcIdx++];
1982
1983 if (b != ASN_OBJECT_ID)
1984 return ASN_OBJECT_ID_E;
1985
1986 if (GetLength(cert->source,&cert->srcIdx,&oidSz,cert->maxIdx) < 0)
1987 return ASN_PARSE_E;
1988
1989 while(oidSz--)
1990 cert->pkCurveOID += cert->source[cert->srcIdx++];
1991
1992 if (CheckCurve(cert->pkCurveOID) < 0)
1993 return ECC_CURVE_OID_E;
1994
1995 /* key header */
1996 b = cert->source[cert->srcIdx++];
1997 if (b != ASN_BIT_STRING)
1998 return ASN_BITSTR_E;
1999
2000 if (GetLength(cert->source,&cert->srcIdx,&length,cert->maxIdx) < 0)
2001 return ASN_PARSE_E;
2002 b = cert->source[cert->srcIdx++];
2003 if (b != 0x00)
2004 return ASN_EXPECT_0_E;
2005
2006 /* actual key, use length - 1 since ate preceding 0 */
2007 length -= 1;
2008
2009 cert->publicKey = (byte*) XMALLOC(length, cert->heap,
2010 DYNAMIC_TYPE_PUBLIC_KEY);
2011 if (cert->publicKey == NULL)
2012 return MEMORY_E;
2013 XMEMCPY(cert->publicKey, &cert->source[cert->srcIdx], length);
2014 cert->pubKeyStored = 1;
2015 cert->pubKeySize = length;
2016
2017 cert->srcIdx += length;
2018
2019 return 0;
2020 }
2021 #endif /* HAVE_ECC */
2022 default:
2023 return ASN_UNKNOWN_OID_E;
2024 }
2025}
2026
2027
2028/* process NAME, either issuer or subject */
2029static int GetName(DecodedCert* cert, int nameType)
2030{
2031 int length; /* length of all distinguished names */
2032 int dummy;
2033 int ret;
2034 char* full;
2035 byte* hash;
2036 word32 idx;
2037 #ifdef OPENSSL_EXTRA
2038 DecodedName* dName =
2039 (nameType == ISSUER) ? &cert->issuerName : &cert->subjectName;
2040 #endif /* OPENSSL_EXTRA */
2041
2042 WOLFSSL_MSG("Getting Cert Name");
2043
2044 if (nameType == ISSUER) {
2045 full = cert->issuer;
2046 hash = cert->issuerHash;
2047 }
2048 else {
2049 full = cert->subject;
2050 hash = cert->subjectHash;
2051 }
2052
2053 if (cert->source[cert->srcIdx] == ASN_OBJECT_ID) {
2054 WOLFSSL_MSG("Trying optional prefix...");
2055
2056 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
2057 return ASN_PARSE_E;
2058
2059 cert->srcIdx += length;
2060 WOLFSSL_MSG("Got optional prefix");
2061 }
2062
2063 /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
2064 * calculated over the entire DER encoding of the Name field, including
2065 * the tag and length. */
2066 idx = cert->srcIdx;
2067 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
2068 return ASN_PARSE_E;
2069
2070#ifdef NO_SHA
2071 ret = wc_Sha256Hash(&cert->source[idx], length + cert->srcIdx - idx, hash);
2072#else
2073 ret = wc_ShaHash(&cert->source[idx], length + cert->srcIdx - idx, hash);
2074#endif
2075 if (ret != 0)
2076 return ret;
2077
2078 length += cert->srcIdx;
2079 idx = 0;
2080
2081#ifdef HAVE_PKCS7
2082 /* store pointer to raw issuer */
2083 if (nameType == ISSUER) {
2084 cert->issuerRaw = &cert->source[cert->srcIdx];
2085 cert->issuerRawLen = length - cert->srcIdx;
2086 }
2087#endif
2088#ifndef IGNORE_NAME_CONSTRAINTS
2089 if (nameType == SUBJECT) {
2090 cert->subjectRaw = &cert->source[cert->srcIdx];
2091 cert->subjectRawLen = length - cert->srcIdx;
2092 }
2093#endif
2094
2095 while (cert->srcIdx < (word32)length) {
2096 byte b;
2097 byte joint[2];
2098 byte tooBig = FALSE;
2099 int oidSz;
2100
2101 if (GetSet(cert->source, &cert->srcIdx, &dummy, cert->maxIdx) < 0) {
2102 WOLFSSL_MSG("Cert name lacks set header, trying sequence");
2103 }
2104
2105 if (GetSequence(cert->source, &cert->srcIdx, &dummy, cert->maxIdx) < 0)
2106 return ASN_PARSE_E;
2107
2108 b = cert->source[cert->srcIdx++];
2109 if (b != ASN_OBJECT_ID)
2110 return ASN_OBJECT_ID_E;
2111
2112 if (GetLength(cert->source, &cert->srcIdx, &oidSz, cert->maxIdx) < 0)
2113 return ASN_PARSE_E;
2114
2115 XMEMCPY(joint, &cert->source[cert->srcIdx], sizeof(joint));
2116
2117 /* v1 name types */
2118 if (joint[0] == 0x55 && joint[1] == 0x04) {
2119 byte id;
2120 byte copy = FALSE;
2121 int strLen;
2122
2123 cert->srcIdx += 2;
2124 id = cert->source[cert->srcIdx++];
2125 b = cert->source[cert->srcIdx++]; /* encoding */
2126
2127 if (GetLength(cert->source, &cert->srcIdx, &strLen,
2128 cert->maxIdx) < 0)
2129 return ASN_PARSE_E;
2130
2131 if ( (strLen + 14) > (int)(ASN_NAME_MAX - idx)) {
2132 /* include biggest pre fix header too 4 = "/serialNumber=" */
2133 WOLFSSL_MSG("ASN Name too big, skipping");
2134 tooBig = TRUE;
2135 }
2136
2137 if (id == ASN_COMMON_NAME) {
2138 if (nameType == SUBJECT) {
2139 cert->subjectCN = (char *)&cert->source[cert->srcIdx];
2140 cert->subjectCNLen = strLen;
2141 cert->subjectCNEnc = b;
2142 }
2143
2144 if (!tooBig) {
2145 XMEMCPY(&full[idx], "/CN=", 4);
2146 idx += 4;
2147 copy = TRUE;
2148 }
2149 #ifdef OPENSSL_EXTRA
2150 dName->cnIdx = cert->srcIdx;
2151 dName->cnLen = strLen;
2152 #endif /* OPENSSL_EXTRA */
2153 }
2154 else if (id == ASN_SUR_NAME) {
2155 if (!tooBig) {
2156 XMEMCPY(&full[idx], "/SN=", 4);
2157 idx += 4;
2158 copy = TRUE;
2159 }
2160 #ifdef WOLFSSL_CERT_GEN
2161 if (nameType == SUBJECT) {
2162 cert->subjectSN = (char*)&cert->source[cert->srcIdx];
2163 cert->subjectSNLen = strLen;
2164 cert->subjectSNEnc = b;
2165 }
2166 #endif /* WOLFSSL_CERT_GEN */
2167 #ifdef OPENSSL_EXTRA
2168 dName->snIdx = cert->srcIdx;
2169 dName->snLen = strLen;
2170 #endif /* OPENSSL_EXTRA */
2171 }
2172 else if (id == ASN_COUNTRY_NAME) {
2173 if (!tooBig) {
2174 XMEMCPY(&full[idx], "/C=", 3);
2175 idx += 3;
2176 copy = TRUE;
2177 }
2178 #ifdef WOLFSSL_CERT_GEN
2179 if (nameType == SUBJECT) {
2180 cert->subjectC = (char*)&cert->source[cert->srcIdx];
2181 cert->subjectCLen = strLen;
2182 cert->subjectCEnc = b;
2183 }
2184 #endif /* WOLFSSL_CERT_GEN */
2185 #ifdef OPENSSL_EXTRA
2186 dName->cIdx = cert->srcIdx;
2187 dName->cLen = strLen;
2188 #endif /* OPENSSL_EXTRA */
2189 }
2190 else if (id == ASN_LOCALITY_NAME) {
2191 if (!tooBig) {
2192 XMEMCPY(&full[idx], "/L=", 3);
2193 idx += 3;
2194 copy = TRUE;
2195 }
2196 #ifdef WOLFSSL_CERT_GEN
2197 if (nameType == SUBJECT) {
2198 cert->subjectL = (char*)&cert->source[cert->srcIdx];
2199 cert->subjectLLen = strLen;
2200 cert->subjectLEnc = b;
2201 }
2202 #endif /* WOLFSSL_CERT_GEN */
2203 #ifdef OPENSSL_EXTRA
2204 dName->lIdx = cert->srcIdx;
2205 dName->lLen = strLen;
2206 #endif /* OPENSSL_EXTRA */
2207 }
2208 else if (id == ASN_STATE_NAME) {
2209 if (!tooBig) {
2210 XMEMCPY(&full[idx], "/ST=", 4);
2211 idx += 4;
2212 copy = TRUE;
2213 }
2214 #ifdef WOLFSSL_CERT_GEN
2215 if (nameType == SUBJECT) {
2216 cert->subjectST = (char*)&cert->source[cert->srcIdx];
2217 cert->subjectSTLen = strLen;
2218 cert->subjectSTEnc = b;
2219 }
2220 #endif /* WOLFSSL_CERT_GEN */
2221 #ifdef OPENSSL_EXTRA
2222 dName->stIdx = cert->srcIdx;
2223 dName->stLen = strLen;
2224 #endif /* OPENSSL_EXTRA */
2225 }
2226 else if (id == ASN_ORG_NAME) {
2227 if (!tooBig) {
2228 XMEMCPY(&full[idx], "/O=", 3);
2229 idx += 3;
2230 copy = TRUE;
2231 }
2232 #ifdef WOLFSSL_CERT_GEN
2233 if (nameType == SUBJECT) {
2234 cert->subjectO = (char*)&cert->source[cert->srcIdx];
2235 cert->subjectOLen = strLen;
2236 cert->subjectOEnc = b;
2237 }
2238 #endif /* WOLFSSL_CERT_GEN */
2239 #ifdef OPENSSL_EXTRA
2240 dName->oIdx = cert->srcIdx;
2241 dName->oLen = strLen;
2242 #endif /* OPENSSL_EXTRA */
2243 }
2244 else if (id == ASN_ORGUNIT_NAME) {
2245 if (!tooBig) {
2246 XMEMCPY(&full[idx], "/OU=", 4);
2247 idx += 4;
2248 copy = TRUE;
2249 }
2250 #ifdef WOLFSSL_CERT_GEN
2251 if (nameType == SUBJECT) {
2252 cert->subjectOU = (char*)&cert->source[cert->srcIdx];
2253 cert->subjectOULen = strLen;
2254 cert->subjectOUEnc = b;
2255 }
2256 #endif /* WOLFSSL_CERT_GEN */
2257 #ifdef OPENSSL_EXTRA
2258 dName->ouIdx = cert->srcIdx;
2259 dName->ouLen = strLen;
2260 #endif /* OPENSSL_EXTRA */
2261 }
2262 else if (id == ASN_SERIAL_NUMBER) {
2263 if (!tooBig) {
2264 XMEMCPY(&full[idx], "/serialNumber=", 14);
2265 idx += 14;
2266 copy = TRUE;
2267 }
2268 #ifdef OPENSSL_EXTRA
2269 dName->snIdx = cert->srcIdx;
2270 dName->snLen = strLen;
2271 #endif /* OPENSSL_EXTRA */
2272 }
2273
2274 if (copy && !tooBig) {
2275 XMEMCPY(&full[idx], &cert->source[cert->srcIdx], strLen);
2276 idx += strLen;
2277 }
2278
2279 cert->srcIdx += strLen;
2280 }
2281 else {
2282 /* skip */
2283 byte email = FALSE;
2284 byte uid = FALSE;
2285 int adv;
2286
2287 if (joint[0] == 0x2a && joint[1] == 0x86) /* email id hdr */
2288 email = TRUE;
2289
2290 if (joint[0] == 0x9 && joint[1] == 0x92) /* uid id hdr */
2291 uid = TRUE;
2292
2293 cert->srcIdx += oidSz + 1;
2294
2295 if (GetLength(cert->source, &cert->srcIdx, &adv, cert->maxIdx) < 0)
2296 return ASN_PARSE_E;
2297
2298 if (adv > (int)(ASN_NAME_MAX - idx)) {
2299 WOLFSSL_MSG("ASN name too big, skipping");
2300 tooBig = TRUE;
2301 }
2302
2303 if (email) {
2304 if ( (14 + adv) > (int)(ASN_NAME_MAX - idx)) {
2305 WOLFSSL_MSG("ASN name too big, skipping");
2306 tooBig = TRUE;
2307 }
2308 if (!tooBig) {
2309 XMEMCPY(&full[idx], "/emailAddress=", 14);
2310 idx += 14;
2311 }
2312
2313 #ifdef WOLFSSL_CERT_GEN
2314 if (nameType == SUBJECT) {
2315 cert->subjectEmail = (char*)&cert->source[cert->srcIdx];
2316 cert->subjectEmailLen = adv;
2317 }
2318 #endif /* WOLFSSL_CERT_GEN */
2319 #ifdef OPENSSL_EXTRA
2320 dName->emailIdx = cert->srcIdx;
2321 dName->emailLen = adv;
2322 #endif /* OPENSSL_EXTRA */
2323 #ifndef IGNORE_NAME_CONSTRAINTS
2324 {
2325 DNS_entry* emailName = NULL;
2326
2327 emailName = (DNS_entry*)XMALLOC(sizeof(DNS_entry),
2328 cert->heap, DYNAMIC_TYPE_ALTNAME);
2329 if (emailName == NULL) {
2330 WOLFSSL_MSG("\tOut of Memory");
2331 return MEMORY_E;
2332 }
2333 emailName->name = (char*)XMALLOC(adv + 1,
2334 cert->heap, DYNAMIC_TYPE_ALTNAME);
2335 if (emailName->name == NULL) {
2336 WOLFSSL_MSG("\tOut of Memory");
2337 return MEMORY_E;
2338 }
2339 XMEMCPY(emailName->name,
2340 &cert->source[cert->srcIdx], adv);
2341 emailName->name[adv] = 0;
2342
2343 emailName->next = cert->altEmailNames;
2344 cert->altEmailNames = emailName;
2345 }
2346 #endif /* IGNORE_NAME_CONSTRAINTS */
2347 if (!tooBig) {
2348 XMEMCPY(&full[idx], &cert->source[cert->srcIdx], adv);
2349 idx += adv;
2350 }
2351 }
2352
2353 if (uid) {
2354 if ( (5 + adv) > (int)(ASN_NAME_MAX - idx)) {
2355 WOLFSSL_MSG("ASN name too big, skipping");
2356 tooBig = TRUE;
2357 }
2358 if (!tooBig) {
2359 XMEMCPY(&full[idx], "/UID=", 5);
2360 idx += 5;
2361
2362 XMEMCPY(&full[idx], &cert->source[cert->srcIdx], adv);
2363 idx += adv;
2364 }
2365 #ifdef OPENSSL_EXTRA
2366 dName->uidIdx = cert->srcIdx;
2367 dName->uidLen = adv;
2368 #endif /* OPENSSL_EXTRA */
2369 }
2370
2371 cert->srcIdx += adv;
2372 }
2373 }
2374 full[idx++] = 0;
2375
2376 #ifdef OPENSSL_EXTRA
2377 {
2378 int totalLen = 0;
2379
2380 if (dName->cnLen != 0)
2381 totalLen += dName->cnLen + 4;
2382 if (dName->snLen != 0)
2383 totalLen += dName->snLen + 4;
2384 if (dName->cLen != 0)
2385 totalLen += dName->cLen + 3;
2386 if (dName->lLen != 0)
2387 totalLen += dName->lLen + 3;
2388 if (dName->stLen != 0)
2389 totalLen += dName->stLen + 4;
2390 if (dName->oLen != 0)
2391 totalLen += dName->oLen + 3;
2392 if (dName->ouLen != 0)
2393 totalLen += dName->ouLen + 4;
2394 if (dName->emailLen != 0)
2395 totalLen += dName->emailLen + 14;
2396 if (dName->uidLen != 0)
2397 totalLen += dName->uidLen + 5;
2398 if (dName->serialLen != 0)
2399 totalLen += dName->serialLen + 14;
2400
2401 dName->fullName = (char*)XMALLOC(totalLen + 1, NULL, DYNAMIC_TYPE_X509);
2402 if (dName->fullName != NULL) {
2403 idx = 0;
2404
2405 if (dName->cnLen != 0) {
2406 dName->entryCount++;
2407 XMEMCPY(&dName->fullName[idx], "/CN=", 4);
2408 idx += 4;
2409 XMEMCPY(&dName->fullName[idx],
2410 &cert->source[dName->cnIdx], dName->cnLen);
2411 dName->cnIdx = idx;
2412 idx += dName->cnLen;
2413 }
2414 if (dName->snLen != 0) {
2415 dName->entryCount++;
2416 XMEMCPY(&dName->fullName[idx], "/SN=", 4);
2417 idx += 4;
2418 XMEMCPY(&dName->fullName[idx],
2419 &cert->source[dName->snIdx], dName->snLen);
2420 dName->snIdx = idx;
2421 idx += dName->snLen;
2422 }
2423 if (dName->cLen != 0) {
2424 dName->entryCount++;
2425 XMEMCPY(&dName->fullName[idx], "/C=", 3);
2426 idx += 3;
2427 XMEMCPY(&dName->fullName[idx],
2428 &cert->source[dName->cIdx], dName->cLen);
2429 dName->cIdx = idx;
2430 idx += dName->cLen;
2431 }
2432 if (dName->lLen != 0) {
2433 dName->entryCount++;
2434 XMEMCPY(&dName->fullName[idx], "/L=", 3);
2435 idx += 3;
2436 XMEMCPY(&dName->fullName[idx],
2437 &cert->source[dName->lIdx], dName->lLen);
2438 dName->lIdx = idx;
2439 idx += dName->lLen;
2440 }
2441 if (dName->stLen != 0) {
2442 dName->entryCount++;
2443 XMEMCPY(&dName->fullName[idx], "/ST=", 4);
2444 idx += 4;
2445 XMEMCPY(&dName->fullName[idx],
2446 &cert->source[dName->stIdx], dName->stLen);
2447 dName->stIdx = idx;
2448 idx += dName->stLen;
2449 }
2450 if (dName->oLen != 0) {
2451 dName->entryCount++;
2452 XMEMCPY(&dName->fullName[idx], "/O=", 3);
2453 idx += 3;
2454 XMEMCPY(&dName->fullName[idx],
2455 &cert->source[dName->oIdx], dName->oLen);
2456 dName->oIdx = idx;
2457 idx += dName->oLen;
2458 }
2459 if (dName->ouLen != 0) {
2460 dName->entryCount++;
2461 XMEMCPY(&dName->fullName[idx], "/OU=", 4);
2462 idx += 4;
2463 XMEMCPY(&dName->fullName[idx],
2464 &cert->source[dName->ouIdx], dName->ouLen);
2465 dName->ouIdx = idx;
2466 idx += dName->ouLen;
2467 }
2468 if (dName->emailLen != 0) {
2469 dName->entryCount++;
2470 XMEMCPY(&dName->fullName[idx], "/emailAddress=", 14);
2471 idx += 14;
2472 XMEMCPY(&dName->fullName[idx],
2473 &cert->source[dName->emailIdx], dName->emailLen);
2474 dName->emailIdx = idx;
2475 idx += dName->emailLen;
2476 }
2477 if (dName->uidLen != 0) {
2478 dName->entryCount++;
2479 XMEMCPY(&dName->fullName[idx], "/UID=", 5);
2480 idx += 5;
2481 XMEMCPY(&dName->fullName[idx],
2482 &cert->source[dName->uidIdx], dName->uidLen);
2483 dName->uidIdx = idx;
2484 idx += dName->uidLen;
2485 }
2486 if (dName->serialLen != 0) {
2487 dName->entryCount++;
2488 XMEMCPY(&dName->fullName[idx], "/serialNumber=", 14);
2489 idx += 14;
2490 XMEMCPY(&dName->fullName[idx],
2491 &cert->source[dName->serialIdx], dName->serialLen);
2492 dName->serialIdx = idx;
2493 idx += dName->serialLen;
2494 }
2495 dName->fullName[idx] = '\0';
2496 dName->fullNameLen = totalLen;
2497 }
2498 }
2499 #endif /* OPENSSL_EXTRA */
2500
2501 return 0;
2502}
2503
2504
2505#ifndef NO_TIME_H
2506
2507/* to the second */
2508static int DateGreaterThan(const struct tm* a, const struct tm* b)
2509{
2510 if (a->tm_year > b->tm_year)
2511 return 1;
2512
2513 if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
2514 return 1;
2515
2516 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
2517 a->tm_mday > b->tm_mday)
2518 return 1;
2519
2520 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
2521 a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
2522 return 1;
2523
2524 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
2525 a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
2526 a->tm_min > b->tm_min)
2527 return 1;
2528
2529 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
2530 a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
2531 a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
2532 return 1;
2533
2534 return 0; /* false */
2535}
2536
2537
2538static INLINE int DateLessThan(const struct tm* a, const struct tm* b)
2539{
2540 return DateGreaterThan(b,a);
2541}
2542
2543
2544/* like atoi but only use first byte */
2545/* Make sure before and after dates are valid */
2546int ValidateDate(const byte* date, byte format, int dateType)
2547{
2548 time_t ltime;
2549 struct tm certTime;
2550 struct tm* localTime;
2551 struct tm* tmpTime = NULL;
2552 int i = 0;
2553
2554#if defined(FREESCALE_MQX) || defined(TIME_OVERRIDES)
2555 struct tm tmpTimeStorage;
2556 tmpTime = &tmpTimeStorage;
2557#else
2558 (void)tmpTime;
2559#endif
2560
2561 ltime = XTIME(0);
2562 XMEMSET(&certTime, 0, sizeof(certTime));
2563
2564 if (format == ASN_UTC_TIME) {
2565 if (btoi(date[0]) >= 5)
2566 certTime.tm_year = 1900;
2567 else
2568 certTime.tm_year = 2000;
2569 }
2570 else { /* format == GENERALIZED_TIME */
2571 certTime.tm_year += btoi(date[i++]) * 1000;
2572 certTime.tm_year += btoi(date[i++]) * 100;
2573 }
2574
2575 /* adjust tm_year, tm_mon */
2576 GetTime((int*)&certTime.tm_year, date, &i); certTime.tm_year -= 1900;
2577 GetTime((int*)&certTime.tm_mon, date, &i); certTime.tm_mon -= 1;
2578 GetTime((int*)&certTime.tm_mday, date, &i);
2579 GetTime((int*)&certTime.tm_hour, date, &i);
2580 GetTime((int*)&certTime.tm_min, date, &i);
2581 GetTime((int*)&certTime.tm_sec, date, &i);
2582
2583 if (date[i] != 'Z') { /* only Zulu supported for this profile */
2584 WOLFSSL_MSG("Only Zulu time supported for this profile");
2585 return 0;
2586 }
2587
2588 localTime = XGMTIME(&ltime, tmpTime);
2589
2590 if (localTime == NULL) {
2591 WOLFSSL_MSG("XGMTIME failed");
2592 return 0;
2593 }
2594
2595 if (dateType == BEFORE) {
2596 if (DateLessThan(localTime, &certTime))
2597 return 0;
2598 }
2599 else
2600 if (DateGreaterThan(localTime, &certTime))
2601 return 0;
2602
2603 return 1;
2604}
2605
2606#endif /* NO_TIME_H */
2607
2608
2609static int GetDate(DecodedCert* cert, int dateType)
2610{
2611 int length;
2612 byte date[MAX_DATE_SIZE];
2613 byte b;
2614 word32 startIdx = 0;
2615
2616 if (dateType == BEFORE)
2617 cert->beforeDate = &cert->source[cert->srcIdx];
2618 else
2619 cert->afterDate = &cert->source[cert->srcIdx];
2620 startIdx = cert->srcIdx;
2621
2622 b = cert->source[cert->srcIdx++];
2623 if (b != ASN_UTC_TIME && b != ASN_GENERALIZED_TIME)
2624 return ASN_TIME_E;
2625
2626 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
2627 return ASN_PARSE_E;
2628
2629 if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
2630 return ASN_DATE_SZ_E;
2631
2632 XMEMCPY(date, &cert->source[cert->srcIdx], length);
2633 cert->srcIdx += length;
2634
2635 if (dateType == BEFORE)
2636 cert->beforeDateLen = cert->srcIdx - startIdx;
2637 else
2638 cert->afterDateLen = cert->srcIdx - startIdx;
2639
2640 if (!XVALIDATE_DATE(date, b, dateType)) {
2641 if (dateType == BEFORE)
2642 return ASN_BEFORE_DATE_E;
2643 else
2644 return ASN_AFTER_DATE_E;
2645 }
2646
2647 return 0;
2648}
2649
2650
2651static int GetValidity(DecodedCert* cert, int verify)
2652{
2653 int length;
2654 int badDate = 0;
2655
2656 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
2657 return ASN_PARSE_E;
2658
2659 if (GetDate(cert, BEFORE) < 0 && verify)
2660 badDate = ASN_BEFORE_DATE_E; /* continue parsing */
2661
2662 if (GetDate(cert, AFTER) < 0 && verify)
2663 return ASN_AFTER_DATE_E;
2664
2665 if (badDate != 0)
2666 return badDate;
2667
2668 return 0;
2669}
2670
2671
2672int DecodeToKey(DecodedCert* cert, int verify)
2673{
2674 int badDate = 0;
2675 int ret;
2676
2677 if ( (ret = GetCertHeader(cert)) < 0)
2678 return ret;
2679
2680 WOLFSSL_MSG("Got Cert Header");
2681
2682 if ( (ret = GetAlgoId(cert->source, &cert->srcIdx, &cert->signatureOID,
2683 cert->maxIdx)) < 0)
2684 return ret;
2685
2686 WOLFSSL_MSG("Got Algo ID");
2687
2688 if ( (ret = GetName(cert, ISSUER)) < 0)
2689 return ret;
2690
2691 if ( (ret = GetValidity(cert, verify)) < 0)
2692 badDate = ret;
2693
2694 if ( (ret = GetName(cert, SUBJECT)) < 0)
2695 return ret;
2696
2697 WOLFSSL_MSG("Got Subject Name");
2698
2699 if ( (ret = GetKey(cert)) < 0)
2700 return ret;
2701
2702 WOLFSSL_MSG("Got Key");
2703
2704 if (badDate != 0)
2705 return badDate;
2706
2707 return ret;
2708}
2709
2710
2711static int GetSignature(DecodedCert* cert)
2712{
2713 int length;
2714 byte b = cert->source[cert->srcIdx++];
2715
2716 if (b != ASN_BIT_STRING)
2717 return ASN_BITSTR_E;
2718
2719 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
2720 return ASN_PARSE_E;
2721
2722 cert->sigLength = length;
2723
2724 b = cert->source[cert->srcIdx++];
2725 if (b != 0x00)
2726 return ASN_EXPECT_0_E;
2727
2728 cert->sigLength--;
2729 cert->signature = &cert->source[cert->srcIdx];
2730 cert->srcIdx += cert->sigLength;
2731
2732 return 0;
2733}
2734
2735
2736static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
2737{
2738 output[0] = ASN_OCTET_STRING;
2739 output[1] = (byte)digSz;
2740 XMEMCPY(&output[2], digest, digSz);
2741
2742 return digSz + 2;
2743}
2744
2745
2746static word32 BytePrecision(word32 value)
2747{
2748 word32 i;
2749 for (i = sizeof(value); i; --i)
2750 if (value >> ((i - 1) * WOLFSSL_BIT_SIZE))
2751 break;
2752
2753 return i;
2754}
2755
2756
2757WOLFSSL_LOCAL word32 SetLength(word32 length, byte* output)
2758{
2759 word32 i = 0, j;
2760
2761 if (length < ASN_LONG_LENGTH)
2762 output[i++] = (byte)length;
2763 else {
2764 output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);
2765
2766 for (j = BytePrecision(length); j; --j) {
2767 output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
2768 i++;
2769 }
2770 }
2771
2772 return i;
2773}
2774
2775
2776WOLFSSL_LOCAL word32 SetSequence(word32 len, byte* output)
2777{
2778 output[0] = ASN_SEQUENCE | ASN_CONSTRUCTED;
2779 return SetLength(len, output + 1) + 1;
2780}
2781
2782WOLFSSL_LOCAL word32 SetOctetString(word32 len, byte* output)
2783{
2784 output[0] = ASN_OCTET_STRING;
2785 return SetLength(len, output + 1) + 1;
2786}
2787
2788/* Write a set header to output */
2789WOLFSSL_LOCAL word32 SetSet(word32 len, byte* output)
2790{
2791 output[0] = ASN_SET | ASN_CONSTRUCTED;
2792 return SetLength(len, output + 1) + 1;
2793}
2794
2795WOLFSSL_LOCAL word32 SetImplicit(byte tag, byte number, word32 len, byte* output)
2796{
2797
2798 output[0] = ((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0)
2799 | ASN_CONTEXT_SPECIFIC | number;
2800 return SetLength(len, output + 1) + 1;
2801}
2802
2803WOLFSSL_LOCAL word32 SetExplicit(byte number, word32 len, byte* output)
2804{
2805 output[0] = ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | number;
2806 return SetLength(len, output + 1) + 1;
2807}
2808
2809
2810#if defined(HAVE_ECC) && (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN))
2811
2812static int SetCurve(ecc_key* key, byte* output)
2813{
2814
2815 /* curve types */
2816#if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC192)
2817 static const byte ECC_192v1_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE, 0x3d,
2818 0x03, 0x01, 0x01};
2819#endif
2820#if defined(HAVE_ALL_CURVES) || !defined(NO_ECC256)
2821 static const byte ECC_256v1_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE, 0x3d,
2822 0x03, 0x01, 0x07};
2823#endif
2824#if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC160)
2825 static const byte ECC_160r1_AlgoID[] = { 0x2b, 0x81, 0x04, 0x00,
2826 0x02};
2827#endif
2828#if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC224)
2829 static const byte ECC_224r1_AlgoID[] = { 0x2b, 0x81, 0x04, 0x00,
2830 0x21};
2831#endif
2832#if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC384)
2833 static const byte ECC_384r1_AlgoID[] = { 0x2b, 0x81, 0x04, 0x00,
2834 0x22};
2835#endif
2836#if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC521)
2837 static const byte ECC_521r1_AlgoID[] = { 0x2b, 0x81, 0x04, 0x00,
2838 0x23};
2839#endif
2840
2841 int oidSz = 0;
2842 int idx = 0;
2843 int lenSz = 0;
2844 const byte* oid = 0;
2845
2846 output[0] = ASN_OBJECT_ID;
2847 idx++;
2848
2849 switch (key->dp->size) {
2850#if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC160)
2851 case 20:
2852 oidSz = sizeof(ECC_160r1_AlgoID);
2853 oid = ECC_160r1_AlgoID;
2854 break;
2855#endif
2856
2857#if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC192)
2858 case 24:
2859 oidSz = sizeof(ECC_192v1_AlgoID);
2860 oid = ECC_192v1_AlgoID;
2861 break;
2862#endif
2863
2864#if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC224)
2865 case 28:
2866 oidSz = sizeof(ECC_224r1_AlgoID);
2867 oid = ECC_224r1_AlgoID;
2868 break;
2869#endif
2870
2871#if defined(HAVE_ALL_CURVES) || !defined(NO_ECC256)
2872 case 32:
2873 oidSz = sizeof(ECC_256v1_AlgoID);
2874 oid = ECC_256v1_AlgoID;
2875 break;
2876#endif
2877
2878#if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC384)
2879 case 48:
2880 oidSz = sizeof(ECC_384r1_AlgoID);
2881 oid = ECC_384r1_AlgoID;
2882 break;
2883#endif
2884
2885#if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC521)
2886 case 66:
2887 oidSz = sizeof(ECC_521r1_AlgoID);
2888 oid = ECC_521r1_AlgoID;
2889 break;
2890#endif
2891
2892 default:
2893 return ASN_UNKNOWN_OID_E;
2894 }
2895 lenSz = SetLength(oidSz, output+idx);
2896 idx += lenSz;
2897
2898 XMEMCPY(output+idx, oid, oidSz);
2899 idx += oidSz;
2900
2901 return idx;
2902}
2903
2904#endif /* HAVE_ECC && WOLFSSL_CERT_GEN */
2905
2906
2907WOLFSSL_LOCAL word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz)
2908{
2909 /* adding TAG_NULL and 0 to end */
2910
2911 /* hashTypes */
2912 static const byte shaAlgoID[] = { 0x2b, 0x0e, 0x03, 0x02, 0x1a,
2913 0x05, 0x00 };
2914 static const byte sha256AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
2915 0x04, 0x02, 0x01, 0x05, 0x00 };
2916 static const byte sha384AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
2917 0x04, 0x02, 0x02, 0x05, 0x00 };
2918 static const byte sha512AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
2919 0x04, 0x02, 0x03, 0x05, 0x00 };
2920 static const byte md5AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
2921 0x02, 0x05, 0x05, 0x00 };
2922 static const byte md2AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
2923 0x02, 0x02, 0x05, 0x00};
2924
2925 /* blkTypes, no NULL tags because IV is there instead */
2926 static const byte desCbcAlgoID[] = { 0x2B, 0x0E, 0x03, 0x02, 0x07 };
2927 static const byte des3CbcAlgoID[] = { 0x2A, 0x86, 0x48, 0x86, 0xF7,
2928 0x0D, 0x03, 0x07 };
2929
2930 /* RSA sigTypes */
2931 #ifndef NO_RSA
2932 static const byte md5wRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7,
2933 0x0d, 0x01, 0x01, 0x04, 0x05, 0x00};
2934 static const byte shawRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7,
2935 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00};
2936 static const byte sha256wRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7,
2937 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00};
2938 static const byte sha384wRSA_AlgoID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
2939 0x0d, 0x01, 0x01, 0x0c, 0x05, 0x00};
2940 static const byte sha512wRSA_AlgoID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
2941 0x0d, 0x01, 0x01, 0x0d, 0x05, 0x00};
2942 #endif /* NO_RSA */
2943
2944 /* ECDSA sigTypes */
2945 #ifdef HAVE_ECC
2946 static const byte shawECDSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE, 0x3d,
2947 0x04, 0x01, 0x05, 0x00};
2948 static const byte sha256wECDSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE,0x3d,
2949 0x04, 0x03, 0x02, 0x05, 0x00};
2950 static const byte sha384wECDSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE,0x3d,
2951 0x04, 0x03, 0x03, 0x05, 0x00};
2952 static const byte sha512wECDSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE,0x3d,
2953 0x04, 0x03, 0x04, 0x05, 0x00};
2954 #endif /* HAVE_ECC */
2955
2956 /* RSA keyType */
2957 #ifndef NO_RSA
2958 static const byte RSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
2959 0x01, 0x01, 0x01, 0x05, 0x00};
2960 #endif /* NO_RSA */
2961
2962 #ifdef HAVE_ECC
2963 /* ECC keyType */
2964 /* no tags, so set tagSz smaller later */
2965 static const byte ECC_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE, 0x3d,
2966 0x02, 0x01};
2967 #endif /* HAVE_ECC */
2968
2969 int algoSz = 0;
2970 int tagSz = 2; /* tag null and terminator */
2971 word32 idSz, seqSz;
2972 const byte* algoName = 0;
2973 byte ID_Length[MAX_LENGTH_SZ];
2974 byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
2975
2976 if (type == hashType) {
2977 switch (algoOID) {
2978 case SHAh:
2979 algoSz = sizeof(shaAlgoID);
2980 algoName = shaAlgoID;
2981 break;
2982
2983 case SHA256h:
2984 algoSz = sizeof(sha256AlgoID);
2985 algoName = sha256AlgoID;
2986 break;
2987
2988 case SHA384h:
2989 algoSz = sizeof(sha384AlgoID);
2990 algoName = sha384AlgoID;
2991 break;
2992
2993 case SHA512h:
2994 algoSz = sizeof(sha512AlgoID);
2995 algoName = sha512AlgoID;
2996 break;
2997
2998 case MD2h:
2999 algoSz = sizeof(md2AlgoID);
3000 algoName = md2AlgoID;
3001 break;
3002
3003 case MD5h:
3004 algoSz = sizeof(md5AlgoID);
3005 algoName = md5AlgoID;
3006 break;
3007
3008 default:
3009 WOLFSSL_MSG("Unknown Hash Algo");
3010 return 0; /* UNKOWN_HASH_E; */
3011 }
3012 }
3013 else if (type == blkType) {
3014 switch (algoOID) {
3015 case DESb:
3016 algoSz = sizeof(desCbcAlgoID);
3017 algoName = desCbcAlgoID;
3018 tagSz = 0;
3019 break;
3020 case DES3b:
3021 algoSz = sizeof(des3CbcAlgoID);
3022 algoName = des3CbcAlgoID;
3023 tagSz = 0;
3024 break;
3025 default:
3026 WOLFSSL_MSG("Unknown Block Algo");
3027 return 0;
3028 }
3029 }
3030 else if (type == sigType) { /* sigType */
3031 switch (algoOID) {
3032 #ifndef NO_RSA
3033 case CTC_MD5wRSA:
3034 algoSz = sizeof(md5wRSA_AlgoID);
3035 algoName = md5wRSA_AlgoID;
3036 break;
3037
3038 case CTC_SHAwRSA:
3039 algoSz = sizeof(shawRSA_AlgoID);
3040 algoName = shawRSA_AlgoID;
3041 break;
3042
3043 case CTC_SHA256wRSA:
3044 algoSz = sizeof(sha256wRSA_AlgoID);
3045 algoName = sha256wRSA_AlgoID;
3046 break;
3047
3048 case CTC_SHA384wRSA:
3049 algoSz = sizeof(sha384wRSA_AlgoID);
3050 algoName = sha384wRSA_AlgoID;
3051 break;
3052
3053 case CTC_SHA512wRSA:
3054 algoSz = sizeof(sha512wRSA_AlgoID);
3055 algoName = sha512wRSA_AlgoID;
3056 break;
3057 #endif /* NO_RSA */
3058 #ifdef HAVE_ECC
3059 case CTC_SHAwECDSA:
3060 algoSz = sizeof(shawECDSA_AlgoID);
3061 algoName = shawECDSA_AlgoID;
3062 break;
3063
3064 case CTC_SHA256wECDSA:
3065 algoSz = sizeof(sha256wECDSA_AlgoID);
3066 algoName = sha256wECDSA_AlgoID;
3067 break;
3068
3069 case CTC_SHA384wECDSA:
3070 algoSz = sizeof(sha384wECDSA_AlgoID);
3071 algoName = sha384wECDSA_AlgoID;
3072 break;
3073
3074 case CTC_SHA512wECDSA:
3075 algoSz = sizeof(sha512wECDSA_AlgoID);
3076 algoName = sha512wECDSA_AlgoID;
3077 break;
3078 #endif /* HAVE_ECC */
3079 default:
3080 WOLFSSL_MSG("Unknown Signature Algo");
3081 return 0;
3082 }
3083 }
3084 else if (type == keyType) { /* keyType */
3085 switch (algoOID) {
3086 #ifndef NO_RSA
3087 case RSAk:
3088 algoSz = sizeof(RSA_AlgoID);
3089 algoName = RSA_AlgoID;
3090 break;
3091 #endif /* NO_RSA */
3092 #ifdef HAVE_ECC
3093 case ECDSAk:
3094 algoSz = sizeof(ECC_AlgoID);
3095 algoName = ECC_AlgoID;
3096 tagSz = 0;
3097 break;
3098 #endif /* HAVE_ECC */
3099 default:
3100 WOLFSSL_MSG("Unknown Key Algo");
3101 return 0;
3102 }
3103 }
3104 else {
3105 WOLFSSL_MSG("Unknown Algo type");
3106 return 0;
3107 }
3108
3109 idSz = SetLength(algoSz - tagSz, ID_Length); /* don't include tags */
3110 seqSz = SetSequence(idSz + algoSz + 1 + curveSz, seqArray);
3111 /* +1 for object id, curveID of curveSz follows for ecc */
3112 seqArray[seqSz++] = ASN_OBJECT_ID;
3113
3114 XMEMCPY(output, seqArray, seqSz);
3115 XMEMCPY(output + seqSz, ID_Length, idSz);
3116 XMEMCPY(output + seqSz + idSz, algoName, algoSz);
3117
3118 return seqSz + idSz + algoSz;
3119
3120}
3121
3122
3123word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz,
3124 int hashOID)
3125{
3126 byte digArray[MAX_ENCODED_DIG_SZ];
3127 byte algoArray[MAX_ALGO_SZ];
3128 byte seqArray[MAX_SEQ_SZ];
3129 word32 encDigSz, algoSz, seqSz;
3130
3131 encDigSz = SetDigest(digest, digSz, digArray);
3132 algoSz = SetAlgoID(hashOID, algoArray, hashType, 0);
3133 seqSz = SetSequence(encDigSz + algoSz, seqArray);
3134
3135 XMEMCPY(out, seqArray, seqSz);
3136 XMEMCPY(out + seqSz, algoArray, algoSz);
3137 XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
3138
3139 return encDigSz + algoSz + seqSz;
3140}
3141
3142
3143int wc_GetCTC_HashOID(int type)
3144{
3145 switch (type) {
3146#ifdef WOLFSSL_MD2
3147 case MD2:
3148 return MD2h;
3149#endif
3150#ifndef NO_MD5
3151 case MD5:
3152 return MD5h;
3153#endif
3154#ifndef NO_SHA
3155 case SHA:
3156 return SHAh;
3157#endif
3158#ifndef NO_SHA256
3159 case SHA256:
3160 return SHA256h;
3161#endif
3162#ifdef WOLFSSL_SHA384
3163 case SHA384:
3164 return SHA384h;
3165#endif
3166#ifdef WOLFSSL_SHA512
3167 case SHA512:
3168 return SHA512h;
3169#endif
3170 default:
3171 return 0;
3172 };
3173}
3174
3175
3176/* return true (1) or false (0) for Confirmation */
3177static int ConfirmSignature(const byte* buf, word32 bufSz,
3178 const byte* key, word32 keySz, word32 keyOID,
3179 const byte* sig, word32 sigSz, word32 sigOID,
3180 void* heap)
3181{
3182 int typeH = 0, digestSz = 0, ret = 0;
3183#ifdef WOLFSSL_SMALL_STACK
3184 byte* digest;
3185#else
3186 byte digest[MAX_DIGEST_SIZE];
3187#endif
3188
3189#ifdef WOLFSSL_SMALL_STACK
3190 digest = (byte*)XMALLOC(MAX_DIGEST_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3191 if (digest == NULL)
3192 return 0; /* not confirmed */
3193#endif
3194
3195 (void)key;
3196 (void)keySz;
3197 (void)sig;
3198 (void)sigSz;
3199 (void)heap;
3200
3201 switch (sigOID) {
3202 #ifndef NO_MD5
3203 case CTC_MD5wRSA:
3204 if (wc_Md5Hash(buf, bufSz, digest) == 0) {
3205 typeH = MD5h;
3206 digestSz = MD5_DIGEST_SIZE;
3207 }
3208 break;
3209 #endif
3210 #if defined(WOLFSSL_MD2)
3211 case CTC_MD2wRSA:
3212 if (wc_Md2Hash(buf, bufSz, digest) == 0) {
3213 typeH = MD2h;
3214 digestSz = MD2_DIGEST_SIZE;
3215 }
3216 break;
3217 #endif
3218 #ifndef NO_SHA
3219 case CTC_SHAwRSA:
3220 case CTC_SHAwDSA:
3221 case CTC_SHAwECDSA:
3222 if (wc_ShaHash(buf, bufSz, digest) == 0) {
3223 typeH = SHAh;
3224 digestSz = SHA_DIGEST_SIZE;
3225 }
3226 break;
3227 #endif
3228 #ifndef NO_SHA256
3229 case CTC_SHA256wRSA:
3230 case CTC_SHA256wECDSA:
3231 if (wc_Sha256Hash(buf, bufSz, digest) == 0) {
3232 typeH = SHA256h;
3233 digestSz = SHA256_DIGEST_SIZE;
3234 }
3235 break;
3236 #endif
3237 #ifdef WOLFSSL_SHA512
3238 case CTC_SHA512wRSA:
3239 case CTC_SHA512wECDSA:
3240 if (wc_Sha512Hash(buf, bufSz, digest) == 0) {
3241 typeH = SHA512h;
3242 digestSz = SHA512_DIGEST_SIZE;
3243 }
3244 break;
3245 #endif
3246 #ifdef WOLFSSL_SHA384
3247 case CTC_SHA384wRSA:
3248 case CTC_SHA384wECDSA:
3249 if (wc_Sha384Hash(buf, bufSz, digest) == 0) {
3250 typeH = SHA384h;
3251 digestSz = SHA384_DIGEST_SIZE;
3252 }
3253 break;
3254 #endif
3255 default:
3256 WOLFSSL_MSG("Verify Signautre has unsupported type");
3257 }
3258
3259 if (typeH == 0) {
3260#ifdef WOLFSSL_SMALL_STACK
3261 XFREE(digest, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3262#endif
3263 return 0; /* not confirmed */
3264 }
3265
3266 switch (keyOID) {
3267 #ifndef NO_RSA
3268 case RSAk:
3269 {
3270 word32 idx = 0;
3271 int encodedSigSz, verifySz;
3272 byte* out;
3273#ifdef WOLFSSL_SMALL_STACK
3274 RsaKey* pubKey;
3275 byte* plain;
3276 byte* encodedSig;
3277#else
3278 RsaKey pubKey[1];
3279 byte plain[MAX_ENCODED_SIG_SZ];
3280 byte encodedSig[MAX_ENCODED_SIG_SZ];
3281#endif
3282
3283#ifdef WOLFSSL_SMALL_STACK
3284 pubKey = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL,
3285 DYNAMIC_TYPE_TMP_BUFFER);
3286 plain = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, NULL,
3287 DYNAMIC_TYPE_TMP_BUFFER);
3288 encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, NULL,
3289 DYNAMIC_TYPE_TMP_BUFFER);
3290
3291 if (pubKey == NULL || plain == NULL || encodedSig == NULL) {
3292 WOLFSSL_MSG("Failed to allocate memory at ConfirmSignature");
3293
3294 if (pubKey)
3295 XFREE(pubKey, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3296 if (plain)
3297 XFREE(plain, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3298 if (encodedSig)
3299 XFREE(encodedSig, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3300
3301 break; /* not confirmed */
3302 }
3303#endif
3304
3305 if (sigSz > MAX_ENCODED_SIG_SZ) {
3306 WOLFSSL_MSG("Verify Signautre is too big");
3307 }
3308 else if (wc_InitRsaKey(pubKey, heap) != 0) {
3309 WOLFSSL_MSG("InitRsaKey failed");
3310 }
3311 else if (wc_RsaPublicKeyDecode(key, &idx, pubKey, keySz) < 0) {
3312 WOLFSSL_MSG("ASN Key decode error RSA");
3313 }
3314 else {
3315 XMEMCPY(plain, sig, sigSz);
3316
3317 if ((verifySz = wc_RsaSSL_VerifyInline(plain, sigSz, &out,
3318 pubKey)) < 0) {
3319 WOLFSSL_MSG("Rsa SSL verify error");
3320 }
3321 else {
3322 /* make sure we're right justified */
3323 encodedSigSz =
3324 wc_EncodeSignature(encodedSig, digest, digestSz, typeH);
3325 if (encodedSigSz != verifySz ||
3326 XMEMCMP(out, encodedSig, encodedSigSz) != 0) {
3327 WOLFSSL_MSG("Rsa SSL verify match encode error");
3328 }
3329 else
3330 ret = 1; /* match */
3331
3332 #ifdef WOLFSSL_DEBUG_ENCODING
3333 {
3334 int x;
3335
3336 printf("wolfssl encodedSig:\n");
3337
3338 for (x = 0; x < encodedSigSz; x++) {
3339 printf("%02x ", encodedSig[x]);
3340 if ( (x % 16) == 15)
3341 printf("\n");
3342 }
3343
3344 printf("\n");
3345 printf("actual digest:\n");
3346
3347 for (x = 0; x < verifySz; x++) {
3348 printf("%02x ", out[x]);
3349 if ( (x % 16) == 15)
3350 printf("\n");
3351 }
3352
3353 printf("\n");
3354 }
3355 #endif /* WOLFSSL_DEBUG_ENCODING */
3356
3357 }
3358
3359 }
3360
3361 wc_FreeRsaKey(pubKey);
3362
3363#ifdef WOLFSSL_SMALL_STACK
3364 XFREE(pubKey, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3365 XFREE(plain, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3366 XFREE(encodedSig, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3367#endif
3368 break;
3369 }
3370
3371 #endif /* NO_RSA */
3372 #ifdef HAVE_ECC
3373 case ECDSAk:
3374 {
3375 int verify = 0;
3376#ifdef WOLFSSL_SMALL_STACK
3377 ecc_key* pubKey;
3378#else
3379 ecc_key pubKey[1];
3380#endif
3381
3382#ifdef WOLFSSL_SMALL_STACK
3383 pubKey = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL,
3384 DYNAMIC_TYPE_TMP_BUFFER);
3385 if (pubKey == NULL) {
3386 WOLFSSL_MSG("Failed to allocate pubKey");
3387 break; /* not confirmed */
3388 }
3389#endif
3390
3391 if (wc_ecc_init(pubKey) < 0) {
3392 WOLFSSL_MSG("Failed to initialize key");
3393 break; /* not confirmed */
3394 }
3395 if (wc_ecc_import_x963(key, keySz, pubKey) < 0) {
3396 WOLFSSL_MSG("ASN Key import error ECC");
3397 }
3398 else {
3399 if (wc_ecc_verify_hash(sig, sigSz, digest, digestSz, &verify,
3400 pubKey) != 0) {
3401 WOLFSSL_MSG("ECC verify hash error");
3402 }
3403 else if (1 != verify) {
3404 WOLFSSL_MSG("ECC Verify didn't match");
3405 } else
3406 ret = 1; /* match */
3407
3408 }
3409 wc_ecc_free(pubKey);
3410
3411#ifdef WOLFSSL_SMALL_STACK
3412 XFREE(pubKey, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3413#endif
3414 break;
3415 }
3416 #endif /* HAVE_ECC */
3417 default:
3418 WOLFSSL_MSG("Verify Key type unknown");
3419 }
3420
3421#ifdef WOLFSSL_SMALL_STACK
3422 XFREE(digest, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3423#endif
3424
3425 return ret;
3426}
3427
3428
3429#ifndef IGNORE_NAME_CONSTRAINTS
3430
3431static int MatchBaseName(int type, const char* name, int nameSz,
3432 const char* base, int baseSz)
3433{
3434 if (base == NULL || baseSz <= 0 || name == NULL || nameSz <= 0 ||
3435 name[0] == '.' || nameSz < baseSz ||
3436 (type != ASN_RFC822_TYPE && type != ASN_DNS_TYPE))
3437 return 0;
3438
3439 /* If an email type, handle special cases where the base is only
3440 * a domain, or is an email address itself. */
3441 if (type == ASN_RFC822_TYPE) {
3442 const char* p = NULL;
3443 int count = 0;
3444
3445 if (base[0] != '.') {
3446 p = base;
3447 count = 0;
3448
3449 /* find the '@' in the base */
3450 while (*p != '@' && count < baseSz) {
3451 count++;
3452 p++;
3453 }
3454
3455 /* No '@' in base, reset p to NULL */
3456 if (count >= baseSz)
3457 p = NULL;
3458 }
3459
3460 if (p == NULL) {
3461 /* Base isn't an email address, it is a domain name,
3462 * wind the name forward one character past its '@'. */
3463 p = name;
3464 count = 0;
3465 while (*p != '@' && count < baseSz) {
3466 count++;
3467 p++;
3468 }
3469
3470 if (count < baseSz && *p == '@') {
3471 name = p + 1;
3472 nameSz -= count + 1;
3473 }
3474 }
3475 }
3476
3477 if ((type == ASN_DNS_TYPE || type == ASN_RFC822_TYPE) && base[0] == '.') {
3478 int szAdjust = nameSz - baseSz;
3479 name += szAdjust;
3480 nameSz -= szAdjust;
3481 }
3482
3483 while (nameSz > 0) {
3484 if (XTOLOWER((unsigned char)*name++) !=
3485 XTOLOWER((unsigned char)*base++))
3486 return 0;
3487 nameSz--;
3488 }
3489
3490 return 1;
3491}
3492
3493
3494static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert)
3495{
3496 if (signer == NULL || cert == NULL)
3497 return 0;
3498
3499 /* Check against the excluded list */
3500 if (signer->excludedNames) {
3501 Base_entry* base = signer->excludedNames;
3502
3503 while (base != NULL) {
3504 if (base->type == ASN_DNS_TYPE) {
3505 DNS_entry* name = cert->altNames;
3506 while (name != NULL) {
3507 if (MatchBaseName(ASN_DNS_TYPE,
3508 name->name, (int)XSTRLEN(name->name),
3509 base->name, base->nameSz))
3510 return 0;
3511 name = name->next;
3512 }
3513 }
3514 else if (base->type == ASN_RFC822_TYPE) {
3515 DNS_entry* name = cert->altEmailNames;
3516 while (name != NULL) {
3517 if (MatchBaseName(ASN_RFC822_TYPE,
3518 name->name, (int)XSTRLEN(name->name),
3519 base->name, base->nameSz))
3520 return 0;
3521
3522 name = name->next;
3523 }
3524 }
3525 else if (base->type == ASN_DIR_TYPE) {
3526 if (cert->subjectRawLen == base->nameSz &&
3527 XMEMCMP(cert->subjectRaw, base->name, base->nameSz) == 0) {
3528
3529 return 0;
3530 }
3531 }
3532 base = base->next;
3533 }
3534 }
3535
3536 /* Check against the permitted list */
3537 if (signer->permittedNames != NULL) {
3538 int needDns = 0;
3539 int matchDns = 0;
3540 int needEmail = 0;
3541 int matchEmail = 0;
3542 int needDir = 0;
3543 int matchDir = 0;
3544 Base_entry* base = signer->permittedNames;
3545
3546 while (base != NULL) {
3547 if (base->type == ASN_DNS_TYPE) {
3548 DNS_entry* name = cert->altNames;
3549
3550 if (name != NULL)
3551 needDns = 1;
3552
3553 while (name != NULL) {
3554 matchDns = MatchBaseName(ASN_DNS_TYPE,
3555 name->name, (int)XSTRLEN(name->name),
3556 base->name, base->nameSz);
3557 name = name->next;
3558 }
3559 }
3560 else if (base->type == ASN_RFC822_TYPE) {
3561 DNS_entry* name = cert->altEmailNames;
3562
3563 if (name != NULL)
3564 needEmail = 1;
3565
3566 while (name != NULL) {
3567 matchEmail = MatchBaseName(ASN_DNS_TYPE,
3568 name->name, (int)XSTRLEN(name->name),
3569 base->name, base->nameSz);
3570 name = name->next;
3571 }
3572 }
3573 else if (base->type == ASN_DIR_TYPE) {
3574 needDir = 1;
3575 if (cert->subjectRaw != NULL &&
3576 cert->subjectRawLen == base->nameSz &&
3577 XMEMCMP(cert->subjectRaw, base->name, base->