3 * Copyright (C) 2006-2015 wolfSSL Inc.
5 * This file is part of wolfSSL. (formerly known as CyaSSL)
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.
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.
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
26 #include <wolfssl/wolfcrypt/settings.h>
31 #include "os.h" /* dc_rtc_api needs */
32 #include "dc_rtc_api.h" /* to get current time */
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>
44 #include <wolfssl/wolfcrypt/random.h>
48 #include <wolfssl/wolfcrypt/arc4.h>
52 #include "ntru_crypto.h"
55 #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
56 #include <wolfssl/wolfcrypt/sha512.h>
60 #include <wolfssl/wolfcrypt/sha256.h>
64 #include <wolfssl/wolfcrypt/ecc.h>
67 #ifdef WOLFSSL_DEBUG_ENCODING
76 /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
77 #pragma warning(disable: 4996)
90 /* uses parital <time.h> structures */
92 #define XGMTIME(c, t) my_gmtime((c))
93 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
94 #elif defined(MICRIUM)
95 #if (NET_SECURE_MGR_CFG_EN == DEF_ENABLED)
96 #define XVALIDATE_DATE(d,f,t) NetSecure_ValidateDateHandler((d),(f),(t))
98 #define XVALIDATE_DATE(d, f, t) (0)
101 /* since Micrium not defining XTIME or XGMTIME, CERT_GEN not available */
102 #elif defined(MICROCHIP_TCPIP_V5) || defined(MICROCHIP_TCPIP)
104 #define XTIME(t1) pic32_time((t1))
105 #define XGMTIME(c, t) gmtime((c))
106 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
107 #elif defined(FREESCALE_MQX)
108 #define XTIME(t1) mqx_time((t1))
109 #define XGMTIME(c, t) mqx_gmtime((c), (t))
110 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
111 #elif defined(WOLFSSL_MDK_ARM)
112 #if defined(WOLFSSL_MDK5)
113 #include "cmsis_os.h"
118 #include "wolfssl_MDK_ARM.h"
120 #define RNG wolfSSL_RNG /*for avoiding name conflict in "stm32f2xx.h" */
121 #define XTIME(tl) (0)
122 #define XGMTIME(c, t) wolfssl_MDK_gmtime((c))
123 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
124 #elif defined(USER_TIME)
125 /* user time, and gmtime compatible functions, there is a gmtime
126 implementation here that WINCE uses, so really just need some ticks
131 int tm_sec; /* seconds after the minute [0-60] */
132 int tm_min; /* minutes after the hour [0-59] */
133 int tm_hour; /* hours since midnight [0-23] */
134 int tm_mday; /* day of the month [1-31] */
135 int tm_mon; /* months since January [0-11] */
136 int tm_year; /* years since 1900 */
137 int tm_wday; /* days since Sunday [0-6] */
138 int tm_yday; /* days since January 1 [0-365] */
139 int tm_isdst; /* Daylight Savings Time flag */
140 long tm_gmtoff; /* offset from CUT in seconds */
141 char *tm_zone; /* timezone abbreviation */
145 /* forward declaration */
146 struct tm* gmtime(const time_t* timer);
147 extern time_t XTIME(time_t * timer);
149 #define XGMTIME(c, t) gmtime((c))
150 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
153 /* for stack trap tracking, don't call os gmtime on OS X/linux,
154 uses a lot of stack spce */
155 extern time_t time(time_t * timer);
156 #define XTIME(tl) time((tl))
157 #endif /* STACK_TRAP */
159 #elif defined(TIME_OVERRIDES)
160 /* user would like to override time() and gmtime() functionality */
162 #ifndef HAVE_TIME_T_TYPE
165 extern time_t XTIME(time_t * timer);
169 int tm_sec; /* seconds after the minute [0-60] */
170 int tm_min; /* minutes after the hour [0-59] */
171 int tm_hour; /* hours since midnight [0-23] */
172 int tm_mday; /* day of the month [1-31] */
173 int tm_mon; /* months since January [0-11] */
174 int tm_year; /* years since 1900 */
175 int tm_wday; /* days since Sunday [0-6] */
176 int tm_yday; /* days since January 1 [0-365] */
177 int tm_isdst; /* Daylight Savings Time flag */
178 long tm_gmtoff; /* offset from CUT in seconds */
179 char *tm_zone; /* timezone abbreviation */
182 extern struct tm* XGMTIME(const time_t* timer, struct tm* tmp);
184 #ifndef HAVE_VALIDATE_DATE
185 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
189 /* uses complete <time.h> facility */
191 #define XTIME(tl) time((tl))
192 #define XGMTIME(c, t) gmtime((c))
193 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
198 /* no time() or gmtime() even though in time.h header?? */
203 time_t time(time_t* timer)
207 ULARGE_INTEGER intTime;
213 GetSystemTime(&sysTime);
214 SystemTimeToFileTime(&sysTime, &fTime);
216 XMEMCPY(&intTime, &fTime, sizeof(FILETIME));
218 intTime.QuadPart -= 0x19db1ded53e8000;
220 intTime.QuadPart /= 10000000;
221 *timer = (time_t)intTime.QuadPart;
226 #endif /* _WIN32_WCE */
227 #if defined( _WIN32_WCE ) || defined( USER_TIME )
229 struct tm* gmtime(const time_t* timer)
232 #define EPOCH_YEAR 1970
233 #define SECS_DAY (24L * 60L * 60L)
234 #define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) %400)))
235 #define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365)
237 static const int _ytab[2][12] =
239 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
240 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
243 static struct tm st_time;
244 struct tm* ret = &st_time;
245 time_t secs = *timer;
246 unsigned long dayclock, dayno;
247 int year = EPOCH_YEAR;
249 dayclock = (unsigned long)secs % SECS_DAY;
250 dayno = (unsigned long)secs / SECS_DAY;
252 ret->tm_sec = (int) dayclock % 60;
253 ret->tm_min = (int)(dayclock % 3600) / 60;
254 ret->tm_hour = (int) dayclock / 3600;
255 ret->tm_wday = (int) (dayno + 4) % 7; /* day 0 a Thursday */
257 while(dayno >= (unsigned long)YEARSIZE(year)) {
258 dayno -= YEARSIZE(year);
262 ret->tm_year = year - YEAR0;
263 ret->tm_yday = (int)dayno;
266 while(dayno >= (unsigned long)_ytab[LEAPYEAR(year)][ret->tm_mon]) {
267 dayno -= _ytab[LEAPYEAR(year)][ret->tm_mon];
271 ret->tm_mday = (int)++dayno;
277 #endif /* _WIN32_WCE || USER_TIME */
284 struct tm* my_gmtime(const time_t* timer) /* has a gmtime() but hangs */
286 static struct tm st_time;
287 struct tm* ret = &st_time;
290 dc_rtc_time_get(&cal, TRUE);
292 ret->tm_year = cal.year - YEAR0; /* gm starts at 1900 */
293 ret->tm_mon = cal.month - 1; /* gm starts at 0 */
294 ret->tm_mday = cal.day;
295 ret->tm_hour = cal.hour;
296 ret->tm_min = cal.minute;
297 ret->tm_sec = cal.second;
302 #endif /* HAVE_RTP_SYS */
305 #if defined(MICROCHIP_TCPIP_V5) || defined(MICROCHIP_TCPIP)
308 * time() is just a stub in Microchip libraries. We need our own
309 * implementation. Use SNTP client to get seconds since epoch.
311 time_t pic32_time(time_t* timer)
313 #ifdef MICROCHIP_TCPIP_V5
323 #ifdef MICROCHIP_MPLAB_HARMONY
324 sec = TCPIP_SNTP_UTCSecondsGet();
326 sec = SNTPGetUTCSeconds();
328 *timer = (time_t) sec;
333 #endif /* MICROCHIP_TCPIP */
338 time_t mqx_time(time_t* timer)
347 *timer = (time_t) time_s.SECONDS;
352 /* CodeWarrior GCC toolchain only has gmtime_r(), no gmtime() */
353 struct tm* mqx_gmtime(const time_t* clock, struct tm* tmpTime)
355 return gmtime_r(clock, tmpTime);
358 #endif /* FREESCALE_MQX */
360 #ifdef WOLFSSL_TIRTOS
362 time_t XTIME(time_t * timer)
366 sec = (time_t) Seconds_get();
374 #endif /* WOLFSSL_TIRTOS */
376 static INLINE word32 btoi(byte b)
382 /* two byte date/time, add to value */
383 static INLINE void GetTime(int* value, const byte* date, int* idx)
387 *value += btoi(date[i++]) * 10;
388 *value += btoi(date[i++]);
396 CPU_INT32S NetSecure_ValidateDateHandler(CPU_INT08U *date, CPU_INT08U format,
399 CPU_BOOLEAN rtn_code;
412 if (format == ASN_UTC_TIME) {
413 if (btoi(date[0]) >= 5)
418 else { /* format == GENERALIZED_TIME */
419 year += btoi(date[i++]) * 1000;
420 year += btoi(date[i++]) * 100;
424 GetTime(&val, date, &i);
425 year = (CPU_INT16U)val;
428 GetTime(&val, date, &i);
429 month = (CPU_INT08U)val;
432 GetTime(&val, date, &i);
433 day = (CPU_INT16U)val;
436 GetTime(&val, date, &i);
437 hour = (CPU_INT08U)val;
440 GetTime(&val, date, &i);
441 min = (CPU_INT08U)val;
444 GetTime(&val, date, &i);
445 sec = (CPU_INT08U)val;
447 return NetSecure_ValidateDate(year, month, day, hour, min, sec, dateType);
453 WOLFSSL_LOCAL int GetLength(const byte* input, word32* inOutIdx, int* len,
457 word32 i = *inOutIdx;
460 *len = 0; /* default length */
462 if ( (i+1) > maxIdx) { /* for first read */
463 WOLFSSL_MSG("GetLength bad index on input");
468 if (b >= ASN_LONG_LENGTH) {
469 word32 bytes = b & 0x7F;
471 if ( (i+bytes) > maxIdx) { /* for reading bytes */
472 WOLFSSL_MSG("GetLength bad long length");
478 length = (length << 8) | b;
484 if ( (i+length) > maxIdx) { /* for user of length */
485 WOLFSSL_MSG("GetLength value exceeds buffer length");
497 WOLFSSL_LOCAL int GetSequence(const byte* input, word32* inOutIdx, int* len,
501 word32 idx = *inOutIdx;
503 if (input[idx++] != (ASN_SEQUENCE | ASN_CONSTRUCTED) ||
504 GetLength(input, &idx, &length, maxIdx) < 0)
514 WOLFSSL_LOCAL int GetSet(const byte* input, word32* inOutIdx, int* len,
518 word32 idx = *inOutIdx;
520 if (input[idx++] != (ASN_SET | ASN_CONSTRUCTED) ||
521 GetLength(input, &idx, &length, maxIdx) < 0)
531 /* winodws header clash for WinCE using GetVersion */
532 WOLFSSL_LOCAL int GetMyVersion(const byte* input, word32* inOutIdx, int* version)
534 word32 idx = *inOutIdx;
536 WOLFSSL_ENTER("GetMyVersion");
538 if (input[idx++] != ASN_INTEGER)
541 if (input[idx++] != 0x01)
542 return ASN_VERSION_E;
544 *version = input[idx++];
552 /* Get small count integer, 32 bits or less */
553 static int GetShortInt(const byte* input, word32* inOutIdx, int* number)
555 word32 idx = *inOutIdx;
560 if (input[idx++] != ASN_INTEGER)
568 *number = *number << 8 | input[idx++];
575 #endif /* !NO_PWDBASED */
578 /* May not have one, not an error */
579 static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version)
581 word32 idx = *inOutIdx;
583 WOLFSSL_ENTER("GetExplicitVersion");
584 if (input[idx++] == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
585 *inOutIdx = ++idx; /* eat header */
586 return GetMyVersion(input, inOutIdx, version);
596 WOLFSSL_LOCAL int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx,
599 word32 i = *inOutIdx;
603 if (b != ASN_INTEGER)
606 if (GetLength(input, &i, &length, maxIdx) < 0)
609 if ( (b = input[i++]) == 0x00)
614 if (mp_init(mpi) != MP_OKAY)
617 if (mp_read_unsigned_bin(mpi, (byte*)input + i, length) != 0) {
622 *inOutIdx = i + length;
627 static int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
631 word32 i = *inOutIdx;
636 if (b != ASN_OBJECT_ID)
637 return ASN_OBJECT_ID_E;
639 if (GetLength(input, &i, &length, maxIdx) < 0)
644 /* just sum it up for now */
652 WOLFSSL_LOCAL int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
656 word32 i = *inOutIdx;
660 WOLFSSL_ENTER("GetAlgoId");
662 if (GetSequence(input, &i, &length, maxIdx) < 0)
666 if (b != ASN_OBJECT_ID)
667 return ASN_OBJECT_ID_E;
669 if (GetLength(input, &i, &length, maxIdx) < 0)
673 /* odd HC08 compiler behavior here when input[i++] */
677 /* just sum it up for now */
679 /* could have NULL tag and 0 terminator, but may not */
682 if (b == ASN_TAG_NULL) {
685 return ASN_EXPECT_0_E;
688 /* go back, didn't have it */
701 static int GetCaviumInt(byte** buff, word16* buffSz, const byte* input,
702 word32* inOutIdx, word32 maxIdx, void* heap)
704 word32 i = *inOutIdx;
708 if (b != ASN_INTEGER)
711 if (GetLength(input, &i, &length, maxIdx) < 0)
714 if ( (b = input[i++]) == 0x00)
719 *buffSz = (word16)length;
720 *buff = XMALLOC(*buffSz, heap, DYNAMIC_TYPE_CAVIUM_RSA);
724 XMEMCPY(*buff, input + i, *buffSz);
726 *inOutIdx = i + length;
730 static int CaviumRsaPrivateKeyDecode(const byte* input, word32* inOutIdx,
731 RsaKey* key, word32 inSz)
736 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
739 if (GetMyVersion(input, inOutIdx, &version) < 0)
742 key->type = RSA_PRIVATE;
744 if (GetCaviumInt(&key->c_n, &key->c_nSz, input, inOutIdx, inSz, h) < 0 ||
745 GetCaviumInt(&key->c_e, &key->c_eSz, input, inOutIdx, inSz, h) < 0 ||
746 GetCaviumInt(&key->c_d, &key->c_dSz, input, inOutIdx, inSz, h) < 0 ||
747 GetCaviumInt(&key->c_p, &key->c_pSz, input, inOutIdx, inSz, h) < 0 ||
748 GetCaviumInt(&key->c_q, &key->c_qSz, input, inOutIdx, inSz, h) < 0 ||
749 GetCaviumInt(&key->c_dP, &key->c_dP_Sz, input, inOutIdx, inSz, h) < 0 ||
750 GetCaviumInt(&key->c_dQ, &key->c_dQ_Sz, input, inOutIdx, inSz, h) < 0 ||
751 GetCaviumInt(&key->c_u, &key->c_uSz, input, inOutIdx, inSz, h) < 0 )
752 return ASN_RSA_KEY_E;
758 #endif /* HAVE_CAVIUM */
760 int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
766 if (key->magic == WOLFSSL_RSA_CAVIUM_MAGIC)
767 return CaviumRsaPrivateKeyDecode(input, inOutIdx, key, inSz);
770 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
773 if (GetMyVersion(input, inOutIdx, &version) < 0)
776 key->type = RSA_PRIVATE;
778 if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
779 GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
780 GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
781 GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
782 GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
783 GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
784 GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
785 GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
792 /* Remove PKCS8 header, move beginning of traditional to beginning of input */
793 int ToTraditional(byte* input, word32 sz)
795 word32 inOutIdx = 0, oid;
798 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
801 if (GetMyVersion(input, &inOutIdx, &version) < 0)
804 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
807 if (input[inOutIdx] == ASN_OBJECT_ID) {
808 /* pkcs8 ecc uses slightly different format */
809 inOutIdx++; /* past id */
810 if (GetLength(input, &inOutIdx, &length, sz) < 0)
812 inOutIdx += length; /* over sub id, key input will verify */
815 if (input[inOutIdx++] != ASN_OCTET_STRING)
818 if (GetLength(input, &inOutIdx, &length, sz) < 0)
821 XMEMMOVE(input, input + inOutIdx, length);
829 /* Check To see if PKCS version algo is supported, set id if it is return 0
831 static int CheckAlgo(int first, int second, int* id, int* version)
834 *version = PKCS5; /* default */
839 *id = PBE_SHA1_RC4_128;
852 return ASN_INPUT_E; /* VERSION ERROR */
854 if (second == PBES2) {
860 case 3: /* see RFC 2898 for ids */
873 /* Check To see if PKCS v2 algo is supported, set id if it is return 0
875 static int CheckAlgoV2(int oid, int* id)
891 /* Decrypt intput in place from parameters based on id */
892 static int DecryptKey(const char* password, int passwordSz, byte* salt,
893 int saltSz, int iterations, int id, byte* input,
894 int length, int version, byte* cbcIv)
900 #ifdef WOLFSSL_SMALL_STACK
903 byte key[MAX_KEY_SIZE];
909 derivedLen = 16; /* may need iv for v1.5 */
910 decryptionType = DES_TYPE;
915 derivedLen = 16; /* may need iv for v1.5 */
916 decryptionType = DES_TYPE;
921 derivedLen = 32; /* may need iv for v1.5 */
922 decryptionType = DES3_TYPE;
925 case PBE_SHA1_RC4_128:
928 decryptionType = RC4_TYPE;
935 #ifdef WOLFSSL_SMALL_STACK
936 key = (byte*)XMALLOC(MAX_KEY_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
941 if (version == PKCS5v2)
942 ret = wc_PBKDF2(key, (byte*)password, passwordSz, salt, saltSz, iterations,
945 else if (version == PKCS5)
946 ret = wc_PBKDF1(key, (byte*)password, passwordSz, salt, saltSz, iterations,
949 else if (version == PKCS12) {
951 byte unicodePasswd[MAX_UNICODE_SZ];
953 if ( (passwordSz * 2 + 2) > (int)sizeof(unicodePasswd)) {
954 #ifdef WOLFSSL_SMALL_STACK
955 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
957 return UNICODE_SIZE_E;
960 for (i = 0; i < passwordSz; i++) {
961 unicodePasswd[idx++] = 0x00;
962 unicodePasswd[idx++] = (byte)password[i];
964 /* add trailing NULL */
965 unicodePasswd[idx++] = 0x00;
966 unicodePasswd[idx++] = 0x00;
968 ret = wc_PKCS12_PBKDF(key, unicodePasswd, idx, salt, saltSz,
969 iterations, derivedLen, typeH, 1);
970 if (decryptionType != RC4_TYPE)
971 ret += wc_PKCS12_PBKDF(cbcIv, unicodePasswd, idx, salt, saltSz,
972 iterations, 8, typeH, 2);
975 #ifdef WOLFSSL_SMALL_STACK
976 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
982 #ifdef WOLFSSL_SMALL_STACK
983 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
988 switch (decryptionType) {
993 byte* desIv = key + 8;
995 if (version == PKCS5v2 || version == PKCS12)
998 ret = wc_Des_SetKey(&dec, key, desIv, DES_DECRYPTION);
1000 #ifdef WOLFSSL_SMALL_STACK
1001 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1006 wc_Des_CbcDecrypt(&dec, input, input, length);
1013 byte* desIv = key + 24;
1015 if (version == PKCS5v2 || version == PKCS12)
1017 ret = wc_Des3_SetKey(&dec, key, desIv, DES_DECRYPTION);
1019 #ifdef WOLFSSL_SMALL_STACK
1020 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1024 ret = wc_Des3_CbcDecrypt(&dec, input, input, length);
1026 #ifdef WOLFSSL_SMALL_STACK
1027 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1039 wc_Arc4SetKey(&dec, key, derivedLen);
1040 wc_Arc4Process(&dec, input, input, length);
1046 #ifdef WOLFSSL_SMALL_STACK
1047 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1052 #ifdef WOLFSSL_SMALL_STACK
1053 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1060 /* Remove Encrypted PKCS8 header, move beginning of traditional to beginning
1062 int ToTraditionalEnc(byte* input, word32 sz,const char* password,int passwordSz)
1064 word32 inOutIdx = 0, oid;
1065 int first, second, length, version, saltSz, id;
1067 #ifdef WOLFSSL_SMALL_STACK
1071 byte salt[MAX_SALT_SIZE];
1072 byte cbcIv[MAX_IV_SIZE];
1075 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
1078 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
1081 first = input[inOutIdx - 2]; /* PKCS version alwyas 2nd to last byte */
1082 second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
1084 if (CheckAlgo(first, second, &id, &version) < 0)
1085 return ASN_INPUT_E; /* Algo ID error */
1087 if (version == PKCS5v2) {
1089 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
1092 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
1095 if (oid != PBKDF2_OID)
1099 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
1102 if (input[inOutIdx++] != ASN_OCTET_STRING)
1105 if (GetLength(input, &inOutIdx, &saltSz, sz) < 0)
1108 if (saltSz > MAX_SALT_SIZE)
1111 #ifdef WOLFSSL_SMALL_STACK
1112 salt = (byte*)XMALLOC(MAX_SALT_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1117 XMEMCPY(salt, &input[inOutIdx], saltSz);
1120 if (GetShortInt(input, &inOutIdx, &iterations) < 0) {
1121 #ifdef WOLFSSL_SMALL_STACK
1122 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1127 #ifdef WOLFSSL_SMALL_STACK
1128 cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1129 if (cbcIv == NULL) {
1130 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1135 if (version == PKCS5v2) {
1136 /* get encryption algo */
1137 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0) {
1138 #ifdef WOLFSSL_SMALL_STACK
1139 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1140 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1145 if (CheckAlgoV2(oid, &id) < 0) {
1146 #ifdef WOLFSSL_SMALL_STACK
1147 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1148 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1150 return ASN_PARSE_E; /* PKCS v2 algo id error */
1153 if (input[inOutIdx++] != ASN_OCTET_STRING) {
1154 #ifdef WOLFSSL_SMALL_STACK
1155 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1156 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1161 if (GetLength(input, &inOutIdx, &length, sz) < 0) {
1162 #ifdef WOLFSSL_SMALL_STACK
1163 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1164 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1169 XMEMCPY(cbcIv, &input[inOutIdx], length);
1173 if (input[inOutIdx++] != ASN_OCTET_STRING) {
1174 #ifdef WOLFSSL_SMALL_STACK
1175 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1176 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1181 if (GetLength(input, &inOutIdx, &length, sz) < 0) {
1182 #ifdef WOLFSSL_SMALL_STACK
1183 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1184 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1189 if (DecryptKey(password, passwordSz, salt, saltSz, iterations, id,
1190 input + inOutIdx, length, version, cbcIv) < 0) {
1191 #ifdef WOLFSSL_SMALL_STACK
1192 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1193 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1195 return ASN_INPUT_E; /* decrypt failure */
1198 #ifdef WOLFSSL_SMALL_STACK
1199 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1200 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1203 XMEMMOVE(input, input + inOutIdx, length);
1204 return ToTraditional(input, length);
1207 #endif /* NO_PWDBASED */
1211 int wc_RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
1216 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1219 key->type = RSA_PUBLIC;
1221 #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
1223 byte b = input[*inOutIdx];
1224 if (b != ASN_INTEGER) {
1225 /* not from decoded cert, will have algo id, skip past */
1226 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1229 b = input[(*inOutIdx)++];
1230 if (b != ASN_OBJECT_ID)
1231 return ASN_OBJECT_ID_E;
1233 if (GetLength(input, inOutIdx, &length, inSz) < 0)
1236 *inOutIdx += length; /* skip past */
1238 /* could have NULL tag and 0 terminator, but may not */
1239 b = input[(*inOutIdx)++];
1241 if (b == ASN_TAG_NULL) {
1242 b = input[(*inOutIdx)++];
1244 return ASN_EXPECT_0_E;
1247 /* go back, didn't have it */
1250 /* should have bit tag length and seq next */
1251 b = input[(*inOutIdx)++];
1252 if (b != ASN_BIT_STRING)
1253 return ASN_BITSTR_E;
1255 if (GetLength(input, inOutIdx, &length, inSz) < 0)
1259 b = input[(*inOutIdx)++];
1263 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1266 } /* openssl var block */
1267 #endif /* OPENSSL_EXTRA */
1269 if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
1270 GetInt(&key->e, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
1275 /* import RSA public key elements (n, e) into RsaKey structure (key) */
1276 int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e,
1277 word32 eSz, RsaKey* key)
1279 if (n == NULL || e == NULL || key == NULL)
1280 return BAD_FUNC_ARG;
1282 key->type = RSA_PUBLIC;
1284 if (mp_init(&key->n) != MP_OKAY)
1287 if (mp_read_unsigned_bin(&key->n, n, nSz) != 0) {
1289 return ASN_GETINT_E;
1292 if (mp_init(&key->e) != MP_OKAY) {
1297 if (mp_read_unsigned_bin(&key->e, e, eSz) != 0) {
1300 return ASN_GETINT_E;
1310 int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
1314 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1317 if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
1318 GetInt(&key->g, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
1324 int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
1325 byte* g, word32* gInOutSz)
1331 if (GetSequence(input, &i, &length, inSz) < 0)
1335 if (b != ASN_INTEGER)
1338 if (GetLength(input, &i, &length, inSz) < 0)
1341 if ( (b = input[i++]) == 0x00)
1346 if (length <= (int)*pInOutSz) {
1347 XMEMCPY(p, &input[i], length);
1356 if (b != ASN_INTEGER)
1359 if (GetLength(input, &i, &length, inSz) < 0)
1362 if (length <= (int)*gInOutSz) {
1363 XMEMCPY(g, &input[i], length);
1377 int DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
1382 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1385 if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
1386 GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
1387 GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
1388 GetInt(&key->y, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
1390 key->type = DSA_PUBLIC;
1395 int DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
1398 int length, version;
1400 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1403 if (GetMyVersion(input, inOutIdx, &version) < 0)
1406 if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
1407 GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
1408 GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
1409 GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
1410 GetInt(&key->x, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
1412 key->type = DSA_PRIVATE;
1419 void InitDecodedCert(DecodedCert* cert, byte* source, word32 inSz, void* heap)
1421 cert->publicKey = 0;
1422 cert->pubKeySize = 0;
1423 cert->pubKeyStored = 0;
1425 cert->signature = 0;
1426 cert->subjectCN = 0;
1427 cert->subjectCNLen = 0;
1428 cert->subjectCNEnc = CTC_UTF8;
1429 cert->subjectCNStored = 0;
1430 cert->weOwnAltNames = 0;
1431 cert->altNames = NULL;
1432 #ifndef IGNORE_NAME_CONSTRAINTS
1433 cert->altEmailNames = NULL;
1434 cert->permittedNames = NULL;
1435 cert->excludedNames = NULL;
1436 #endif /* IGNORE_NAME_CONSTRAINTS */
1437 cert->issuer[0] = '\0';
1438 cert->subject[0] = '\0';
1439 cert->source = source; /* don't own */
1441 cert->maxIdx = inSz; /* can't go over this index */
1443 XMEMSET(cert->serial, 0, EXTERNAL_SERIAL_SIZE);
1445 cert->extensions = 0;
1446 cert->extensionsSz = 0;
1447 cert->extensionsIdx = 0;
1448 cert->extAuthInfo = NULL;
1449 cert->extAuthInfoSz = 0;
1450 cert->extCrlInfo = NULL;
1451 cert->extCrlInfoSz = 0;
1452 XMEMSET(cert->extSubjKeyId, 0, KEYID_SIZE);
1453 cert->extSubjKeyIdSet = 0;
1454 XMEMSET(cert->extAuthKeyId, 0, KEYID_SIZE);
1455 cert->extAuthKeyIdSet = 0;
1456 cert->extKeyUsageSet = 0;
1457 cert->extKeyUsage = 0;
1458 cert->extExtKeyUsageSet = 0;
1459 cert->extExtKeyUsage = 0;
1462 cert->issuerRaw = NULL;
1463 cert->issuerRawLen = 0;
1465 #ifdef WOLFSSL_CERT_GEN
1466 cert->subjectSN = 0;
1467 cert->subjectSNLen = 0;
1468 cert->subjectSNEnc = CTC_UTF8;
1470 cert->subjectCLen = 0;
1471 cert->subjectCEnc = CTC_PRINTABLE;
1473 cert->subjectLLen = 0;
1474 cert->subjectLEnc = CTC_UTF8;
1475 cert->subjectST = 0;
1476 cert->subjectSTLen = 0;
1477 cert->subjectSTEnc = CTC_UTF8;
1479 cert->subjectOLen = 0;
1480 cert->subjectOEnc = CTC_UTF8;
1481 cert->subjectOU = 0;
1482 cert->subjectOULen = 0;
1483 cert->subjectOUEnc = CTC_UTF8;
1484 cert->subjectEmail = 0;
1485 cert->subjectEmailLen = 0;
1486 #endif /* WOLFSSL_CERT_GEN */
1487 cert->beforeDate = NULL;
1488 cert->beforeDateLen = 0;
1489 cert->afterDate = NULL;
1490 cert->afterDateLen = 0;
1491 #ifdef OPENSSL_EXTRA
1492 XMEMSET(&cert->issuerName, 0, sizeof(DecodedName));
1493 XMEMSET(&cert->subjectName, 0, sizeof(DecodedName));
1494 cert->extBasicConstSet = 0;
1495 cert->extBasicConstCrit = 0;
1496 cert->extBasicConstPlSet = 0;
1497 cert->pathLength = 0;
1498 cert->extSubjAltNameSet = 0;
1499 cert->extSubjAltNameCrit = 0;
1500 cert->extAuthKeyIdCrit = 0;
1501 cert->extSubjKeyIdCrit = 0;
1502 cert->extKeyUsageCrit = 0;
1503 cert->extExtKeyUsageCrit = 0;
1504 cert->extExtKeyUsageSrc = NULL;
1505 cert->extExtKeyUsageSz = 0;
1506 cert->extExtKeyUsageCount = 0;
1507 cert->extAuthKeyIdSrc = NULL;
1508 cert->extAuthKeyIdSz = 0;
1509 cert->extSubjKeyIdSrc = NULL;
1510 cert->extSubjKeyIdSz = 0;
1511 #endif /* OPENSSL_EXTRA */
1512 #if defined(OPENSSL_EXTRA) || !defined(IGNORE_NAME_CONSTRAINTS)
1513 cert->extNameConstraintSet = 0;
1514 #endif /* OPENSSL_EXTRA || !IGNORE_NAME_CONSTRAINTS */
1516 cert->pkCurveOID = 0;
1517 #endif /* HAVE_ECC */
1519 cert->deviceTypeSz = 0;
1520 cert->deviceType = NULL;
1522 cert->hwType = NULL;
1523 cert->hwSerialNumSz = 0;
1524 cert->hwSerialNum = NULL;
1525 #ifdef OPENSSL_EXTRA
1526 cert->extCertPolicySet = 0;
1527 cert->extCertPolicyCrit = 0;
1528 #endif /* OPENSSL_EXTRA */
1529 #endif /* WOLFSSL_SEP */
1533 void FreeAltNames(DNS_entry* altNames, void* heap)
1538 DNS_entry* tmp = altNames->next;
1540 XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
1541 XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME);
1546 #ifndef IGNORE_NAME_CONSTRAINTS
1548 void FreeNameSubtrees(Base_entry* names, void* heap)
1553 Base_entry* tmp = names->next;
1555 XFREE(names->name, heap, DYNAMIC_TYPE_ALTNAME);
1556 XFREE(names, heap, DYNAMIC_TYPE_ALTNAME);
1561 #endif /* IGNORE_NAME_CONSTRAINTS */
1563 void FreeDecodedCert(DecodedCert* cert)
1565 if (cert->subjectCNStored == 1)
1566 XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
1567 if (cert->pubKeyStored == 1)
1568 XFREE(cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
1569 if (cert->weOwnAltNames && cert->altNames)
1570 FreeAltNames(cert->altNames, cert->heap);
1571 #ifndef IGNORE_NAME_CONSTRAINTS
1572 if (cert->altEmailNames)
1573 FreeAltNames(cert->altEmailNames, cert->heap);
1574 if (cert->permittedNames)
1575 FreeNameSubtrees(cert->permittedNames, cert->heap);
1576 if (cert->excludedNames)
1577 FreeNameSubtrees(cert->excludedNames, cert->heap);
1578 #endif /* IGNORE_NAME_CONSTRAINTS */
1580 XFREE(cert->deviceType, cert->heap, 0);
1581 XFREE(cert->hwType, cert->heap, 0);
1582 XFREE(cert->hwSerialNum, cert->heap, 0);
1583 #endif /* WOLFSSL_SEP */
1584 #ifdef OPENSSL_EXTRA
1585 if (cert->issuerName.fullName != NULL)
1586 XFREE(cert->issuerName.fullName, NULL, DYNAMIC_TYPE_X509);
1587 if (cert->subjectName.fullName != NULL)
1588 XFREE(cert->subjectName.fullName, NULL, DYNAMIC_TYPE_X509);
1589 #endif /* OPENSSL_EXTRA */
1593 static int GetCertHeader(DecodedCert* cert)
1596 byte serialTmp[EXTERNAL_SERIAL_SIZE];
1597 #if defined(WOLFSSL_SMALL_STACK) && defined(USE_FAST_MATH)
1601 mp_int* mpi = &stack_mpi;
1604 if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
1607 cert->certBegin = cert->srcIdx;
1609 if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
1611 cert->sigIndex = len + cert->srcIdx;
1613 if (GetExplicitVersion(cert->source, &cert->srcIdx, &cert->version) < 0)
1616 #if defined(WOLFSSL_SMALL_STACK) && defined(USE_FAST_MATH)
1617 mpi = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_TMP_BUFFER);
1622 if (GetInt(mpi, cert->source, &cert->srcIdx, cert->maxIdx) < 0) {
1623 #if defined(WOLFSSL_SMALL_STACK) && defined(USE_FAST_MATH)
1624 XFREE(mpi, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1629 len = mp_unsigned_bin_size(mpi);
1630 if (len < (int)sizeof(serialTmp)) {
1631 if ( (ret = mp_to_unsigned_bin(mpi, serialTmp)) == MP_OKAY) {
1632 XMEMCPY(cert->serial, serialTmp, len);
1633 cert->serialSz = len;
1638 #if defined(WOLFSSL_SMALL_STACK) && defined(USE_FAST_MATH)
1639 XFREE(mpi, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1645 #if !defined(NO_RSA)
1646 /* Store Rsa Key, may save later, Dsa could use in future */
1647 static int StoreRsaKey(DecodedCert* cert)
1650 word32 recvd = cert->srcIdx;
1652 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1655 recvd = cert->srcIdx - recvd;
1661 cert->pubKeySize = length;
1662 cert->publicKey = cert->source + cert->srcIdx;
1663 cert->srcIdx += length;
1672 /* return 0 on sucess if the ECC curve oid sum is supported */
1673 static int CheckCurve(word32 oid)
1678 #if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC160)
1681 #if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC192)
1684 #if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC224)
1687 #if defined(HAVE_ALL_CURVES) || !defined(NO_ECC256)
1690 #if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC384)
1693 #if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC521)
1705 #endif /* HAVE_ECC */
1708 static int GetKey(DecodedCert* cert)
1712 int tmpIdx = cert->srcIdx;
1715 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1718 if (GetAlgoId(cert->source, &cert->srcIdx, &cert->keyOID, cert->maxIdx) < 0)
1721 switch (cert->keyOID) {
1725 byte b = cert->source[cert->srcIdx++];
1726 if (b != ASN_BIT_STRING)
1727 return ASN_BITSTR_E;
1729 if (GetLength(cert->source,&cert->srcIdx,&length,cert->maxIdx) < 0)
1731 b = cert->source[cert->srcIdx++];
1733 return ASN_EXPECT_0_E;
1735 return StoreRsaKey(cert);
1742 const byte* key = &cert->source[tmpIdx];
1743 byte* next = (byte*)key;
1746 word32 remaining = cert->maxIdx - cert->srcIdx;
1747 #ifdef WOLFSSL_SMALL_STACK
1748 byte* keyBlob = NULL;
1750 byte keyBlob[MAX_NTRU_KEY_SZ];
1752 rc = ntru_crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key,
1753 &keyLen, NULL, &next, &remaining);
1755 return ASN_NTRU_KEY_E;
1756 if (keyLen > MAX_NTRU_KEY_SZ)
1757 return ASN_NTRU_KEY_E;
1759 #ifdef WOLFSSL_SMALL_STACK
1760 keyBlob = (byte*)XMALLOC(MAX_NTRU_KEY_SZ, NULL,
1761 DYNAMIC_TYPE_TMP_BUFFER);
1762 if (keyBlob == NULL)
1766 rc = ntru_crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key,
1767 &keyLen, keyBlob, &next, &remaining);
1768 if (rc != NTRU_OK) {
1769 #ifdef WOLFSSL_SMALL_STACK
1770 XFREE(keyBlob, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1772 return ASN_NTRU_KEY_E;
1775 if ( (next - key) < 0) {
1776 #ifdef WOLFSSL_SMALL_STACK
1777 XFREE(keyBlob, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1779 return ASN_NTRU_KEY_E;
1782 cert->srcIdx = tmpIdx + (int)(next - key);
1784 cert->publicKey = (byte*) XMALLOC(keyLen, cert->heap,
1785 DYNAMIC_TYPE_PUBLIC_KEY);
1786 if (cert->publicKey == NULL) {
1787 #ifdef WOLFSSL_SMALL_STACK
1788 XFREE(keyBlob, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1792 XMEMCPY(cert->publicKey, keyBlob, keyLen);
1793 cert->pubKeyStored = 1;
1794 cert->pubKeySize = keyLen;
1796 #ifdef WOLFSSL_SMALL_STACK
1797 XFREE(keyBlob, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1802 #endif /* HAVE_NTRU */
1807 byte b = cert->source[cert->srcIdx++];
1809 if (b != ASN_OBJECT_ID)
1810 return ASN_OBJECT_ID_E;
1812 if (GetLength(cert->source,&cert->srcIdx,&oidSz,cert->maxIdx) < 0)
1816 cert->pkCurveOID += cert->source[cert->srcIdx++];
1818 if (CheckCurve(cert->pkCurveOID) < 0)
1819 return ECC_CURVE_OID_E;
1822 b = cert->source[cert->srcIdx++];
1823 if (b != ASN_BIT_STRING)
1824 return ASN_BITSTR_E;
1826 if (GetLength(cert->source,&cert->srcIdx,&length,cert->maxIdx) < 0)
1828 b = cert->source[cert->srcIdx++];
1830 return ASN_EXPECT_0_E;
1832 /* actual key, use length - 1 since ate preceding 0 */
1835 cert->publicKey = (byte*) XMALLOC(length, cert->heap,
1836 DYNAMIC_TYPE_PUBLIC_KEY);
1837 if (cert->publicKey == NULL)
1839 XMEMCPY(cert->publicKey, &cert->source[cert->srcIdx], length);
1840 cert->pubKeyStored = 1;
1841 cert->pubKeySize = length;
1843 cert->srcIdx += length;
1847 #endif /* HAVE_ECC */
1849 return ASN_UNKNOWN_OID_E;
1854 /* process NAME, either issuer or subject */
1855 static int GetName(DecodedCert* cert, int nameType)
1857 int length; /* length of all distinguished names */
1863 #ifdef OPENSSL_EXTRA
1864 DecodedName* dName =
1865 (nameType == ISSUER) ? &cert->issuerName : &cert->subjectName;
1866 #endif /* OPENSSL_EXTRA */
1868 WOLFSSL_MSG("Getting Cert Name");
1870 if (nameType == ISSUER) {
1871 full = cert->issuer;
1872 hash = cert->issuerHash;
1875 full = cert->subject;
1876 hash = cert->subjectHash;
1879 if (cert->source[cert->srcIdx] == ASN_OBJECT_ID) {
1880 WOLFSSL_MSG("Trying optional prefix...");
1882 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1885 cert->srcIdx += length;
1886 WOLFSSL_MSG("Got optional prefix");
1889 /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
1890 * calculated over the entire DER encoding of the Name field, including
1891 * the tag and length. */
1893 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1897 ret = wc_Sha256Hash(&cert->source[idx], length + cert->srcIdx - idx, hash);
1899 ret = wc_ShaHash(&cert->source[idx], length + cert->srcIdx - idx, hash);
1904 length += cert->srcIdx;
1908 /* store pointer to raw issuer */
1909 if (nameType == ISSUER) {
1910 cert->issuerRaw = &cert->source[cert->srcIdx];
1911 cert->issuerRawLen = length - cert->srcIdx;
1914 #ifndef IGNORE_NAME_CONSTRAINTS
1915 if (nameType == SUBJECT) {
1916 cert->subjectRaw = &cert->source[cert->srcIdx];
1917 cert->subjectRawLen = length - cert->srcIdx;
1921 while (cert->srcIdx < (word32)length) {
1924 byte tooBig = FALSE;
1927 if (GetSet(cert->source, &cert->srcIdx, &dummy, cert->maxIdx) < 0) {
1928 WOLFSSL_MSG("Cert name lacks set header, trying sequence");
1931 if (GetSequence(cert->source, &cert->srcIdx, &dummy, cert->maxIdx) < 0)
1934 b = cert->source[cert->srcIdx++];
1935 if (b != ASN_OBJECT_ID)
1936 return ASN_OBJECT_ID_E;
1938 if (GetLength(cert->source, &cert->srcIdx, &oidSz, cert->maxIdx) < 0)
1941 XMEMCPY(joint, &cert->source[cert->srcIdx], sizeof(joint));
1944 if (joint[0] == 0x55 && joint[1] == 0x04) {
1950 id = cert->source[cert->srcIdx++];
1951 b = cert->source[cert->srcIdx++]; /* encoding */
1953 if (GetLength(cert->source, &cert->srcIdx, &strLen,
1957 if ( (strLen + 14) > (int)(ASN_NAME_MAX - idx)) {
1958 /* include biggest pre fix header too 4 = "/serialNumber=" */
1959 WOLFSSL_MSG("ASN Name too big, skipping");
1963 if (id == ASN_COMMON_NAME) {
1964 if (nameType == SUBJECT) {
1965 cert->subjectCN = (char *)&cert->source[cert->srcIdx];
1966 cert->subjectCNLen = strLen;
1967 cert->subjectCNEnc = b;
1971 XMEMCPY(&full[idx], "/CN=", 4);
1975 #ifdef OPENSSL_EXTRA
1976 dName->cnIdx = cert->srcIdx;
1977 dName->cnLen = strLen;
1978 #endif /* OPENSSL_EXTRA */
1980 else if (id == ASN_SUR_NAME) {
1982 XMEMCPY(&full[idx], "/SN=", 4);
1986 #ifdef WOLFSSL_CERT_GEN
1987 if (nameType == SUBJECT) {
1988 cert->subjectSN = (char*)&cert->source[cert->srcIdx];
1989 cert->subjectSNLen = strLen;
1990 cert->subjectSNEnc = b;
1992 #endif /* WOLFSSL_CERT_GEN */
1993 #ifdef OPENSSL_EXTRA
1994 dName->snIdx = cert->srcIdx;
1995 dName->snLen = strLen;
1996 #endif /* OPENSSL_EXTRA */
1998 else if (id == ASN_COUNTRY_NAME) {
2000 XMEMCPY(&full[idx], "/C=", 3);
2004 #ifdef WOLFSSL_CERT_GEN
2005 if (nameType == SUBJECT) {
2006 cert->subjectC = (char*)&cert->source[cert->srcIdx];
2007 cert->subjectCLen = strLen;
2008 cert->subjectCEnc = b;
2010 #endif /* WOLFSSL_CERT_GEN */
2011 #ifdef OPENSSL_EXTRA
2012 dName->cIdx = cert->srcIdx;
2013 dName->cLen = strLen;
2014 #endif /* OPENSSL_EXTRA */
2016 else if (id == ASN_LOCALITY_NAME) {
2018 XMEMCPY(&full[idx], "/L=", 3);
2022 #ifdef WOLFSSL_CERT_GEN
2023 if (nameType == SUBJECT) {
2024 cert->subjectL = (char*)&cert->source[cert->srcIdx];
2025 cert->subjectLLen = strLen;
2026 cert->subjectLEnc = b;
2028 #endif /* WOLFSSL_CERT_GEN */
2029 #ifdef OPENSSL_EXTRA
2030 dName->lIdx = cert->srcIdx;
2031 dName->lLen = strLen;
2032 #endif /* OPENSSL_EXTRA */
2034 else if (id == ASN_STATE_NAME) {
2036 XMEMCPY(&full[idx], "/ST=", 4);
2040 #ifdef WOLFSSL_CERT_GEN
2041 if (nameType == SUBJECT) {
2042 cert->subjectST = (char*)&cert->source[cert->srcIdx];
2043 cert->subjectSTLen = strLen;
2044 cert->subjectSTEnc = b;
2046 #endif /* WOLFSSL_CERT_GEN */
2047 #ifdef OPENSSL_EXTRA
2048 dName->stIdx = cert->srcIdx;
2049 dName->stLen = strLen;
2050 #endif /* OPENSSL_EXTRA */
2052 else if (id == ASN_ORG_NAME) {
2054 XMEMCPY(&full[idx], "/O=", 3);
2058 #ifdef WOLFSSL_CERT_GEN
2059 if (nameType == SUBJECT) {
2060 cert->subjectO = (char*)&cert->source[cert->srcIdx];
2061 cert->subjectOLen = strLen;
2062 cert->subjectOEnc = b;
2064 #endif /* WOLFSSL_CERT_GEN */
2065 #ifdef OPENSSL_EXTRA
2066 dName->oIdx = cert->srcIdx;
2067 dName->oLen = strLen;
2068 #endif /* OPENSSL_EXTRA */
2070 else if (id == ASN_ORGUNIT_NAME) {
2072 XMEMCPY(&full[idx], "/OU=", 4);
2076 #ifdef WOLFSSL_CERT_GEN
2077 if (nameType == SUBJECT) {
2078 cert->subjectOU = (char*)&cert->source[cert->srcIdx];
2079 cert->subjectOULen = strLen;
2080 cert->subjectOUEnc = b;
2082 #endif /* WOLFSSL_CERT_GEN */
2083 #ifdef OPENSSL_EXTRA
2084 dName->ouIdx = cert->srcIdx;
2085 dName->ouLen = strLen;
2086 #endif /* OPENSSL_EXTRA */
2088 else if (id == ASN_SERIAL_NUMBER) {
2090 XMEMCPY(&full[idx], "/serialNumber=", 14);
2094 #ifdef OPENSSL_EXTRA
2095 dName->snIdx = cert->srcIdx;
2096 dName->snLen = strLen;
2097 #endif /* OPENSSL_EXTRA */
2100 if (copy && !tooBig) {
2101 XMEMCPY(&full[idx], &cert->source[cert->srcIdx], strLen);
2105 cert->srcIdx += strLen;
2113 if (joint[0] == 0x2a && joint[1] == 0x86) /* email id hdr */
2116 if (joint[0] == 0x9 && joint[1] == 0x92) /* uid id hdr */
2119 cert->srcIdx += oidSz + 1;
2121 if (GetLength(cert->source, &cert->srcIdx, &adv, cert->maxIdx) < 0)
2124 if (adv > (int)(ASN_NAME_MAX - idx)) {
2125 WOLFSSL_MSG("ASN name too big, skipping");
2130 if ( (14 + adv) > (int)(ASN_NAME_MAX - idx)) {
2131 WOLFSSL_MSG("ASN name too big, skipping");
2135 XMEMCPY(&full[idx], "/emailAddress=", 14);
2139 #ifdef WOLFSSL_CERT_GEN
2140 if (nameType == SUBJECT) {
2141 cert->subjectEmail = (char*)&cert->source[cert->srcIdx];
2142 cert->subjectEmailLen = adv;
2144 #endif /* WOLFSSL_CERT_GEN */
2145 #ifdef OPENSSL_EXTRA
2146 dName->emailIdx = cert->srcIdx;
2147 dName->emailLen = adv;
2148 #endif /* OPENSSL_EXTRA */
2149 #ifndef IGNORE_NAME_CONSTRAINTS
2151 DNS_entry* emailName = NULL;
2153 emailName = (DNS_entry*)XMALLOC(sizeof(DNS_entry),
2154 cert->heap, DYNAMIC_TYPE_ALTNAME);
2155 if (emailName == NULL) {
2156 WOLFSSL_MSG("\tOut of Memory");
2159 emailName->name = (char*)XMALLOC(adv + 1,
2160 cert->heap, DYNAMIC_TYPE_ALTNAME);
2161 if (emailName->name == NULL) {
2162 WOLFSSL_MSG("\tOut of Memory");
2165 XMEMCPY(emailName->name,
2166 &cert->source[cert->srcIdx], adv);
2167 emailName->name[adv] = 0;
2169 emailName->next = cert->altEmailNames;
2170 cert->altEmailNames = emailName;
2172 #endif /* IGNORE_NAME_CONSTRAINTS */
2174 XMEMCPY(&full[idx], &cert->source[cert->srcIdx], adv);
2180 if ( (5 + adv) > (int)(ASN_NAME_MAX - idx)) {
2181 WOLFSSL_MSG("ASN name too big, skipping");
2185 XMEMCPY(&full[idx], "/UID=", 5);
2188 XMEMCPY(&full[idx], &cert->source[cert->srcIdx], adv);
2191 #ifdef OPENSSL_EXTRA
2192 dName->uidIdx = cert->srcIdx;
2193 dName->uidLen = adv;
2194 #endif /* OPENSSL_EXTRA */
2197 cert->srcIdx += adv;
2202 #ifdef OPENSSL_EXTRA
2206 if (dName->cnLen != 0)
2207 totalLen += dName->cnLen + 4;
2208 if (dName->snLen != 0)
2209 totalLen += dName->snLen + 4;
2210 if (dName->cLen != 0)
2211 totalLen += dName->cLen + 3;
2212 if (dName->lLen != 0)
2213 totalLen += dName->lLen + 3;
2214 if (dName->stLen != 0)
2215 totalLen += dName->stLen + 4;
2216 if (dName->oLen != 0)
2217 totalLen += dName->oLen + 3;
2218 if (dName->ouLen != 0)
2219 totalLen += dName->ouLen + 4;
2220 if (dName->emailLen != 0)
2221 totalLen += dName->emailLen + 14;
2222 if (dName->uidLen != 0)
2223 totalLen += dName->uidLen + 5;
2224 if (dName->serialLen != 0)
2225 totalLen += dName->serialLen + 14;
2227 dName->fullName = (char*)XMALLOC(totalLen + 1, NULL, DYNAMIC_TYPE_X509);
2228 if (dName->fullName != NULL) {
2231 if (dName->cnLen != 0) {
2232 dName->entryCount++;
2233 XMEMCPY(&dName->fullName[idx], "/CN=", 4);
2235 XMEMCPY(&dName->fullName[idx],
2236 &cert->source[dName->cnIdx], dName->cnLen);
2238 idx += dName->cnLen;
2240 if (dName->snLen != 0) {
2241 dName->entryCount++;
2242 XMEMCPY(&dName->fullName[idx], "/SN=", 4);
2244 XMEMCPY(&dName->fullName[idx],
2245 &cert->source[dName->snIdx], dName->snLen);
2247 idx += dName->snLen;
2249 if (dName->cLen != 0) {
2250 dName->entryCount++;
2251 XMEMCPY(&dName->fullName[idx], "/C=", 3);
2253 XMEMCPY(&dName->fullName[idx],
2254 &cert->source[dName->cIdx], dName->cLen);
2258 if (dName->lLen != 0) {
2259 dName->entryCount++;
2260 XMEMCPY(&dName->fullName[idx], "/L=", 3);
2262 XMEMCPY(&dName->fullName[idx],
2263 &cert->source[dName->lIdx], dName->lLen);
2267 if (dName->stLen != 0) {
2268 dName->entryCount++;
2269 XMEMCPY(&dName->fullName[idx], "/ST=", 4);
2271 XMEMCPY(&dName->fullName[idx],
2272 &cert->source[dName->stIdx], dName->stLen);
2274 idx += dName->stLen;
2276 if (dName->oLen != 0) {
2277 dName->entryCount++;
2278 XMEMCPY(&dName->fullName[idx], "/O=", 3);
2280 XMEMCPY(&dName->fullName[idx],
2281 &cert->source[dName->oIdx], dName->oLen);
2285 if (dName->ouLen != 0) {
2286 dName->entryCount++;
2287 XMEMCPY(&dName->fullName[idx], "/OU=", 4);
2289 XMEMCPY(&dName->fullName[idx],
2290 &cert->source[dName->ouIdx], dName->ouLen);
2292 idx += dName->ouLen;
2294 if (dName->emailLen != 0) {
2295 dName->entryCount++;
2296 XMEMCPY(&dName->fullName[idx], "/emailAddress=", 14);
2298 XMEMCPY(&dName->fullName[idx],
2299 &cert->source[dName->emailIdx], dName->emailLen);
2300 dName->emailIdx = idx;
2301 idx += dName->emailLen;
2303 if (dName->uidLen != 0) {
2304 dName->entryCount++;
2305 XMEMCPY(&dName->fullName[idx], "/UID=", 5);
2307 XMEMCPY(&dName->fullName[idx],
2308 &cert->source[dName->uidIdx], dName->uidLen);
2309 dName->uidIdx = idx;
2310 idx += dName->uidLen;
2312 if (dName->serialLen != 0) {
2313 dName->entryCount++;
2314 XMEMCPY(&dName->fullName[idx], "/serialNumber=", 14);
2316 XMEMCPY(&dName->fullName[idx],
2317 &cert->source[dName->serialIdx], dName->serialLen);
2318 dName->serialIdx = idx;
2319 idx += dName->serialLen;
2321 dName->fullName[idx] = '\0';
2322 dName->fullNameLen = totalLen;
2325 #endif /* OPENSSL_EXTRA */
2334 static int DateGreaterThan(const struct tm* a, const struct tm* b)
2336 if (a->tm_year > b->tm_year)
2339 if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
2342 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
2343 a->tm_mday > b->tm_mday)
2346 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
2347 a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
2350 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
2351 a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
2352 a->tm_min > b->tm_min)
2355 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
2356 a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
2357 a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
2360 return 0; /* false */
2364 static INLINE int DateLessThan(const struct tm* a, const struct tm* b)
2366 return DateGreaterThan(b,a);
2370 /* like atoi but only use first byte */
2371 /* Make sure before and after dates are valid */
2372 int ValidateDate(const byte* date, byte format, int dateType)
2376 struct tm* localTime;
2377 struct tm* tmpTime = NULL;
2380 #if defined(FREESCALE_MQX) || defined(TIME_OVERRIDES)
2381 struct tm tmpTimeStorage;
2382 tmpTime = &tmpTimeStorage;
2388 XMEMSET(&certTime, 0, sizeof(certTime));
2390 if (format == ASN_UTC_TIME) {
2391 if (btoi(date[0]) >= 5)
2392 certTime.tm_year = 1900;
2394 certTime.tm_year = 2000;
2396 else { /* format == GENERALIZED_TIME */
2397 certTime.tm_year += btoi(date[i++]) * 1000;
2398 certTime.tm_year += btoi(date[i++]) * 100;
2401 /* adjust tm_year, tm_mon */
2402 GetTime((int*)&certTime.tm_year, date, &i); certTime.tm_year -= 1900;
2403 GetTime((int*)&certTime.tm_mon, date, &i); certTime.tm_mon -= 1;
2404 GetTime((int*)&certTime.tm_mday, date, &i);
2405 GetTime((int*)&certTime.tm_hour, date, &i);
2406 GetTime((int*)&certTime.tm_min, date, &i);
2407 GetTime((int*)&certTime.tm_sec, date, &i);
2409 if (date[i] != 'Z') { /* only Zulu supported for this profile */
2410 WOLFSSL_MSG("Only Zulu time supported for this profile");
2414 localTime = XGMTIME(<ime, tmpTime);
2416 if (dateType == BEFORE) {
2417 if (DateLessThan(localTime, &certTime))
2421 if (DateGreaterThan(localTime, &certTime))
2427 #endif /* NO_TIME_H */
2430 static int GetDate(DecodedCert* cert, int dateType)
2433 byte date[MAX_DATE_SIZE];
2435 word32 startIdx = 0;
2437 if (dateType == BEFORE)
2438 cert->beforeDate = &cert->source[cert->srcIdx];
2440 cert->afterDate = &cert->source[cert->srcIdx];
2441 startIdx = cert->srcIdx;
2443 b = cert->source[cert->srcIdx++];
2444 if (b != ASN_UTC_TIME && b != ASN_GENERALIZED_TIME)
2447 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
2450 if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
2451 return ASN_DATE_SZ_E;
2453 XMEMCPY(date, &cert->source[cert->srcIdx], length);
2454 cert->srcIdx += length;
2456 if (dateType == BEFORE)
2457 cert->beforeDateLen = cert->srcIdx - startIdx;
2459 cert->afterDateLen = cert->srcIdx - startIdx;
2461 if (!XVALIDATE_DATE(date, b, dateType)) {
2462 if (dateType == BEFORE)
2463 return ASN_BEFORE_DATE_E;
2465 return ASN_AFTER_DATE_E;
2472 static int GetValidity(DecodedCert* cert, int verify)
2477 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
2480 if (GetDate(cert, BEFORE) < 0 && verify)
2481 badDate = ASN_BEFORE_DATE_E; /* continue parsing */
2483 if (GetDate(cert, AFTER) < 0 && verify)
2484 return ASN_AFTER_DATE_E;
2493 int DecodeToKey(DecodedCert* cert, int verify)
2498 if ( (ret = GetCertHeader(cert)) < 0)
2501 WOLFSSL_MSG("Got Cert Header");
2503 if ( (ret = GetAlgoId(cert->source, &cert->srcIdx, &cert->signatureOID,
2507 WOLFSSL_MSG("Got Algo ID");
2509 if ( (ret = GetName(cert, ISSUER)) < 0)
2512 if ( (ret = GetValidity(cert, verify)) < 0)
2515 if ( (ret = GetName(cert, SUBJECT)) < 0)
2518 WOLFSSL_MSG("Got Subject Name");
2520 if ( (ret = GetKey(cert)) < 0)
2523 WOLFSSL_MSG("Got Key");
2532 static int GetSignature(DecodedCert* cert)
2535 byte b = cert->source[cert->srcIdx++];
2537 if (b != ASN_BIT_STRING)
2538 return ASN_BITSTR_E;
2540 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
2543 cert->sigLength = length;
2545 b = cert->source[cert->srcIdx++];
2547 return ASN_EXPECT_0_E;
2550 cert->signature = &cert->source[cert->srcIdx];
2551 cert->srcIdx += cert->sigLength;
2557 static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
2559 output[0] = ASN_OCTET_STRING;
2560 output[1] = (byte)digSz;
2561 XMEMCPY(&output[2], digest, digSz);
2567 static word32 BytePrecision(word32 value)
2570 for (i = sizeof(value); i; --i)
2571 if (value >> ((i - 1) * WOLFSSL_BIT_SIZE))
2578 WOLFSSL_LOCAL word32 SetLength(word32 length, byte* output)
2582 if (length < ASN_LONG_LENGTH)
2583 output[i++] = (byte)length;
2585 output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);
2587 for (j = BytePrecision(length); j; --j) {
2588 output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
2597 WOLFSSL_LOCAL word32 SetSequence(word32 len, byte* output)
2599 output[0] = ASN_SEQUENCE | ASN_CONSTRUCTED;
2600 return SetLength(len, output + 1) + 1;
2603 WOLFSSL_LOCAL word32 SetOctetString(word32 len, byte* output)
2605 output[0] = ASN_OCTET_STRING;
2606 return SetLength(len, output + 1) + 1;
2609 /* Write a set header to output */
2610 WOLFSSL_LOCAL word32 SetSet(word32 len, byte* output)
2612 output[0] = ASN_SET | ASN_CONSTRUCTED;
2613 return SetLength(len, output + 1) + 1;
2616 WOLFSSL_LOCAL word32 SetImplicit(byte tag, byte number, word32 len, byte* output)
2619 output[0] = ((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0)
2620 | ASN_CONTEXT_SPECIFIC | number;
2621 return SetLength(len, output + 1) + 1;
2624 WOLFSSL_LOCAL word32 SetExplicit(byte number, word32 len, byte* output)
2626 output[0] = ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | number;
2627 return SetLength(len, output + 1) + 1;
2631 #if defined(HAVE_ECC) && (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN))
2633 static word32 SetCurve(ecc_key* key, byte* output)
2637 #if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC192)
2638 static const byte ECC_192v1_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE, 0x3d,
2641 #if defined(HAVE_ALL_CURVES) || !defined(NO_ECC256)
2642 static const byte ECC_256v1_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE, 0x3d,
2645 #if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC160)
2646 static const byte ECC_160r1_AlgoID[] = { 0x2b, 0x81, 0x04, 0x00,
2649 #if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC224)
2650 static const byte ECC_224r1_AlgoID[] = { 0x2b, 0x81, 0x04, 0x00,
2653 #if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC384)
2654 static const byte ECC_384r1_AlgoID[] = { 0x2b, 0x81, 0x04, 0x00,
2657 #if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC521)
2658 static const byte ECC_521r1_AlgoID[] = { 0x2b, 0x81, 0x04, 0x00,
2665 const byte* oid = 0;
2667 output[0] = ASN_OBJECT_ID;
2670 switch (key->dp->size) {
2671 #if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC160)
2673 oidSz = sizeof(ECC_160r1_AlgoID);
2674 oid = ECC_160r1_AlgoID;
2678 #if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC192)
2680 oidSz = sizeof(ECC_192v1_AlgoID);
2681 oid = ECC_192v1_AlgoID;
2685 #if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC224)
2687 oidSz = sizeof(ECC_224r1_AlgoID);
2688 oid = ECC_224r1_AlgoID;
2692 #if defined(HAVE_ALL_CURVES) || !defined(NO_ECC256)
2694 oidSz = sizeof(ECC_256v1_AlgoID);
2695 oid = ECC_256v1_AlgoID;
2699 #if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC384)
2701 oidSz = sizeof(ECC_384r1_AlgoID);
2702 oid = ECC_384r1_AlgoID;
2706 #if defined(HAVE_ALL_CURVES) || defined(HAVE_ECC521)
2708 oidSz = sizeof(ECC_521r1_AlgoID);
2709 oid = ECC_521r1_AlgoID;
2714 return ASN_UNKNOWN_OID_E;
2716 lenSz = SetLength(oidSz, output+idx);
2719 XMEMCPY(output+idx, oid, oidSz);
2725 #endif /* HAVE_ECC && WOLFSSL_CERT_GEN */
2728 WOLFSSL_LOCAL word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz)
2730 /* adding TAG_NULL and 0 to end */
2733 static const byte shaAlgoID[] = { 0x2b, 0x0e, 0x03, 0x02, 0x1a,
2735 static const byte sha256AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
2736 0x04, 0x02, 0x01, 0x05, 0x00 };
2737 static const byte sha384AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
2738 0x04, 0x02, 0x02, 0x05, 0x00 };
2739 static const byte sha512AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
2740 0x04, 0x02, 0x03, 0x05, 0x00 };
2741 static const byte md5AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
2742 0x02, 0x05, 0x05, 0x00 };
2743 static const byte md2AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
2744 0x02, 0x02, 0x05, 0x00};
2746 /* blkTypes, no NULL tags because IV is there instead */
2747 static const byte desCbcAlgoID[] = { 0x2B, 0x0E, 0x03, 0x02, 0x07 };
2748 static const byte des3CbcAlgoID[] = { 0x2A, 0x86, 0x48, 0x86, 0xF7,
2753 static const byte md5wRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7,
2754 0x0d, 0x01, 0x01, 0x04, 0x05, 0x00};
2755 static const byte shawRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7,
2756 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00};
2757 static const byte sha256wRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7,
2758 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00};
2759 static const byte sha384wRSA_AlgoID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
2760 0x0d, 0x01, 0x01, 0x0c, 0x05, 0x00};
2761 static const byte sha512wRSA_AlgoID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
2762 0x0d, 0x01, 0x01, 0x0d, 0x05, 0x00};
2765 /* ECDSA sigTypes */
2767 static const byte shawECDSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE, 0x3d,
2768 0x04, 0x01, 0x05, 0x00};
2769 static const byte sha256wECDSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE,0x3d,
2770 0x04, 0x03, 0x02, 0x05, 0x00};
2771 static const byte sha384wECDSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE,0x3d,
2772 0x04, 0x03, 0x03, 0x05, 0x00};
2773 static const byte sha512wECDSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE,0x3d,
2774 0x04, 0x03, 0x04, 0x05, 0x00};
2775 #endif /* HAVE_ECC */
2779 static const byte RSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
2780 0x01, 0x01, 0x01, 0x05, 0x00};
2785 /* no tags, so set tagSz smaller later */
2786 static const byte ECC_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE, 0x3d,
2788 #endif /* HAVE_ECC */
2791 int tagSz = 2; /* tag null and terminator */
2793 const byte* algoName = 0;
2794 byte ID_Length[MAX_LENGTH_SZ];
2795 byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
2797 if (type == hashType) {
2800 algoSz = sizeof(shaAlgoID);
2801 algoName = shaAlgoID;
2805 algoSz = sizeof(sha256AlgoID);
2806 algoName = sha256AlgoID;
2810 algoSz = sizeof(sha384AlgoID);
2811 algoName = sha384AlgoID;
2815 algoSz = sizeof(sha512AlgoID);
2816 algoName = sha512AlgoID;
2820 algoSz = sizeof(md2AlgoID);
2821 algoName = md2AlgoID;
2825 algoSz = sizeof(md5AlgoID);
2826 algoName = md5AlgoID;
2830 WOLFSSL_MSG("Unknown Hash Algo");
2831 return 0; /* UNKOWN_HASH_E; */
2834 else if (type == blkType) {
2837 algoSz = sizeof(desCbcAlgoID);
2838 algoName = desCbcAlgoID;
2842 algoSz = sizeof(des3CbcAlgoID);
2843 algoName = des3CbcAlgoID;
2847 WOLFSSL_MSG("Unknown Block Algo");
2851 else if (type == sigType) { /* sigType */
2855 algoSz = sizeof(md5wRSA_AlgoID);
2856 algoName = md5wRSA_AlgoID;
2860 algoSz = sizeof(shawRSA_AlgoID);
2861 algoName = shawRSA_AlgoID;
2864 case CTC_SHA256wRSA:
2865 algoSz = sizeof(sha256wRSA_AlgoID);
2866 algoName = sha256wRSA_AlgoID;
2869 case CTC_SHA384wRSA:
2870 algoSz = sizeof(sha384wRSA_AlgoID);
2871 algoName = sha384wRSA_AlgoID;
2874 case CTC_SHA512wRSA:
2875 algoSz = sizeof(sha512wRSA_AlgoID);
2876 algoName = sha512wRSA_AlgoID;
2881 algoSz = sizeof(shawECDSA_AlgoID);
2882 algoName = shawECDSA_AlgoID;
2885 case CTC_SHA256wECDSA:
2886 algoSz = sizeof(sha256wECDSA_AlgoID);
2887 algoName = sha256wECDSA_AlgoID;
2890 case CTC_SHA384wECDSA:
2891 algoSz = sizeof(sha384wECDSA_AlgoID);
2892 algoName = sha384wECDSA_AlgoID;
2895 case CTC_SHA512wECDSA:
2896 algoSz = sizeof(sha512wECDSA_AlgoID);
2897 algoName = sha512wECDSA_AlgoID;
2899 #endif /* HAVE_ECC */
2901 WOLFSSL_MSG("Unknown Signature Algo");
2905 else if (type == keyType) { /* keyType */
2909 algoSz = sizeof(RSA_AlgoID);
2910 algoName = RSA_AlgoID;
2915 algoSz = sizeof(ECC_AlgoID);
2916 algoName = ECC_AlgoID;
2919 #endif /* HAVE_ECC */
2921 WOLFSSL_MSG("Unknown Key Algo");
2926 WOLFSSL_MSG("Unknown Algo type");
2930 idSz = SetLength(algoSz - tagSz, ID_Length); /* don't include tags */
2931 seqSz = SetSequence(idSz + algoSz + 1 + curveSz, seqArray);
2932 /* +1 for object id, curveID of curveSz follows for ecc */
2933 seqArray[seqSz++] = ASN_OBJECT_ID;
2935 XMEMCPY(output, seqArray, seqSz);
2936 XMEMCPY(output + seqSz, ID_Length, idSz);
2937 XMEMCPY(output + seqSz + idSz, algoName, algoSz);
2939 return seqSz + idSz + algoSz;
2944 word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz,
2947 byte digArray[MAX_ENCODED_DIG_SZ];
2948 byte algoArray[MAX_ALGO_SZ];
2949 byte seqArray[MAX_SEQ_SZ];
2950 word32 encDigSz, algoSz, seqSz;
2952 encDigSz = SetDigest(digest, digSz, digArray);
2953 algoSz = SetAlgoID(hashOID, algoArray, hashType, 0);
2954 seqSz = SetSequence(encDigSz + algoSz, seqArray);
2956 XMEMCPY(out, seqArray, seqSz);
2957 XMEMCPY(out + seqSz, algoArray, algoSz);
2958 XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
2960 return encDigSz + algoSz + seqSz;
2964 int wc_GetCTC_HashOID(int type)
2983 #ifdef WOLFSSL_SHA384
2987 #ifdef WOLFSSL_SHA512
2997 /* return true (1) or false (0) for Confirmation */
2998 static int ConfirmSignature(const byte* buf, word32 bufSz,
2999 const byte* key, word32 keySz, word32 keyOID,
3000 const byte* sig, word32 sigSz, word32 sigOID,
3003 int typeH = 0, digestSz = 0, ret = 0;
3004 #ifdef WOLFSSL_SMALL_STACK
3007 byte digest[MAX_DIGEST_SIZE];
3010 #ifdef WOLFSSL_SMALL_STACK
3011 digest = (byte*)XMALLOC(MAX_DIGEST_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3013 return 0; /* not confirmed */
3025 if (wc_Md5Hash(buf, bufSz, digest) == 0) {
3027 digestSz = MD5_DIGEST_SIZE;
3031 #if defined(WOLFSSL_MD2)
3033 if (wc_Md2Hash(buf, bufSz, digest) == 0) {
3035 digestSz = MD2_DIGEST_SIZE;
3043 if (wc_ShaHash(buf, bufSz, digest) == 0) {
3045 digestSz = SHA_DIGEST_SIZE;
3050 case CTC_SHA256wRSA:
3051 case CTC_SHA256wECDSA:
3052 if (wc_Sha256Hash(buf, bufSz, digest) == 0) {
3054 digestSz = SHA256_DIGEST_SIZE;
3058 #ifdef WOLFSSL_SHA512
3059 case CTC_SHA512wRSA:
3060 case CTC_SHA512wECDSA:
3061 if (wc_Sha512Hash(buf, bufSz, digest) == 0) {
3063 digestSz = SHA512_DIGEST_SIZE;
3067 #ifdef WOLFSSL_SHA384
3068 case CTC_SHA384wRSA:
3069 case CTC_SHA384wECDSA:
3070 if (wc_Sha384Hash(buf, bufSz, digest) == 0) {
3072 digestSz = SHA384_DIGEST_SIZE;
3077 WOLFSSL_MSG("Verify Signautre has unsupported type");
3081 #ifdef WOLFSSL_SMALL_STACK
3082 XFREE(digest, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3084 return 0; /* not confirmed */
3092 int encodedSigSz, verifySz;
3094 #ifdef WOLFSSL_SMALL_STACK
3100 byte plain[MAX_ENCODED_SIG_SZ];
3101 byte encodedSig[MAX_ENCODED_SIG_SZ];
3104 #ifdef WOLFSSL_SMALL_STACK
3105 pubKey = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL,
3106 DYNAMIC_TYPE_TMP_BUFFER);
3107 plain = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, NULL,
3108 DYNAMIC_TYPE_TMP_BUFFER);
3109 encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, NULL,
3110 DYNAMIC_TYPE_TMP_BUFFER);
3112 if (pubKey == NULL || plain == NULL || encodedSig == NULL) {
3113 WOLFSSL_MSG("Failed to allocate memory at ConfirmSignature");
3116 XFREE(pubKey, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3118 XFREE(plain, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3120 XFREE(encodedSig, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3122 break; /* not confirmed */
3126 if (sigSz > MAX_ENCODED_SIG_SZ) {
3127 WOLFSSL_MSG("Verify Signautre is too big");
3129 else if (wc_InitRsaKey(pubKey, heap) != 0) {
3130 WOLFSSL_MSG("InitRsaKey failed");
3132 else if (wc_RsaPublicKeyDecode(key, &idx, pubKey, keySz) < 0) {
3133 WOLFSSL_MSG("ASN Key decode error RSA");
3136 XMEMCPY(plain, sig, sigSz);
3138 if ((verifySz = wc_RsaSSL_VerifyInline(plain, sigSz, &out,
3140 WOLFSSL_MSG("Rsa SSL verify error");
3143 /* make sure we're right justified */
3145 wc_EncodeSignature(encodedSig, digest, digestSz, typeH);
3146 if (encodedSigSz != verifySz ||
3147 XMEMCMP(out, encodedSig, encodedSigSz) != 0) {
3148 WOLFSSL_MSG("Rsa SSL verify match encode error");
3151 ret = 1; /* match */
3153 #ifdef WOLFSSL_DEBUG_ENCODING
3157 printf("wolfssl encodedSig:\n");
3159 for (x = 0; x < encodedSigSz; x++) {
3160 printf("%02x ", encodedSig[x]);
3161 if ( (x % 16) == 15)
3166 printf("actual digest:\n");
3168 for (x = 0; x < verifySz; x++) {
3169 printf("%02x ", out[x]);
3170 if ( (x % 16) == 15)
3176 #endif /* WOLFSSL_DEBUG_ENCODING */
3182 wc_FreeRsaKey(pubKey);
3184 #ifdef WOLFSSL_SMALL_STACK
3185 XFREE(pubKey, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3186 XFREE(plain, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3187 XFREE(encodedSig, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3197 #ifdef WOLFSSL_SMALL_STACK
3203 #ifdef WOLFSSL_SMALL_STACK
3204 pubKey = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL,
3205 DYNAMIC_TYPE_TMP_BUFFER);
3206 if (pubKey == NULL) {
3207 WOLFSSL_MSG("Failed to allocate pubKey");
3208 break; /* not confirmed */
3212 if (wc_ecc_init(pubKey) < 0) {
3213 WOLFSSL_MSG("Failed to initialize key");
3214 break; /* not confirmed */
3216 if (wc_ecc_import_x963(key, keySz, pubKey) < 0) {
3217 WOLFSSL_MSG("ASN Key import error ECC");
3220 if (wc_ecc_verify_hash(sig, sigSz, digest, digestSz, &verify,
3222 WOLFSSL_MSG("ECC verify hash error");
3224 else if (1 != verify) {
3225 WOLFSSL_MSG("ECC Verify didn't match");
3227 ret = 1; /* match */
3230 wc_ecc_free(pubKey);
3232 #ifdef WOLFSSL_SMALL_STACK
3233 XFREE(pubKey, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3237 #endif /* HAVE_ECC */
3239 WOLFSSL_MSG("Verify Key type unknown");
3242 #ifdef WOLFSSL_SMALL_STACK
3243 XFREE(digest, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3250 #ifndef IGNORE_NAME_CONSTRAINTS
3252 static int MatchBaseName(int type, const char* name, int nameSz,
3253 const char* base, int baseSz)
3255 if (base == NULL || baseSz <= 0 || name == NULL || nameSz <= 0 ||
3256 name[0] == '.' || nameSz < baseSz ||
3257 (type != ASN_RFC822_TYPE && type != ASN_DNS_TYPE))
3260 /* If an email type, handle special cases where the base is only
3261 * a domain, or is an email address itself. */
3262 if (type == ASN_RFC822_TYPE) {
3263 const char* p = NULL;
3266 if (base[0] != '.') {
3270 /* find the '@' in the base */
3271 while (*p != '@' && count < baseSz) {
3276 /* No '@' in base, reset p to NULL */
3277 if (count >= baseSz)
3282 /* Base isn't an email address, it is a domain name,
3283 * wind the name forward one character past its '@'. */
3286 while (*p != '@' && count < baseSz) {
3291 if (count < baseSz && *p == '@') {
3293 nameSz -= count + 1;
3298 if ((type == ASN_DNS_TYPE || type == ASN_RFC822_TYPE) && base[0] == '.') {
3299 int szAdjust = nameSz - baseSz;
3304 while (nameSz > 0) {
3305 if (XTOLOWER((unsigned char)*name++) !=
3306 XTOLOWER((unsigned char)*base++))
3315 static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert)
3317 if (signer == NULL || cert == NULL)
3320 /* Check against the excluded list */
3321 if (signer->excludedNames) {
3322 Base_entry* base = signer->excludedNames;
3324 while (base != NULL) {
3325 if (base->type == ASN_DNS_TYPE) {
3326 DNS_entry* name = cert->altNames;
3327 while (name != NULL) {
3328 if (MatchBaseName(ASN_DNS_TYPE,
3329 name->name, (int)XSTRLEN(name->name),
3330 base->name, base->nameSz))
3335 else if (base->type == ASN_RFC822_TYPE) {
3336 DNS_entry* name = cert->altEmailNames;
3337 while (name != NULL) {
3338 if (MatchBaseName(ASN_RFC822_TYPE,
3339 name->name, (int)XSTRLEN(name->name),
3340 base->name, base->nameSz))
3346 else if (base->type == ASN_DIR_TYPE) {
3347 if (cert->subjectRawLen == base->nameSz &&
3348 XMEMCMP(cert->subjectRaw, base->name, base->nameSz) == 0) {
3357 /* Check against the permitted list */
3358 if (signer->permittedNames != NULL) {
3365 Base_entry* base = signer->permittedNames;
3367 while (base != NULL) {
3368 if (base->type == ASN_DNS_TYPE) {
3369 DNS_entry* name = cert->altNames;
3374 while (name != NULL) {
3375 matchDns = MatchBaseName(ASN_DNS_TYPE,
3376 name->name, (int)XSTRLEN(name->name),
3377 base->name, base->nameSz);
3381 else if (base->type == ASN_RFC822_TYPE) {
3382 DNS_entry* name = cert->altEmailNames;
3387 while (name != NULL) {
3388 matchEmail = MatchBaseName(ASN_DNS_TYPE,
3389 name->name, (int)XSTRLEN(name->name),
3390 base->name, base->nameSz);
3394 else if (base->type == ASN_DIR_TYPE) {
3396 if (cert->subjectRaw != NULL &&
3397 cert->subjectRawLen == base->nameSz &&
3398 XMEMCMP(cert->subjectRaw, base->name, base->nameSz) == 0) {
3406 if ((needDns && !matchDns) || (needEmail && !matchEmail) ||
3407 (needDir && !matchDir)) {
3416 #endif /* IGNORE_NAME_CONSTRAINTS */
3419 static int DecodeAltNames(byte* input, int sz, DecodedCert* cert)
3424 WOLFSSL_ENTER("DecodeAltNames");
3426 if (GetSequence(input, &idx, &length, sz) < 0) {
3427 WOLFSSL_MSG("\tBad Sequence");
3431 cert->weOwnAltNames = 1;
3433 while (length > 0) {
3434 byte b = input[idx++];
3438 /* Save DNS Type names in the altNames list. */
3439 /* Save Other Type names in the cert's OidMap */
3440 if (b == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
3441 DNS_entry* dnsEntry;
3443 word32 lenStartIdx = idx;
3445 if (GetLength(input, &idx, &strLen, sz) < 0) {
3446 WOLFSSL_MSG("\tfail: str length");
3449 length -= (idx - lenStartIdx);
3451 dnsEntry = (DNS_entry*)XMALLOC(sizeof(DNS_entry), cert->heap,
3452 DYNAMIC_TYPE_ALTNAME);
3453 if (dnsEntry == NULL) {
3454 WOLFSSL_MSG("\tOut of Memory");
3458 dnsEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
3459 DYNAMIC_TYPE_ALTNAME);
3460 if (dnsEntry->name == NULL) {
3461 WOLFSSL_MSG("\tOut of Memory");
3462 XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
3466 XMEMCPY(dnsEntry->name, &input[idx], strLen);
3467 dnsEntry->name[strLen] = '\0';
3469 dnsEntry->next = cert->altNames;
3470 cert->altNames = dnsEntry;
3475 #ifndef IGNORE_NAME_CONSTRAINTS
3476 else if (b == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
3477 DNS_entry* emailEntry;
3479 word32 lenStartIdx = idx;
3481 if (GetLength(input, &idx, &strLen, sz) < 0) {
3482 WOLFSSL_MSG("\tfail: str length");
3485 length -= (idx - lenStartIdx);
3487 emailEntry = (DNS_entry*)XMALLOC(sizeof(DNS_entry), cert->heap,
3488 DYNAMIC_TYPE_ALTNAME);
3489 if (emailEntry == NULL) {
3490 WOLFSSL_MSG("\tOut of Memory");
3494 emailEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
3495 DYNAMIC_TYPE_ALTNAME);
3496 if (emailEntry->name == NULL) {
3497 WOLFSSL_MSG("\tOut of Memory");
3498 XFREE(emailEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
3502 XMEMCPY(emailEntry->name, &input[idx], strLen);
3503 emailEntry->name[strLen] = '\0';
3505 emailEntry->next = cert->altEmailNames;
3506 cert->altEmailNames = emailEntry;
3511 #endif /* IGNORE_NAME_CONSTRAINTS */
3513 else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE))
3516 word32 lenStartIdx = idx;
3519 if (GetLength(input, &idx, &strLen, sz) < 0) {
3520 WOLFSSL_MSG("\tfail: other name length");
3523 /* Consume the rest of this sequence. */
3524 length -= (strLen + idx - lenStartIdx);
3526 if (GetObjectId(input, &idx, &oid, sz) < 0) {
3527 WOLFSSL_MSG("\tbad OID");
3531 if (oid != HW_NAME_OID) {
3532 WOLFSSL_MSG("\tincorrect OID");
3536 if (input[idx++] != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
3537 WOLFSSL_MSG("\twrong type");
3541 if (GetLength(input, &idx, &strLen, sz) < 0) {
3542 WOLFSSL_MSG("\tfail: str len");
3546 if (GetSequence(input, &idx, &strLen, sz) < 0) {
3547 WOLFSSL_MSG("\tBad Sequence");
3551 if (input[idx++] != ASN_OBJECT_ID) {
3552 WOLFSSL_MSG("\texpected OID");
3556 if (GetLength(input, &idx, &strLen, sz) < 0) {
3557 WOLFSSL_MSG("\tfailed: str len");
3561 cert->hwType = (byte*)XMALLOC(strLen, cert->heap, 0);
3562 if (cert->hwType == NULL) {
3563 WOLFSSL_MSG("\tOut of Memory");
3567 XMEMCPY(cert->hwType, &input[idx], strLen);
3568 cert->hwTypeSz = strLen;
3571 if (input[idx++] != ASN_OCTET_STRING) {
3572 WOLFSSL_MSG("\texpected Octet String");
3576 if (GetLength(input, &idx, &strLen, sz) < 0) {
3577 WOLFSSL_MSG("\tfailed: str len");
3581 cert->hwSerialNum = (byte*)XMALLOC(strLen + 1, cert->heap, 0);
3582 if (cert->hwSerialNum == NULL) {
3583 WOLFSSL_MSG("\tOut of Memory");
3587 XMEMCPY(cert->hwSerialNum, &input[idx], strLen);
3588 cert->hwSerialNum[strLen] = '\0';
3589 cert->hwSerialNumSz = strLen;
3592 #endif /* WOLFSSL_SEP */
3595 word32 lenStartIdx = idx;
3597 WOLFSSL_MSG("\tUnsupported name type, skipping");
3599 if (GetLength(input, &idx, &strLen, sz) < 0) {
3600 WOLFSSL_MSG("\tfail: unsupported name length");
3603 length -= (strLen + idx - lenStartIdx);
3611 static int DecodeBasicCaConstraint(byte* input, int sz, DecodedCert* cert)
3616 WOLFSSL_ENTER("DecodeBasicCaConstraint");
3617 if (GetSequence(input, &idx, &length, sz) < 0) {
3618 WOLFSSL_MSG("\tfail: bad SEQUENCE");
3625 /* If the basic ca constraint is false, this extension may be named, but
3626 * left empty. So, if the length is 0, just return. */
3628 if (input[idx++] != ASN_BOOLEAN)
3630 WOLFSSL_MSG("\tfail: constraint not BOOLEAN");
3634 if (GetLength(input, &idx, &length, sz) < 0)
3636 WOLFSSL_MSG("\tfail: length");
3643 #ifdef OPENSSL_EXTRA
3644 /* If there isn't any more data, return. */
3645 if (idx >= (word32)sz)
3648 /* Anything left should be the optional pathlength */
3649 if (input[idx++] != ASN_INTEGER) {
3650 WOLFSSL_MSG("\tfail: pathlen not INTEGER");
3654 if (input[idx++] != 1) {
3655 WOLFSSL_MSG("\tfail: pathlen too long");
3659 cert->pathLength = input[idx];
3660 cert->extBasicConstPlSet = 1;
3661 #endif /* OPENSSL_EXTRA */
3667 #define CRLDP_FULL_NAME 0
3668 /* From RFC3280 SS4.2.1.14, Distribution Point Name*/
3669 #define GENERALNAME_URI 6
3670 /* From RFC3280 SS4.2.1.7, GeneralName */
3672 static int DecodeCrlDist(byte* input, int sz, DecodedCert* cert)
3677 WOLFSSL_ENTER("DecodeCrlDist");
3679 /* Unwrap the list of Distribution Points*/
3680 if (GetSequence(input, &idx, &length, sz) < 0)
3683 /* Unwrap a single Distribution Point */
3684 if (GetSequence(input, &idx, &length, sz) < 0)
3687 /* The Distribution Point has three explicit optional members
3688 * First check for a DistributionPointName
3690 if (input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
3693 if (GetLength(input, &idx, &length, sz) < 0)
3697 (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CRLDP_FULL_NAME))
3700 if (GetLength(input, &idx, &length, sz) < 0)
3703 if (input[idx] == (ASN_CONTEXT_SPECIFIC | GENERALNAME_URI))
3706 if (GetLength(input, &idx, &length, sz) < 0)
3709 cert->extCrlInfoSz = length;
3710 cert->extCrlInfo = input + idx;
3714 /* This isn't a URI, skip it. */
3718 /* This isn't a FULLNAME, skip it. */
3722 /* Check for reasonFlags */
3723 if (idx < (word32)sz &&
3724 input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
3727 if (GetLength(input, &idx, &length, sz) < 0)
3732 /* Check for cRLIssuer */
3733 if (idx < (word32)sz &&
3734 input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
3737 if (GetLength(input, &idx, &length, sz) < 0)
3742 if (idx < (word32)sz)
3744 WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
3745 "but we only use the first one.");
3752 static int DecodeAuthInfo(byte* input, int sz, DecodedCert* cert)
3754 * Read the first of the Authority Information Access records. If there are
3755 * any issues, return without saving the record.
3763 WOLFSSL_ENTER("DecodeAuthInfo");
3765 /* Unwrap the list of AIAs */
3766 if (GetSequence(input, &idx, &length, sz) < 0)
3769 while (idx < (word32)sz) {
3770 /* Unwrap a single AIA */
3771 if (GetSequence(input, &idx, &length, sz) < 0)
3775 if (GetObjectId(input, &idx, &oid, sz) < 0)
3778 /* Only supporting URIs right now. */
3780 if (GetLength(input, &idx, &length, sz) < 0)
3783 if (b == (ASN_CONTEXT_SPECIFIC | GENERALNAME_URI) &&
3784 oid == AIA_OCSP_OID)
3786 cert->extAuthInfoSz = length;
3787 cert->extAuthInfo = input + idx;
3797 static int DecodeAuthKeyId(byte* input, int sz, DecodedCert* cert)
3800 int length = 0, ret = 0;
3802 WOLFSSL_ENTER("DecodeAuthKeyId");
3804 if (GetSequence(input, &idx, &length, sz) < 0) {
3805 WOLFSSL_MSG("\tfail: should be a SEQUENCE\n");
3809 if (input[idx++] != (ASN_CONTEXT_SPECIFIC | 0)) {
3810 WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available\n");
3814 if (GetLength(input, &idx, &length, sz) < 0) {
3815 WOLFSSL_MSG("\tfail: extension data length");
3819 #ifdef OPENSSL_EXTRA
3820 cert->extAuthKeyIdSrc = &input[idx];
3821 cert->extAuthKeyIdSz = length;
3822 #endif /* OPENSSL_EXTRA */
3824 if (length == KEYID_SIZE) {
3825 XMEMCPY(cert->extAuthKeyId, input + idx, length);
3829 ret = wc_Sha256Hash(input + idx, length, cert->extAuthKeyId);
3831 ret = wc_ShaHash(input + idx, length, cert->extAuthKeyId);
3839 static int DecodeSubjKeyId(byte* input, int sz, DecodedCert* cert)
3842 int length = 0, ret = 0;
3844 WOLFSSL_ENTER("DecodeSubjKeyId");
3846 if (input[idx++] != ASN_OCTET_STRING) {
3847 WOLFSSL_MSG("\tfail: should be an OCTET STRING");
3851 if (GetLength(input, &idx, &length, sz) < 0) {
3852 WOLFSSL_MSG("\tfail: extension data length");
3856 #ifdef OPENSSL_EXTRA
3857 cert->extSubjKeyIdSrc = &input[idx];
3858 cert->extSubjKeyIdSz = length;
3859 #endif /* OPENSSL_EXTRA */
3861 if (length == SIGNER_DIGEST_SIZE) {
3862 XMEMCPY(cert->extSubjKeyId, input + idx, length);
3866 ret = wc_Sha256Hash(input + idx, length, cert->extSubjKeyId);
3868 ret = wc_ShaHash(input + idx, length, cert->extSubjKeyId);
3876 static int DecodeKeyUsage(byte* input, int sz, DecodedCert* cert)
3881 WOLFSSL_ENTER("DecodeKeyUsage");
3883 if (input[idx++] != ASN_BIT_STRING) {
3884 WOLFSSL_MSG("\tfail: key usage expected bit string");
3888 if (GetLength(input, &idx, &length, sz) < 0) {
3889 WOLFSSL_MSG("\tfail: key usage bad length");
3893 unusedBits = input[idx++];
3897 cert->extKeyUsage = (word16)((input[idx] << 8) | input[idx+1]);
3898 cert->extKeyUsage >>= unusedBits;
3900 else if (length == 1)
3901 cert->extKeyUsage = (word16)(input[idx] << 1);
3907 static int DecodeExtKeyUsage(byte* input, int sz, DecodedCert* cert)
3909 word32 idx = 0, oid;
3912 WOLFSSL_ENTER("DecodeExtKeyUsage");
3914 if (GetSequence(input, &idx, &length, sz) < 0) {
3915 WOLFSSL_MSG("\tfail: should be a SEQUENCE");
3919 #ifdef OPENSSL_EXTRA
3920 cert->extExtKeyUsageSrc = input + idx;
3921 cert->extExtKeyUsageSz = length;
3924 while (idx < (word32)sz) {
3925 if (GetObjectId(input, &idx, &oid, sz) < 0)
3930 cert->extExtKeyUsage |= EXTKEYUSE_ANY;
3932 case EKU_SERVER_AUTH_OID:
3933 cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
3935 case EKU_CLIENT_AUTH_OID:
3936 cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
3938 case EKU_OCSP_SIGN_OID:
3939 cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
3943 #ifdef OPENSSL_EXTRA
3944 cert->extExtKeyUsageCount++;
3952 #ifndef IGNORE_NAME_CONSTRAINTS
3953 static int DecodeSubtree(byte* input, int sz, Base_entry** head, void* heap)
3959 while (idx < (word32)sz) {
3960 int seqLength, strLength;
3964 if (GetSequence(input, &idx, &seqLength, sz) < 0) {
3965 WOLFSSL_MSG("\tfail: should be a SEQUENCE");
3970 b = input[nameIdx++];
3971 if (GetLength(input, &nameIdx, &strLength, sz) <= 0) {
3972 WOLFSSL_MSG("\tinvalid length");
3976 if (b == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE) ||
3977 b == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE) ||
3978 b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
3980 Base_entry* entry = (Base_entry*)XMALLOC(sizeof(Base_entry),
3981 heap, DYNAMIC_TYPE_ALTNAME);
3983 if (entry == NULL) {
3984 WOLFSSL_MSG("allocate error");
3988 entry->name = (char*)XMALLOC(strLength, heap, DYNAMIC_TYPE_ALTNAME);
3989 if (entry->name == NULL) {
3990 WOLFSSL_MSG("allocate error");
3994 XMEMCPY(entry->name, &input[nameIdx], strLength);
3995 entry->nameSz = strLength;
3996 entry->type = b & 0x0F;
3998 entry->next = *head;
4009 static int DecodeNameConstraints(byte* input, int sz, DecodedCert* cert)
4014 WOLFSSL_ENTER("DecodeNameConstraints");
4016 if (GetSequence(input, &idx, &length, sz) < 0) {
4017 WOLFSSL_MSG("\tfail: should be a SEQUENCE");
4021 while (idx < (word32)sz) {
4022 byte b = input[idx++];
4023 Base_entry** subtree = NULL;
4025 if (GetLength(input, &idx, &length, sz) <= 0) {
4026 WOLFSSL_MSG("\tinvalid length");
4030 if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
4031 subtree = &cert->permittedNames;
4032 else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
4033 subtree = &cert->excludedNames;
4035 WOLFSSL_MSG("\tinvalid subtree");
4039 DecodeSubtree(input + idx, length, subtree, cert->heap);
4046 #endif /* IGNORE_NAME_CONSTRAINTS */
4050 static int DecodeCertPolicy(byte* input, int sz, DecodedCert* cert)
4055 WOLFSSL_ENTER("DecodeCertPolicy");
4057 /* Unwrap certificatePolicies */
4058 if (GetSequence(input, &idx, &length, sz) < 0) {
4059 WOLFSSL_MSG("\tdeviceType isn't OID");
4063 if (GetSequence(input, &idx, &length, sz) < 0) {
4064 WOLFSSL_MSG("\tdeviceType isn't OID");
4068 if (input[idx++] != ASN_OBJECT_ID) {
4069 WOLFSSL_MSG("\tdeviceType isn't OID");
4073 if (GetLength(input, &idx, &length, sz) < 0) {
4074 WOLFSSL_MSG("\tCouldn't read length of deviceType");
4079 cert->deviceType = (byte*)XMALLOC(length, cert->heap, 0);
4080 if (cert->deviceType == NULL) {
4081 WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
4084 cert->deviceTypeSz = length;
4085 XMEMCPY(cert->deviceType, input + idx, length);
4088 WOLFSSL_LEAVE("DecodeCertPolicy", 0);
4091 #endif /* WOLFSSL_SEP */
4094 static int DecodeCertExtensions(DecodedCert* cert)
4096 * Processing the Certificate Extensions. This does not modify the current
4097 * index. It is works starting with the recorded extensions pointer.
4101 int sz = cert->extensionsSz;
4102 byte* input = cert->extensions;
4106 byte criticalFail = 0;
4108 WOLFSSL_ENTER("DecodeCertExtensions");
4110 if (input == NULL || sz == 0)
4111 return BAD_FUNC_ARG;
4113 if (input[idx++] != ASN_EXTENSIONS)
4116 if (GetLength(input, &idx, &length, sz) < 0)
4119 if (GetSequence(input, &idx, &length, sz) < 0)
4122 while (idx < (word32)sz) {
4123 if (GetSequence(input, &idx, &length, sz) < 0) {
4124 WOLFSSL_MSG("\tfail: should be a SEQUENCE");
4129 if (GetObjectId(input, &idx, &oid, sz) < 0) {
4130 WOLFSSL_MSG("\tfail: OBJECT ID");
4134 /* check for critical flag */
4136 if (input[idx] == ASN_BOOLEAN) {
4139 if (GetLength(input, &idx, &boolLength, sz) < 0) {
4140 WOLFSSL_MSG("\tfail: critical boolean length");
4147 /* process the extension based on the OID */
4148 if (input[idx++] != ASN_OCTET_STRING) {
4149 WOLFSSL_MSG("\tfail: should be an OCTET STRING");
4153 if (GetLength(input, &idx, &length, sz) < 0) {
4154 WOLFSSL_MSG("\tfail: extension data length");
4160 #ifdef OPENSSL_EXTRA
4161 cert->extBasicConstSet = 1;
4162 cert->extBasicConstCrit = critical;
4164 if (DecodeBasicCaConstraint(&input[idx], length, cert) < 0)
4169 if (DecodeCrlDist(&input[idx], length, cert) < 0)
4174 if (DecodeAuthInfo(&input[idx], length, cert) < 0)
4179 #ifdef OPENSSL_EXTRA
4180 cert->extSubjAltNameSet = 1;
4181 cert->extSubjAltNameCrit = critical;
4183 if (DecodeAltNames(&input[idx], length, cert) < 0)
4188 cert->extAuthKeyIdSet = 1;
4189 #ifdef OPENSSL_EXTRA
4190 cert->extAuthKeyIdCrit = critical;
4192 if (DecodeAuthKeyId(&input[idx], length, cert) < 0)
4197 cert->extSubjKeyIdSet = 1;
4198 #ifdef OPENSSL_EXTRA
4199 cert->extSubjKeyIdCrit = critical;
4201 if (DecodeSubjKeyId(&input[idx], length, cert) < 0)
4205 case CERT_POLICY_OID:
4206 WOLFSSL_MSG("Certificate Policy extension not supported yet.");
4208 #ifdef OPENSSL_EXTRA
4209 cert->extCertPolicySet = 1;
4210 cert->extCertPolicyCrit = critical;
4212 if (DecodeCertPolicy(&input[idx], length, cert) < 0)
4218 cert->extKeyUsageSet = 1;
4219 #ifdef OPENSSL_EXTRA
4220 cert->extKeyUsageCrit = critical;
4222 if (DecodeKeyUsage(&input[idx], length, cert) < 0)
4226 case EXT_KEY_USAGE_OID:
4227 cert->extExtKeyUsageSet = 1;
4228 #ifdef OPENSSL_EXTRA
4229 cert->extExtKeyUsageCrit = critical;
4231 if (DecodeExtKeyUsage(&input[idx], length, cert) < 0)
4235 #ifndef IGNORE_NAME_CONSTRAINTS
4237 cert->extNameConstraintSet = 1;
4238 #ifdef OPENSSL_EXTRA
4239 cert->extNameConstraintCrit = critical;
4241 if (DecodeNameConstraints(&input[idx], length, cert) < 0)
4244 #endif /* IGNORE_NAME_CONSTRAINTS */
4246 case INHIBIT_ANY_OID:
4247 WOLFSSL_MSG("Inhibit anyPolicy extension not supported yet.");
4251 /* While it is a failure to not support critical extensions,
4252 * still parse the certificate ignoring the unsupported
4253 * extention to allow caller to accept it with the verify
4262 return criticalFail ? ASN_CRIT_EXT_E : 0;
4266 int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
4271 ret = ParseCertRelative(cert, type, verify, cm);
4275 if (cert->subjectCNLen > 0) {
4276 ptr = (char*) XMALLOC(cert->subjectCNLen + 1, cert->heap,
4277 DYNAMIC_TYPE_SUBJECT_CN);
4280 XMEMCPY(ptr, cert->subjectCN, cert->subjectCNLen);
4281 ptr[cert->subjectCNLen] = '\0';
4282 cert->subjectCN = ptr;
4283 cert->subjectCNStored = 1;
4286 if (cert->keyOID == RSAk &&
4287 cert->publicKey != NULL && cert->pubKeySize > 0) {
4288 ptr = (char*) XMALLOC(cert->pubKeySize, cert->heap,
4289 DYNAMIC_TYPE_PUBLIC_KEY);
4292 XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
4293 cert->publicKey = (byte *)ptr;
4294 cert->pubKeyStored = 1;
4301 /* from SSL proper, for locking can't do find here anymore */
4305 WOLFSSL_LOCAL Signer* GetCA(void* signers, byte* hash);
4307 WOLFSSL_LOCAL Signer* GetCAByName(void* signers, byte* hash);
4314 int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
4319 int criticalExt = 0;
4321 if ((ret = DecodeToKey(cert, verify)) < 0) {
4322 if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E)
4328 WOLFSSL_MSG("Parsed Past Key");
4330 if (cert->srcIdx < cert->sigIndex) {
4331 #ifndef ALLOW_V1_EXTENSIONS
4332 if (cert->version < 2) {
4333 WOLFSSL_MSG(" v1 and v2 certs not allowed extensions");
4334 return ASN_VERSION_E;
4337 /* save extensions */
4338 cert->extensions = &cert->source[cert->srcIdx];
4339 cert->extensionsSz = cert->sigIndex - cert->srcIdx;
4340 cert->extensionsIdx = cert->srcIdx; /* for potential later use */
4342 if ((ret = DecodeCertExtensions(cert)) < 0) {
4343 if (ret == ASN_CRIT_EXT_E)
4349 /* advance past extensions */
4350 cert->srcIdx = cert->sigIndex;
4353 if ((ret = GetAlgoId(cert->source, &cert->srcIdx, &confirmOID,
4357 if ((ret = GetSignature(cert)) < 0)
4360 if (confirmOID != cert->signatureOID)
4361 return ASN_SIG_OID_E;
4364 if (cert->extSubjKeyIdSet == 0
4365 && cert->publicKey != NULL && cert->pubKeySize > 0) {
4367 ret = wc_Sha256Hash(cert->publicKey, cert->pubKeySize,
4368 cert->extSubjKeyId);
4370 ret = wc_ShaHash(cert->publicKey, cert->pubKeySize,
4371 cert->extSubjKeyId);
4378 if (verify && type != CA_TYPE) {
4381 if (cert->extAuthKeyIdSet)
4382 ca = GetCA(cm, cert->extAuthKeyId);
4384 ca = GetCAByName(cm, cert->issuerHash);
4386 ca = GetCA(cm, cert->issuerHash);
4387 #endif /* NO SKID */
4388 WOLFSSL_MSG("About to verify certificate signature");
4392 /* Need the ca's public key hash for OCSP */
4394 ret = wc_Sha256Hash(ca->publicKey, ca->pubKeySize,
4395 cert->issuerKeyHash);
4397 ret = wc_ShaHash(ca->publicKey, ca->pubKeySize,
4398 cert->issuerKeyHash);
4402 #endif /* HAVE_OCSP */
4403 /* try to confirm/verify signature */
4404 if (!ConfirmSignature(cert->source + cert->certBegin,
4405 cert->sigIndex - cert->certBegin,
4406 ca->publicKey, ca->pubKeySize, ca->keyOID,
4407 cert->signature, cert->sigLength, cert->signatureOID,
4409 WOLFSSL_MSG("Confirm signature failed");
4410 return ASN_SIG_CONFIRM_E;
4412 #ifndef IGNORE_NAME_CONSTRAINTS
4413 /* check that this cert's name is permitted by the signer's
4414 * name constraints */
4415 if (!ConfirmNameConstraints(ca, cert)) {
4416 WOLFSSL_MSG("Confirm name constraint failed");
4417 return ASN_NAME_INVALID_E;
4419 #endif /* IGNORE_NAME_CONSTRAINTS */
4423 WOLFSSL_MSG("No CA signer to verify with");
4424 return ASN_NO_SIGNER_E;
4431 if (criticalExt != 0)
4438 /* Create and init an new signer */
4439 Signer* MakeSigner(void* heap)
4441 Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
4442 DYNAMIC_TYPE_SIGNER);
4444 signer->pubKeySize = 0;
4446 signer->publicKey = NULL;
4447 signer->nameLen = 0;
4448 signer->name = NULL;
4449 #ifndef IGNORE_NAME_CONSTRAINTS
4450 signer->permittedNames = NULL;
4451 signer->excludedNames = NULL;
4452 #endif /* IGNORE_NAME_CONSTRAINTS */
4453 signer->next = NULL;
4461 /* Free an individual signer */
4462 void FreeSigner(Signer* signer, void* heap)
4464 XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
4465 XFREE(signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
4466 #ifndef IGNORE_NAME_CONSTRAINTS
4467 if (signer->permittedNames)
4468 FreeNameSubtrees(signer->permittedNames, heap);
4469 if (signer->excludedNames)
4470 FreeNameSubtrees(signer->excludedNames, heap);
4472 XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
4478 /* Free the whole singer table with number of rows */
4479 void FreeSignerTable(Signer** table, int rows, void* heap)
4483 for (i = 0; i < rows; i++) {
4484 Signer* signer = table[i];
4486 Signer* next = signer->next;
4487 FreeSigner(signer, heap);
4495 WOLFSSL_LOCAL int SetMyVersion(word32 version, byte* output, int header)
4500 output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
4501 output[i++] = ASN_BIT_STRING;
4503 output[i++] = ASN_INTEGER;
4505 output[i++] = (byte)version;
4511 WOLFSSL_LOCAL int SetSerialNumber(const byte* sn, word32 snSz, byte* output)
4515 WOLFSSL_ENTER("SetSerialNumber");
4517 if (snSz <= EXTERNAL_SERIAL_SIZE) {
4518 output[0] = ASN_INTEGER;
4519 /* The serial number is always positive. When encoding the
4520 * INTEGER, if the MSB is 1, add a padding zero to keep the
4521 * number positive. */
4523 output[1] = (byte)snSz + 1;
4525 XMEMCPY(&output[3], sn, snSz);
4529 output[1] = (byte)snSz;
4530 XMEMCPY(&output[2], sn, snSz);
4540 #if defined(WOLFSSL_KEY_GEN) || defined(WOLFSSL_CERT_GEN)
4542 /* convert der buffer to pem into output, can't do inplace, der and output
4543 need to be different */
4544 int wc_DerToPem(const byte* der, word32 derSz, byte* output, word32 outSz,
4547 #ifdef WOLFSSL_SMALL_STACK
4548 char* header = NULL;
4549 char* footer = NULL;
4559 int outLen; /* return length or error */
4561 if (der == output) /* no in place conversion */
4562 return BAD_FUNC_ARG;
4564 #ifdef WOLFSSL_SMALL_STACK
4565 header = (char*)XMALLOC(headerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4569 footer = (char*)XMALLOC(footerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4570 if (footer == NULL) {
4571 XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4576 if (type == CERT_TYPE) {
4577 XSTRNCPY(header, "-----BEGIN CERTIFICATE-----\n", headerLen);
4578 XSTRNCPY(footer, "-----END CERTIFICATE-----\n", footerLen);
4580 else if (type == PRIVATEKEY_TYPE) {
4581 XSTRNCPY(header, "-----BEGIN RSA PRIVATE KEY-----\n", headerLen);
4582 XSTRNCPY(footer, "-----END RSA PRIVATE KEY-----\n", footerLen);
4585 else if (type == ECC_PRIVATEKEY_TYPE) {
4586 XSTRNCPY(header, "-----BEGIN EC PRIVATE KEY-----\n", headerLen);
4587 XSTRNCPY(footer, "-----END EC PRIVATE KEY-----\n", footerLen);
4590 #ifdef WOLFSSL_CERT_REQ
4591 else if (type == CERTREQ_TYPE)
4594 "-----BEGIN CERTIFICATE REQUEST-----\n", headerLen);
4595 XSTRNCPY(footer, "-----END CERTIFICATE REQUEST-----\n", footerLen);
4599 #ifdef WOLFSSL_SMALL_STACK
4600 XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4601 XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4603 return BAD_FUNC_ARG;
4606 headerLen = (int)XSTRLEN(header);
4607 footerLen = (int)XSTRLEN(footer);
4609 if (!der || !output) {
4610 #ifdef WOLFSSL_SMALL_STACK
4611 XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4612 XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4614 return BAD_FUNC_ARG;
4617 /* don't even try if outSz too short */
4618 if (outSz < headerLen + footerLen + derSz) {
4619 #ifdef WOLFSSL_SMALL_STACK
4620 XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4621 XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4623 return BAD_FUNC_ARG;
4627 XMEMCPY(output, header, headerLen);
4630 #ifdef WOLFSSL_SMALL_STACK
4631 XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4635 outLen = outSz - (headerLen + footerLen); /* input to Base64_Encode */
4636 if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0) {
4637 #ifdef WOLFSSL_SMALL_STACK
4638 XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4645 if ( (i + footerLen) > (int)outSz) {
4646 #ifdef WOLFSSL_SMALL_STACK
4647 XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4649 return BAD_FUNC_ARG;
4651 XMEMCPY(output + i, footer, footerLen);
4653 #ifdef WOLFSSL_SMALL_STACK
4654 XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4657 return outLen + headerLen + footerLen;
4661 #endif /* WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN */
4664 #if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA)
4667 static mp_int* GetRsaInt(RsaKey* key, int idx)
4690 /* Release Tmp RSA resources */
4691 static INLINE void FreeTmpRsas(byte** tmps, void* heap)
4697 for (i = 0; i < RSA_INTS; i++)
4698 XFREE(tmps[i], heap, DYNAMIC_TYPE_RSA);
4702 /* Convert RsaKey key to DER format, write to output (inLen), return bytes
4704 int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
4706 word32 seqSz, verSz, rawLen, intTotalLen = 0;
4707 word32 sizes[RSA_INTS];
4708 int i, j, outLen, ret = 0;
4710 byte seq[MAX_SEQ_SZ];
4711 byte ver[MAX_VERSION_SZ];
4712 byte* tmps[RSA_INTS];
4714 if (!key || !output)
4715 return BAD_FUNC_ARG;
4717 if (key->type != RSA_PRIVATE)
4718 return BAD_FUNC_ARG;
4720 for (i = 0; i < RSA_INTS; i++)
4723 /* write all big ints from key to DER tmps */
4724 for (i = 0; i < RSA_INTS; i++) {
4725 mp_int* keyInt = GetRsaInt(key, i);
4726 rawLen = mp_unsigned_bin_size(keyInt);
4727 tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
4729 if (tmps[i] == NULL) {
4734 tmps[i][0] = ASN_INTEGER;
4735 sizes[i] = SetLength(rawLen, tmps[i] + 1) + 1; /* int tag */
4737 if (sizes[i] <= MAX_SEQ_SZ) {
4738 int err = mp_to_unsigned_bin(keyInt, tmps[i] + sizes[i]);
4739 if (err == MP_OKAY) {
4741 intTotalLen += sizes[i];
4755 FreeTmpRsas(tmps, key->heap);
4760 verSz = SetMyVersion(0, ver, FALSE);
4761 seqSz = SetSequence(verSz + intTotalLen, seq);
4763 outLen = seqSz + verSz + intTotalLen;
4764 if (outLen > (int)inLen)
4765 return BAD_FUNC_ARG;
4767 /* write to output */
4768 XMEMCPY(output, seq, seqSz);
4770 XMEMCPY(output + j, ver, verSz);
4773 for (i = 0; i < RSA_INTS; i++) {
4774 XMEMCPY(output + j, tmps[i], sizes[i]);
4777 FreeTmpRsas(tmps, key->heap);
4782 #endif /* WOLFSSL_KEY_GEN && !NO_RSA */
4785 #if defined(WOLFSSL_CERT_GEN) && !defined(NO_RSA)
4788 #ifndef WOLFSSL_HAVE_MIN
4789 #define WOLFSSL_HAVE_MIN
4791 static INLINE word32 min(word32 a, word32 b)
4793 return a > b ? b : a;
4796 #endif /* WOLFSSL_HAVE_MIN */
4799 /* Initialize and Set Certficate defaults:
4802 sigType = SHA_WITH_RSA
4805 selfSigned = 1 (true) use subject as issuer
4808 void wc_InitCert(Cert* cert)
4810 cert->version = 2; /* version 3 is hex 2 */
4811 cert->sigType = CTC_SHAwRSA;
4812 cert->daysValid = 500;
4813 cert->selfSigned = 1;
4816 #ifdef WOLFSSL_ALT_NAMES
4817 cert->altNamesSz = 0;
4818 cert->beforeDateSz = 0;
4819 cert->afterDateSz = 0;
4821 cert->keyType = RSA_KEY;
4822 XMEMSET(cert->serial, 0, CTC_SERIAL_SIZE);
4824 cert->issuer.country[0] = '\0';
4825 cert->issuer.countryEnc = CTC_PRINTABLE;
4826 cert->issuer.state[0] = '\0';
4827 cert->issuer.stateEnc = CTC_UTF8;
4828 cert->issuer.locality[0] = '\0';
4829 cert->issuer.localityEnc = CTC_UTF8;
4830 cert->issuer.sur[0] = '\0';
4831 cert->issuer.surEnc = CTC_UTF8;
4832 cert->issuer.org[0] = '\0';
4833 cert->issuer.orgEnc = CTC_UTF8;
4834 cert->issuer.unit[0] = '\0';
4835 cert->issuer.unitEnc = CTC_UTF8;
4836 cert->issuer.commonName[0] = '\0';
4837 cert->issuer.commonNameEnc = CTC_UTF8;
4838 cert->issuer.email[0] = '\0';
4840 cert->subject.country[0] = '\0';
4841 cert->subject.countryEnc = CTC_PRINTABLE;
4842 cert->subject.state[0] = '\0';
4843 cert->subject.stateEnc = CTC_UTF8;
4844 cert->subject.locality[0] = '\0';
4845 cert->subject.localityEnc = CTC_UTF8;
4846 cert->subject.sur[0] = '\0';
4847 cert->subject.surEnc = CTC_UTF8;
4848 cert->subject.org[0] = '\0';
4849 cert->subject.orgEnc = CTC_UTF8;
4850 cert->subject.unit[0] = '\0';
4851 cert->subject.unitEnc = CTC_UTF8;
4852 cert->subject.commonName[0] = '\0';
4853 cert->subject.commonNameEnc = CTC_UTF8;
4854 cert->subject.email[0] = '\0';
4856 #ifdef WOLFSSL_CERT_REQ
4857 cert->challengePw[0] ='\0';
4862 /* DER encoded x509 Certificate */
4863 typedef struct DerCert {
4864 byte size[MAX_LENGTH_SZ]; /* length encoded */
4865 byte version[MAX_VERSION_SZ]; /* version encoded */
4866 byte serial[CTC_SERIAL_SIZE + MAX_LENGTH_SZ]; /* serial number encoded */
4867 byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
4868 byte issuer[ASN_NAME_MAX]; /* issuer encoded */
4869 byte subject[ASN_NAME_MAX]; /* subject encoded */
4870 byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
4871 byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa / ntru public key encoded */
4872 byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
4873 byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
4874 #ifdef WOLFSSL_CERT_REQ
4875 byte attrib[MAX_ATTRIB_SZ]; /* Cert req attributes encoded */
4877 int sizeSz; /* encoded size length */
4878 int versionSz; /* encoded version length */
4879 int serialSz; /* encoded serial length */
4880 int sigAlgoSz; /* enocded sig alog length */
4881 int issuerSz; /* encoded issuer length */
4882 int subjectSz; /* encoded subject length */
4883 int validitySz; /* encoded validity length */
4884 int publicKeySz; /* encoded public key length */
4885 int caSz; /* encoded CA extension length */
4886 int extensionsSz; /* encoded extensions total length */
4887 int total; /* total encoded lengths */
4888 #ifdef WOLFSSL_CERT_REQ
4894 #ifdef WOLFSSL_CERT_REQ
4896 /* Write a set header to output */
4897 static word32 SetUTF8String(word32 len, byte* output)
4899 output[0] = ASN_UTF8STRING;
4900 return SetLength(len, output + 1) + 1;
4903 #endif /* WOLFSSL_CERT_REQ */
4906 /* Write a serial number to output */
4907 static int SetSerial(const byte* serial, byte* output)
4911 output[length++] = ASN_INTEGER;
4912 length += SetLength(CTC_SERIAL_SIZE, &output[length]);
4913 XMEMCPY(&output[length], serial, CTC_SERIAL_SIZE);
4915 return length + CTC_SERIAL_SIZE;
4922 /* Write a public ECC key to output */
4923 static int SetEccPublicKey(byte* output, ecc_key* key)
4925 byte len[MAX_LENGTH_SZ + 1]; /* trailing 0 */
4930 word32 pubSz = ECC_BUFSIZE;
4931 #ifdef WOLFSSL_SMALL_STACK
4936 byte algo[MAX_ALGO_SZ];
4937 byte curve[MAX_ALGO_SZ];
4938 byte pub[ECC_BUFSIZE];
4941 #ifdef WOLFSSL_SMALL_STACK
4942 pub = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4947 int ret = wc_ecc_export_x963(key, pub, &pubSz);
4949 #ifdef WOLFSSL_SMALL_STACK
4950 XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4955 #ifdef WOLFSSL_SMALL_STACK
4956 curve = (byte*)XMALLOC(MAX_ALGO_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4957 if (curve == NULL) {
4958 XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4964 curveSz = SetCurve(key, curve);
4966 #ifdef WOLFSSL_SMALL_STACK
4967 XFREE(curve, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4968 XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4973 #ifdef WOLFSSL_SMALL_STACK
4974 algo = (byte*)XMALLOC(MAX_ALGO_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4976 XFREE(curve, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4977 XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4982 algoSz = SetAlgoID(ECDSAk, algo, keyType, curveSz);
4983 lenSz = SetLength(pubSz + 1, len);
4984 len[lenSz++] = 0; /* trailing 0 */
4987 idx = SetSequence(pubSz + curveSz + lenSz + 1 + algoSz, output);
4988 /* 1 is for ASN_BIT_STRING */
4990 XMEMCPY(output + idx, algo, algoSz);
4993 XMEMCPY(output + idx, curve, curveSz);
4996 output[idx++] = ASN_BIT_STRING;
4998 XMEMCPY(output + idx, len, lenSz);
5001 XMEMCPY(output + idx, pub, pubSz);
5004 #ifdef WOLFSSL_SMALL_STACK
5005 XFREE(algo, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5006 XFREE(curve, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5007 XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5014 #endif /* HAVE_ECC */
5017 /* Write a public RSA key to output */
5018 static int SetRsaPublicKey(byte* output, RsaKey* key)
5020 #ifdef WOLFSSL_SMALL_STACK
5025 byte n[MAX_RSA_INT_SZ];
5026 byte e[MAX_RSA_E_SZ];
5027 byte algo[MAX_ALGO_SZ];
5029 byte seq[MAX_SEQ_SZ];
5030 byte len[MAX_LENGTH_SZ + 1]; /* trailing 0 */
5042 #ifdef WOLFSSL_SMALL_STACK
5043 n = (byte*)XMALLOC(MAX_RSA_INT_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5048 leadingBit = mp_leading_bit(&key->n);
5049 rawLen = mp_unsigned_bin_size(&key->n) + leadingBit;
5051 nSz = SetLength(rawLen, n + 1) + 1; /* int tag */
5053 if ( (nSz + rawLen) < MAX_RSA_INT_SZ) {
5056 err = mp_to_unsigned_bin(&key->n, n + nSz + leadingBit);
5060 #ifdef WOLFSSL_SMALL_STACK
5061 XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5067 #ifdef WOLFSSL_SMALL_STACK
5068 XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5074 #ifdef WOLFSSL_SMALL_STACK
5075 e = (byte*)XMALLOC(MAX_RSA_E_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5077 #ifdef WOLFSSL_SMALL_STACK
5078 XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5084 leadingBit = mp_leading_bit(&key->e);
5085 rawLen = mp_unsigned_bin_size(&key->e) + leadingBit;
5087 eSz = SetLength(rawLen, e + 1) + 1; /* int tag */
5089 if ( (eSz + rawLen) < MAX_RSA_E_SZ) {
5092 err = mp_to_unsigned_bin(&key->e, e + eSz + leadingBit);
5096 #ifdef WOLFSSL_SMALL_STACK
5097 XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5098 XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5104 #ifdef WOLFSSL_SMALL_STACK
5105 XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5106 XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5111 #ifdef WOLFSSL_SMALL_STACK
5112 algo = (byte*)XMALLOC(MAX_ALGO_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5114 XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5115 XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5121 algoSz = SetAlgoID(RSAk, algo, keyType, 0);
5122 seqSz = SetSequence(nSz + eSz, seq);
5123 lenSz = SetLength(seqSz + nSz + eSz + 1, len);
5124 len[lenSz++] = 0; /* trailing 0 */
5127 idx = SetSequence(nSz + eSz + seqSz + lenSz + 1 + algoSz, output);
5128 /* 1 is for ASN_BIT_STRING */
5130 XMEMCPY(output + idx, algo, algoSz);
5133 output[idx++] = ASN_BIT_STRING;
5135 XMEMCPY(output + idx, len, lenSz);
5138 XMEMCPY(output + idx, seq, seqSz);
5141 XMEMCPY(output + idx, n, nSz);
5144 XMEMCPY(output + idx, e, eSz);
5147 #ifdef WOLFSSL_SMALL_STACK
5148 XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5149 XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5150 XFREE(algo, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5157 static INLINE byte itob(int number)
5159 return (byte)number + 0x30;
5163 /* write time to output, format */
5164 static void SetTime(struct tm* date, byte* output)
5168 output[i++] = itob((date->tm_year % 10000) / 1000);
5169 output[i++] = itob((date->tm_year % 1000) / 100);
5170 output[i++] = itob((date->tm_year % 100) / 10);
5171 output[i++] = itob( date->tm_year % 10);
5173 output[i++] = itob(date->tm_mon / 10);
5174 output[i++] = itob(date->tm_mon % 10);
5176 output[i++] = itob(date->tm_mday / 10);
5177 output[i++] = itob(date->tm_mday % 10);
5179 output[i++] = itob(date->tm_hour / 10);
5180 output[i++] = itob(date->tm_hour % 10);
5182 output[i++] = itob(date->tm_min / 10);
5183 output[i++] = itob(date->tm_min % 10);
5185 output[i++] = itob(date->tm_sec / 10);
5186 output[i++] = itob(date->tm_sec % 10);
5188 output[i] = 'Z'; /* Zulu profile */
5192 #ifdef WOLFSSL_ALT_NAMES
5194 /* Copy Dates from cert, return bytes written */
5195 static int CopyValidity(byte* output, Cert* cert)
5199 WOLFSSL_ENTER("CopyValidity");
5201 /* headers and output */
5202 seqSz = SetSequence(cert->beforeDateSz + cert->afterDateSz, output);
5203 XMEMCPY(output + seqSz, cert->beforeDate, cert->beforeDateSz);
5204 XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
5206 return seqSz + cert->beforeDateSz + cert->afterDateSz;
5212 /* for systems where mktime() doesn't normalize fully */
5213 static void RebuildTime(time_t* in, struct tm* out)
5215 #ifdef FREESCALE_MQX
5216 out = localtime_r(in, out);
5224 /* Set Date validity from now until now + daysValid */
5225 static int SetValidity(byte* output, int daysValid)
5227 byte before[MAX_DATE_SIZE];
5228 byte after[MAX_DATE_SIZE];
5237 struct tm* tmpTime = NULL;
5240 #if defined(FREESCALE_MQX) || defined(TIME_OVERRIDES)
5241 /* for use with gmtime_r */
5242 struct tm tmpTimeStorage;
5243 tmpTime = &tmpTimeStorage;
5249 now = XGMTIME(&ticks, tmpTime);
5253 before[0] = ASN_GENERALIZED_TIME;
5254 beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
5256 /* subtract 1 day for more compliance */
5258 normalTime = mktime(&local);
5259 RebuildTime(&normalTime, &local);
5262 local.tm_year += 1900;
5265 SetTime(&local, before + beforeSz);
5266 beforeSz += ASN_GEN_TIME_SZ;
5268 /* after now + daysValid */
5270 after[0] = ASN_GENERALIZED_TIME;
5271 afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
5274 local.tm_mday += daysValid;
5275 normalTime = mktime(&local);
5276 RebuildTime(&normalTime, &local);
5279 local.tm_year += 1900;
5282 SetTime(&local, after + afterSz);
5283 afterSz += ASN_GEN_TIME_SZ;
5285 /* headers and output */
5286 seqSz = SetSequence(beforeSz + afterSz, output);
5287 XMEMCPY(output + seqSz, before, beforeSz);
5288 XMEMCPY(output + seqSz + beforeSz, after, afterSz);
5290 return seqSz + beforeSz + afterSz;
5294 /* ASN Encoded Name field */
5295 typedef struct EncodedName {
5296 int nameLen; /* actual string value length */
5297 int totalLen; /* total encoded length */
5298 int type; /* type of name */
5299 int used; /* are we actually using this one */
5300 byte encoded[CTC_NAME_SIZE * 2]; /* encoding */
5304 /* Get Which Name from index */
5305 static const char* GetOneName(CertName* name, int idx)
5309 return name->country;
5315 return name->locality;
5327 return name->commonName;
5338 /* Get Which Name Encoding from index */
5339 static char GetNameType(CertName* name, int idx)
5343 return name->countryEnc;
5346 return name->stateEnc;
5349 return name->localityEnc;
5352 return name->surEnc;
5355 return name->orgEnc;
5358 return name->unitEnc;
5361 return name->commonNameEnc;
5369 /* Get ASN Name from index */
5370 static byte GetNameId(int idx)
5374 return ASN_COUNTRY_NAME;
5377 return ASN_STATE_NAME;
5380 return ASN_LOCALITY_NAME;
5383 return ASN_SUR_NAME;
5386 return ASN_ORG_NAME;
5389 return ASN_ORGUNIT_NAME;
5392 return ASN_COMMON_NAME;
5395 /* email uses different id type */
5404 /* encode all extensions, return total bytes written */
5405 static int SetExtensions(byte* output, const byte* ext, int extSz, int header)
5407 byte sequence[MAX_SEQ_SZ];
5408 byte len[MAX_LENGTH_SZ];
5411 int seqSz = SetSequence(extSz, sequence);
5414 int lenSz = SetLength(seqSz + extSz, len);
5415 output[0] = ASN_EXTENSIONS; /* extensions id */
5417 XMEMCPY(&output[sz], len, lenSz); /* length */
5420 XMEMCPY(&output[sz], sequence, seqSz); /* sequence */
5422 XMEMCPY(&output[sz], ext, extSz); /* extensions */
5429 /* encode CA basic constraint true, return total bytes written */
5430 static int SetCa(byte* output)
5432 static const byte ca[] = { 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
5433 0x05, 0x30, 0x03, 0x01, 0x01, 0xff };
5435 XMEMCPY(output, ca, sizeof(ca));
5437 return (int)sizeof(ca);
5441 /* encode CertName into output, return total bytes written */
5442 static int SetName(byte* output, CertName* name)
5444 int totalBytes = 0, i, idx;
5445 #ifdef WOLFSSL_SMALL_STACK
5446 EncodedName* names = NULL;
5448 EncodedName names[NAME_ENTRIES];
5451 #ifdef WOLFSSL_SMALL_STACK
5452 names = (EncodedName*)XMALLOC(sizeof(EncodedName) * NAME_ENTRIES, NULL,
5453 DYNAMIC_TYPE_TMP_BUFFER);
5458 for (i = 0; i < NAME_ENTRIES; i++) {
5459 const char* nameStr = GetOneName(name, i);
5462 byte firstLen[MAX_LENGTH_SZ];
5463 byte secondLen[MAX_LENGTH_SZ];
5464 byte sequence[MAX_SEQ_SZ];
5465 byte set[MAX_SET_SZ];
5467 int email = i == (NAME_ENTRIES - 1) ? 1 : 0;
5468 int strLen = (int)XSTRLEN(nameStr);
5469 int thisLen = strLen;
5470 int firstSz, secondSz, seqSz, setSz;
5472 if (strLen == 0) { /* no user data for this item */
5477 secondSz = SetLength(strLen, secondLen);
5478 thisLen += secondSz;
5480 thisLen += EMAIL_JOINT_LEN;
5481 thisLen ++; /* id type */
5482 firstSz = SetLength(EMAIL_JOINT_LEN, firstLen);
5485 thisLen++; /* str type */
5486 thisLen++; /* id type */
5487 thisLen += JOINT_LEN;
5488 firstSz = SetLength(JOINT_LEN + 1, firstLen);
5491 thisLen++; /* object id */
5493 seqSz = SetSequence(thisLen, sequence);
5495 setSz = SetSet(thisLen, set);
5498 if (thisLen > (int)sizeof(names[i].encoded)) {
5499 #ifdef WOLFSSL_SMALL_STACK
5500 XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5508 XMEMCPY(names[i].encoded, set, setSz);
5511 XMEMCPY(names[i].encoded + idx, sequence, seqSz);
5514 names[i].encoded[idx++] = ASN_OBJECT_ID;
5516 XMEMCPY(names[i].encoded + idx, firstLen, firstSz);
5519 const byte EMAIL_OID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
5520 0x01, 0x09, 0x01, 0x16 };
5521 /* email joint id */
5522 XMEMCPY(names[i].encoded + idx, EMAIL_OID, sizeof(EMAIL_OID));
5523 idx += (int)sizeof(EMAIL_OID);
5527 byte bType = GetNameId(i);
5528 names[i].encoded[idx++] = 0x55;
5529 names[i].encoded[idx++] = 0x04;
5531 names[i].encoded[idx++] = bType;
5533 names[i].encoded[idx++] = GetNameType(name, i);
5536 XMEMCPY(names[i].encoded + idx, secondLen, secondSz);
5539 XMEMCPY(names[i].encoded + idx, nameStr, strLen);
5543 names[i].totalLen = idx;
5551 idx = SetSequence(totalBytes, output);
5553 if (totalBytes > ASN_NAME_MAX) {
5554 #ifdef WOLFSSL_SMALL_STACK
5555 XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5560 for (i = 0; i < NAME_ENTRIES; i++) {
5561 if (names[i].used) {
5562 XMEMCPY(output + idx, names[i].encoded, names[i].totalLen);
5563 idx += names[i].totalLen;
5567 #ifdef WOLFSSL_SMALL_STACK
5568 XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5574 /* encode info from cert into DER encoded format */
5575 static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey,
5576 RNG* rng, const byte* ntruKey, word16 ntruSz)
5585 XMEMSET(der, 0, sizeof(DerCert));
5588 der->versionSz = SetMyVersion(cert->version, der->version, TRUE);
5591 ret = wc_RNG_GenerateBlock(rng, cert->serial, CTC_SERIAL_SIZE);
5595 cert->serial[0] = 0x01; /* ensure positive */
5596 der->serialSz = SetSerial(cert->serial, der->serial);
5598 /* signature algo */
5599 der->sigAlgoSz = SetAlgoID(cert->sigType, der->sigAlgo, sigType, 0);
5600 if (der->sigAlgoSz == 0)
5604 if (cert->keyType == RSA_KEY) {
5606 return PUBLIC_KEY_E;
5607 der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey);
5608 if (der->publicKeySz <= 0)
5609 return PUBLIC_KEY_E;
5613 if (cert->keyType == ECC_KEY) {
5615 return PUBLIC_KEY_E;
5616 der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey);
5617 if (der->publicKeySz <= 0)
5618 return PUBLIC_KEY_E;
5620 #endif /* HAVE_ECC */
5623 if (cert->keyType == NTRU_KEY) {
5627 rc = ntru_crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo( ntruSz,
5628 ntruKey, &encodedSz, NULL);
5630 return PUBLIC_KEY_E;
5631 if (encodedSz > MAX_PUBLIC_KEY_SZ)
5632 return PUBLIC_KEY_E;
5634 rc = ntru_crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo( ntruSz,
5635 ntruKey, &encodedSz, der->publicKey);
5637 return PUBLIC_KEY_E;
5639 der->publicKeySz = encodedSz;
5641 #endif /* HAVE_NTRU */
5643 der->validitySz = 0;
5644 #ifdef WOLFSSL_ALT_NAMES
5645 /* date validity copy ? */
5646 if (cert->beforeDateSz && cert->afterDateSz) {
5647 der->validitySz = CopyValidity(der->validity, cert);
5648 if (der->validitySz == 0)
5654 if (der->validitySz == 0) {
5655 der->validitySz = SetValidity(der->validity, cert->daysValid);
5656 if (der->validitySz == 0)
5661 der->subjectSz = SetName(der->subject, &cert->subject);
5662 if (der->subjectSz == 0)
5666 der->issuerSz = SetName(der->issuer, cert->selfSigned ?
5667 &cert->subject : &cert->issuer);
5668 if (der->issuerSz == 0)
5673 der->caSz = SetCa(der->ca);
5680 /* extensions, just CA now */
5682 der->extensionsSz = SetExtensions(der->extensions,
5683 der->ca, der->caSz, TRUE);
5684 if (der->extensionsSz == 0)
5685 return EXTENSIONS_E;
5688 der->extensionsSz = 0;
5690 #ifdef WOLFSSL_ALT_NAMES
5691 if (der->extensionsSz == 0 && cert->altNamesSz) {
5692 der->extensionsSz = SetExtensions(der->extensions, cert->altNames,
5693 cert->altNamesSz, TRUE);
5694 if (der->extensionsSz == 0)
5695 return EXTENSIONS_E;
5699 der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
5700 der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
5707 /* write DER encoded cert to buffer, size already checked */
5708 static int WriteCertBody(DerCert* der, byte* buffer)
5712 /* signed part header */
5713 idx = SetSequence(der->total, buffer);
5715 XMEMCPY(buffer + idx, der->version, der->versionSz);
5716 idx += der->versionSz;
5718 XMEMCPY(buffer + idx, der->serial, der->serialSz);
5719 idx += der->serialSz;
5721 XMEMCPY(buffer + idx, der->sigAlgo, der->sigAlgoSz);
5722 idx += der->sigAlgoSz;
5724 XMEMCPY(buffer + idx, der->issuer, der->issuerSz);
5725 idx += der->issuerSz;
5727 XMEMCPY(buffer + idx, der->validity, der->validitySz);
5728 idx += der->validitySz;
5730 XMEMCPY(buffer + idx, der->subject, der->subjectSz);
5731 idx += der->subjectSz;
5733 XMEMCPY(buffer + idx, der->publicKey, der->publicKeySz);
5734 idx += der->publicKeySz;
5735 if (der->extensionsSz) {
5737 XMEMCPY(buffer + idx, der->extensions, min(der->extensionsSz,
5738 sizeof(der->extensions)));
5739 idx += der->extensionsSz;
5746 /* Make RSA signature from buffer (sz), write to sig (sigSz) */
5747 static int MakeSignature(const byte* buffer, int sz, byte* sig, int sigSz,
5748 RsaKey* rsaKey, ecc_key* eccKey, RNG* rng,
5751 int encSigSz, digestSz, typeH = 0, ret = 0;
5752 byte digest[SHA256_DIGEST_SIZE]; /* max size */
5753 #ifdef WOLFSSL_SMALL_STACK
5756 byte encSig[MAX_ENCODED_DIG_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ];
5773 switch (sigAlgoType) {
5776 if ((ret = wc_Md5Hash(buffer, sz, digest)) == 0) {
5778 digestSz = MD5_DIGEST_SIZE;
5785 if ((ret = wc_ShaHash(buffer, sz, digest)) == 0) {
5787 digestSz = SHA_DIGEST_SIZE;
5792 case CTC_SHA256wRSA:
5793 case CTC_SHA256wECDSA:
5794 if ((ret = wc_Sha256Hash(buffer, sz, digest)) == 0) {
5796 digestSz = SHA256_DIGEST_SIZE;
5801 WOLFSSL_MSG("MakeSignautre called with unsupported type");
5808 #ifdef WOLFSSL_SMALL_STACK
5809 encSig = (byte*)XMALLOC(MAX_ENCODED_DIG_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ,
5810 NULL, DYNAMIC_TYPE_TMP_BUFFER);
5820 encSigSz = wc_EncodeSignature(encSig, digest, digestSz, typeH);
5821 ret = wc_RsaSSL_Sign(encSig, encSigSz, sig, sigSz, rsaKey, rng);
5826 if (!rsaKey && eccKey) {
5827 word32 outSz = sigSz;
5828 ret = wc_ecc_sign_hash(digest, digestSz, sig, &outSz, rng, eccKey);
5835 #ifdef WOLFSSL_SMALL_STACK
5836 XFREE(encSig, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5843 /* add signature to end of buffer, size of buffer assumed checked, return
5845 static int AddSignature(byte* buffer, int bodySz, const byte* sig, int sigSz,
5848 byte seq[MAX_SEQ_SZ];
5849 int idx = bodySz, seqSz;
5852 idx += SetAlgoID(sigAlgoType, buffer + idx, sigType, 0);
5854 buffer[idx++] = ASN_BIT_STRING;
5856 idx += SetLength(sigSz + 1, buffer + idx);
5857 buffer[idx++] = 0; /* trailing 0 */
5859 XMEMCPY(buffer + idx, sig, sigSz);
5862 /* make room for overall header */
5863 seqSz = SetSequence(idx, seq);
5864 XMEMMOVE(buffer + seqSz, buffer, idx);
5865 XMEMCPY(buffer, seq, seqSz);
5871 /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
5872 static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
5873 RsaKey* rsaKey, ecc_key* eccKey, RNG* rng,
5874 const byte* ntruKey, word16 ntruSz)
5877 #ifdef WOLFSSL_SMALL_STACK
5883 cert->keyType = eccKey ? ECC_KEY : (rsaKey ? RSA_KEY : NTRU_KEY);
5885 #ifdef WOLFSSL_SMALL_STACK
5886 der = (DerCert*)XMALLOC(sizeof(DerCert), NULL, DYNAMIC_TYPE_TMP_BUFFER);
5891 ret = EncodeCert(cert, der, rsaKey, eccKey, rng, ntruKey, ntruSz);
5894 if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
5897 ret = cert->bodySz = WriteCertBody(der, derBuffer);
5900 #ifdef WOLFSSL_SMALL_STACK
5901 XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5908 /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
5909 int wc_MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,
5910 ecc_key* eccKey, RNG* rng)
5912 return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, 0);
5918 int wc_MakeNtruCert(Cert* cert, byte* derBuffer, word32 derSz,
5919 const byte* ntruKey, word16 keySz, RNG* rng)
5921 return MakeAnyCert(cert, derBuffer, derSz, NULL, NULL, rng, ntruKey, keySz);
5924 #endif /* HAVE_NTRU */
5927 #ifdef WOLFSSL_CERT_REQ
5929 static int SetReqAttrib(byte* output, char* pw, int extSz)
5931 static const byte cpOid[] =
5932 { ASN_OBJECT_ID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01,
5934 static const byte erOid[] =
5935 { ASN_OBJECT_ID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01,
5938 int sz = 0; /* overall size */
5939 int cpSz = 0; /* Challenge Password section size */
5944 int erSz = 0; /* Extension Request section size */
5947 byte cpSeq[MAX_SEQ_SZ];
5948 byte cpSet[MAX_SET_SZ];
5949 byte cpStr[MAX_PRSTR_SZ];
5950 byte erSeq[MAX_SEQ_SZ];
5951 byte erSet[MAX_SET_SZ];
5957 pwSz = (int)XSTRLEN(pw);
5958 cpStrSz = SetUTF8String(pwSz, cpStr);
5959 cpSetSz = SetSet(cpStrSz + pwSz, cpSet);
5960 cpSeqSz = SetSequence(sizeof(cpOid) + cpSetSz + cpStrSz + pwSz, cpSeq);
5961 cpSz = cpSeqSz + sizeof(cpOid) + cpSetSz + cpStrSz + pwSz;
5965 erSetSz = SetSet(extSz, erSet);
5966 erSeqSz = SetSequence(erSetSz + sizeof(erOid) + extSz, erSeq);
5967 erSz = extSz + erSetSz + erSeqSz + sizeof(erOid);
5970 /* Put the pieces together. */
5971 sz += SetLength(cpSz + erSz, &output[sz]);
5974 XMEMCPY(&output[sz], cpSeq, cpSeqSz);
5976 XMEMCPY(&output[sz], cpOid, sizeof(cpOid));
5977 sz += sizeof(cpOid);
5978 XMEMCPY(&output[sz], cpSet, cpSetSz);
5980 XMEMCPY(&output[sz], cpStr, cpStrSz);
5982 XMEMCPY(&output[sz], pw, pwSz);
5987 XMEMCPY(&output[sz], erSeq, erSeqSz);
5989 XMEMCPY(&output[sz], erOid, sizeof(erOid));
5990 sz += sizeof(erOid);
5991 XMEMCPY(&output[sz], erSet, erSetSz);
5993 /* The actual extension data will be tacked onto the output later. */
6000 /* encode info from cert into DER encoded format */
6001 static int EncodeCertReq(Cert* cert, DerCert* der,
6002 RsaKey* rsaKey, ecc_key* eccKey)
6007 XMEMSET(der, 0, sizeof(DerCert));
6010 der->versionSz = SetMyVersion(cert->version, der->version, FALSE);
6013 der->subjectSz = SetName(der->subject, &cert->subject);
6014 if (der->subjectSz == 0)
6018 if (cert->keyType == RSA_KEY) {
6020 return PUBLIC_KEY_E;
6021 der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey);
6022 if (der->publicKeySz <= 0)
6023 return PUBLIC_KEY_E;
6027 if (cert->keyType == ECC_KEY) {
6029 return PUBLIC_KEY_E;
6030 der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey);
6031 if (der->publicKeySz <= 0)
6032 return PUBLIC_KEY_E;
6034 #endif /* HAVE_ECC */
6038 der->caSz = SetCa(der->ca);
6045 /* extensions, just CA now */
6047 der->extensionsSz = SetExtensions(der->extensions,
6048 der->ca, der->caSz, FALSE);
6049 if (der->extensionsSz == 0)
6050 return EXTENSIONS_E;
6053 der->extensionsSz = 0;
6055 der->attribSz = SetReqAttrib(der->attrib,
6056 cert->challengePw, der->extensionsSz);
6057 if (der->attribSz == 0)
6058 return REQ_ATTRIBUTE_E;
6060 der->total = der->versionSz + der->subjectSz + der->publicKeySz +
6061 der->extensionsSz + der->attribSz;
6067 /* write DER encoded cert req to buffer, size already checked */
6068 static int WriteCertReqBody(DerCert* der, byte* buffer)
6072 /* signed part header */
6073 idx = SetSequence(der->total, buffer);
6075 XMEMCPY(buffer + idx, der->version, der->versionSz);
6076 idx += der->versionSz;
6078 XMEMCPY(buffer + idx, der->subject, der->subjectSz);
6079 idx += der->subjectSz;
6081 XMEMCPY(buffer + idx, der->publicKey, der->publicKeySz);
6082 idx += der->publicKeySz;
6084 XMEMCPY(buffer + idx, der->attrib, der->attribSz);
6085 idx += der->attribSz;
6087 if (der->extensionsSz) {
6088 XMEMCPY(buffer + idx, der->extensions, min(der->extensionsSz,
6089 sizeof(der->extensions)));
6090 idx += der->extensionsSz;
6097 int wc_MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
6098 RsaKey* rsaKey, ecc_key* eccKey)
6101 #ifdef WOLFSSL_SMALL_STACK
6107 cert->keyType = eccKey ? ECC_KEY : RSA_KEY;
6109 #ifdef WOLFSSL_SMALL_STACK
6110 der = (DerCert*)XMALLOC(sizeof(DerCert), NULL, DYNAMIC_TYPE_TMP_BUFFER);
6115 ret = EncodeCertReq(cert, der, rsaKey, eccKey);
6118 if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
6121 ret = cert->bodySz = WriteCertReqBody(der, derBuffer);
6124 #ifdef WOLFSSL_SMALL_STACK
6125 XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6131 #endif /* WOLFSSL_CERT_REQ */
6134 int wc_SignCert(int requestSz, int sType, byte* buffer, word32 buffSz,
6135 RsaKey* rsaKey, ecc_key* eccKey, RNG* rng)
6138 #ifdef WOLFSSL_SMALL_STACK
6141 byte sig[MAX_ENCODED_SIG_SZ];
6147 #ifdef WOLFSSL_SMALL_STACK
6148 sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6153 sigSz = MakeSignature(buffer, requestSz, sig, MAX_ENCODED_SIG_SZ, rsaKey,
6154 eccKey, rng, sType);
6157 if (requestSz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
6160 sigSz = AddSignature(buffer, requestSz, sig, sigSz, sType);
6163 #ifdef WOLFSSL_SMALL_STACK
6164 XFREE(sig, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6171 int wc_MakeSelfCert(Cert* cert, byte* buffer, word32 buffSz, RsaKey* key, RNG* rng)
6173 int ret = wc_MakeCert(cert, buffer, buffSz, key, NULL, rng);
6178 return wc_SignCert(cert->bodySz, cert->sigType, buffer, buffSz, key, NULL,rng);
6182 #ifdef WOLFSSL_ALT_NAMES
6184 /* Set Alt Names from der cert, return 0 on success */
6185 static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz)
6188 #ifdef WOLFSSL_SMALL_STACK
6189 DecodedCert* decoded;
6191 DecodedCert decoded[1];
6197 #ifdef WOLFSSL_SMALL_STACK
6198 decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
6199 DYNAMIC_TYPE_TMP_BUFFER);
6200 if (decoded == NULL)
6204 InitDecodedCert(decoded, (byte*)der, derSz, 0);
6205 ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
6208 WOLFSSL_MSG("ParseCertRelative error");
6210 else if (decoded->extensions) {
6213 word32 maxExtensionsIdx;
6215 decoded->srcIdx = decoded->extensionsIdx;
6216 b = decoded->source[decoded->srcIdx++];
6218 if (b != ASN_EXTENSIONS) {
6221 else if (GetLength(decoded->source, &decoded->srcIdx, &length,
6222 decoded->maxIdx) < 0) {
6225 else if (GetSequence(decoded->source, &decoded->srcIdx, &length,
6226 decoded->maxIdx) < 0) {
6230 maxExtensionsIdx = decoded->srcIdx + length;
6232 while (decoded->srcIdx < maxExtensionsIdx) {
6234 word32 startIdx = decoded->srcIdx;
6237 if (GetSequence(decoded->source, &decoded->srcIdx, &length,
6238 decoded->maxIdx) < 0) {
6243 tmpIdx = decoded->srcIdx;
6244 decoded->srcIdx = startIdx;
6246 if (GetAlgoId(decoded->source, &decoded->srcIdx, &oid,
6247 decoded->maxIdx) < 0) {
6252 if (oid == ALT_NAMES_OID) {
6253 cert->altNamesSz = length + (tmpIdx - startIdx);
6255 if (cert->altNamesSz < (int)sizeof(cert->altNames))
6256 XMEMCPY(cert->altNames, &decoded->source[startIdx],
6259 cert->altNamesSz = 0;
6260 WOLFSSL_MSG("AltNames extensions too big");
6265 decoded->srcIdx = tmpIdx + length;
6270 FreeDecodedCert(decoded);
6271 #ifdef WOLFSSL_SMALL_STACK
6272 XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6275 return ret < 0 ? ret : 0;
6279 /* Set Dates from der cert, return 0 on success */
6280 static int SetDatesFromCert(Cert* cert, const byte* der, int derSz)
6283 #ifdef WOLFSSL_SMALL_STACK
6284 DecodedCert* decoded;
6286 DecodedCert decoded[1];
6289 WOLFSSL_ENTER("SetDatesFromCert");
6293 #ifdef WOLFSSL_SMALL_STACK
6294 decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
6295 DYNAMIC_TYPE_TMP_BUFFER);
6296 if (decoded == NULL)
6300 InitDecodedCert(decoded, (byte*)der, derSz, 0);
6301 ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
6304 WOLFSSL_MSG("ParseCertRelative error");
6306 else if (decoded->beforeDate == NULL || decoded->afterDate == NULL) {
6307 WOLFSSL_MSG("Couldn't extract dates");
6310 else if (decoded->beforeDateLen > MAX_DATE_SIZE ||
6311 decoded->afterDateLen > MAX_DATE_SIZE) {
6312 WOLFSSL_MSG("Bad date size");
6316 XMEMCPY(cert->beforeDate, decoded->beforeDate, decoded->beforeDateLen);
6317 XMEMCPY(cert->afterDate, decoded->afterDate, decoded->afterDateLen);
6319 cert->beforeDateSz = decoded->beforeDateLen;
6320 cert->afterDateSz = decoded->afterDateLen;
6323 FreeDecodedCert(decoded);
6325 #ifdef WOLFSSL_SMALL_STACK
6326 XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6329 return ret < 0 ? ret : 0;
6333 #endif /* WOLFSSL_ALT_NAMES && !NO_RSA */
6336 /* Set cn name from der buffer, return 0 on success */
6337 static int SetNameFromCert(CertName* cn, const byte* der, int derSz)
6340 #ifdef WOLFSSL_SMALL_STACK
6341 DecodedCert* decoded;
6343 DecodedCert decoded[1];
6349 #ifdef WOLFSSL_SMALL_STACK
6350 decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
6351 DYNAMIC_TYPE_TMP_BUFFER);
6352 if (decoded == NULL)
6356 InitDecodedCert(decoded, (byte*)der, derSz, 0);
6357 ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
6360 WOLFSSL_MSG("ParseCertRelative error");
6363 if (decoded->subjectCN) {
6364 sz = (decoded->subjectCNLen < CTC_NAME_SIZE) ? decoded->subjectCNLen
6365 : CTC_NAME_SIZE - 1;
6366 strncpy(cn->commonName, decoded->subjectCN, CTC_NAME_SIZE);
6367 cn->commonName[sz] = 0;
6368 cn->commonNameEnc = decoded->subjectCNEnc;
6370 if (decoded->subjectC) {
6371 sz = (decoded->subjectCLen < CTC_NAME_SIZE) ? decoded->subjectCLen
6372 : CTC_NAME_SIZE - 1;
6373 strncpy(cn->country, decoded->subjectC, CTC_NAME_SIZE);
6374 cn->country[sz] = 0;
6375 cn->countryEnc = decoded->subjectCEnc;
6377 if (decoded->subjectST) {
6378 sz = (decoded->subjectSTLen < CTC_NAME_SIZE) ? decoded->subjectSTLen
6379 : CTC_NAME_SIZE - 1;
6380 strncpy(cn->state, decoded->subjectST, CTC_NAME_SIZE);
6382 cn->stateEnc = decoded->subjectSTEnc;
6384 if (decoded->subjectL) {
6385 sz = (decoded->subjectLLen < CTC_NAME_SIZE) ? decoded->subjectLLen
6386 : CTC_NAME_SIZE - 1;
6387 strncpy(cn->locality, decoded->subjectL, CTC_NAME_SIZE);
6388 cn->locality[sz] = 0;
6389 cn->localityEnc = decoded->subjectLEnc;
6391 if (decoded->subjectO) {
6392 sz = (decoded->subjectOLen < CTC_NAME_SIZE) ? decoded->subjectOLen
6393 : CTC_NAME_SIZE - 1;
6394 strncpy(cn->org, decoded->subjectO, CTC_NAME_SIZE);
6396 cn->orgEnc = decoded->subjectOEnc;
6398 if (decoded->subjectOU) {
6399 sz = (decoded->subjectOULen < CTC_NAME_SIZE) ? decoded->subjectOULen
6400 : CTC_NAME_SIZE - 1;
6401 strncpy(cn->unit, decoded->subjectOU, CTC_NAME_SIZE);
6403 cn->unitEnc = decoded->subjectOUEnc;
6405 if (decoded->subjectSN) {
6406 sz = (decoded->subjectSNLen < CTC_NAME_SIZE) ? decoded->subjectSNLen
6407 : CTC_NAME_SIZE - 1;
6408 strncpy(cn->sur, decoded->subjectSN, CTC_NAME_SIZE);
6410 cn->surEnc = decoded->subjectSNEnc;
6412 if (decoded->subjectEmail) {
6413 sz = (decoded->subjectEmailLen < CTC_NAME_SIZE)
6414 ? decoded->subjectEmailLen : CTC_NAME_SIZE - 1;
6415 strncpy(cn->email, decoded->subjectEmail, CTC_NAME_SIZE);
6420 FreeDecodedCert(decoded);
6422 #ifdef WOLFSSL_SMALL_STACK
6423 XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6426 return ret < 0 ? ret : 0;
6430 #ifndef NO_FILESYSTEM
6432 /* Set cert issuer from issuerFile in PEM */
6433 int wc_SetIssuer(Cert* cert, const char* issuerFile)
6437 byte* der = (byte*)XMALLOC(EIGHTK_BUF, NULL, DYNAMIC_TYPE_CERT);
6440 WOLFSSL_MSG("wc_SetIssuer OOF Problem");
6443 derSz = wolfSSL_PemCertToDer(issuerFile, der, EIGHTK_BUF);
6444 cert->selfSigned = 0;
6445 ret = SetNameFromCert(&cert->issuer, der, derSz);
6446 XFREE(der, NULL, DYNAMIC_TYPE_CERT);
6452 /* Set cert subject from subjectFile in PEM */
6453 int wc_SetSubject(Cert* cert, const char* subjectFile)
6457 byte* der = (byte*)XMALLOC(EIGHTK_BUF, NULL, DYNAMIC_TYPE_CERT);
6460 WOLFSSL_MSG("wc_SetSubject OOF Problem");
6463 derSz = wolfSSL_PemCertToDer(subjectFile, der, EIGHTK_BUF);
6464 ret = SetNameFromCert(&cert->subject, der, derSz);
6465 XFREE(der, NULL, DYNAMIC_TYPE_CERT);
6471 #ifdef WOLFSSL_ALT_NAMES
6473 /* Set atl names from file in PEM */
6474 int wc_SetAltNames(Cert* cert, const char* file)
6478 byte* der = (byte*)XMALLOC(EIGHTK_BUF, NULL, DYNAMIC_TYPE_CERT);
6481 WOLFSSL_MSG("wc_SetAltNames OOF Problem");
6484 derSz = wolfSSL_PemCertToDer(file, der, EIGHTK_BUF);
6485 ret = SetAltNamesFromCert(cert, der, derSz);
6486 XFREE(der, NULL, DYNAMIC_TYPE_CERT);
6491 #endif /* WOLFSSL_ALT_NAMES */
6493 #endif /* NO_FILESYSTEM */
6495 /* Set cert issuer from DER buffer */
6496 int wc_SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
6498 cert->selfSigned = 0;
6499 return SetNameFromCert(&cert->issuer, der, derSz);
6503 /* Set cert subject from DER buffer */
6504 int wc_SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
6506 return SetNameFromCert(&cert->subject, der, derSz);
6510 #ifdef WOLFSSL_ALT_NAMES
6512 /* Set cert alt names from DER buffer */
6513 int wc_SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
6515 return SetAltNamesFromCert(cert, der, derSz);
6518 /* Set cert dates from DER buffer */
6519 int wc_SetDatesBuffer(Cert* cert, const byte* der, int derSz)
6521 return SetDatesFromCert(cert, der, derSz);
6524 #endif /* WOLFSSL_ALT_NAMES */
6526 #endif /* WOLFSSL_CERT_GEN */
6531 /* Der Encode r & s ints into out, outLen is (in/out) size */
6532 int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
6535 word32 rSz; /* encoding size */
6537 word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
6539 /* If the leading bit on the INTEGER is a 1, add a leading zero */
6540 int rLeadingZero = mp_leading_bit(r);
6541 int sLeadingZero = mp_leading_bit(s);
6542 int rLen = mp_unsigned_bin_size(r); /* big int size */
6543 int sLen = mp_unsigned_bin_size(s);
6546 if (*outLen < (rLen + rLeadingZero + sLen + sLeadingZero +
6547 headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
6548 return BAD_FUNC_ARG;
6550 idx = SetSequence(rLen+rLeadingZero+sLen+sLeadingZero+headerSz, out);
6553 out[idx++] = ASN_INTEGER;
6554 rSz = SetLength(rLen + rLeadingZero, &out[idx]);
6558 err = mp_to_unsigned_bin(r, &out[idx]);
6559 if (err != MP_OKAY) return err;
6563 out[idx++] = ASN_INTEGER;
6564 sSz = SetLength(sLen + sLeadingZero, &out[idx]);
6568 err = mp_to_unsigned_bin(s, &out[idx]);
6569 if (err != MP_OKAY) return err;
6578 /* Der Decode ECC-DSA Signautre, r & s stored as big ints */
6579 int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
6584 if (GetSequence(sig, &idx, &len, sigLen) < 0)
6585 return ASN_ECC_KEY_E;
6587 if ((word32)len > (sigLen - idx))
6588 return ASN_ECC_KEY_E;
6590 if (GetInt(r, sig, &idx, sigLen) < 0)
6591 return ASN_ECC_KEY_E;
6593 if (GetInt(s, sig, &idx, sigLen) < 0)
6594 return ASN_ECC_KEY_E;
6600 int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
6604 int version, length;
6608 #ifdef WOLFSSL_SMALL_STACK
6612 byte priv[ECC_MAXSIZE];
6613 byte pub[ECC_MAXSIZE * 2 + 1]; /* public key has two parts plus header */
6616 if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
6617 return BAD_FUNC_ARG;
6619 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
6622 if (GetMyVersion(input, inOutIdx, &version) < 0)
6625 b = input[*inOutIdx];
6629 if (b != 4 && b != 6 && b != 7)
6632 if (GetLength(input, inOutIdx, &length, inSz) < 0)
6635 if (length > ECC_MAXSIZE)
6638 #ifdef WOLFSSL_SMALL_STACK
6639 priv = (byte*)XMALLOC(ECC_MAXSIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6643 pub = (byte*)XMALLOC(ECC_MAXSIZE * 2 + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6645 XFREE(priv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6652 XMEMCPY(priv, &input[*inOutIdx], privSz);
6653 *inOutIdx += length;
6655 /* prefix 0, may have */
6656 b = input[*inOutIdx];
6657 if (b == ECC_PREFIX_0) {
6660 if (GetLength(input, inOutIdx, &length, inSz) < 0)
6664 b = input[*inOutIdx];
6667 if (b != ASN_OBJECT_ID) {
6668 ret = ASN_OBJECT_ID_E;
6670 else if (GetLength(input, inOutIdx, &length, inSz) < 0) {
6675 oid += input[*inOutIdx];
6678 if (CheckCurve(oid) < 0)
6679 ret = ECC_CURVE_OID_E;
6686 b = input[*inOutIdx];
6689 if (b != ECC_PREFIX_1) {
6690 ret = ASN_ECC_KEY_E;
6692 else if (GetLength(input, inOutIdx, &length, inSz) < 0) {
6697 b = input[*inOutIdx];
6700 if (b != ASN_BIT_STRING) {
6703 else if (GetLength(input, inOutIdx, &length, inSz) < 0) {
6707 b = input[*inOutIdx];
6711 ret = ASN_EXPECT_0_E;
6715 pubSz = length - 1; /* null prefix */
6716 if (pubSz < (ECC_MAXSIZE*2 + 1)) {
6717 XMEMCPY(pub, &input[*inOutIdx], pubSz);
6718 *inOutIdx += length;
6719 ret = wc_ecc_import_private_key(priv, privSz, pub, pubSz,
6728 #ifdef WOLFSSL_SMALL_STACK
6729 XFREE(priv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6730 XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6737 #ifdef WOLFSSL_KEY_GEN
6739 /* Write a Private ecc key to DER format, length on success else < 0 */
6740 int wc_EccKeyToDer(ecc_key* key, byte* output, word32 inLen)
6742 byte curve[MAX_ALGO_SZ];
6743 byte ver[MAX_VERSION_SZ];
6744 byte seq[MAX_SEQ_SZ];
6748 int privHdrSz = ASN_ECC_HEADER_SZ;
6749 int pubHdrSz = ASN_ECC_CONTEXT_SZ + ASN_ECC_HEADER_SZ;
6750 int curveHdrSz = ASN_ECC_CONTEXT_SZ;
6753 word32 pubSz = ECC_BUFSIZE;
6757 if (key == NULL || output == NULL || inLen == 0)
6758 return BAD_FUNC_ARG;
6760 ret = wc_ecc_export_x963(key, NULL, &pubSz);
6761 if (ret != LENGTH_ONLY_E) {
6764 curveSz = SetCurve(key, curve);
6769 privSz = key->dp->size;
6771 verSz = SetMyVersion(1, ver, FALSE);
6776 totalSz = verSz + privSz + privHdrSz + curveSz + curveHdrSz +
6777 pubSz + pubHdrSz + 1; /* plus null byte b4 public */
6778 seqSz = SetSequence(totalSz, seq);
6781 if (totalSz > inLen) {
6787 XMEMCPY(output + idx, seq, seqSz);
6791 XMEMCPY(output + idx, ver, verSz);
6795 output[idx++] = ASN_OCTET_STRING;
6796 output[idx++] = (byte)privSz;
6797 ret = wc_ecc_export_private_only(key, output + idx, &privSz);
6804 output[idx++] = ECC_PREFIX_0;
6805 output[idx++] = (byte)curveSz;
6806 XMEMCPY(output + idx, curve, curveSz);
6810 output[idx++] = ECC_PREFIX_1;
6811 output[idx++] = (byte)pubSz + ASN_ECC_CONTEXT_SZ + 1; /* plus null byte */
6812 output[idx++] = ASN_BIT_STRING;
6813 output[idx++] = (byte)pubSz + 1; /* plus null byte */
6814 output[idx++] = (byte)0; /* null byte */
6815 ret = wc_ecc_export_x963(key, output + idx, &pubSz);
6819 /* idx += pubSz if do more later */
6824 #endif /* WOLFSSL_KEY_GEN */
6826 #endif /* HAVE_ECC */
6829 #if defined(HAVE_OCSP) || defined(HAVE_CRL)
6831 /* Get raw Date only, no processing, 0 on success */
6832 static int GetBasicDate(const byte* source, word32* idx, byte* date,
6833 byte* format, int maxIdx)
6837 WOLFSSL_ENTER("GetBasicDate");
6839 *format = source[*idx];
6841 if (*format != ASN_UTC_TIME && *format != ASN_GENERALIZED_TIME)
6844 if (GetLength(source, idx, &length, maxIdx) < 0)
6847 if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
6848 return ASN_DATE_SZ_E;
6850 XMEMCPY(date, &source[*idx], length);
6861 static int GetEnumerated(const byte* input, word32* inOutIdx, int *value)
6863 word32 idx = *inOutIdx;
6866 WOLFSSL_ENTER("GetEnumerated");
6870 if (input[idx++] != ASN_ENUMERATED)
6878 *value = *value << 8 | input[idx++];
6887 static int DecodeSingleResponse(byte* source,
6888 word32* ioIndex, OcspResponse* resp, word32 size)
6890 word32 idx = *ioIndex, prevIndex, oid;
6891 int length, wrapperSz;
6892 CertStatus* cs = resp->status;
6894 WOLFSSL_ENTER("DecodeSingleResponse");
6896 /* Outer wrapper of the SEQUENCE OF Single Responses. */
6897 if (GetSequence(source, &idx, &wrapperSz, size) < 0)
6902 /* When making a request, we only request one status on one certificate
6903 * at a time. There should only be one SingleResponse */
6905 /* Wrapper around the Single Response */
6906 if (GetSequence(source, &idx, &length, size) < 0)
6909 /* Wrapper around the CertID */
6910 if (GetSequence(source, &idx, &length, size) < 0)
6912 /* Skip the hash algorithm */
6913 if (GetAlgoId(source, &idx, &oid, size) < 0)
6915 /* Save reference to the hash of CN */
6916 if (source[idx++] != ASN_OCTET_STRING)
6918 if (GetLength(source, &idx, &length, size) < 0)
6920 resp->issuerHash = source + idx;
6922 /* Save reference to the hash of the issuer public key */
6923 if (source[idx++] != ASN_OCTET_STRING)
6925 if (GetLength(source, &idx, &length, size) < 0)
6927 resp->issuerKeyHash = source + idx;
6930 /* Read the serial number, it is handled as a string, not as a
6931 * proper number. Just XMEMCPY the data over, rather than load it
6933 if (source[idx++] != ASN_INTEGER)
6935 if (GetLength(source, &idx, &length, size) < 0)
6937 if (length <= EXTERNAL_SERIAL_SIZE)
6939 if (source[idx] == 0)
6944 XMEMCPY(cs->serial, source + idx, length);
6945 cs->serialSz = length;
6949 return ASN_GETINT_E;
6954 switch (source[idx++])
6956 case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
6957 cs->status = CERT_GOOD;
6960 case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
6961 cs->status = CERT_REVOKED;
6962 if (GetLength(source, &idx, &length, size) < 0)
6966 case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
6967 cs->status = CERT_UNKNOWN;
6974 if (GetBasicDate(source, &idx, cs->thisDate,
6975 &cs->thisDateFormat, size) < 0)
6977 if (!XVALIDATE_DATE(cs->thisDate, cs->thisDateFormat, BEFORE))
6978 return ASN_BEFORE_DATE_E;
6980 /* The following items are optional. Only check for them if there is more
6981 * unprocessed data in the singleResponse wrapper. */
6983 if (((int)(idx - prevIndex) < wrapperSz) &&
6984 (source[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0)))
6987 if (GetLength(source, &idx, &length, size) < 0)
6989 if (GetBasicDate(source, &idx, cs->nextDate,
6990 &cs->nextDateFormat, size) < 0)
6993 if (((int)(idx - prevIndex) < wrapperSz) &&
6994 (source[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1)))
6997 if (GetLength(source, &idx, &length, size) < 0)
7007 static int DecodeOcspRespExtensions(byte* source,
7008 word32* ioIndex, OcspResponse* resp, word32 sz)
7010 word32 idx = *ioIndex;
7012 int ext_bound; /* boundary index for the sequence of extensions */
7015 WOLFSSL_ENTER("DecodeOcspRespExtensions");
7017 if (source[idx++] != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
7020 if (GetLength(source, &idx, &length, sz) < 0) return ASN_PARSE_E;
7022 if (GetSequence(source, &idx, &length, sz) < 0) return ASN_PARSE_E;
7024 ext_bound = idx + length;
7026 while (idx < (word32)ext_bound) {
7027 if (GetSequence(source, &idx, &length, sz) < 0) {
7028 WOLFSSL_MSG("\tfail: should be a SEQUENCE");
7033 if (GetObjectId(source, &idx, &oid, sz) < 0) {
7034 WOLFSSL_MSG("\tfail: OBJECT ID");
7038 /* check for critical flag */
7039 if (source[idx] == ASN_BOOLEAN) {
7040 WOLFSSL_MSG("\tfound optional critical flag, moving past");
7041 idx += (ASN_BOOL_SIZE + 1);
7044 /* process the extension based on the OID */
7045 if (source[idx++] != ASN_OCTET_STRING) {
7046 WOLFSSL_MSG("\tfail: should be an OCTET STRING");
7050 if (GetLength(source, &idx, &length, sz) < 0) {
7051 WOLFSSL_MSG("\tfail: extension data length");
7055 if (oid == OCSP_NONCE_OID) {
7056 resp->nonce = source + idx;
7057 resp->nonceSz = length;
7068 static int DecodeResponseData(byte* source,
7069 word32* ioIndex, OcspResponse* resp, word32 size)
7071 word32 idx = *ioIndex, prev_idx;
7074 word32 responderId = 0;
7076 WOLFSSL_ENTER("DecodeResponseData");
7078 resp->response = source + idx;
7080 if (GetSequence(source, &idx, &length, size) < 0)
7082 resp->responseSz = length + idx - prev_idx;
7084 /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
7085 * item isn't an EXPLICIT[0], then set version to zero and move
7086 * onto the next item.
7088 if (source[idx] == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
7090 idx += 2; /* Eat the value and length */
7091 if (GetMyVersion(source, &idx, &version) < 0)
7096 responderId = source[idx++];
7097 if ((responderId == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) ||
7098 (responderId == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)))
7100 if (GetLength(source, &idx, &length, size) < 0)
7107 /* save pointer to the producedAt time */
7108 if (GetBasicDate(source, &idx, resp->producedDate,
7109 &resp->producedDateFormat, size) < 0)
7112 if (DecodeSingleResponse(source, &idx, resp, size) < 0)
7115 if (DecodeOcspRespExtensions(source, &idx, resp, size) < 0)
7123 static int DecodeCerts(byte* source,
7124 word32* ioIndex, OcspResponse* resp, word32 size)
7126 word32 idx = *ioIndex;
7128 WOLFSSL_ENTER("DecodeCerts");
7130 if (source[idx++] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
7134 if (GetLength(source, &idx, &length, size) < 0)
7137 if (GetSequence(source, &idx, &length, size) < 0)
7140 resp->cert = source + idx;
7141 resp->certSz = length;
7149 static int DecodeBasicOcspResponse(byte* source,
7150 word32* ioIndex, OcspResponse* resp, word32 size)
7153 word32 idx = *ioIndex;
7156 WOLFSSL_ENTER("DecodeBasicOcspResponse");
7158 if (GetSequence(source, &idx, &length, size) < 0)
7161 if (idx + length > size)
7163 end_index = idx + length;
7165 if (DecodeResponseData(source, &idx, resp, size) < 0)
7168 /* Get the signature algorithm */
7169 if (GetAlgoId(source, &idx, &resp->sigOID, size) < 0)
7172 /* Obtain pointer to the start of the signature, and save the size */
7173 if (source[idx++] == ASN_BIT_STRING)
7176 if (GetLength(source, &idx, &sigLength, size) < 0)
7178 resp->sigSz = sigLength;
7179 resp->sig = source + idx;
7184 * Check the length of the BasicOcspResponse against the current index to
7185 * see if there are certificates, they are optional.
7187 if (idx < end_index)
7192 if (DecodeCerts(source, &idx, resp, size) < 0)
7195 InitDecodedCert(&cert, resp->cert, resp->certSz, 0);
7196 ret = ParseCertRelative(&cert, CA_TYPE, NO_VERIFY, 0);
7200 ret = ConfirmSignature(resp->response, resp->responseSz,
7201 cert.publicKey, cert.pubKeySize, cert.keyOID,
7202 resp->sig, resp->sigSz, resp->sigOID, NULL);
7203 FreeDecodedCert(&cert);
7207 WOLFSSL_MSG("\tOCSP Confirm signature failed");
7208 return ASN_OCSP_CONFIRM_E;
7217 void InitOcspResponse(OcspResponse* resp, CertStatus* status,
7218 byte* source, word32 inSz)
7220 WOLFSSL_ENTER("InitOcspResponse");
7222 resp->responseStatus = -1;
7223 resp->response = NULL;
7224 resp->responseSz = 0;
7225 resp->producedDateFormat = 0;
7226 resp->issuerHash = NULL;
7227 resp->issuerKeyHash = NULL;
7231 resp->status = status;
7234 resp->source = source;
7235 resp->maxIdx = inSz;
7239 int OcspResponseDecode(OcspResponse* resp)
7243 byte* source = resp->source;
7244 word32 size = resp->maxIdx;
7247 WOLFSSL_ENTER("OcspResponseDecode");
7249 /* peel the outer SEQUENCE wrapper */
7250 if (GetSequence(source, &idx, &length, size) < 0)
7253 /* First get the responseStatus, an ENUMERATED */
7254 if (GetEnumerated(source, &idx, &resp->responseStatus) < 0)
7257 if (resp->responseStatus != OCSP_SUCCESSFUL)
7260 /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
7263 if (source[idx++] != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
7265 if (GetLength(source, &idx, &length, size) < 0)
7268 /* Get the responseBytes SEQUENCE */
7269 if (GetSequence(source, &idx, &length, size) < 0)
7272 /* Check ObjectID for the resposeBytes */
7273 if (GetObjectId(source, &idx, &oid, size) < 0)
7275 if (oid != OCSP_BASIC_OID)
7277 if (source[idx++] != ASN_OCTET_STRING)
7280 if (GetLength(source, &idx, &length, size) < 0)
7283 if (DecodeBasicOcspResponse(source, &idx, resp, size) < 0)
7290 static word32 SetOcspReqExtensions(word32 extSz, byte* output,
7291 const byte* nonce, word32 nonceSz)
7293 static const byte NonceObjId[] = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07,
7295 byte seqArray[5][MAX_SEQ_SZ];
7296 word32 seqSz[5], totalSz;
7298 WOLFSSL_ENTER("SetOcspReqExtensions");
7300 if (nonce == NULL || nonceSz == 0) return 0;
7302 seqArray[0][0] = ASN_OCTET_STRING;
7303 seqSz[0] = 1 + SetLength(nonceSz, &seqArray[0][1]);
7305 seqArray[1][0] = ASN_OBJECT_ID;
7306 seqSz[1] = 1 + SetLength(sizeof(NonceObjId), &seqArray[1][1]);
7308 totalSz = seqSz[0] + seqSz[1] + nonceSz + (word32)sizeof(NonceObjId);
7310 seqSz[2] = SetSequence(totalSz, seqArray[2]);
7311 totalSz += seqSz[2];
7313 seqSz[3] = SetSequence(totalSz, seqArray[3]);
7314 totalSz += seqSz[3];
7316 seqArray[4][0] = (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2);
7317 seqSz[4] = 1 + SetLength(totalSz, &seqArray[4][1]);
7318 totalSz += seqSz[4];
7320 if (totalSz < extSz)
7323 XMEMCPY(output + totalSz, seqArray[4], seqSz[4]);
7324 totalSz += seqSz[4];
7325 XMEMCPY(output + totalSz, seqArray[3], seqSz[3]);
7326 totalSz += seqSz[3];
7327 XMEMCPY(output + totalSz, seqArray[2], seqSz[2]);
7328 totalSz += seqSz[2];
7329 XMEMCPY(output + totalSz, seqArray[1], seqSz[1]);
7330 totalSz += seqSz[1];
7331 XMEMCPY(output + totalSz, NonceObjId, sizeof(NonceObjId));
7332 totalSz += (word32)sizeof(NonceObjId);
7333 XMEMCPY(output + totalSz, seqArray[0], seqSz[0]);
7334 totalSz += seqSz[0];
7335 XMEMCPY(output + totalSz, nonce, nonceSz);
7343 int EncodeOcspRequest(OcspRequest* req)
7345 byte seqArray[5][MAX_SEQ_SZ];
7346 /* The ASN.1 of the OCSP Request is an onion of sequences */
7347 byte algoArray[MAX_ALGO_SZ];
7348 byte issuerArray[MAX_ENCODED_DIG_SZ];
7349 byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
7350 byte snArray[MAX_SN_SZ];
7351 byte extArray[MAX_OCSP_EXT_SZ];
7352 byte* output = req->dest;
7353 word32 seqSz[5], algoSz, issuerSz, issuerKeySz, snSz, extSz, totalSz;
7356 WOLFSSL_ENTER("EncodeOcspRequest");
7359 algoSz = SetAlgoID(SHA256h, algoArray, hashType, 0);
7361 algoSz = SetAlgoID(SHAh, algoArray, hashType, 0);
7364 req->issuerHash = req->cert->issuerHash;
7365 issuerSz = SetDigest(req->cert->issuerHash, KEYID_SIZE, issuerArray);
7367 req->issuerKeyHash = req->cert->issuerKeyHash;
7368 issuerKeySz = SetDigest(req->cert->issuerKeyHash,
7369 KEYID_SIZE, issuerKeyArray);
7371 req->serial = req->cert->serial;
7372 req->serialSz = req->cert->serialSz;
7373 snSz = SetSerialNumber(req->cert->serial, req->cert->serialSz, snArray);
7376 if (req->useNonce) {
7378 if (wc_InitRng(&rng) != 0) {
7379 WOLFSSL_MSG("\tCannot initialize RNG. Skipping the OSCP Nonce.");
7381 if (wc_RNG_GenerateBlock(&rng, req->nonce, MAX_OCSP_NONCE_SZ) != 0)
7382 WOLFSSL_MSG("\tCannot run RNG. Skipping the OSCP Nonce.");
7384 req->nonceSz = MAX_OCSP_NONCE_SZ;
7385 extSz = SetOcspReqExtensions(MAX_OCSP_EXT_SZ, extArray,
7386 req->nonce, req->nonceSz);
7392 totalSz = algoSz + issuerSz + issuerKeySz + snSz;
7394 for (i = 4; i >= 0; i--) {
7395 seqSz[i] = SetSequence(totalSz, seqArray[i]);
7396 totalSz += seqSz[i];
7397 if (i == 2) totalSz += extSz;
7400 for (i = 0; i < 5; i++) {
7401 XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
7402 totalSz += seqSz[i];
7404 XMEMCPY(output + totalSz, algoArray, algoSz);
7406 XMEMCPY(output + totalSz, issuerArray, issuerSz);
7407 totalSz += issuerSz;
7408 XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
7409 totalSz += issuerKeySz;
7410 XMEMCPY(output + totalSz, snArray, snSz);
7413 XMEMCPY(output + totalSz, extArray, extSz);
7421 void InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce,
7422 byte* dest, word32 destSz)
7424 WOLFSSL_ENTER("InitOcspRequest");
7427 req->useNonce = useNonce;
7429 req->issuerHash = NULL;
7430 req->issuerKeyHash = NULL;
7433 req->destSz = destSz;
7437 int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
7441 WOLFSSL_ENTER("CompareOcspReqResp");
7445 WOLFSSL_MSG("\tReq missing");
7451 WOLFSSL_MSG("\tResp missing");
7455 /* Nonces are not critical. The responder may not necessarily add
7456 * the nonce to the response. */
7457 if (req->useNonce && resp->nonceSz != 0) {
7458 cmp = req->nonceSz - resp->nonceSz;
7461 WOLFSSL_MSG("\tnonceSz mismatch");
7465 cmp = XMEMCMP(req->nonce, resp->nonce, req->nonceSz);
7468 WOLFSSL_MSG("\tnonce mismatch");
7473 cmp = XMEMCMP(req->issuerHash, resp->issuerHash, KEYID_SIZE);
7476 WOLFSSL_MSG("\tissuerHash mismatch");
7480 cmp = XMEMCMP(req->issuerKeyHash, resp->issuerKeyHash, KEYID_SIZE);
7483 WOLFSSL_MSG("\tissuerKeyHash mismatch");
7487 cmp = req->serialSz - resp->status->serialSz;
7490 WOLFSSL_MSG("\tserialSz mismatch");
7494 cmp = XMEMCMP(req->serial, resp->status->serial, req->serialSz);
7497 WOLFSSL_MSG("\tserial mismatch");
7507 /* store SHA hash of NAME */
7508 WOLFSSL_LOCAL int GetNameHash(const byte* source, word32* idx, byte* hash,
7511 int length; /* length of all distinguished names */
7515 WOLFSSL_ENTER("GetNameHash");
7517 if (source[*idx] == ASN_OBJECT_ID) {
7518 WOLFSSL_MSG("Trying optional prefix...");
7520 if (GetLength(source, idx, &length, maxIdx) < 0)
7524 WOLFSSL_MSG("Got optional prefix");
7527 /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
7528 * calculated over the entire DER encoding of the Name field, including
7529 * the tag and length. */
7531 if (GetSequence(source, idx, &length, maxIdx) < 0)
7535 ret = wc_Sha256Hash(source + dummy, length + *idx - dummy, hash);
7537 ret = wc_ShaHash(source + dummy, length + *idx - dummy, hash);
7548 /* initialize decoded CRL */
7549 void InitDecodedCRL(DecodedCRL* dcrl)
7551 WOLFSSL_MSG("InitDecodedCRL");
7553 dcrl->certBegin = 0;
7555 dcrl->sigLength = 0;
7556 dcrl->signatureOID = 0;
7558 dcrl->totalCerts = 0;
7562 /* free decoded CRL resources */
7563 void FreeDecodedCRL(DecodedCRL* dcrl)
7565 RevokedCert* tmp = dcrl->certs;
7567 WOLFSSL_MSG("FreeDecodedCRL");
7570 RevokedCert* next = tmp->next;
7571 XFREE(tmp, NULL, DYNAMIC_TYPE_REVOKED);
7577 /* Get Revoked Cert list, 0 on success */
7578 static int GetRevoked(const byte* buff, word32* idx, DecodedCRL* dcrl,
7586 WOLFSSL_ENTER("GetRevoked");
7588 if (GetSequence(buff, idx, &len, maxIdx) < 0)
7593 /* get serial number */
7597 if (b != ASN_INTEGER) {
7598 WOLFSSL_MSG("Expecting Integer");
7602 if (GetLength(buff, idx, &len, maxIdx) < 0)
7605 if (len > EXTERNAL_SERIAL_SIZE) {
7606 WOLFSSL_MSG("Serial Size too big");
7610 rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), NULL, DYNAMIC_TYPE_CRL);
7612 WOLFSSL_MSG("Alloc Revoked Cert failed");
7616 XMEMCPY(rc->serialNumber, &buff[*idx], len);
7620 rc->next = dcrl->certs;
7630 if (b != ASN_UTC_TIME && b != ASN_GENERALIZED_TIME) {
7631 WOLFSSL_MSG("Expecting Date");
7635 if (GetLength(buff, idx, &len, maxIdx) < 0)
7641 if (*idx != end) /* skip extensions */
7648 /* Get CRL Signature, 0 on success */
7649 static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
7655 WOLFSSL_ENTER("GetCRL_Signature");
7659 if (b != ASN_BIT_STRING)
7660 return ASN_BITSTR_E;
7662 if (GetLength(source, idx, &length, maxIdx) < 0)
7665 dcrl->sigLength = length;
7670 return ASN_EXPECT_0_E;
7673 dcrl->signature = (byte*)&source[*idx];
7675 *idx += dcrl->sigLength;
7681 /* prase crl buffer into decoded state, 0 on success */
7682 int ParseCRL(DecodedCRL* dcrl, const byte* buff, word32 sz, void* cm)
7685 word32 oid, idx = 0;
7688 WOLFSSL_MSG("ParseCRL");
7691 /* hash here if needed for optimized comparisons
7694 * wc_ShaUpdate(&sha, buff, sz);
7695 * wc_ShaFinal(&sha, dcrl->crlHash); */
7697 if (GetSequence(buff, &idx, &len, sz) < 0)
7700 dcrl->certBegin = idx;
7702 if (GetSequence(buff, &idx, &len, sz) < 0)
7704 dcrl->sigIndex = len + idx;
7706 /* may have version */
7707 if (buff[idx] == ASN_INTEGER) {
7708 if (GetMyVersion(buff, &idx, &version) < 0)
7712 if (GetAlgoId(buff, &idx, &oid, sz) < 0)
7715 if (GetNameHash(buff, &idx, dcrl->issuerHash, sz) < 0)
7718 if (GetBasicDate(buff, &idx, dcrl->lastDate, &dcrl->lastDateFormat, sz) < 0)
7721 if (GetBasicDate(buff, &idx, dcrl->nextDate, &dcrl->nextDateFormat, sz) < 0)
7724 if (!XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
7725 WOLFSSL_MSG("CRL after date is no longer valid");
7726 return ASN_AFTER_DATE_E;
7729 if (idx != dcrl->sigIndex && buff[idx] != CRL_EXTENSIONS) {
7730 if (GetSequence(buff, &idx, &len, sz) < 0)
7735 while (idx < (word32)len) {
7736 if (GetRevoked(buff, &idx, dcrl, sz) < 0)
7741 if (idx != dcrl->sigIndex)
7742 idx = dcrl->sigIndex; /* skip extensions */
7744 if (GetAlgoId(buff, &idx, &dcrl->signatureOID, sz) < 0)
7747 if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
7750 /* openssl doesn't add skid by default for CRLs cause firefox chokes
7751 we're not assuming it's available yet */
7752 #if !defined(NO_SKID) && defined(CRL_SKID_READY)
7753 if (dcrl->extAuthKeyIdSet)
7754 ca = GetCA(cm, dcrl->extAuthKeyId);
7756 ca = GetCAByName(cm, dcrl->issuerHash);
7758 ca = GetCA(cm, dcrl->issuerHash);
7759 #endif /* NO_SKID */
7760 WOLFSSL_MSG("About to verify CRL signature");
7763 WOLFSSL_MSG("Found CRL issuer CA");
7764 /* try to confirm/verify signature */
7765 #ifndef IGNORE_KEY_EXTENSIONS
7766 if ((ca->keyUsage & KEYUSE_CRL_SIGN) == 0) {
7767 WOLFSSL_MSG("CA cannot sign CRLs");
7768 return ASN_CRL_NO_SIGNER_E;
7770 #endif /* IGNORE_KEY_EXTENSIONS */
7771 if (!ConfirmSignature(buff + dcrl->certBegin,
7772 dcrl->sigIndex - dcrl->certBegin,
7773 ca->publicKey, ca->pubKeySize, ca->keyOID,
7774 dcrl->signature, dcrl->sigLength, dcrl->signatureOID, NULL)) {
7775 WOLFSSL_MSG("CRL Confirm signature failed");
7776 return ASN_CRL_CONFIRM_E;
7780 WOLFSSL_MSG("Did NOT find CRL issuer CA");
7781 return ASN_CRL_NO_SIGNER_E;
7787 #endif /* HAVE_CRL */
7794 #endif /* WOLFSSL_SEP */