3 * Copyright (C) 2006-2014 wolfSSL Inc.
5 * This file is part of CyaSSL.
7 * CyaSSL 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 * CyaSSL 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 <cyassl/ctaocrypt/settings.h>
31 #include "os.h" /* dc_rtc_api needs */
32 #include "dc_rtc_api.h" /* to get current time */
35 #include <cyassl/ctaocrypt/integer.h>
36 #include <cyassl/ctaocrypt/asn.h>
37 #include <cyassl/ctaocrypt/coding.h>
38 #include <cyassl/ctaocrypt/md2.h>
39 #include <cyassl/ctaocrypt/hmac.h>
40 #include <cyassl/ctaocrypt/error-crypt.h>
41 #include <cyassl/ctaocrypt/pwdbased.h>
42 #include <cyassl/ctaocrypt/des3.h>
43 #include <cyassl/ctaocrypt/logging.h>
45 #include <cyassl/ctaocrypt/random.h>
49 #include <cyassl/ctaocrypt/arc4.h>
53 #include "ntru_crypto.h"
57 #include <cyassl/ctaocrypt/ecc.h>
60 #ifdef CYASSL_DEBUG_ENCODING
69 /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
70 #pragma warning(disable: 4996)
83 /* uses parital <time.h> structures */
85 #define XGMTIME(c) my_gmtime((c))
86 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
87 #elif defined(MICRIUM)
88 #if (NET_SECURE_MGR_CFG_EN == DEF_ENABLED)
89 #define XVALIDATE_DATE(d,f,t) NetSecure_ValidateDateHandler((d),(f),(t))
91 #define XVALIDATE_DATE(d, f, t) (0)
94 /* since Micrium not defining XTIME or XGMTIME, CERT_GEN not available */
95 #elif defined(MICROCHIP_TCPIP_V5) || defined(MICROCHIP_TCPIP)
97 #define XTIME(t1) pic32_time((t1))
98 #define XGMTIME(c) gmtime((c))
99 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
100 #elif defined(FREESCALE_MQX)
102 #define XTIME(t1) mqx_time((t1))
103 #define XGMTIME(c) gmtime((c))
104 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
105 #elif defined(CYASSL_MDK_ARM)
106 #if defined(CYASSL_MDK5)
107 #include "cmsis_os.h"
112 #include "cyassl_MDK_ARM.h"
114 #define RNG CyaSSL_RNG /*for avoiding name conflict in "stm32f2xx.h" */
115 #define XTIME(tl) (0)
116 #define XGMTIME(c) Cyassl_MDK_gmtime((c))
117 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
118 #elif defined(USER_TIME)
119 /* user time, and gmtime compatible functions, there is a gmtime
120 implementation here that WINCE uses, so really just need some ticks
125 int tm_sec; /* seconds after the minute [0-60] */
126 int tm_min; /* minutes after the hour [0-59] */
127 int tm_hour; /* hours since midnight [0-23] */
128 int tm_mday; /* day of the month [1-31] */
129 int tm_mon; /* months since January [0-11] */
130 int tm_year; /* years since 1900 */
131 int tm_wday; /* days since Sunday [0-6] */
132 int tm_yday; /* days since January 1 [0-365] */
133 int tm_isdst; /* Daylight Savings Time flag */
134 long tm_gmtoff; /* offset from CUT in seconds */
135 char *tm_zone; /* timezone abbreviation */
139 /* forward declaration */
140 struct tm* gmtime(const time_t* timer);
141 extern time_t XTIME(time_t * timer);
143 #define XGMTIME(c) gmtime((c))
144 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
147 /* for stack trap tracking, don't call os gmtime on OS X/linux,
148 uses a lot of stack spce */
149 extern time_t time(time_t * timer);
150 #define XTIME(tl) time((tl))
151 #endif /* STACK_TRAP */
155 /* uses complete <time.h> facility */
157 #define XTIME(tl) time((tl))
158 #define XGMTIME(c) gmtime((c))
159 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
164 /* no time() or gmtime() even though in time.h header?? */
169 time_t time(time_t* timer)
173 ULARGE_INTEGER intTime;
179 GetSystemTime(&sysTime);
180 SystemTimeToFileTime(&sysTime, &fTime);
182 XMEMCPY(&intTime, &fTime, sizeof(FILETIME));
184 intTime.QuadPart -= 0x19db1ded53e8000;
186 intTime.QuadPart /= 10000000;
187 *timer = (time_t)intTime.QuadPart;
192 #endif /* _WIN32_WCE */
193 #if defined( _WIN32_WCE ) || defined( USER_TIME )
195 struct tm* gmtime(const time_t* timer)
198 #define EPOCH_YEAR 1970
199 #define SECS_DAY (24L * 60L * 60L)
200 #define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) %400)))
201 #define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365)
203 static const int _ytab[2][12] =
205 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
206 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
209 static struct tm st_time;
210 struct tm* ret = &st_time;
211 time_t secs = *timer;
212 unsigned long dayclock, dayno;
213 int year = EPOCH_YEAR;
215 dayclock = (unsigned long)secs % SECS_DAY;
216 dayno = (unsigned long)secs / SECS_DAY;
218 ret->tm_sec = (int) dayclock % 60;
219 ret->tm_min = (int)(dayclock % 3600) / 60;
220 ret->tm_hour = (int) dayclock / 3600;
221 ret->tm_wday = (int) (dayno + 4) % 7; /* day 0 a Thursday */
223 while(dayno >= (unsigned long)YEARSIZE(year)) {
224 dayno -= YEARSIZE(year);
228 ret->tm_year = year - YEAR0;
229 ret->tm_yday = (int)dayno;
232 while(dayno >= (unsigned long)_ytab[LEAPYEAR(year)][ret->tm_mon]) {
233 dayno -= _ytab[LEAPYEAR(year)][ret->tm_mon];
237 ret->tm_mday = (int)++dayno;
243 #endif /* _WIN32_WCE || USER_TIME */
250 struct tm* my_gmtime(const time_t* timer) /* has a gmtime() but hangs */
252 static struct tm st_time;
253 struct tm* ret = &st_time;
256 dc_rtc_time_get(&cal, TRUE);
258 ret->tm_year = cal.year - YEAR0; /* gm starts at 1900 */
259 ret->tm_mon = cal.month - 1; /* gm starts at 0 */
260 ret->tm_mday = cal.day;
261 ret->tm_hour = cal.hour;
262 ret->tm_min = cal.minute;
263 ret->tm_sec = cal.second;
268 #endif /* HAVE_RTP_SYS */
271 #if defined(MICROCHIP_TCPIP_V5) || defined(MICROCHIP_TCPIP)
274 * time() is just a stub in Microchip libraries. We need our own
275 * implementation. Use SNTP client to get seconds since epoch.
277 time_t pic32_time(time_t* timer)
279 #ifdef MICROCHIP_TCPIP_V5
289 #ifdef MICROCHIP_MPLAB_HARMONY
290 sec = TCPIP_SNTP_UTCSecondsGet();
292 sec = SNTPGetUTCSeconds();
294 *timer = (time_t) sec;
299 #endif /* MICROCHIP_TCPIP */
304 time_t mqx_time(time_t* timer)
313 *timer = (time_t) time_s.SECONDS;
318 #endif /* FREESCALE_MQX */
321 static INLINE word32 btoi(byte b)
327 /* two byte date/time, add to value */
328 static INLINE void GetTime(int* value, const byte* date, int* idx)
332 *value += btoi(date[i++]) * 10;
333 *value += btoi(date[i++]);
341 CPU_INT32S NetSecure_ValidateDateHandler(CPU_INT08U *date, CPU_INT08U format,
344 CPU_BOOLEAN rtn_code;
357 if (format == ASN_UTC_TIME) {
358 if (btoi(date[0]) >= 5)
363 else { /* format == GENERALIZED_TIME */
364 year += btoi(date[i++]) * 1000;
365 year += btoi(date[i++]) * 100;
369 GetTime(&val, date, &i);
370 year = (CPU_INT16U)val;
373 GetTime(&val, date, &i);
374 month = (CPU_INT08U)val;
377 GetTime(&val, date, &i);
378 day = (CPU_INT16U)val;
381 GetTime(&val, date, &i);
382 hour = (CPU_INT08U)val;
385 GetTime(&val, date, &i);
386 min = (CPU_INT08U)val;
389 GetTime(&val, date, &i);
390 sec = (CPU_INT08U)val;
392 return NetSecure_ValidateDate(year, month, day, hour, min, sec, dateType);
398 CYASSL_LOCAL int GetLength(const byte* input, word32* inOutIdx, int* len,
402 word32 i = *inOutIdx;
405 if ( (i+1) > maxIdx) { /* for first read */
406 CYASSL_MSG("GetLength bad index on input");
411 if (b >= ASN_LONG_LENGTH) {
412 word32 bytes = b & 0x7F;
414 if ( (i+bytes) > maxIdx) { /* for reading bytes */
415 CYASSL_MSG("GetLength bad long length");
421 length = (length << 8) | b;
427 if ( (i+length) > maxIdx) { /* for user of length */
428 CYASSL_MSG("GetLength value exceeds buffer length");
439 CYASSL_LOCAL int GetSequence(const byte* input, word32* inOutIdx, int* len,
443 word32 idx = *inOutIdx;
445 if (input[idx++] != (ASN_SEQUENCE | ASN_CONSTRUCTED) ||
446 GetLength(input, &idx, &length, maxIdx) < 0)
456 CYASSL_LOCAL int GetSet(const byte* input, word32* inOutIdx, int* len,
460 word32 idx = *inOutIdx;
462 if (input[idx++] != (ASN_SET | ASN_CONSTRUCTED) ||
463 GetLength(input, &idx, &length, maxIdx) < 0)
473 /* winodws header clash for WinCE using GetVersion */
474 CYASSL_LOCAL int GetMyVersion(const byte* input, word32* inOutIdx, int* version)
476 word32 idx = *inOutIdx;
478 CYASSL_ENTER("GetMyVersion");
480 if (input[idx++] != ASN_INTEGER)
483 if (input[idx++] != 0x01)
484 return ASN_VERSION_E;
486 *version = input[idx++];
494 /* Get small count integer, 32 bits or less */
495 static int GetShortInt(const byte* input, word32* inOutIdx, int* number)
497 word32 idx = *inOutIdx;
502 if (input[idx++] != ASN_INTEGER)
510 *number = *number << 8 | input[idx++];
517 #endif /* !NO_PWDBASED */
520 /* May not have one, not an error */
521 static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version)
523 word32 idx = *inOutIdx;
525 CYASSL_ENTER("GetExplicitVersion");
526 if (input[idx++] == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
527 *inOutIdx = ++idx; /* eat header */
528 return GetMyVersion(input, inOutIdx, version);
538 CYASSL_LOCAL int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx,
541 word32 i = *inOutIdx;
545 if (b != ASN_INTEGER)
548 if (GetLength(input, &i, &length, maxIdx) < 0)
551 if ( (b = input[i++]) == 0x00)
556 if (mp_init(mpi) != MP_OKAY)
559 if (mp_read_unsigned_bin(mpi, (byte*)input + i, length) != 0) {
564 *inOutIdx = i + length;
569 static int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
573 word32 i = *inOutIdx;
578 if (b != ASN_OBJECT_ID)
579 return ASN_OBJECT_ID_E;
581 if (GetLength(input, &i, &length, maxIdx) < 0)
586 /* just sum it up for now */
594 CYASSL_LOCAL int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
598 word32 i = *inOutIdx;
602 CYASSL_ENTER("GetAlgoId");
604 if (GetSequence(input, &i, &length, maxIdx) < 0)
608 if (b != ASN_OBJECT_ID)
609 return ASN_OBJECT_ID_E;
611 if (GetLength(input, &i, &length, maxIdx) < 0)
615 /* odd HC08 compiler behavior here when input[i++] */
619 /* just sum it up for now */
621 /* could have NULL tag and 0 terminator, but may not */
624 if (b == ASN_TAG_NULL) {
627 return ASN_EXPECT_0_E;
630 /* go back, didn't have it */
643 static int GetCaviumInt(byte** buff, word16* buffSz, const byte* input,
644 word32* inOutIdx, word32 maxIdx, void* heap)
646 word32 i = *inOutIdx;
650 if (b != ASN_INTEGER)
653 if (GetLength(input, &i, &length, maxIdx) < 0)
656 if ( (b = input[i++]) == 0x00)
661 *buffSz = (word16)length;
662 *buff = XMALLOC(*buffSz, heap, DYNAMIC_TYPE_CAVIUM_RSA);
666 XMEMCPY(*buff, input + i, *buffSz);
668 *inOutIdx = i + length;
672 static int CaviumRsaPrivateKeyDecode(const byte* input, word32* inOutIdx,
673 RsaKey* key, word32 inSz)
678 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
681 if (GetMyVersion(input, inOutIdx, &version) < 0)
684 key->type = RSA_PRIVATE;
686 if (GetCaviumInt(&key->c_n, &key->c_nSz, input, inOutIdx, inSz, h) < 0 ||
687 GetCaviumInt(&key->c_e, &key->c_eSz, input, inOutIdx, inSz, h) < 0 ||
688 GetCaviumInt(&key->c_d, &key->c_dSz, input, inOutIdx, inSz, h) < 0 ||
689 GetCaviumInt(&key->c_p, &key->c_pSz, input, inOutIdx, inSz, h) < 0 ||
690 GetCaviumInt(&key->c_q, &key->c_qSz, input, inOutIdx, inSz, h) < 0 ||
691 GetCaviumInt(&key->c_dP, &key->c_dP_Sz, input, inOutIdx, inSz, h) < 0 ||
692 GetCaviumInt(&key->c_dQ, &key->c_dQ_Sz, input, inOutIdx, inSz, h) < 0 ||
693 GetCaviumInt(&key->c_u, &key->c_uSz, input, inOutIdx, inSz, h) < 0 )
694 return ASN_RSA_KEY_E;
700 #endif /* HAVE_CAVIUM */
702 int RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
708 if (key->magic == CYASSL_RSA_CAVIUM_MAGIC)
709 return CaviumRsaPrivateKeyDecode(input, inOutIdx, key, inSz);
712 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
715 if (GetMyVersion(input, inOutIdx, &version) < 0)
718 key->type = RSA_PRIVATE;
720 if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
721 GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
722 GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
723 GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
724 GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
725 GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
726 GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
727 GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
734 /* Remove PKCS8 header, move beginning of traditional to beginning of input */
735 int ToTraditional(byte* input, word32 sz)
737 word32 inOutIdx = 0, oid;
740 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
743 if (GetMyVersion(input, &inOutIdx, &version) < 0)
746 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
749 if (input[inOutIdx] == ASN_OBJECT_ID) {
750 /* pkcs8 ecc uses slightly different format */
751 inOutIdx++; /* past id */
752 if (GetLength(input, &inOutIdx, &length, sz) < 0)
754 inOutIdx += length; /* over sub id, key input will verify */
757 if (input[inOutIdx++] != ASN_OCTET_STRING)
760 if (GetLength(input, &inOutIdx, &length, sz) < 0)
763 XMEMMOVE(input, input + inOutIdx, length);
771 /* Check To see if PKCS version algo is supported, set id if it is return 0
773 static int CheckAlgo(int first, int second, int* id, int* version)
776 *version = PKCS5; /* default */
781 *id = PBE_SHA1_RC4_128;
794 return ASN_INPUT_E; /* VERSION ERROR */
796 if (second == PBES2) {
802 case 3: /* see RFC 2898 for ids */
815 /* Check To see if PKCS v2 algo is supported, set id if it is return 0
817 static int CheckAlgoV2(int oid, int* id)
833 /* Decrypt intput in place from parameters based on id */
834 static int DecryptKey(const char* password, int passwordSz, byte* salt,
835 int saltSz, int iterations, int id, byte* input,
836 int length, int version, byte* cbcIv)
842 #ifdef CYASSL_SMALL_STACK
845 byte key[MAX_KEY_SIZE];
851 derivedLen = 16; /* may need iv for v1.5 */
852 decryptionType = DES_TYPE;
857 derivedLen = 16; /* may need iv for v1.5 */
858 decryptionType = DES_TYPE;
863 derivedLen = 32; /* may need iv for v1.5 */
864 decryptionType = DES3_TYPE;
867 case PBE_SHA1_RC4_128:
870 decryptionType = RC4_TYPE;
877 #ifdef CYASSL_SMALL_STACK
878 key = (byte*)XMALLOC(MAX_KEY_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
883 if (version == PKCS5v2)
884 ret = PBKDF2(key, (byte*)password, passwordSz, salt, saltSz, iterations,
886 else if (version == PKCS5)
887 ret = PBKDF1(key, (byte*)password, passwordSz, salt, saltSz, iterations,
889 else if (version == PKCS12) {
891 byte unicodePasswd[MAX_UNICODE_SZ];
893 if ( (passwordSz * 2 + 2) > (int)sizeof(unicodePasswd)) {
894 #ifdef CYASSL_SMALL_STACK
895 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
897 return UNICODE_SIZE_E;
900 for (i = 0; i < passwordSz; i++) {
901 unicodePasswd[idx++] = 0x00;
902 unicodePasswd[idx++] = (byte)password[i];
904 /* add trailing NULL */
905 unicodePasswd[idx++] = 0x00;
906 unicodePasswd[idx++] = 0x00;
908 ret = PKCS12_PBKDF(key, unicodePasswd, idx, salt, saltSz,
909 iterations, derivedLen, typeH, 1);
910 if (decryptionType != RC4_TYPE)
911 ret += PKCS12_PBKDF(cbcIv, unicodePasswd, idx, salt, saltSz,
912 iterations, 8, typeH, 2);
915 #ifdef CYASSL_SMALL_STACK
916 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
922 #ifdef CYASSL_SMALL_STACK
923 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
928 switch (decryptionType) {
933 byte* desIv = key + 8;
935 if (version == PKCS5v2 || version == PKCS12)
938 ret = Des_SetKey(&dec, key, desIv, DES_DECRYPTION);
940 #ifdef CYASSL_SMALL_STACK
941 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
946 Des_CbcDecrypt(&dec, input, input, length);
953 byte* desIv = key + 24;
955 if (version == PKCS5v2 || version == PKCS12)
957 ret = Des3_SetKey(&dec, key, desIv, DES_DECRYPTION);
959 #ifdef CYASSL_SMALL_STACK
960 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
964 ret = Des3_CbcDecrypt(&dec, input, input, length);
966 #ifdef CYASSL_SMALL_STACK
967 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
979 Arc4SetKey(&dec, key, derivedLen);
980 Arc4Process(&dec, input, input, length);
986 #ifdef CYASSL_SMALL_STACK
987 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
992 #ifdef CYASSL_SMALL_STACK
993 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1000 /* Remove Encrypted PKCS8 header, move beginning of traditional to beginning
1002 int ToTraditionalEnc(byte* input, word32 sz,const char* password,int passwordSz)
1004 word32 inOutIdx = 0, oid;
1005 int first, second, length, version, saltSz, id;
1007 #ifdef CYASSL_SMALL_STACK
1011 byte salt[MAX_SALT_SIZE];
1012 byte cbcIv[MAX_IV_SIZE];
1015 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
1018 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
1021 first = input[inOutIdx - 2]; /* PKCS version alwyas 2nd to last byte */
1022 second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
1024 if (CheckAlgo(first, second, &id, &version) < 0)
1025 return ASN_INPUT_E; /* Algo ID error */
1027 if (version == PKCS5v2) {
1029 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
1032 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
1035 if (oid != PBKDF2_OID)
1039 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
1042 if (input[inOutIdx++] != ASN_OCTET_STRING)
1045 if (GetLength(input, &inOutIdx, &saltSz, sz) < 0)
1048 if (saltSz > MAX_SALT_SIZE)
1051 #ifdef CYASSL_SMALL_STACK
1052 salt = (byte*)XMALLOC(MAX_SALT_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1057 XMEMCPY(salt, &input[inOutIdx], saltSz);
1060 if (GetShortInt(input, &inOutIdx, &iterations) < 0) {
1061 #ifdef CYASSL_SMALL_STACK
1062 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1067 #ifdef CYASSL_SMALL_STACK
1068 cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1069 if (cbcIv == NULL) {
1070 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1075 if (version == PKCS5v2) {
1076 /* get encryption algo */
1077 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0) {
1078 #ifdef CYASSL_SMALL_STACK
1079 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1080 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1085 if (CheckAlgoV2(oid, &id) < 0) {
1086 #ifdef CYASSL_SMALL_STACK
1087 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1088 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1090 return ASN_PARSE_E; /* PKCS v2 algo id error */
1093 if (input[inOutIdx++] != ASN_OCTET_STRING) {
1094 #ifdef CYASSL_SMALL_STACK
1095 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1096 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1101 if (GetLength(input, &inOutIdx, &length, sz) < 0) {
1102 #ifdef CYASSL_SMALL_STACK
1103 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1104 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1109 XMEMCPY(cbcIv, &input[inOutIdx], length);
1113 if (input[inOutIdx++] != ASN_OCTET_STRING) {
1114 #ifdef CYASSL_SMALL_STACK
1115 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1116 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1121 if (GetLength(input, &inOutIdx, &length, sz) < 0) {
1122 #ifdef CYASSL_SMALL_STACK
1123 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1124 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1129 if (DecryptKey(password, passwordSz, salt, saltSz, iterations, id,
1130 input + inOutIdx, length, version, cbcIv) < 0) {
1131 #ifdef CYASSL_SMALL_STACK
1132 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1133 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1135 return ASN_INPUT_E; /* decrypt failure */
1138 #ifdef CYASSL_SMALL_STACK
1139 XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1140 XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1143 XMEMMOVE(input, input + inOutIdx, length);
1144 return ToTraditional(input, length);
1147 #endif /* NO_PWDBASED */
1151 int RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
1156 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1159 key->type = RSA_PUBLIC;
1161 #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
1163 byte b = input[*inOutIdx];
1164 if (b != ASN_INTEGER) {
1165 /* not from decoded cert, will have algo id, skip past */
1166 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1169 b = input[(*inOutIdx)++];
1170 if (b != ASN_OBJECT_ID)
1171 return ASN_OBJECT_ID_E;
1173 if (GetLength(input, inOutIdx, &length, inSz) < 0)
1176 *inOutIdx += length; /* skip past */
1178 /* could have NULL tag and 0 terminator, but may not */
1179 b = input[(*inOutIdx)++];
1181 if (b == ASN_TAG_NULL) {
1182 b = input[(*inOutIdx)++];
1184 return ASN_EXPECT_0_E;
1187 /* go back, didn't have it */
1190 /* should have bit tag length and seq next */
1191 b = input[(*inOutIdx)++];
1192 if (b != ASN_BIT_STRING)
1193 return ASN_BITSTR_E;
1195 if (GetLength(input, inOutIdx, &length, inSz) < 0)
1199 b = input[(*inOutIdx)++];
1203 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1206 } /* openssl var block */
1207 #endif /* OPENSSL_EXTRA */
1209 if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
1210 GetInt(&key->e, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
1219 int DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
1223 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1226 if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
1227 GetInt(&key->g, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
1232 int DhSetKey(DhKey* key, const byte* p, word32 pSz, const byte* g, word32 gSz)
1234 if (key == NULL || p == NULL || g == NULL || pSz == 0 || gSz == 0)
1235 return BAD_FUNC_ARG;
1237 /* may have leading 0 */
1246 if (mp_init(&key->p) != MP_OKAY)
1248 if (mp_read_unsigned_bin(&key->p, p, pSz) != 0) {
1250 return ASN_DH_KEY_E;
1253 if (mp_init(&key->g) != MP_OKAY) {
1257 if (mp_read_unsigned_bin(&key->g, g, gSz) != 0) {
1260 return ASN_DH_KEY_E;
1267 int DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
1268 byte* g, word32* gInOutSz)
1274 if (GetSequence(input, &i, &length, inSz) < 0)
1278 if (b != ASN_INTEGER)
1281 if (GetLength(input, &i, &length, inSz) < 0)
1284 if ( (b = input[i++]) == 0x00)
1289 if (length <= (int)*pInOutSz) {
1290 XMEMCPY(p, &input[i], length);
1299 if (b != ASN_INTEGER)
1302 if (GetLength(input, &i, &length, inSz) < 0)
1305 if (length <= (int)*gInOutSz) {
1306 XMEMCPY(g, &input[i], length);
1320 int DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
1325 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1328 if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
1329 GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
1330 GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
1331 GetInt(&key->y, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
1333 key->type = DSA_PUBLIC;
1338 int DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
1341 int length, version;
1343 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1346 if (GetMyVersion(input, inOutIdx, &version) < 0)
1349 if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
1350 GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
1351 GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
1352 GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
1353 GetInt(&key->x, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
1355 key->type = DSA_PRIVATE;
1362 void InitDecodedCert(DecodedCert* cert, byte* source, word32 inSz, void* heap)
1364 cert->publicKey = 0;
1365 cert->pubKeySize = 0;
1366 cert->pubKeyStored = 0;
1368 cert->signature = 0;
1369 cert->subjectCN = 0;
1370 cert->subjectCNLen = 0;
1371 cert->subjectCNEnc = CTC_UTF8;
1372 cert->subjectCNStored = 0;
1373 cert->altNames = NULL;
1374 #ifndef IGNORE_NAME_CONSTRAINTS
1375 cert->altEmailNames = NULL;
1376 cert->permittedNames = NULL;
1377 cert->excludedNames = NULL;
1378 #endif /* IGNORE_NAME_CONSTRAINTS */
1379 cert->issuer[0] = '\0';
1380 cert->subject[0] = '\0';
1381 cert->source = source; /* don't own */
1383 cert->maxIdx = inSz; /* can't go over this index */
1385 XMEMSET(cert->serial, 0, EXTERNAL_SERIAL_SIZE);
1387 cert->extensions = 0;
1388 cert->extensionsSz = 0;
1389 cert->extensionsIdx = 0;
1390 cert->extAuthInfo = NULL;
1391 cert->extAuthInfoSz = 0;
1392 cert->extCrlInfo = NULL;
1393 cert->extCrlInfoSz = 0;
1394 XMEMSET(cert->extSubjKeyId, 0, SHA_SIZE);
1395 cert->extSubjKeyIdSet = 0;
1396 XMEMSET(cert->extAuthKeyId, 0, SHA_SIZE);
1397 cert->extAuthKeyIdSet = 0;
1398 cert->extKeyUsageSet = 0;
1399 cert->extKeyUsage = 0;
1400 cert->extExtKeyUsageSet = 0;
1401 cert->extExtKeyUsage = 0;
1404 cert->issuerRaw = NULL;
1405 cert->issuerRawLen = 0;
1407 #ifdef CYASSL_CERT_GEN
1408 cert->subjectSN = 0;
1409 cert->subjectSNLen = 0;
1410 cert->subjectSNEnc = CTC_UTF8;
1412 cert->subjectCLen = 0;
1413 cert->subjectCEnc = CTC_PRINTABLE;
1415 cert->subjectLLen = 0;
1416 cert->subjectLEnc = CTC_UTF8;
1417 cert->subjectST = 0;
1418 cert->subjectSTLen = 0;
1419 cert->subjectSTEnc = CTC_UTF8;
1421 cert->subjectOLen = 0;
1422 cert->subjectOEnc = CTC_UTF8;
1423 cert->subjectOU = 0;
1424 cert->subjectOULen = 0;
1425 cert->subjectOUEnc = CTC_UTF8;
1426 cert->subjectEmail = 0;
1427 cert->subjectEmailLen = 0;
1428 #endif /* CYASSL_CERT_GEN */
1429 cert->beforeDate = NULL;
1430 cert->beforeDateLen = 0;
1431 cert->afterDate = NULL;
1432 cert->afterDateLen = 0;
1433 #ifdef OPENSSL_EXTRA
1434 XMEMSET(&cert->issuerName, 0, sizeof(DecodedName));
1435 XMEMSET(&cert->subjectName, 0, sizeof(DecodedName));
1436 cert->extBasicConstSet = 0;
1437 cert->extBasicConstCrit = 0;
1438 cert->extBasicConstPlSet = 0;
1439 cert->pathLength = 0;
1440 cert->extSubjAltNameSet = 0;
1441 cert->extSubjAltNameCrit = 0;
1442 cert->extAuthKeyIdCrit = 0;
1443 cert->extSubjKeyIdCrit = 0;
1444 cert->extKeyUsageCrit = 0;
1445 cert->extExtKeyUsageCrit = 0;
1446 cert->extExtKeyUsageSrc = NULL;
1447 cert->extExtKeyUsageSz = 0;
1448 cert->extExtKeyUsageCount = 0;
1449 cert->extAuthKeyIdSrc = NULL;
1450 cert->extAuthKeyIdSz = 0;
1451 cert->extSubjKeyIdSrc = NULL;
1452 cert->extSubjKeyIdSz = 0;
1453 #endif /* OPENSSL_EXTRA */
1454 #if defined(OPENSSL_EXTRA) || !defined(IGNORE_NAME_CONSTRAINTS)
1455 cert->extNameConstraintSet = 0;
1456 #endif /* OPENSSL_EXTRA || !IGNORE_NAME_CONSTRAINTS */
1458 cert->pkCurveOID = 0;
1459 #endif /* HAVE_ECC */
1461 cert->deviceTypeSz = 0;
1462 cert->deviceType = NULL;
1464 cert->hwType = NULL;
1465 cert->hwSerialNumSz = 0;
1466 cert->hwSerialNum = NULL;
1467 #ifdef OPENSSL_EXTRA
1468 cert->extCertPolicySet = 0;
1469 cert->extCertPolicyCrit = 0;
1470 #endif /* OPENSSL_EXTRA */
1471 #endif /* CYASSL_SEP */
1475 void FreeAltNames(DNS_entry* altNames, void* heap)
1480 DNS_entry* tmp = altNames->next;
1482 XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
1483 XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME);
1488 #ifndef IGNORE_NAME_CONSTRAINTS
1490 void FreeNameSubtrees(Base_entry* names, void* heap)
1495 Base_entry* tmp = names->next;
1497 XFREE(names->name, heap, DYNAMIC_TYPE_ALTNAME);
1498 XFREE(names, heap, DYNAMIC_TYPE_ALTNAME);
1503 #endif /* IGNORE_NAME_CONSTRAINTS */
1505 void FreeDecodedCert(DecodedCert* cert)
1507 if (cert->subjectCNStored == 1)
1508 XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
1509 if (cert->pubKeyStored == 1)
1510 XFREE(cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
1512 FreeAltNames(cert->altNames, cert->heap);
1513 #ifndef IGNORE_NAME_CONSTRAINTS
1514 if (cert->altEmailNames)
1515 FreeAltNames(cert->altEmailNames, cert->heap);
1516 if (cert->permittedNames)
1517 FreeNameSubtrees(cert->permittedNames, cert->heap);
1518 if (cert->excludedNames)
1519 FreeNameSubtrees(cert->excludedNames, cert->heap);
1520 #endif /* IGNORE_NAME_CONSTRAINTS */
1522 XFREE(cert->deviceType, cert->heap, 0);
1523 XFREE(cert->hwType, cert->heap, 0);
1524 XFREE(cert->hwSerialNum, cert->heap, 0);
1525 #endif /* CYASSL_SEP */
1526 #ifdef OPENSSL_EXTRA
1527 if (cert->issuerName.fullName != NULL)
1528 XFREE(cert->issuerName.fullName, NULL, DYNAMIC_TYPE_X509);
1529 if (cert->subjectName.fullName != NULL)
1530 XFREE(cert->subjectName.fullName, NULL, DYNAMIC_TYPE_X509);
1531 #endif /* OPENSSL_EXTRA */
1535 static int GetCertHeader(DecodedCert* cert)
1538 byte serialTmp[EXTERNAL_SERIAL_SIZE];
1539 #if defined(CYASSL_SMALL_STACK) && defined(USE_FAST_MATH)
1543 mp_int* mpi = &stack_mpi;
1546 if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
1549 cert->certBegin = cert->srcIdx;
1551 if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
1553 cert->sigIndex = len + cert->srcIdx;
1555 if (GetExplicitVersion(cert->source, &cert->srcIdx, &cert->version) < 0)
1558 #if defined(CYASSL_SMALL_STACK) && defined(USE_FAST_MATH)
1559 mpi = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_TMP_BUFFER);
1564 if (GetInt(mpi, cert->source, &cert->srcIdx, cert->maxIdx) < 0) {
1565 #if defined(CYASSL_SMALL_STACK) && defined(USE_FAST_MATH)
1566 XFREE(mpi, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1571 len = mp_unsigned_bin_size(mpi);
1572 if (len < (int)sizeof(serialTmp)) {
1573 if ( (ret = mp_to_unsigned_bin(mpi, serialTmp)) == MP_OKAY) {
1574 XMEMCPY(cert->serial, serialTmp, len);
1575 cert->serialSz = len;
1580 #if defined(CYASSL_SMALL_STACK) && defined(USE_FAST_MATH)
1581 XFREE(mpi, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1587 #if !defined(NO_RSA)
1588 /* Store Rsa Key, may save later, Dsa could use in future */
1589 static int StoreRsaKey(DecodedCert* cert)
1592 word32 recvd = cert->srcIdx;
1594 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1597 recvd = cert->srcIdx - recvd;
1603 cert->pubKeySize = length;
1604 cert->publicKey = cert->source + cert->srcIdx;
1605 cert->srcIdx += length;
1614 /* return 0 on sucess if the ECC curve oid sum is supported */
1615 static int CheckCurve(word32 oid)
1617 if (oid != ECC_256R1 && oid != ECC_384R1 && oid != ECC_521R1 && oid !=
1618 ECC_160R1 && oid != ECC_192R1 && oid != ECC_224R1)
1624 #endif /* HAVE_ECC */
1627 static int GetKey(DecodedCert* cert)
1631 int tmpIdx = cert->srcIdx;
1634 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1637 if (GetAlgoId(cert->source, &cert->srcIdx, &cert->keyOID, cert->maxIdx) < 0)
1640 switch (cert->keyOID) {
1644 byte b = cert->source[cert->srcIdx++];
1645 if (b != ASN_BIT_STRING)
1646 return ASN_BITSTR_E;
1648 if (GetLength(cert->source,&cert->srcIdx,&length,cert->maxIdx) < 0)
1650 b = cert->source[cert->srcIdx++];
1652 return ASN_EXPECT_0_E;
1654 return StoreRsaKey(cert);
1661 const byte* key = &cert->source[tmpIdx];
1662 byte* next = (byte*)key;
1665 word32 remaining = cert->maxIdx - cert->srcIdx;
1666 #ifdef CYASSL_SMALL_STACK
1667 byte* keyBlob = NULL;
1669 byte keyBlob[MAX_NTRU_KEY_SZ];
1671 rc = ntru_crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key,
1672 &keyLen, NULL, &next, &remaining);
1674 return ASN_NTRU_KEY_E;
1675 if (keyLen > MAX_NTRU_KEY_SZ)
1676 return ASN_NTRU_KEY_E;
1678 #ifdef CYASSL_SMALL_STACK
1679 keyBlob = (byte*)XMALLOC(MAX_NTRU_KEY_SZ, NULL,
1680 DYNAMIC_TYPE_TMP_BUFFER);
1681 if (keyBlob == NULL)
1685 rc = ntru_crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key,
1686 &keyLen, keyBlob, &next, &remaining);
1687 if (rc != NTRU_OK) {
1688 #ifdef CYASSL_SMALL_STACK
1689 XFREE(keyBlob, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1691 return ASN_NTRU_KEY_E;
1694 if ( (next - key) < 0) {
1695 #ifdef CYASSL_SMALL_STACK
1696 XFREE(keyBlob, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1698 return ASN_NTRU_KEY_E;
1701 cert->srcIdx = tmpIdx + (int)(next - key);
1703 cert->publicKey = (byte*) XMALLOC(keyLen, cert->heap,
1704 DYNAMIC_TYPE_PUBLIC_KEY);
1705 if (cert->publicKey == NULL) {
1706 #ifdef CYASSL_SMALL_STACK
1707 XFREE(keyBlob, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1711 XMEMCPY(cert->publicKey, keyBlob, keyLen);
1712 cert->pubKeyStored = 1;
1713 cert->pubKeySize = keyLen;
1715 #ifdef CYASSL_SMALL_STACK
1716 XFREE(keyBlob, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1721 #endif /* HAVE_NTRU */
1726 byte b = cert->source[cert->srcIdx++];
1728 if (b != ASN_OBJECT_ID)
1729 return ASN_OBJECT_ID_E;
1731 if (GetLength(cert->source,&cert->srcIdx,&oidSz,cert->maxIdx) < 0)
1735 cert->pkCurveOID += cert->source[cert->srcIdx++];
1737 if (CheckCurve(cert->pkCurveOID) < 0)
1738 return ECC_CURVE_OID_E;
1741 b = cert->source[cert->srcIdx++];
1742 if (b != ASN_BIT_STRING)
1743 return ASN_BITSTR_E;
1745 if (GetLength(cert->source,&cert->srcIdx,&length,cert->maxIdx) < 0)
1747 b = cert->source[cert->srcIdx++];
1749 return ASN_EXPECT_0_E;
1751 /* actual key, use length - 1 since ate preceding 0 */
1754 cert->publicKey = (byte*) XMALLOC(length, cert->heap,
1755 DYNAMIC_TYPE_PUBLIC_KEY);
1756 if (cert->publicKey == NULL)
1758 XMEMCPY(cert->publicKey, &cert->source[cert->srcIdx], length);
1759 cert->pubKeyStored = 1;
1760 cert->pubKeySize = length;
1762 cert->srcIdx += length;
1766 #endif /* HAVE_ECC */
1768 return ASN_UNKNOWN_OID_E;
1773 /* process NAME, either issuer or subject */
1774 static int GetName(DecodedCert* cert, int nameType)
1776 Sha sha; /* MUST have SHA-1 hash for cert names */
1777 int length; /* length of all distinguished names */
1780 char* full = (nameType == ISSUER) ? cert->issuer : cert->subject;
1782 #ifdef OPENSSL_EXTRA
1783 DecodedName* dName =
1784 (nameType == ISSUER) ? &cert->issuerName : &cert->subjectName;
1785 #endif /* OPENSSL_EXTRA */
1787 CYASSL_MSG("Getting Cert Name");
1789 if (cert->source[cert->srcIdx] == ASN_OBJECT_ID) {
1790 CYASSL_MSG("Trying optional prefix...");
1792 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1795 cert->srcIdx += length;
1796 CYASSL_MSG("Got optional prefix");
1799 /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
1800 * calculated over the entire DER encoding of the Name field, including
1801 * the tag and length. */
1803 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1806 ret = InitSha(&sha);
1809 ShaUpdate(&sha, &cert->source[idx], length + cert->srcIdx - idx);
1810 if (nameType == ISSUER)
1811 ShaFinal(&sha, cert->issuerHash);
1813 ShaFinal(&sha, cert->subjectHash);
1815 length += cert->srcIdx;
1819 /* store pointer to raw issuer */
1820 if (nameType == ISSUER) {
1821 cert->issuerRaw = &cert->source[cert->srcIdx];
1822 cert->issuerRawLen = length - cert->srcIdx;
1825 #ifndef IGNORE_NAME_CONSTRAINTS
1826 if (nameType == SUBJECT) {
1827 cert->subjectRaw = &cert->source[cert->srcIdx];
1828 cert->subjectRawLen = length - cert->srcIdx;
1832 while (cert->srcIdx < (word32)length) {
1835 byte tooBig = FALSE;
1838 if (GetSet(cert->source, &cert->srcIdx, &dummy, cert->maxIdx) < 0) {
1839 CYASSL_MSG("Cert name lacks set header, trying sequence");
1842 if (GetSequence(cert->source, &cert->srcIdx, &dummy, cert->maxIdx) < 0)
1845 b = cert->source[cert->srcIdx++];
1846 if (b != ASN_OBJECT_ID)
1847 return ASN_OBJECT_ID_E;
1849 if (GetLength(cert->source, &cert->srcIdx, &oidSz, cert->maxIdx) < 0)
1852 XMEMCPY(joint, &cert->source[cert->srcIdx], sizeof(joint));
1855 if (joint[0] == 0x55 && joint[1] == 0x04) {
1861 id = cert->source[cert->srcIdx++];
1862 b = cert->source[cert->srcIdx++]; /* encoding */
1864 if (GetLength(cert->source, &cert->srcIdx, &strLen,
1868 if ( (strLen + 14) > (int)(ASN_NAME_MAX - idx)) {
1869 /* include biggest pre fix header too 4 = "/serialNumber=" */
1870 CYASSL_MSG("ASN Name too big, skipping");
1874 if (id == ASN_COMMON_NAME) {
1875 if (nameType == SUBJECT) {
1876 cert->subjectCN = (char *)&cert->source[cert->srcIdx];
1877 cert->subjectCNLen = strLen;
1878 cert->subjectCNEnc = b;
1882 XMEMCPY(&full[idx], "/CN=", 4);
1886 #ifdef OPENSSL_EXTRA
1887 dName->cnIdx = cert->srcIdx;
1888 dName->cnLen = strLen;
1889 #endif /* OPENSSL_EXTRA */
1891 else if (id == ASN_SUR_NAME) {
1893 XMEMCPY(&full[idx], "/SN=", 4);
1897 #ifdef CYASSL_CERT_GEN
1898 if (nameType == SUBJECT) {
1899 cert->subjectSN = (char*)&cert->source[cert->srcIdx];
1900 cert->subjectSNLen = strLen;
1901 cert->subjectSNEnc = b;
1903 #endif /* CYASSL_CERT_GEN */
1904 #ifdef OPENSSL_EXTRA
1905 dName->snIdx = cert->srcIdx;
1906 dName->snLen = strLen;
1907 #endif /* OPENSSL_EXTRA */
1909 else if (id == ASN_COUNTRY_NAME) {
1911 XMEMCPY(&full[idx], "/C=", 3);
1915 #ifdef CYASSL_CERT_GEN
1916 if (nameType == SUBJECT) {
1917 cert->subjectC = (char*)&cert->source[cert->srcIdx];
1918 cert->subjectCLen = strLen;
1919 cert->subjectCEnc = b;
1921 #endif /* CYASSL_CERT_GEN */
1922 #ifdef OPENSSL_EXTRA
1923 dName->cIdx = cert->srcIdx;
1924 dName->cLen = strLen;
1925 #endif /* OPENSSL_EXTRA */
1927 else if (id == ASN_LOCALITY_NAME) {
1929 XMEMCPY(&full[idx], "/L=", 3);
1933 #ifdef CYASSL_CERT_GEN
1934 if (nameType == SUBJECT) {
1935 cert->subjectL = (char*)&cert->source[cert->srcIdx];
1936 cert->subjectLLen = strLen;
1937 cert->subjectLEnc = b;
1939 #endif /* CYASSL_CERT_GEN */
1940 #ifdef OPENSSL_EXTRA
1941 dName->lIdx = cert->srcIdx;
1942 dName->lLen = strLen;
1943 #endif /* OPENSSL_EXTRA */
1945 else if (id == ASN_STATE_NAME) {
1947 XMEMCPY(&full[idx], "/ST=", 4);
1951 #ifdef CYASSL_CERT_GEN
1952 if (nameType == SUBJECT) {
1953 cert->subjectST = (char*)&cert->source[cert->srcIdx];
1954 cert->subjectSTLen = strLen;
1955 cert->subjectSTEnc = b;
1957 #endif /* CYASSL_CERT_GEN */
1958 #ifdef OPENSSL_EXTRA
1959 dName->stIdx = cert->srcIdx;
1960 dName->stLen = strLen;
1961 #endif /* OPENSSL_EXTRA */
1963 else if (id == ASN_ORG_NAME) {
1965 XMEMCPY(&full[idx], "/O=", 3);
1969 #ifdef CYASSL_CERT_GEN
1970 if (nameType == SUBJECT) {
1971 cert->subjectO = (char*)&cert->source[cert->srcIdx];
1972 cert->subjectOLen = strLen;
1973 cert->subjectOEnc = b;
1975 #endif /* CYASSL_CERT_GEN */
1976 #ifdef OPENSSL_EXTRA
1977 dName->oIdx = cert->srcIdx;
1978 dName->oLen = strLen;
1979 #endif /* OPENSSL_EXTRA */
1981 else if (id == ASN_ORGUNIT_NAME) {
1983 XMEMCPY(&full[idx], "/OU=", 4);
1987 #ifdef CYASSL_CERT_GEN
1988 if (nameType == SUBJECT) {
1989 cert->subjectOU = (char*)&cert->source[cert->srcIdx];
1990 cert->subjectOULen = strLen;
1991 cert->subjectOUEnc = b;
1993 #endif /* CYASSL_CERT_GEN */
1994 #ifdef OPENSSL_EXTRA
1995 dName->ouIdx = cert->srcIdx;
1996 dName->ouLen = strLen;
1997 #endif /* OPENSSL_EXTRA */
1999 else if (id == ASN_SERIAL_NUMBER) {
2001 XMEMCPY(&full[idx], "/serialNumber=", 14);
2005 #ifdef OPENSSL_EXTRA
2006 dName->snIdx = cert->srcIdx;
2007 dName->snLen = strLen;
2008 #endif /* OPENSSL_EXTRA */
2011 if (copy && !tooBig) {
2012 XMEMCPY(&full[idx], &cert->source[cert->srcIdx], strLen);
2016 cert->srcIdx += strLen;
2024 if (joint[0] == 0x2a && joint[1] == 0x86) /* email id hdr */
2027 if (joint[0] == 0x9 && joint[1] == 0x92) /* uid id hdr */
2030 cert->srcIdx += oidSz + 1;
2032 if (GetLength(cert->source, &cert->srcIdx, &adv, cert->maxIdx) < 0)
2035 if (adv > (int)(ASN_NAME_MAX - idx)) {
2036 CYASSL_MSG("ASN name too big, skipping");
2041 if ( (14 + adv) > (int)(ASN_NAME_MAX - idx)) {
2042 CYASSL_MSG("ASN name too big, skipping");
2046 XMEMCPY(&full[idx], "/emailAddress=", 14);
2050 #ifdef CYASSL_CERT_GEN
2051 if (nameType == SUBJECT) {
2052 cert->subjectEmail = (char*)&cert->source[cert->srcIdx];
2053 cert->subjectEmailLen = adv;
2055 #endif /* CYASSL_CERT_GEN */
2056 #ifdef OPENSSL_EXTRA
2057 dName->emailIdx = cert->srcIdx;
2058 dName->emailLen = adv;
2059 #endif /* OPENSSL_EXTRA */
2060 #ifndef IGNORE_NAME_CONSTRAINTS
2062 DNS_entry* emailName = NULL;
2064 emailName = (DNS_entry*)XMALLOC(sizeof(DNS_entry),
2065 cert->heap, DYNAMIC_TYPE_ALTNAME);
2066 if (emailName == NULL) {
2067 CYASSL_MSG("\tOut of Memory");
2070 emailName->name = (char*)XMALLOC(adv + 1,
2071 cert->heap, DYNAMIC_TYPE_ALTNAME);
2072 if (emailName->name == NULL) {
2073 CYASSL_MSG("\tOut of Memory");
2076 XMEMCPY(emailName->name,
2077 &cert->source[cert->srcIdx], adv);
2078 emailName->name[adv] = 0;
2080 emailName->next = cert->altEmailNames;
2081 cert->altEmailNames = emailName;
2083 #endif /* IGNORE_NAME_CONSTRAINTS */
2085 XMEMCPY(&full[idx], &cert->source[cert->srcIdx], adv);
2091 if ( (5 + adv) > (int)(ASN_NAME_MAX - idx)) {
2092 CYASSL_MSG("ASN name too big, skipping");
2096 XMEMCPY(&full[idx], "/UID=", 5);
2099 XMEMCPY(&full[idx], &cert->source[cert->srcIdx], adv);
2102 #ifdef OPENSSL_EXTRA
2103 dName->uidIdx = cert->srcIdx;
2104 dName->uidLen = adv;
2105 #endif /* OPENSSL_EXTRA */
2108 cert->srcIdx += adv;
2113 #ifdef OPENSSL_EXTRA
2117 if (dName->cnLen != 0)
2118 totalLen += dName->cnLen + 4;
2119 if (dName->snLen != 0)
2120 totalLen += dName->snLen + 4;
2121 if (dName->cLen != 0)
2122 totalLen += dName->cLen + 3;
2123 if (dName->lLen != 0)
2124 totalLen += dName->lLen + 3;
2125 if (dName->stLen != 0)
2126 totalLen += dName->stLen + 4;
2127 if (dName->oLen != 0)
2128 totalLen += dName->oLen + 3;
2129 if (dName->ouLen != 0)
2130 totalLen += dName->ouLen + 4;
2131 if (dName->emailLen != 0)
2132 totalLen += dName->emailLen + 14;
2133 if (dName->uidLen != 0)
2134 totalLen += dName->uidLen + 5;
2135 if (dName->serialLen != 0)
2136 totalLen += dName->serialLen + 14;
2138 dName->fullName = (char*)XMALLOC(totalLen + 1, NULL, DYNAMIC_TYPE_X509);
2139 if (dName->fullName != NULL) {
2142 if (dName->cnLen != 0) {
2143 dName->entryCount++;
2144 XMEMCPY(&dName->fullName[idx], "/CN=", 4);
2146 XMEMCPY(&dName->fullName[idx],
2147 &cert->source[dName->cnIdx], dName->cnLen);
2149 idx += dName->cnLen;
2151 if (dName->snLen != 0) {
2152 dName->entryCount++;
2153 XMEMCPY(&dName->fullName[idx], "/SN=", 4);
2155 XMEMCPY(&dName->fullName[idx],
2156 &cert->source[dName->snIdx], dName->snLen);
2158 idx += dName->snLen;
2160 if (dName->cLen != 0) {
2161 dName->entryCount++;
2162 XMEMCPY(&dName->fullName[idx], "/C=", 3);
2164 XMEMCPY(&dName->fullName[idx],
2165 &cert->source[dName->cIdx], dName->cLen);
2169 if (dName->lLen != 0) {
2170 dName->entryCount++;
2171 XMEMCPY(&dName->fullName[idx], "/L=", 3);
2173 XMEMCPY(&dName->fullName[idx],
2174 &cert->source[dName->lIdx], dName->lLen);
2178 if (dName->stLen != 0) {
2179 dName->entryCount++;
2180 XMEMCPY(&dName->fullName[idx], "/ST=", 4);
2182 XMEMCPY(&dName->fullName[idx],
2183 &cert->source[dName->stIdx], dName->stLen);
2185 idx += dName->stLen;
2187 if (dName->oLen != 0) {
2188 dName->entryCount++;
2189 XMEMCPY(&dName->fullName[idx], "/O=", 3);
2191 XMEMCPY(&dName->fullName[idx],
2192 &cert->source[dName->oIdx], dName->oLen);
2196 if (dName->ouLen != 0) {
2197 dName->entryCount++;
2198 XMEMCPY(&dName->fullName[idx], "/OU=", 4);
2200 XMEMCPY(&dName->fullName[idx],
2201 &cert->source[dName->ouIdx], dName->ouLen);
2203 idx += dName->ouLen;
2205 if (dName->emailLen != 0) {
2206 dName->entryCount++;
2207 XMEMCPY(&dName->fullName[idx], "/emailAddress=", 14);
2209 XMEMCPY(&dName->fullName[idx],
2210 &cert->source[dName->emailIdx], dName->emailLen);
2211 dName->emailIdx = idx;
2212 idx += dName->emailLen;
2214 if (dName->uidLen != 0) {
2215 dName->entryCount++;
2216 XMEMCPY(&dName->fullName[idx], "/UID=", 5);
2218 XMEMCPY(&dName->fullName[idx],
2219 &cert->source[dName->uidIdx], dName->uidLen);
2220 dName->uidIdx = idx;
2221 idx += dName->uidLen;
2223 if (dName->serialLen != 0) {
2224 dName->entryCount++;
2225 XMEMCPY(&dName->fullName[idx], "/serialNumber=", 14);
2227 XMEMCPY(&dName->fullName[idx],
2228 &cert->source[dName->serialIdx], dName->serialLen);
2229 dName->serialIdx = idx;
2230 idx += dName->serialLen;
2232 dName->fullName[idx] = '\0';
2233 dName->fullNameLen = totalLen;
2236 #endif /* OPENSSL_EXTRA */
2245 static int DateGreaterThan(const struct tm* a, const struct tm* b)
2247 if (a->tm_year > b->tm_year)
2250 if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
2253 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
2254 a->tm_mday > b->tm_mday)
2257 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
2258 a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
2261 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
2262 a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
2263 a->tm_min > b->tm_min)
2266 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
2267 a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
2268 a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
2271 return 0; /* false */
2275 static INLINE int DateLessThan(const struct tm* a, const struct tm* b)
2277 return DateGreaterThan(b,a);
2281 /* like atoi but only use first byte */
2282 /* Make sure before and after dates are valid */
2283 int ValidateDate(const byte* date, byte format, int dateType)
2287 struct tm* localTime;
2291 XMEMSET(&certTime, 0, sizeof(certTime));
2293 if (format == ASN_UTC_TIME) {
2294 if (btoi(date[0]) >= 5)
2295 certTime.tm_year = 1900;
2297 certTime.tm_year = 2000;
2299 else { /* format == GENERALIZED_TIME */
2300 certTime.tm_year += btoi(date[i++]) * 1000;
2301 certTime.tm_year += btoi(date[i++]) * 100;
2304 GetTime(&certTime.tm_year, date, &i); certTime.tm_year -= 1900; /* adjust */
2305 GetTime(&certTime.tm_mon, date, &i); certTime.tm_mon -= 1; /* adjust */
2306 GetTime(&certTime.tm_mday, date, &i);
2307 GetTime(&certTime.tm_hour, date, &i);
2308 GetTime(&certTime.tm_min, date, &i);
2309 GetTime(&certTime.tm_sec, date, &i);
2311 if (date[i] != 'Z') { /* only Zulu supported for this profile */
2312 CYASSL_MSG("Only Zulu time supported for this profile");
2316 localTime = XGMTIME(<ime);
2318 if (dateType == BEFORE) {
2319 if (DateLessThan(localTime, &certTime))
2323 if (DateGreaterThan(localTime, &certTime))
2329 #endif /* NO_TIME_H */
2332 static int GetDate(DecodedCert* cert, int dateType)
2335 byte date[MAX_DATE_SIZE];
2337 word32 startIdx = 0;
2339 if (dateType == BEFORE)
2340 cert->beforeDate = &cert->source[cert->srcIdx];
2342 cert->afterDate = &cert->source[cert->srcIdx];
2343 startIdx = cert->srcIdx;
2345 b = cert->source[cert->srcIdx++];
2346 if (b != ASN_UTC_TIME && b != ASN_GENERALIZED_TIME)
2349 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
2352 if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
2353 return ASN_DATE_SZ_E;
2355 XMEMCPY(date, &cert->source[cert->srcIdx], length);
2356 cert->srcIdx += length;
2358 if (dateType == BEFORE)
2359 cert->beforeDateLen = cert->srcIdx - startIdx;
2361 cert->afterDateLen = cert->srcIdx - startIdx;
2363 if (!XVALIDATE_DATE(date, b, dateType)) {
2364 if (dateType == BEFORE)
2365 return ASN_BEFORE_DATE_E;
2367 return ASN_AFTER_DATE_E;
2374 static int GetValidity(DecodedCert* cert, int verify)
2379 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
2382 if (GetDate(cert, BEFORE) < 0 && verify)
2383 badDate = ASN_BEFORE_DATE_E; /* continue parsing */
2385 if (GetDate(cert, AFTER) < 0 && verify)
2386 return ASN_AFTER_DATE_E;
2395 int DecodeToKey(DecodedCert* cert, int verify)
2400 if ( (ret = GetCertHeader(cert)) < 0)
2403 CYASSL_MSG("Got Cert Header");
2405 if ( (ret = GetAlgoId(cert->source, &cert->srcIdx, &cert->signatureOID,
2409 CYASSL_MSG("Got Algo ID");
2411 if ( (ret = GetName(cert, ISSUER)) < 0)
2414 if ( (ret = GetValidity(cert, verify)) < 0)
2417 if ( (ret = GetName(cert, SUBJECT)) < 0)
2420 CYASSL_MSG("Got Subject Name");
2422 if ( (ret = GetKey(cert)) < 0)
2425 CYASSL_MSG("Got Key");
2434 static int GetSignature(DecodedCert* cert)
2437 byte b = cert->source[cert->srcIdx++];
2439 if (b != ASN_BIT_STRING)
2440 return ASN_BITSTR_E;
2442 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
2445 cert->sigLength = length;
2447 b = cert->source[cert->srcIdx++];
2449 return ASN_EXPECT_0_E;
2452 cert->signature = &cert->source[cert->srcIdx];
2453 cert->srcIdx += cert->sigLength;
2459 static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
2461 output[0] = ASN_OCTET_STRING;
2462 output[1] = (byte)digSz;
2463 XMEMCPY(&output[2], digest, digSz);
2469 static word32 BytePrecision(word32 value)
2472 for (i = sizeof(value); i; --i)
2473 if (value >> ((i - 1) * CYASSL_BIT_SIZE))
2480 CYASSL_LOCAL word32 SetLength(word32 length, byte* output)
2484 if (length < ASN_LONG_LENGTH)
2485 output[i++] = (byte)length;
2487 output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);
2489 for (j = BytePrecision(length); j; --j) {
2490 output[i] = (byte)(length >> ((j - 1) * CYASSL_BIT_SIZE));
2499 CYASSL_LOCAL word32 SetSequence(word32 len, byte* output)
2501 output[0] = ASN_SEQUENCE | ASN_CONSTRUCTED;
2502 return SetLength(len, output + 1) + 1;
2505 CYASSL_LOCAL word32 SetOctetString(word32 len, byte* output)
2507 output[0] = ASN_OCTET_STRING;
2508 return SetLength(len, output + 1) + 1;
2511 /* Write a set header to output */
2512 CYASSL_LOCAL word32 SetSet(word32 len, byte* output)
2514 output[0] = ASN_SET | ASN_CONSTRUCTED;
2515 return SetLength(len, output + 1) + 1;
2518 CYASSL_LOCAL word32 SetImplicit(byte tag, byte number, word32 len, byte* output)
2521 output[0] = ((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0)
2522 | ASN_CONTEXT_SPECIFIC | number;
2523 return SetLength(len, output + 1) + 1;
2526 CYASSL_LOCAL word32 SetExplicit(byte number, word32 len, byte* output)
2528 output[0] = ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | number;
2529 return SetLength(len, output + 1) + 1;
2533 #if defined(HAVE_ECC) && defined(CYASSL_CERT_GEN)
2535 static word32 SetCurve(ecc_key* key, byte* output)
2539 static const byte ECC_192v1_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE, 0x3d,
2541 static const byte ECC_256v1_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE, 0x3d,
2543 static const byte ECC_160r1_AlgoID[] = { 0x2b, 0x81, 0x04, 0x00,
2545 static const byte ECC_224r1_AlgoID[] = { 0x2b, 0x81, 0x04, 0x00,
2547 static const byte ECC_384r1_AlgoID[] = { 0x2b, 0x81, 0x04, 0x00,
2549 static const byte ECC_521r1_AlgoID[] = { 0x2b, 0x81, 0x04, 0x00,
2555 const byte* oid = 0;
2557 output[0] = ASN_OBJECT_ID;
2560 switch (key->dp->size) {
2562 oidSz = sizeof(ECC_160r1_AlgoID);
2563 oid = ECC_160r1_AlgoID;
2567 oidSz = sizeof(ECC_192v1_AlgoID);
2568 oid = ECC_192v1_AlgoID;
2572 oidSz = sizeof(ECC_224r1_AlgoID);
2573 oid = ECC_224r1_AlgoID;
2577 oidSz = sizeof(ECC_256v1_AlgoID);
2578 oid = ECC_256v1_AlgoID;
2582 oidSz = sizeof(ECC_384r1_AlgoID);
2583 oid = ECC_384r1_AlgoID;
2587 oidSz = sizeof(ECC_521r1_AlgoID);
2588 oid = ECC_521r1_AlgoID;
2592 return ASN_UNKNOWN_OID_E;
2594 lenSz = SetLength(oidSz, output+idx);
2597 XMEMCPY(output+idx, oid, oidSz);
2603 #endif /* HAVE_ECC && CYASSL_CERT_GEN */
2606 CYASSL_LOCAL word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz)
2608 /* adding TAG_NULL and 0 to end */
2611 static const byte shaAlgoID[] = { 0x2b, 0x0e, 0x03, 0x02, 0x1a,
2613 static const byte sha256AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
2614 0x04, 0x02, 0x01, 0x05, 0x00 };
2615 static const byte sha384AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
2616 0x04, 0x02, 0x02, 0x05, 0x00 };
2617 static const byte sha512AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
2618 0x04, 0x02, 0x03, 0x05, 0x00 };
2619 static const byte md5AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
2620 0x02, 0x05, 0x05, 0x00 };
2621 static const byte md2AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
2622 0x02, 0x02, 0x05, 0x00};
2624 /* blkTypes, no NULL tags because IV is there instead */
2625 static const byte desCbcAlgoID[] = { 0x2B, 0x0E, 0x03, 0x02, 0x07 };
2626 static const byte des3CbcAlgoID[] = { 0x2A, 0x86, 0x48, 0x86, 0xF7,
2631 static const byte md5wRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7,
2632 0x0d, 0x01, 0x01, 0x04, 0x05, 0x00};
2633 static const byte shawRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7,
2634 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00};
2635 static const byte sha256wRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7,
2636 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00};
2637 static const byte sha384wRSA_AlgoID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
2638 0x0d, 0x01, 0x01, 0x0c, 0x05, 0x00};
2639 static const byte sha512wRSA_AlgoID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
2640 0x0d, 0x01, 0x01, 0x0d, 0x05, 0x00};
2643 /* ECDSA sigTypes */
2645 static const byte shawECDSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE, 0x3d,
2646 0x04, 0x01, 0x05, 0x00};
2647 static const byte sha256wECDSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE,0x3d,
2648 0x04, 0x03, 0x02, 0x05, 0x00};
2649 static const byte sha384wECDSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE,0x3d,
2650 0x04, 0x03, 0x03, 0x05, 0x00};
2651 static const byte sha512wECDSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE,0x3d,
2652 0x04, 0x03, 0x04, 0x05, 0x00};
2653 #endif /* HAVE_ECC */
2657 static const byte RSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
2658 0x01, 0x01, 0x01, 0x05, 0x00};
2663 /* no tags, so set tagSz smaller later */
2664 static const byte ECC_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE, 0x3d,
2666 #endif /* HAVE_ECC */
2669 int tagSz = 2; /* tag null and terminator */
2671 const byte* algoName = 0;
2672 byte ID_Length[MAX_LENGTH_SZ];
2673 byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
2675 if (type == hashType) {
2678 algoSz = sizeof(shaAlgoID);
2679 algoName = shaAlgoID;
2683 algoSz = sizeof(sha256AlgoID);
2684 algoName = sha256AlgoID;
2688 algoSz = sizeof(sha384AlgoID);
2689 algoName = sha384AlgoID;
2693 algoSz = sizeof(sha512AlgoID);
2694 algoName = sha512AlgoID;
2698 algoSz = sizeof(md2AlgoID);
2699 algoName = md2AlgoID;
2703 algoSz = sizeof(md5AlgoID);
2704 algoName = md5AlgoID;
2708 CYASSL_MSG("Unknown Hash Algo");
2709 return 0; /* UNKOWN_HASH_E; */
2712 else if (type == blkType) {
2715 algoSz = sizeof(desCbcAlgoID);
2716 algoName = desCbcAlgoID;
2720 algoSz = sizeof(des3CbcAlgoID);
2721 algoName = des3CbcAlgoID;
2725 CYASSL_MSG("Unknown Block Algo");
2729 else if (type == sigType) { /* sigType */
2733 algoSz = sizeof(md5wRSA_AlgoID);
2734 algoName = md5wRSA_AlgoID;
2738 algoSz = sizeof(shawRSA_AlgoID);
2739 algoName = shawRSA_AlgoID;
2742 case CTC_SHA256wRSA:
2743 algoSz = sizeof(sha256wRSA_AlgoID);
2744 algoName = sha256wRSA_AlgoID;
2747 case CTC_SHA384wRSA:
2748 algoSz = sizeof(sha384wRSA_AlgoID);
2749 algoName = sha384wRSA_AlgoID;
2752 case CTC_SHA512wRSA:
2753 algoSz = sizeof(sha512wRSA_AlgoID);
2754 algoName = sha512wRSA_AlgoID;
2759 algoSz = sizeof(shawECDSA_AlgoID);
2760 algoName = shawECDSA_AlgoID;
2763 case CTC_SHA256wECDSA:
2764 algoSz = sizeof(sha256wECDSA_AlgoID);
2765 algoName = sha256wECDSA_AlgoID;
2768 case CTC_SHA384wECDSA:
2769 algoSz = sizeof(sha384wECDSA_AlgoID);
2770 algoName = sha384wECDSA_AlgoID;
2773 case CTC_SHA512wECDSA:
2774 algoSz = sizeof(sha512wECDSA_AlgoID);
2775 algoName = sha512wECDSA_AlgoID;
2777 #endif /* HAVE_ECC */
2779 CYASSL_MSG("Unknown Signature Algo");
2783 else if (type == keyType) { /* keyType */
2787 algoSz = sizeof(RSA_AlgoID);
2788 algoName = RSA_AlgoID;
2793 algoSz = sizeof(ECC_AlgoID);
2794 algoName = ECC_AlgoID;
2797 #endif /* HAVE_ECC */
2799 CYASSL_MSG("Unknown Key Algo");
2804 CYASSL_MSG("Unknown Algo type");
2808 idSz = SetLength(algoSz - tagSz, ID_Length); /* don't include tags */
2809 seqSz = SetSequence(idSz + algoSz + 1 + curveSz, seqArray);
2810 /* +1 for object id, curveID of curveSz follows for ecc */
2811 seqArray[seqSz++] = ASN_OBJECT_ID;
2813 XMEMCPY(output, seqArray, seqSz);
2814 XMEMCPY(output + seqSz, ID_Length, idSz);
2815 XMEMCPY(output + seqSz + idSz, algoName, algoSz);
2817 return seqSz + idSz + algoSz;
2822 word32 EncodeSignature(byte* out, const byte* digest, word32 digSz, int hashOID)
2824 byte digArray[MAX_ENCODED_DIG_SZ];
2825 byte algoArray[MAX_ALGO_SZ];
2826 byte seqArray[MAX_SEQ_SZ];
2827 word32 encDigSz, algoSz, seqSz;
2829 encDigSz = SetDigest(digest, digSz, digArray);
2830 algoSz = SetAlgoID(hashOID, algoArray, hashType, 0);
2831 seqSz = SetSequence(encDigSz + algoSz, seqArray);
2833 XMEMCPY(out, seqArray, seqSz);
2834 XMEMCPY(out + seqSz, algoArray, algoSz);
2835 XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
2837 return encDigSz + algoSz + seqSz;
2841 /* return true (1) or false (0) for Confirmation */
2842 static int ConfirmSignature(const byte* buf, word32 bufSz,
2843 const byte* key, word32 keySz, word32 keyOID,
2844 const byte* sig, word32 sigSz, word32 sigOID,
2847 int typeH = 0, digestSz = 0, ret = 0;
2848 #ifdef CYASSL_SMALL_STACK
2851 byte digest[MAX_DIGEST_SIZE];
2854 #ifdef CYASSL_SMALL_STACK
2855 digest = (byte*)XMALLOC(MAX_DIGEST_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
2857 return 0; /* not confirmed */
2869 if (Md5Hash(buf, bufSz, digest) == 0) {
2871 digestSz = MD5_DIGEST_SIZE;
2875 #if defined(CYASSL_MD2)
2877 if (Md2Hash(buf, bufSz, digest) == 0) {
2879 digestSz = MD2_DIGEST_SIZE;
2887 if (ShaHash(buf, bufSz, digest) == 0) {
2889 digestSz = SHA_DIGEST_SIZE;
2894 case CTC_SHA256wRSA:
2895 case CTC_SHA256wECDSA:
2896 if (Sha256Hash(buf, bufSz, digest) == 0) {
2898 digestSz = SHA256_DIGEST_SIZE;
2902 #ifdef CYASSL_SHA512
2903 case CTC_SHA512wRSA:
2904 case CTC_SHA512wECDSA:
2905 if (Sha512Hash(buf, bufSz, digest) == 0) {
2907 digestSz = SHA512_DIGEST_SIZE;
2911 #ifdef CYASSL_SHA384
2912 case CTC_SHA384wRSA:
2913 case CTC_SHA384wECDSA:
2914 if (Sha384Hash(buf, bufSz, digest) == 0) {
2916 digestSz = SHA384_DIGEST_SIZE;
2921 CYASSL_MSG("Verify Signautre has unsupported type");
2925 #ifdef CYASSL_SMALL_STACK
2926 XFREE(digest, NULL, DYNAMIC_TYPE_TMP_BUFFER);
2928 return 0; /* not confirmed */
2936 int encodedSigSz, verifySz;
2938 #ifdef CYASSL_SMALL_STACK
2944 byte plain[MAX_ENCODED_SIG_SZ];
2945 byte encodedSig[MAX_ENCODED_SIG_SZ];
2948 #ifdef CYASSL_SMALL_STACK
2949 pubKey = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL,
2950 DYNAMIC_TYPE_TMP_BUFFER);
2951 plain = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, NULL,
2952 DYNAMIC_TYPE_TMP_BUFFER);
2953 encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, NULL,
2954 DYNAMIC_TYPE_TMP_BUFFER);
2956 if (pubKey == NULL || plain == NULL || encodedSig == NULL) {
2957 CYASSL_MSG("Failed to allocate memory at ConfirmSignature");
2960 XFREE(pubKey, NULL, DYNAMIC_TYPE_TMP_BUFFER);
2962 XFREE(plain, NULL, DYNAMIC_TYPE_TMP_BUFFER);
2964 XFREE(encodedSig, NULL, DYNAMIC_TYPE_TMP_BUFFER);
2966 break; /* not confirmed */
2970 if (sigSz > MAX_ENCODED_SIG_SZ) {
2971 CYASSL_MSG("Verify Signautre is too big");
2973 else if (InitRsaKey(pubKey, heap) != 0) {
2974 CYASSL_MSG("InitRsaKey failed");
2976 else if (RsaPublicKeyDecode(key, &idx, pubKey, keySz) < 0) {
2977 CYASSL_MSG("ASN Key decode error RSA");
2980 XMEMCPY(plain, sig, sigSz);
2982 if ((verifySz = RsaSSL_VerifyInline(plain, sigSz, &out,
2984 CYASSL_MSG("Rsa SSL verify error");
2987 /* make sure we're right justified */
2989 EncodeSignature(encodedSig, digest, digestSz, typeH);
2990 if (encodedSigSz != verifySz ||
2991 XMEMCMP(out, encodedSig, encodedSigSz) != 0) {
2992 CYASSL_MSG("Rsa SSL verify match encode error");
2995 ret = 1; /* match */
2997 #ifdef CYASSL_DEBUG_ENCODING
3001 printf("cyassl encodedSig:\n");
3003 for (x = 0; x < encodedSigSz; x++) {
3004 printf("%02x ", encodedSig[x]);
3005 if ( (x % 16) == 15)
3010 printf("actual digest:\n");
3012 for (x = 0; x < verifySz; x++) {
3013 printf("%02x ", out[x]);
3014 if ( (x % 16) == 15)
3020 #endif /* CYASSL_DEBUG_ENCODING */
3028 #ifdef CYASSL_SMALL_STACK
3029 XFREE(pubKey, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3030 XFREE(plain, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3031 XFREE(encodedSig, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3040 #ifdef CYASSL_SMALL_STACK
3046 #ifdef CYASSL_SMALL_STACK
3047 pubKey = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL,
3048 DYNAMIC_TYPE_TMP_BUFFER);
3049 if (pubKey == NULL) {
3050 CYASSL_MSG("Failed to allocate pubKey");
3051 break; /* not confirmed */
3055 if (ecc_import_x963(key, keySz, pubKey) < 0) {
3056 CYASSL_MSG("ASN Key import error ECC");
3059 if (ecc_verify_hash(sig, sigSz, digest, digestSz, &verify,
3061 CYASSL_MSG("ECC verify hash error");
3063 else if (1 != verify) {
3064 CYASSL_MSG("ECC Verify didn't match");
3066 ret = 1; /* match */
3070 #ifdef CYASSL_SMALL_STACK
3071 XFREE(pubKey, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3074 #endif /* HAVE_ECC */
3076 CYASSL_MSG("Verify Key type unknown");
3079 #ifdef CYASSL_SMALL_STACK
3080 XFREE(digest, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3087 #ifndef IGNORE_NAME_CONSTRAINTS
3089 static int MatchBaseName(int type, const char* name, int nameSz,
3090 const char* base, int baseSz)
3092 if (base == NULL || baseSz <= 0 || name == NULL || nameSz <= 0 ||
3093 name[0] == '.' || nameSz < baseSz ||
3094 (type != ASN_RFC822_TYPE && type != ASN_DNS_TYPE))
3097 /* If an email type, handle special cases where the base is only
3098 * a domain, or is an email address itself. */
3099 if (type == ASN_RFC822_TYPE) {
3100 const char* p = NULL;
3103 if (base[0] != '.') {
3107 /* find the '@' in the base */
3108 while (*p != '@' && count < baseSz) {
3113 /* No '@' in base, reset p to NULL */
3114 if (count >= baseSz)
3119 /* Base isn't an email address, it is a domain name,
3120 * wind the name forward one character past its '@'. */
3123 while (*p != '@' && count < baseSz) {
3128 if (count < baseSz && *p == '@') {
3130 nameSz -= count + 1;
3135 if ((type == ASN_DNS_TYPE || type == ASN_RFC822_TYPE) && base[0] == '.') {
3136 int szAdjust = nameSz - baseSz;
3141 while (nameSz > 0) {
3142 if (XTOLOWER(*name++) != XTOLOWER(*base++))
3151 static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert)
3153 if (signer == NULL || cert == NULL)
3156 /* Check against the excluded list */
3157 if (signer->excludedNames) {
3158 Base_entry* base = signer->excludedNames;
3160 while (base != NULL) {
3161 if (base->type == ASN_DNS_TYPE) {
3162 DNS_entry* name = cert->altNames;
3163 while (name != NULL) {
3164 if (MatchBaseName(ASN_DNS_TYPE,
3165 name->name, (int)XSTRLEN(name->name),
3166 base->name, base->nameSz))
3171 else if (base->type == ASN_RFC822_TYPE) {
3172 DNS_entry* name = cert->altEmailNames;
3173 while (name != NULL) {
3174 if (MatchBaseName(ASN_RFC822_TYPE,
3175 name->name, (int)XSTRLEN(name->name),
3176 base->name, base->nameSz))
3182 else if (base->type == ASN_DIR_TYPE) {
3183 if (cert->subjectRawLen == base->nameSz &&
3184 XMEMCMP(cert->subjectRaw, base->name, base->nameSz) == 0) {
3193 /* Check against the permitted list */
3194 if (signer->permittedNames != NULL) {
3201 Base_entry* base = signer->permittedNames;
3203 while (base != NULL) {
3204 if (base->type == ASN_DNS_TYPE) {
3205 DNS_entry* name = cert->altNames;
3210 while (name != NULL) {
3211 matchDns = MatchBaseName(ASN_DNS_TYPE,
3212 name->name, (int)XSTRLEN(name->name),
3213 base->name, base->nameSz);
3217 else if (base->type == ASN_RFC822_TYPE) {
3218 DNS_entry* name = cert->altEmailNames;
3223 while (name != NULL) {
3224 matchEmail = MatchBaseName(ASN_DNS_TYPE,
3225 name->name, (int)XSTRLEN(name->name),
3226 base->name, base->nameSz);
3230 else if (base->type == ASN_DIR_TYPE) {
3232 if (cert->subjectRaw != NULL &&
3233 cert->subjectRawLen == base->nameSz &&
3234 XMEMCMP(cert->subjectRaw, base->name, base->nameSz) == 0) {
3242 if ((needDns && !matchDns) || (needEmail && !matchEmail) ||
3243 (needDir && !matchDir)) {
3252 #endif /* IGNORE_NAME_CONSTRAINTS */
3255 static int DecodeAltNames(byte* input, int sz, DecodedCert* cert)
3260 CYASSL_ENTER("DecodeAltNames");
3262 if (GetSequence(input, &idx, &length, sz) < 0) {
3263 CYASSL_MSG("\tBad Sequence");
3267 while (length > 0) {
3268 byte b = input[idx++];
3272 /* Save DNS Type names in the altNames list. */
3273 /* Save Other Type names in the cert's OidMap */
3274 if (b == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
3275 DNS_entry* dnsEntry;
3277 word32 lenStartIdx = idx;
3279 if (GetLength(input, &idx, &strLen, sz) < 0) {
3280 CYASSL_MSG("\tfail: str length");
3283 length -= (idx - lenStartIdx);
3285 dnsEntry = (DNS_entry*)XMALLOC(sizeof(DNS_entry), cert->heap,
3286 DYNAMIC_TYPE_ALTNAME);
3287 if (dnsEntry == NULL) {
3288 CYASSL_MSG("\tOut of Memory");
3292 dnsEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
3293 DYNAMIC_TYPE_ALTNAME);
3294 if (dnsEntry->name == NULL) {
3295 CYASSL_MSG("\tOut of Memory");
3296 XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
3300 XMEMCPY(dnsEntry->name, &input[idx], strLen);
3301 dnsEntry->name[strLen] = '\0';
3303 dnsEntry->next = cert->altNames;
3304 cert->altNames = dnsEntry;
3309 #ifndef IGNORE_NAME_CONSTRAINTS
3310 else if (b == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
3311 DNS_entry* emailEntry;
3313 word32 lenStartIdx = idx;
3315 if (GetLength(input, &idx, &strLen, sz) < 0) {
3316 CYASSL_MSG("\tfail: str length");
3319 length -= (idx - lenStartIdx);
3321 emailEntry = (DNS_entry*)XMALLOC(sizeof(DNS_entry), cert->heap,
3322 DYNAMIC_TYPE_ALTNAME);
3323 if (emailEntry == NULL) {
3324 CYASSL_MSG("\tOut of Memory");
3328 emailEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
3329 DYNAMIC_TYPE_ALTNAME);
3330 if (emailEntry->name == NULL) {
3331 CYASSL_MSG("\tOut of Memory");
3332 XFREE(emailEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
3336 XMEMCPY(emailEntry->name, &input[idx], strLen);
3337 emailEntry->name[strLen] = '\0';
3339 emailEntry->next = cert->altEmailNames;
3340 cert->altEmailNames = emailEntry;
3345 #endif /* IGNORE_NAME_CONSTRAINTS */
3347 else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE))
3350 word32 lenStartIdx = idx;
3353 if (GetLength(input, &idx, &strLen, sz) < 0) {
3354 CYASSL_MSG("\tfail: other name length");
3357 /* Consume the rest of this sequence. */
3358 length -= (strLen + idx - lenStartIdx);
3360 if (GetObjectId(input, &idx, &oid, sz) < 0) {
3361 CYASSL_MSG("\tbad OID");
3365 if (oid != HW_NAME_OID) {
3366 CYASSL_MSG("\tincorrect OID");
3370 if (input[idx++] != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
3371 CYASSL_MSG("\twrong type");
3375 if (GetLength(input, &idx, &strLen, sz) < 0) {
3376 CYASSL_MSG("\tfail: str len");
3380 if (GetSequence(input, &idx, &strLen, sz) < 0) {
3381 CYASSL_MSG("\tBad Sequence");
3385 if (input[idx++] != ASN_OBJECT_ID) {
3386 CYASSL_MSG("\texpected OID");
3390 if (GetLength(input, &idx, &strLen, sz) < 0) {
3391 CYASSL_MSG("\tfailed: str len");
3395 cert->hwType = (byte*)XMALLOC(strLen, cert->heap, 0);
3396 if (cert->hwType == NULL) {
3397 CYASSL_MSG("\tOut of Memory");
3401 XMEMCPY(cert->hwType, &input[idx], strLen);
3402 cert->hwTypeSz = strLen;
3405 if (input[idx++] != ASN_OCTET_STRING) {
3406 CYASSL_MSG("\texpected Octet String");
3410 if (GetLength(input, &idx, &strLen, sz) < 0) {
3411 CYASSL_MSG("\tfailed: str len");
3415 cert->hwSerialNum = (byte*)XMALLOC(strLen + 1, cert->heap, 0);
3416 if (cert->hwSerialNum == NULL) {
3417 CYASSL_MSG("\tOut of Memory");
3421 XMEMCPY(cert->hwSerialNum, &input[idx], strLen);
3422 cert->hwSerialNum[strLen] = '\0';
3423 cert->hwSerialNumSz = strLen;
3426 #endif /* CYASSL_SEP */
3429 word32 lenStartIdx = idx;
3431 CYASSL_MSG("\tUnsupported name type, skipping");
3433 if (GetLength(input, &idx, &strLen, sz) < 0) {
3434 CYASSL_MSG("\tfail: unsupported name length");
3437 length -= (strLen + idx - lenStartIdx);
3445 static int DecodeBasicCaConstraint(byte* input, int sz, DecodedCert* cert)
3450 CYASSL_ENTER("DecodeBasicCaConstraint");
3451 if (GetSequence(input, &idx, &length, sz) < 0) {
3452 CYASSL_MSG("\tfail: bad SEQUENCE");
3459 /* If the basic ca constraint is false, this extension may be named, but
3460 * left empty. So, if the length is 0, just return. */
3462 if (input[idx++] != ASN_BOOLEAN)
3464 CYASSL_MSG("\tfail: constraint not BOOLEAN");
3468 if (GetLength(input, &idx, &length, sz) < 0)
3470 CYASSL_MSG("\tfail: length");
3477 #ifdef OPENSSL_EXTRA
3478 /* If there isn't any more data, return. */
3479 if (idx >= (word32)sz)
3482 /* Anything left should be the optional pathlength */
3483 if (input[idx++] != ASN_INTEGER) {
3484 CYASSL_MSG("\tfail: pathlen not INTEGER");
3488 if (input[idx++] != 1) {
3489 CYASSL_MSG("\tfail: pathlen too long");
3493 cert->pathLength = input[idx];
3494 cert->extBasicConstPlSet = 1;
3495 #endif /* OPENSSL_EXTRA */
3501 #define CRLDP_FULL_NAME 0
3502 /* From RFC3280 SS4.2.1.14, Distribution Point Name*/
3503 #define GENERALNAME_URI 6
3504 /* From RFC3280 SS4.2.1.7, GeneralName */
3506 static int DecodeCrlDist(byte* input, int sz, DecodedCert* cert)
3511 CYASSL_ENTER("DecodeCrlDist");
3513 /* Unwrap the list of Distribution Points*/
3514 if (GetSequence(input, &idx, &length, sz) < 0)
3517 /* Unwrap a single Distribution Point */
3518 if (GetSequence(input, &idx, &length, sz) < 0)
3521 /* The Distribution Point has three explicit optional members
3522 * First check for a DistributionPointName
3524 if (input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
3527 if (GetLength(input, &idx, &length, sz) < 0)
3531 (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CRLDP_FULL_NAME))
3534 if (GetLength(input, &idx, &length, sz) < 0)
3537 if (input[idx] == (ASN_CONTEXT_SPECIFIC | GENERALNAME_URI))
3540 if (GetLength(input, &idx, &length, sz) < 0)
3543 cert->extCrlInfoSz = length;
3544 cert->extCrlInfo = input + idx;
3548 /* This isn't a URI, skip it. */
3552 /* This isn't a FULLNAME, skip it. */
3556 /* Check for reasonFlags */
3557 if (idx < (word32)sz &&
3558 input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
3561 if (GetLength(input, &idx, &length, sz) < 0)
3566 /* Check for cRLIssuer */
3567 if (idx < (word32)sz &&
3568 input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
3571 if (GetLength(input, &idx, &length, sz) < 0)
3576 if (idx < (word32)sz)
3578 CYASSL_MSG("\tThere are more CRL Distribution Point records, "
3579 "but we only use the first one.");
3586 static int DecodeAuthInfo(byte* input, int sz, DecodedCert* cert)
3588 * Read the first of the Authority Information Access records. If there are
3589 * any issues, return without saving the record.
3597 CYASSL_ENTER("DecodeAuthInfo");
3599 /* Unwrap the list of AIAs */
3600 if (GetSequence(input, &idx, &length, sz) < 0)
3603 while (idx < (word32)sz) {
3604 /* Unwrap a single AIA */
3605 if (GetSequence(input, &idx, &length, sz) < 0)
3609 if (GetObjectId(input, &idx, &oid, sz) < 0)
3612 /* Only supporting URIs right now. */
3614 if (GetLength(input, &idx, &length, sz) < 0)
3617 if (b == (ASN_CONTEXT_SPECIFIC | GENERALNAME_URI) &&
3618 oid == AIA_OCSP_OID)
3620 cert->extAuthInfoSz = length;
3621 cert->extAuthInfo = input + idx;
3631 static int DecodeAuthKeyId(byte* input, int sz, DecodedCert* cert)
3634 int length = 0, ret = 0;
3636 CYASSL_ENTER("DecodeAuthKeyId");
3638 if (GetSequence(input, &idx, &length, sz) < 0) {
3639 CYASSL_MSG("\tfail: should be a SEQUENCE\n");
3643 if (input[idx++] != (ASN_CONTEXT_SPECIFIC | 0)) {
3644 CYASSL_MSG("\tinfo: OPTIONAL item 0, not available\n");
3648 if (GetLength(input, &idx, &length, sz) < 0) {
3649 CYASSL_MSG("\tfail: extension data length");
3653 #ifdef OPENSSL_EXTRA
3654 cert->extAuthKeyIdSrc = &input[idx];
3655 cert->extAuthKeyIdSz = length;
3656 #endif /* OPENSSL_EXTRA */
3658 if (length == SHA_SIZE) {
3659 XMEMCPY(cert->extAuthKeyId, input + idx, length);
3663 ret = InitSha(&sha);
3666 ShaUpdate(&sha, input + idx, length);
3667 ShaFinal(&sha, cert->extAuthKeyId);
3674 static int DecodeSubjKeyId(byte* input, int sz, DecodedCert* cert)
3677 int length = 0, ret = 0;
3679 CYASSL_ENTER("DecodeSubjKeyId");
3681 if (input[idx++] != ASN_OCTET_STRING) {
3682 CYASSL_MSG("\tfail: should be an OCTET STRING");
3686 if (GetLength(input, &idx, &length, sz) < 0) {
3687 CYASSL_MSG("\tfail: extension data length");
3691 #ifdef OPENSSL_EXTRA
3692 cert->extSubjKeyIdSrc = &input[idx];
3693 cert->extSubjKeyIdSz = length;
3694 #endif /* OPENSSL_EXTRA */
3696 if (length == SIGNER_DIGEST_SIZE) {
3697 XMEMCPY(cert->extSubjKeyId, input + idx, length);
3701 ret = InitSha(&sha);
3704 ShaUpdate(&sha, input + idx, length);
3705 ShaFinal(&sha, cert->extSubjKeyId);
3712 static int DecodeKeyUsage(byte* input, int sz, DecodedCert* cert)
3717 CYASSL_ENTER("DecodeKeyUsage");
3719 if (input[idx++] != ASN_BIT_STRING) {
3720 CYASSL_MSG("\tfail: key usage expected bit string");
3724 if (GetLength(input, &idx, &length, sz) < 0) {
3725 CYASSL_MSG("\tfail: key usage bad length");
3729 unusedBits = input[idx++];
3733 cert->extKeyUsage = (word16)((input[idx] << 8) | input[idx+1]);
3734 cert->extKeyUsage >>= unusedBits;
3736 else if (length == 1)
3737 cert->extKeyUsage = (word16)(input[idx] << 1);
3743 static int DecodeExtKeyUsage(byte* input, int sz, DecodedCert* cert)
3745 word32 idx = 0, oid;
3748 CYASSL_ENTER("DecodeExtKeyUsage");
3750 if (GetSequence(input, &idx, &length, sz) < 0) {
3751 CYASSL_MSG("\tfail: should be a SEQUENCE");
3755 #ifdef OPENSSL_EXTRA
3756 cert->extExtKeyUsageSrc = input + idx;
3757 cert->extExtKeyUsageSz = length;
3760 while (idx < (word32)sz) {
3761 if (GetObjectId(input, &idx, &oid, sz) < 0)
3766 cert->extExtKeyUsage |= EXTKEYUSE_ANY;
3768 case EKU_SERVER_AUTH_OID:
3769 cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
3771 case EKU_CLIENT_AUTH_OID:
3772 cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
3774 case EKU_OCSP_SIGN_OID:
3775 cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
3779 #ifdef OPENSSL_EXTRA
3780 cert->extExtKeyUsageCount++;
3788 #ifndef IGNORE_NAME_CONSTRAINTS
3789 static int DecodeSubtree(byte* input, int sz, Base_entry** head, void* heap)
3795 while (idx < (word32)sz) {
3796 int seqLength, strLength;
3800 if (GetSequence(input, &idx, &seqLength, sz) < 0) {
3801 CYASSL_MSG("\tfail: should be a SEQUENCE");
3806 b = input[nameIdx++];
3807 if (GetLength(input, &nameIdx, &strLength, sz) <= 0) {
3808 CYASSL_MSG("\tinvalid length");
3812 if (b == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE) ||
3813 b == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE) ||
3814 b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
3816 Base_entry* entry = (Base_entry*)XMALLOC(sizeof(Base_entry),
3817 heap, DYNAMIC_TYPE_ALTNAME);
3819 if (entry == NULL) {
3820 CYASSL_MSG("allocate error");
3824 entry->name = (char*)XMALLOC(strLength, heap, DYNAMIC_TYPE_ALTNAME);
3825 if (entry->name == NULL) {
3826 CYASSL_MSG("allocate error");
3830 XMEMCPY(entry->name, &input[nameIdx], strLength);
3831 entry->nameSz = strLength;
3832 entry->type = b & 0x0F;
3834 entry->next = *head;
3845 static int DecodeNameConstraints(byte* input, int sz, DecodedCert* cert)
3850 CYASSL_ENTER("DecodeNameConstraints");
3852 if (GetSequence(input, &idx, &length, sz) < 0) {
3853 CYASSL_MSG("\tfail: should be a SEQUENCE");
3857 while (idx < (word32)sz) {
3858 byte b = input[idx++];
3859 Base_entry** subtree = NULL;
3861 if (GetLength(input, &idx, &length, sz) <= 0) {
3862 CYASSL_MSG("\tinvalid length");
3866 if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
3867 subtree = &cert->permittedNames;
3868 else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
3869 subtree = &cert->excludedNames;
3871 CYASSL_MSG("\tinvalid subtree");
3875 DecodeSubtree(input + idx, length, subtree, cert->heap);
3882 #endif /* IGNORE_NAME_CONSTRAINTS */
3886 static int DecodeCertPolicy(byte* input, int sz, DecodedCert* cert)
3891 CYASSL_ENTER("DecodeCertPolicy");
3893 /* Unwrap certificatePolicies */
3894 if (GetSequence(input, &idx, &length, sz) < 0) {
3895 CYASSL_MSG("\tdeviceType isn't OID");
3899 if (GetSequence(input, &idx, &length, sz) < 0) {
3900 CYASSL_MSG("\tdeviceType isn't OID");
3904 if (input[idx++] != ASN_OBJECT_ID) {
3905 CYASSL_MSG("\tdeviceType isn't OID");
3909 if (GetLength(input, &idx, &length, sz) < 0) {
3910 CYASSL_MSG("\tCouldn't read length of deviceType");
3915 cert->deviceType = (byte*)XMALLOC(length, cert->heap, 0);
3916 if (cert->deviceType == NULL) {
3917 CYASSL_MSG("\tCouldn't alloc memory for deviceType");
3920 cert->deviceTypeSz = length;
3921 XMEMCPY(cert->deviceType, input + idx, length);
3924 CYASSL_LEAVE("DecodeCertPolicy", 0);
3927 #endif /* CYASSL_SEP */
3930 static int DecodeCertExtensions(DecodedCert* cert)
3932 * Processing the Certificate Extensions. This does not modify the current
3933 * index. It is works starting with the recorded extensions pointer.
3937 int sz = cert->extensionsSz;
3938 byte* input = cert->extensions;
3942 byte criticalFail = 0;
3944 CYASSL_ENTER("DecodeCertExtensions");
3946 if (input == NULL || sz == 0)
3947 return BAD_FUNC_ARG;
3949 if (input[idx++] != ASN_EXTENSIONS)
3952 if (GetLength(input, &idx, &length, sz) < 0)
3955 if (GetSequence(input, &idx, &length, sz) < 0)
3958 while (idx < (word32)sz) {
3959 if (GetSequence(input, &idx, &length, sz) < 0) {
3960 CYASSL_MSG("\tfail: should be a SEQUENCE");
3965 if (GetObjectId(input, &idx, &oid, sz) < 0) {
3966 CYASSL_MSG("\tfail: OBJECT ID");
3970 /* check for critical flag */
3972 if (input[idx] == ASN_BOOLEAN) {
3975 if (GetLength(input, &idx, &boolLength, sz) < 0) {
3976 CYASSL_MSG("\tfail: critical boolean length");
3983 /* process the extension based on the OID */
3984 if (input[idx++] != ASN_OCTET_STRING) {
3985 CYASSL_MSG("\tfail: should be an OCTET STRING");
3989 if (GetLength(input, &idx, &length, sz) < 0) {
3990 CYASSL_MSG("\tfail: extension data length");
3996 #ifdef OPENSSL_EXTRA
3997 cert->extBasicConstSet = 1;
3998 cert->extBasicConstCrit = critical;
4000 if (DecodeBasicCaConstraint(&input[idx], length, cert) < 0)
4005 if (DecodeCrlDist(&input[idx], length, cert) < 0)
4010 if (DecodeAuthInfo(&input[idx], length, cert) < 0)
4015 #ifdef OPENSSL_EXTRA
4016 cert->extSubjAltNameSet = 1;
4017 cert->extSubjAltNameCrit = critical;
4019 if (DecodeAltNames(&input[idx], length, cert) < 0)
4024 cert->extAuthKeyIdSet = 1;
4025 #ifdef OPENSSL_EXTRA
4026 cert->extAuthKeyIdCrit = critical;
4028 if (DecodeAuthKeyId(&input[idx], length, cert) < 0)
4033 cert->extSubjKeyIdSet = 1;
4034 #ifdef OPENSSL_EXTRA
4035 cert->extSubjKeyIdCrit = critical;
4037 if (DecodeSubjKeyId(&input[idx], length, cert) < 0)
4041 case CERT_POLICY_OID:
4042 CYASSL_MSG("Certificate Policy extension not supported yet.");
4044 #ifdef OPENSSL_EXTRA
4045 cert->extCertPolicySet = 1;
4046 cert->extCertPolicyCrit = critical;
4048 if (DecodeCertPolicy(&input[idx], length, cert) < 0)
4054 cert->extKeyUsageSet = 1;
4055 #ifdef OPENSSL_EXTRA
4056 cert->extKeyUsageCrit = critical;
4058 if (DecodeKeyUsage(&input[idx], length, cert) < 0)
4062 case EXT_KEY_USAGE_OID:
4063 cert->extExtKeyUsageSet = 1;
4064 #ifdef OPENSSL_EXTRA
4065 cert->extExtKeyUsageCrit = critical;
4067 if (DecodeExtKeyUsage(&input[idx], length, cert) < 0)
4071 #ifndef IGNORE_NAME_CONSTRAINTS
4073 cert->extNameConstraintSet = 1;
4074 #ifdef OPENSSL_EXTRA
4075 cert->extNameConstraintCrit = critical;
4077 if (DecodeNameConstraints(&input[idx], length, cert) < 0)
4080 #endif /* IGNORE_NAME_CONSTRAINTS */
4082 case INHIBIT_ANY_OID:
4083 CYASSL_MSG("Inhibit anyPolicy extension not supported yet.");
4087 /* While it is a failure to not support critical extensions,
4088 * still parse the certificate ignoring the unsupported
4089 * extention to allow caller to accept it with the verify
4098 return criticalFail ? ASN_CRIT_EXT_E : 0;
4102 int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
4107 ret = ParseCertRelative(cert, type, verify, cm);
4111 if (cert->subjectCNLen > 0) {
4112 ptr = (char*) XMALLOC(cert->subjectCNLen + 1, cert->heap,
4113 DYNAMIC_TYPE_SUBJECT_CN);
4116 XMEMCPY(ptr, cert->subjectCN, cert->subjectCNLen);
4117 ptr[cert->subjectCNLen] = '\0';
4118 cert->subjectCN = ptr;
4119 cert->subjectCNStored = 1;
4122 if (cert->keyOID == RSAk &&
4123 cert->publicKey != NULL && cert->pubKeySize > 0) {
4124 ptr = (char*) XMALLOC(cert->pubKeySize, cert->heap,
4125 DYNAMIC_TYPE_PUBLIC_KEY);
4128 XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
4129 cert->publicKey = (byte *)ptr;
4130 cert->pubKeyStored = 1;
4137 /* from SSL proper, for locking can't do find here anymore */
4141 CYASSL_LOCAL Signer* GetCA(void* signers, byte* hash);
4143 CYASSL_LOCAL Signer* GetCAByName(void* signers, byte* hash);
4150 int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
4155 int criticalExt = 0;
4157 if ((ret = DecodeToKey(cert, verify)) < 0) {
4158 if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E)
4164 CYASSL_MSG("Parsed Past Key");
4166 if (cert->srcIdx < cert->sigIndex) {
4167 #ifndef ALLOW_V1_EXTENSIONS
4168 if (cert->version < 2) {
4169 CYASSL_MSG(" v1 and v2 certs not allowed extensions");
4170 return ASN_VERSION_E;
4173 /* save extensions */
4174 cert->extensions = &cert->source[cert->srcIdx];
4175 cert->extensionsSz = cert->sigIndex - cert->srcIdx;
4176 cert->extensionsIdx = cert->srcIdx; /* for potential later use */
4178 if ((ret = DecodeCertExtensions(cert)) < 0) {
4179 if (ret == ASN_CRIT_EXT_E)
4185 /* advance past extensions */
4186 cert->srcIdx = cert->sigIndex;
4189 if ((ret = GetAlgoId(cert->source, &cert->srcIdx, &confirmOID,
4193 if ((ret = GetSignature(cert)) < 0)
4196 if (confirmOID != cert->signatureOID)
4197 return ASN_SIG_OID_E;
4200 if (cert->extSubjKeyIdSet == 0
4201 && cert->publicKey != NULL && cert->pubKeySize > 0) {
4203 ret = InitSha(&sha);
4206 ShaUpdate(&sha, cert->publicKey, cert->pubKeySize);
4207 ShaFinal(&sha, cert->extSubjKeyId);
4211 if (verify && type != CA_TYPE) {
4214 if (cert->extAuthKeyIdSet)
4215 ca = GetCA(cm, cert->extAuthKeyId);
4217 ca = GetCAByName(cm, cert->issuerHash);
4219 ca = GetCA(cm, cert->issuerHash);
4220 #endif /* NO SKID */
4221 CYASSL_MSG("About to verify certificate signature");
4225 /* Need the ca's public key hash for OCSP */
4228 ret = InitSha(&sha);
4231 ShaUpdate(&sha, ca->publicKey, ca->pubKeySize);
4232 ShaFinal(&sha, cert->issuerKeyHash);
4234 #endif /* HAVE_OCSP */
4235 /* try to confirm/verify signature */
4236 if (!ConfirmSignature(cert->source + cert->certBegin,
4237 cert->sigIndex - cert->certBegin,
4238 ca->publicKey, ca->pubKeySize, ca->keyOID,
4239 cert->signature, cert->sigLength, cert->signatureOID,
4241 CYASSL_MSG("Confirm signature failed");
4242 return ASN_SIG_CONFIRM_E;
4244 #ifndef IGNORE_NAME_CONSTRAINTS
4245 /* check that this cert's name is permitted by the signer's
4246 * name constraints */
4247 if (!ConfirmNameConstraints(ca, cert)) {
4248 CYASSL_MSG("Confirm name constraint failed");
4249 return ASN_NAME_INVALID_E;
4251 #endif /* IGNORE_NAME_CONSTRAINTS */
4255 CYASSL_MSG("No CA signer to verify with");
4256 return ASN_NO_SIGNER_E;
4263 if (criticalExt != 0)
4270 /* Create and init an new signer */
4271 Signer* MakeSigner(void* heap)
4273 Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
4274 DYNAMIC_TYPE_SIGNER);
4276 signer->pubKeySize = 0;
4278 signer->publicKey = NULL;
4279 signer->nameLen = 0;
4280 signer->name = NULL;
4281 #ifndef IGNORE_NAME_CONSTRAINTS
4282 signer->permittedNames = NULL;
4283 signer->excludedNames = NULL;
4284 #endif /* IGNORE_NAME_CONSTRAINTS */
4285 signer->next = NULL;
4293 /* Free an individual signer */
4294 void FreeSigner(Signer* signer, void* heap)
4296 XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
4297 XFREE(signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
4298 #ifndef IGNORE_NAME_CONSTRAINTS
4299 if (signer->permittedNames)
4300 FreeNameSubtrees(signer->permittedNames, heap);
4301 if (signer->excludedNames)
4302 FreeNameSubtrees(signer->excludedNames, heap);
4304 XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
4310 /* Free the whole singer table with number of rows */
4311 void FreeSignerTable(Signer** table, int rows, void* heap)
4315 for (i = 0; i < rows; i++) {
4316 Signer* signer = table[i];
4318 Signer* next = signer->next;
4319 FreeSigner(signer, heap);
4327 CYASSL_LOCAL int SetMyVersion(word32 version, byte* output, int header)
4332 output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
4333 output[i++] = ASN_BIT_STRING;
4335 output[i++] = ASN_INTEGER;
4337 output[i++] = (byte)version;
4343 CYASSL_LOCAL int SetSerialNumber(const byte* sn, word32 snSz, byte* output)
4347 CYASSL_ENTER("SetSerialNumber");
4349 if (snSz <= EXTERNAL_SERIAL_SIZE) {
4350 output[0] = ASN_INTEGER;
4351 /* The serial number is always positive. When encoding the
4352 * INTEGER, if the MSB is 1, add a padding zero to keep the
4353 * number positive. */
4355 output[1] = (byte)snSz + 1;
4357 XMEMCPY(&output[3], sn, snSz);
4361 output[1] = (byte)snSz;
4362 XMEMCPY(&output[2], sn, snSz);
4372 #if defined(CYASSL_KEY_GEN) || defined(CYASSL_CERT_GEN)
4374 /* convert der buffer to pem into output, can't do inplace, der and output
4375 need to be different */
4376 int DerToPem(const byte* der, word32 derSz, byte* output, word32 outSz,
4379 #ifdef CYASSL_SMALL_STACK
4380 char* header = NULL;
4381 char* footer = NULL;
4391 int outLen; /* return length or error */
4393 if (der == output) /* no in place conversion */
4394 return BAD_FUNC_ARG;
4396 #ifdef CYASSL_SMALL_STACK
4397 header = (char*)XMALLOC(headerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4401 footer = (char*)XMALLOC(footerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4402 if (footer == NULL) {
4403 XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4408 if (type == CERT_TYPE) {
4409 XSTRNCPY(header, "-----BEGIN CERTIFICATE-----\n", headerLen);
4410 XSTRNCPY(footer, "-----END CERTIFICATE-----\n", footerLen);
4412 else if (type == PRIVATEKEY_TYPE) {
4413 XSTRNCPY(header, "-----BEGIN RSA PRIVATE KEY-----\n", headerLen);
4414 XSTRNCPY(footer, "-----END RSA PRIVATE KEY-----\n", footerLen);
4417 else if (type == ECC_PRIVATEKEY_TYPE) {
4418 XSTRNCPY(header, "-----BEGIN EC PRIVATE KEY-----\n", headerLen);
4419 XSTRNCPY(footer, "-----END EC PRIVATE KEY-----\n", footerLen);
4422 #ifdef CYASSL_CERT_REQ
4423 else if (type == CERTREQ_TYPE)
4426 "-----BEGIN CERTIFICATE REQUEST-----\n", headerLen);
4427 XSTRNCPY(footer, "-----END CERTIFICATE REQUEST-----\n", footerLen);
4431 #ifdef CYASSL_SMALL_STACK
4432 XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4433 XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4435 return BAD_FUNC_ARG;
4438 headerLen = (int)XSTRLEN(header);
4439 footerLen = (int)XSTRLEN(footer);
4441 if (!der || !output) {
4442 #ifdef CYASSL_SMALL_STACK
4443 XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4444 XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4446 return BAD_FUNC_ARG;
4449 /* don't even try if outSz too short */
4450 if (outSz < headerLen + footerLen + derSz) {
4451 #ifdef CYASSL_SMALL_STACK
4452 XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4453 XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4455 return BAD_FUNC_ARG;
4459 XMEMCPY(output, header, headerLen);
4462 #ifdef CYASSL_SMALL_STACK
4463 XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4467 outLen = outSz - (headerLen + footerLen); /* input to Base64_Encode */
4468 if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0) {
4469 #ifdef CYASSL_SMALL_STACK
4470 XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4477 if ( (i + footerLen) > (int)outSz) {
4478 #ifdef CYASSL_SMALL_STACK
4479 XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4481 return BAD_FUNC_ARG;
4483 XMEMCPY(output + i, footer, footerLen);
4485 #ifdef CYASSL_SMALL_STACK
4486 XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4489 return outLen + headerLen + footerLen;
4493 #endif /* CYASSL_KEY_GEN || CYASSL_CERT_GEN */
4496 #if defined(CYASSL_KEY_GEN) && !defined(NO_RSA)
4499 static mp_int* GetRsaInt(RsaKey* key, int idx)
4522 /* Release Tmp RSA resources */
4523 static INLINE void FreeTmpRsas(byte** tmps, void* heap)
4529 for (i = 0; i < RSA_INTS; i++)
4530 XFREE(tmps[i], heap, DYNAMIC_TYPE_RSA);
4534 /* Convert RsaKey key to DER format, write to output (inLen), return bytes
4536 int RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
4538 word32 seqSz, verSz, rawLen, intTotalLen = 0;
4539 word32 sizes[RSA_INTS];
4540 int i, j, outLen, ret = 0;
4542 byte seq[MAX_SEQ_SZ];
4543 byte ver[MAX_VERSION_SZ];
4544 byte* tmps[RSA_INTS];
4546 if (!key || !output)
4547 return BAD_FUNC_ARG;
4549 if (key->type != RSA_PRIVATE)
4550 return BAD_FUNC_ARG;
4552 for (i = 0; i < RSA_INTS; i++)
4555 /* write all big ints from key to DER tmps */
4556 for (i = 0; i < RSA_INTS; i++) {
4557 mp_int* keyInt = GetRsaInt(key, i);
4558 rawLen = mp_unsigned_bin_size(keyInt);
4559 tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
4561 if (tmps[i] == NULL) {
4566 tmps[i][0] = ASN_INTEGER;
4567 sizes[i] = SetLength(rawLen, tmps[i] + 1) + 1; /* int tag */
4569 if (sizes[i] <= MAX_SEQ_SZ) {
4570 int err = mp_to_unsigned_bin(keyInt, tmps[i] + sizes[i]);
4571 if (err == MP_OKAY) {
4573 intTotalLen += sizes[i];
4587 FreeTmpRsas(tmps, key->heap);
4592 verSz = SetMyVersion(0, ver, FALSE);
4593 seqSz = SetSequence(verSz + intTotalLen, seq);
4595 outLen = seqSz + verSz + intTotalLen;
4596 if (outLen > (int)inLen)
4597 return BAD_FUNC_ARG;
4599 /* write to output */
4600 XMEMCPY(output, seq, seqSz);
4602 XMEMCPY(output + j, ver, verSz);
4605 for (i = 0; i < RSA_INTS; i++) {
4606 XMEMCPY(output + j, tmps[i], sizes[i]);
4609 FreeTmpRsas(tmps, key->heap);
4614 #endif /* CYASSL_KEY_GEN && !NO_RSA */
4617 #if defined(CYASSL_CERT_GEN) && !defined(NO_RSA)
4622 static INLINE word32 min(word32 a, word32 b)
4624 return a > b ? b : a;
4630 /* Initialize and Set Certficate defaults:
4633 sigType = SHA_WITH_RSA
4636 selfSigned = 1 (true) use subject as issuer
4639 void InitCert(Cert* cert)
4641 cert->version = 2; /* version 3 is hex 2 */
4642 cert->sigType = CTC_SHAwRSA;
4643 cert->daysValid = 500;
4644 cert->selfSigned = 1;
4647 #ifdef CYASSL_ALT_NAMES
4648 cert->altNamesSz = 0;
4649 cert->beforeDateSz = 0;
4650 cert->afterDateSz = 0;
4652 cert->keyType = RSA_KEY;
4653 XMEMSET(cert->serial, 0, CTC_SERIAL_SIZE);
4655 cert->issuer.country[0] = '\0';
4656 cert->issuer.countryEnc = CTC_PRINTABLE;
4657 cert->issuer.state[0] = '\0';
4658 cert->issuer.stateEnc = CTC_UTF8;
4659 cert->issuer.locality[0] = '\0';
4660 cert->issuer.localityEnc = CTC_UTF8;
4661 cert->issuer.sur[0] = '\0';
4662 cert->issuer.surEnc = CTC_UTF8;
4663 cert->issuer.org[0] = '\0';
4664 cert->issuer.orgEnc = CTC_UTF8;
4665 cert->issuer.unit[0] = '\0';
4666 cert->issuer.unitEnc = CTC_UTF8;
4667 cert->issuer.commonName[0] = '\0';
4668 cert->issuer.commonNameEnc = CTC_UTF8;
4669 cert->issuer.email[0] = '\0';
4671 cert->subject.country[0] = '\0';
4672 cert->subject.countryEnc = CTC_PRINTABLE;
4673 cert->subject.state[0] = '\0';
4674 cert->subject.stateEnc = CTC_UTF8;
4675 cert->subject.locality[0] = '\0';
4676 cert->subject.localityEnc = CTC_UTF8;
4677 cert->subject.sur[0] = '\0';
4678 cert->subject.surEnc = CTC_UTF8;
4679 cert->subject.org[0] = '\0';
4680 cert->subject.orgEnc = CTC_UTF8;
4681 cert->subject.unit[0] = '\0';
4682 cert->subject.unitEnc = CTC_UTF8;
4683 cert->subject.commonName[0] = '\0';
4684 cert->subject.commonNameEnc = CTC_UTF8;
4685 cert->subject.email[0] = '\0';
4687 #ifdef CYASSL_CERT_REQ
4688 cert->challengePw[0] ='\0';
4693 /* DER encoded x509 Certificate */
4694 typedef struct DerCert {
4695 byte size[MAX_LENGTH_SZ]; /* length encoded */
4696 byte version[MAX_VERSION_SZ]; /* version encoded */
4697 byte serial[CTC_SERIAL_SIZE + MAX_LENGTH_SZ]; /* serial number encoded */
4698 byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
4699 byte issuer[ASN_NAME_MAX]; /* issuer encoded */
4700 byte subject[ASN_NAME_MAX]; /* subject encoded */
4701 byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
4702 byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa / ntru public key encoded */
4703 byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
4704 byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
4705 #ifdef CYASSL_CERT_REQ
4706 byte attrib[MAX_ATTRIB_SZ]; /* Cert req attributes encoded */
4708 int sizeSz; /* encoded size length */
4709 int versionSz; /* encoded version length */
4710 int serialSz; /* encoded serial length */
4711 int sigAlgoSz; /* enocded sig alog length */
4712 int issuerSz; /* encoded issuer length */
4713 int subjectSz; /* encoded subject length */
4714 int validitySz; /* encoded validity length */
4715 int publicKeySz; /* encoded public key length */
4716 int caSz; /* encoded CA extension length */
4717 int extensionsSz; /* encoded extensions total length */
4718 int total; /* total encoded lengths */
4719 #ifdef CYASSL_CERT_REQ
4725 #ifdef CYASSL_CERT_REQ
4727 /* Write a set header to output */
4728 static word32 SetUTF8String(word32 len, byte* output)
4730 output[0] = ASN_UTF8STRING;
4731 return SetLength(len, output + 1) + 1;
4734 #endif /* CYASSL_CERT_REQ */
4737 /* Write a serial number to output */
4738 static int SetSerial(const byte* serial, byte* output)
4742 output[length++] = ASN_INTEGER;
4743 length += SetLength(CTC_SERIAL_SIZE, &output[length]);
4744 XMEMCPY(&output[length], serial, CTC_SERIAL_SIZE);
4746 return length + CTC_SERIAL_SIZE;
4752 /* Write a public ECC key to output */
4753 static int SetEccPublicKey(byte* output, ecc_key* key)
4755 byte len[MAX_LENGTH_SZ + 1]; /* trailing 0 */
4760 word32 pubSz = ECC_BUFSIZE;
4761 #ifdef CYASSL_SMALL_STACK
4766 byte algo[MAX_ALGO_SZ];
4767 byte curve[MAX_ALGO_SZ];
4768 byte pub[ECC_BUFSIZE];
4771 #ifdef CYASSL_SMALL_STACK
4772 pub = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4777 int ret = ecc_export_x963(key, pub, &pubSz);
4779 #ifdef CYASSL_SMALL_STACK
4780 XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4785 #ifdef CYASSL_SMALL_STACK
4786 curve = (byte*)XMALLOC(MAX_ALGO_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4787 if (curve == NULL) {
4788 XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4794 curveSz = SetCurve(key, curve);
4796 #ifdef CYASSL_SMALL_STACK
4797 XFREE(curve, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4798 XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4803 #ifdef CYASSL_SMALL_STACK
4804 algo = (byte*)XMALLOC(MAX_ALGO_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4806 XFREE(curve, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4807 XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4812 algoSz = SetAlgoID(ECDSAk, algo, keyType, curveSz);
4813 lenSz = SetLength(pubSz + 1, len);
4814 len[lenSz++] = 0; /* trailing 0 */
4817 idx = SetSequence(pubSz + curveSz + lenSz + 1 + algoSz, output);
4818 /* 1 is for ASN_BIT_STRING */
4820 XMEMCPY(output + idx, algo, algoSz);
4823 XMEMCPY(output + idx, curve, curveSz);
4826 output[idx++] = ASN_BIT_STRING;
4828 XMEMCPY(output + idx, len, lenSz);
4831 XMEMCPY(output + idx, pub, pubSz);
4834 #ifdef CYASSL_SMALL_STACK
4835 XFREE(algo, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4836 XFREE(curve, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4837 XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4844 #endif /* HAVE_ECC */
4847 /* Write a public RSA key to output */
4848 static int SetRsaPublicKey(byte* output, RsaKey* key)
4850 #ifdef CYASSL_SMALL_STACK
4855 byte n[MAX_RSA_INT_SZ];
4856 byte e[MAX_RSA_E_SZ];
4857 byte algo[MAX_ALGO_SZ];
4859 byte seq[MAX_SEQ_SZ];
4860 byte len[MAX_LENGTH_SZ + 1]; /* trailing 0 */
4872 #ifdef CYASSL_SMALL_STACK
4873 n = (byte*)XMALLOC(MAX_RSA_INT_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4878 leadingBit = mp_leading_bit(&key->n);
4879 rawLen = mp_unsigned_bin_size(&key->n) + leadingBit;
4881 nSz = SetLength(rawLen, n + 1) + 1; /* int tag */
4883 if ( (nSz + rawLen) < MAX_RSA_INT_SZ) {
4886 err = mp_to_unsigned_bin(&key->n, n + nSz + leadingBit);
4890 #ifdef CYASSL_SMALL_STACK
4891 XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4897 #ifdef CYASSL_SMALL_STACK
4898 XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4904 #ifdef CYASSL_SMALL_STACK
4905 e = (byte*)XMALLOC(MAX_RSA_E_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4907 #ifdef CYASSL_SMALL_STACK
4908 XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4914 leadingBit = mp_leading_bit(&key->e);
4915 rawLen = mp_unsigned_bin_size(&key->e) + leadingBit;
4917 eSz = SetLength(rawLen, e + 1) + 1; /* int tag */
4919 if ( (eSz + rawLen) < MAX_RSA_E_SZ) {
4922 err = mp_to_unsigned_bin(&key->e, e + eSz + leadingBit);
4926 #ifdef CYASSL_SMALL_STACK
4927 XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4928 XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4934 #ifdef CYASSL_SMALL_STACK
4935 XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4936 XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4941 #ifdef CYASSL_SMALL_STACK
4942 algo = (byte*)XMALLOC(MAX_ALGO_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4944 XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4945 XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4951 algoSz = SetAlgoID(RSAk, algo, keyType, 0);
4952 seqSz = SetSequence(nSz + eSz, seq);
4953 lenSz = SetLength(seqSz + nSz + eSz + 1, len);
4954 len[lenSz++] = 0; /* trailing 0 */
4957 idx = SetSequence(nSz + eSz + seqSz + lenSz + 1 + algoSz, output);
4958 /* 1 is for ASN_BIT_STRING */
4960 XMEMCPY(output + idx, algo, algoSz);
4963 output[idx++] = ASN_BIT_STRING;
4965 XMEMCPY(output + idx, len, lenSz);
4968 XMEMCPY(output + idx, seq, seqSz);
4971 XMEMCPY(output + idx, n, nSz);
4974 XMEMCPY(output + idx, e, eSz);
4977 #ifdef CYASSL_SMALL_STACK
4978 XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4979 XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4980 XFREE(algo, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4987 static INLINE byte itob(int number)
4989 return (byte)number + 0x30;
4993 /* write time to output, format */
4994 static void SetTime(struct tm* date, byte* output)
4998 output[i++] = itob((date->tm_year % 10000) / 1000);
4999 output[i++] = itob((date->tm_year % 1000) / 100);
5000 output[i++] = itob((date->tm_year % 100) / 10);
5001 output[i++] = itob( date->tm_year % 10);
5003 output[i++] = itob(date->tm_mon / 10);
5004 output[i++] = itob(date->tm_mon % 10);
5006 output[i++] = itob(date->tm_mday / 10);
5007 output[i++] = itob(date->tm_mday % 10);
5009 output[i++] = itob(date->tm_hour / 10);
5010 output[i++] = itob(date->tm_hour % 10);
5012 output[i++] = itob(date->tm_min / 10);
5013 output[i++] = itob(date->tm_min % 10);
5015 output[i++] = itob(date->tm_sec / 10);
5016 output[i++] = itob(date->tm_sec % 10);
5018 output[i] = 'Z'; /* Zulu profile */
5022 #ifdef CYASSL_ALT_NAMES
5024 /* Copy Dates from cert, return bytes written */
5025 static int CopyValidity(byte* output, Cert* cert)
5029 CYASSL_ENTER("CopyValidity");
5031 /* headers and output */
5032 seqSz = SetSequence(cert->beforeDateSz + cert->afterDateSz, output);
5033 XMEMCPY(output + seqSz, cert->beforeDate, cert->beforeDateSz);
5034 XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
5036 return seqSz + cert->beforeDateSz + cert->afterDateSz;
5042 /* Set Date validity from now until now + daysValid */
5043 static int SetValidity(byte* output, int daysValid)
5045 byte before[MAX_DATE_SIZE];
5046 byte after[MAX_DATE_SIZE];
5057 now = XGMTIME(&ticks);
5061 before[0] = ASN_GENERALIZED_TIME;
5062 beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
5064 /* subtract 1 day for more compliance */
5069 local.tm_year += 1900;
5072 SetTime(&local, before + beforeSz);
5073 beforeSz += ASN_GEN_TIME_SZ;
5075 /* after now + daysValid */
5077 after[0] = ASN_GENERALIZED_TIME;
5078 afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
5081 local.tm_mday += daysValid;
5085 local.tm_year += 1900;
5088 SetTime(&local, after + afterSz);
5089 afterSz += ASN_GEN_TIME_SZ;
5091 /* headers and output */
5092 seqSz = SetSequence(beforeSz + afterSz, output);
5093 XMEMCPY(output + seqSz, before, beforeSz);
5094 XMEMCPY(output + seqSz + beforeSz, after, afterSz);
5096 return seqSz + beforeSz + afterSz;
5100 /* ASN Encoded Name field */
5101 typedef struct EncodedName {
5102 int nameLen; /* actual string value length */
5103 int totalLen; /* total encoded length */
5104 int type; /* type of name */
5105 int used; /* are we actually using this one */
5106 byte encoded[CTC_NAME_SIZE * 2]; /* encoding */
5110 /* Get Which Name from index */
5111 static const char* GetOneName(CertName* name, int idx)
5115 return name->country;
5121 return name->locality;
5133 return name->commonName;
5144 /* Get Which Name Encoding from index */
5145 static char GetNameType(CertName* name, int idx)
5149 return name->countryEnc;
5152 return name->stateEnc;
5155 return name->localityEnc;
5158 return name->surEnc;
5161 return name->orgEnc;
5164 return name->unitEnc;
5167 return name->commonNameEnc;
5175 /* Get ASN Name from index */
5176 static byte GetNameId(int idx)
5180 return ASN_COUNTRY_NAME;
5183 return ASN_STATE_NAME;
5186 return ASN_LOCALITY_NAME;
5189 return ASN_SUR_NAME;
5192 return ASN_ORG_NAME;
5195 return ASN_ORGUNIT_NAME;
5198 return ASN_COMMON_NAME;
5201 /* email uses different id type */
5210 /* encode all extensions, return total bytes written */
5211 static int SetExtensions(byte* output, const byte* ext, int extSz, int header)
5213 byte sequence[MAX_SEQ_SZ];
5214 byte len[MAX_LENGTH_SZ];
5217 int seqSz = SetSequence(extSz, sequence);
5220 int lenSz = SetLength(seqSz + extSz, len);
5221 output[0] = ASN_EXTENSIONS; /* extensions id */
5223 XMEMCPY(&output[sz], len, lenSz); /* length */
5226 XMEMCPY(&output[sz], sequence, seqSz); /* sequence */
5228 XMEMCPY(&output[sz], ext, extSz); /* extensions */
5235 /* encode CA basic constraint true, return total bytes written */
5236 static int SetCa(byte* output)
5238 static const byte ca[] = { 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
5239 0x05, 0x30, 0x03, 0x01, 0x01, 0xff };
5241 XMEMCPY(output, ca, sizeof(ca));
5243 return (int)sizeof(ca);
5247 /* encode CertName into output, return total bytes written */
5248 static int SetName(byte* output, CertName* name)
5250 int totalBytes = 0, i, idx;
5251 #ifdef CYASSL_SMALL_STACK
5252 EncodedName* names = NULL;
5254 EncodedName names[NAME_ENTRIES];
5257 #ifdef CYASSL_SMALL_STACK
5258 names = (EncodedName*)XMALLOC(sizeof(EncodedName) * NAME_ENTRIES, NULL,
5259 DYNAMIC_TYPE_TMP_BUFFER);
5264 for (i = 0; i < NAME_ENTRIES; i++) {
5265 const char* nameStr = GetOneName(name, i);
5268 byte firstLen[MAX_LENGTH_SZ];
5269 byte secondLen[MAX_LENGTH_SZ];
5270 byte sequence[MAX_SEQ_SZ];
5271 byte set[MAX_SET_SZ];
5273 int email = i == (NAME_ENTRIES - 1) ? 1 : 0;
5274 int strLen = (int)XSTRLEN(nameStr);
5275 int thisLen = strLen;
5276 int firstSz, secondSz, seqSz, setSz;
5278 if (strLen == 0) { /* no user data for this item */
5283 secondSz = SetLength(strLen, secondLen);
5284 thisLen += secondSz;
5286 thisLen += EMAIL_JOINT_LEN;
5287 thisLen ++; /* id type */
5288 firstSz = SetLength(EMAIL_JOINT_LEN, firstLen);
5291 thisLen++; /* str type */
5292 thisLen++; /* id type */
5293 thisLen += JOINT_LEN;
5294 firstSz = SetLength(JOINT_LEN + 1, firstLen);
5297 thisLen++; /* object id */
5299 seqSz = SetSequence(thisLen, sequence);
5301 setSz = SetSet(thisLen, set);
5304 if (thisLen > (int)sizeof(names[i].encoded)) {
5305 #ifdef CYASSL_SMALL_STACK
5306 XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5314 XMEMCPY(names[i].encoded, set, setSz);
5317 XMEMCPY(names[i].encoded + idx, sequence, seqSz);
5320 names[i].encoded[idx++] = ASN_OBJECT_ID;
5322 XMEMCPY(names[i].encoded + idx, firstLen, firstSz);
5325 const byte EMAIL_OID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
5326 0x01, 0x09, 0x01, 0x16 };
5327 /* email joint id */
5328 XMEMCPY(names[i].encoded + idx, EMAIL_OID, sizeof(EMAIL_OID));
5329 idx += (int)sizeof(EMAIL_OID);
5333 byte bType = GetNameId(i);
5334 names[i].encoded[idx++] = 0x55;
5335 names[i].encoded[idx++] = 0x04;
5337 names[i].encoded[idx++] = bType;
5339 names[i].encoded[idx++] = GetNameType(name, i);
5342 XMEMCPY(names[i].encoded + idx, secondLen, secondSz);
5345 XMEMCPY(names[i].encoded + idx, nameStr, strLen);
5349 names[i].totalLen = idx;
5357 idx = SetSequence(totalBytes, output);
5359 if (totalBytes > ASN_NAME_MAX) {
5360 #ifdef CYASSL_SMALL_STACK
5361 XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5366 for (i = 0; i < NAME_ENTRIES; i++) {
5367 if (names[i].used) {
5368 XMEMCPY(output + idx, names[i].encoded, names[i].totalLen);
5369 idx += names[i].totalLen;
5373 #ifdef CYASSL_SMALL_STACK
5374 XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5380 /* encode info from cert into DER encoded format */
5381 static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey,
5382 RNG* rng, const byte* ntruKey, word16 ntruSz)
5391 XMEMSET(der, 0, sizeof(DerCert));
5394 der->versionSz = SetMyVersion(cert->version, der->version, TRUE);
5397 ret = RNG_GenerateBlock(rng, cert->serial, CTC_SERIAL_SIZE);
5401 cert->serial[0] = 0x01; /* ensure positive */
5402 der->serialSz = SetSerial(cert->serial, der->serial);
5404 /* signature algo */
5405 der->sigAlgoSz = SetAlgoID(cert->sigType, der->sigAlgo, sigType, 0);
5406 if (der->sigAlgoSz == 0)
5410 if (cert->keyType == RSA_KEY) {
5412 return PUBLIC_KEY_E;
5413 der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey);
5414 if (der->publicKeySz <= 0)
5415 return PUBLIC_KEY_E;
5419 if (cert->keyType == ECC_KEY) {
5421 return PUBLIC_KEY_E;
5422 der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey);
5423 if (der->publicKeySz <= 0)
5424 return PUBLIC_KEY_E;
5426 #endif /* HAVE_ECC */
5429 if (cert->keyType == NTRU_KEY) {
5433 rc = ntru_crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo( ntruSz,
5434 ntruKey, &encodedSz, NULL);
5436 return PUBLIC_KEY_E;
5437 if (encodedSz > MAX_PUBLIC_KEY_SZ)
5438 return PUBLIC_KEY_E;
5440 rc = ntru_crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo( ntruSz,
5441 ntruKey, &encodedSz, der->publicKey);
5443 return PUBLIC_KEY_E;
5445 der->publicKeySz = encodedSz;
5447 #endif /* HAVE_NTRU */
5449 der->validitySz = 0;
5450 #ifdef CYASSL_ALT_NAMES
5451 /* date validity copy ? */
5452 if (cert->beforeDateSz && cert->afterDateSz) {
5453 der->validitySz = CopyValidity(der->validity, cert);
5454 if (der->validitySz == 0)
5460 if (der->validitySz == 0) {
5461 der->validitySz = SetValidity(der->validity, cert->daysValid);
5462 if (der->validitySz == 0)
5467 der->subjectSz = SetName(der->subject, &cert->subject);
5468 if (der->subjectSz == 0)
5472 der->issuerSz = SetName(der->issuer, cert->selfSigned ?
5473 &cert->subject : &cert->issuer);
5474 if (der->issuerSz == 0)
5479 der->caSz = SetCa(der->ca);
5486 /* extensions, just CA now */
5488 der->extensionsSz = SetExtensions(der->extensions,
5489 der->ca, der->caSz, TRUE);
5490 if (der->extensionsSz == 0)
5491 return EXTENSIONS_E;
5494 der->extensionsSz = 0;
5496 #ifdef CYASSL_ALT_NAMES
5497 if (der->extensionsSz == 0 && cert->altNamesSz) {
5498 der->extensionsSz = SetExtensions(der->extensions, cert->altNames,
5499 cert->altNamesSz, TRUE);
5500 if (der->extensionsSz == 0)
5501 return EXTENSIONS_E;
5505 der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
5506 der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
5513 /* write DER encoded cert to buffer, size already checked */
5514 static int WriteCertBody(DerCert* der, byte* buffer)
5518 /* signed part header */
5519 idx = SetSequence(der->total, buffer);
5521 XMEMCPY(buffer + idx, der->version, der->versionSz);
5522 idx += der->versionSz;
5524 XMEMCPY(buffer + idx, der->serial, der->serialSz);
5525 idx += der->serialSz;
5527 XMEMCPY(buffer + idx, der->sigAlgo, der->sigAlgoSz);
5528 idx += der->sigAlgoSz;
5530 XMEMCPY(buffer + idx, der->issuer, der->issuerSz);
5531 idx += der->issuerSz;
5533 XMEMCPY(buffer + idx, der->validity, der->validitySz);
5534 idx += der->validitySz;
5536 XMEMCPY(buffer + idx, der->subject, der->subjectSz);
5537 idx += der->subjectSz;
5539 XMEMCPY(buffer + idx, der->publicKey, der->publicKeySz);
5540 idx += der->publicKeySz;
5541 if (der->extensionsSz) {
5543 XMEMCPY(buffer + idx, der->extensions, min(der->extensionsSz,
5544 sizeof(der->extensions)));
5545 idx += der->extensionsSz;
5552 /* Make RSA signature from buffer (sz), write to sig (sigSz) */
5553 static int MakeSignature(const byte* buffer, int sz, byte* sig, int sigSz,
5554 RsaKey* rsaKey, ecc_key* eccKey, RNG* rng,
5557 int encSigSz, digestSz, typeH = 0, ret = 0;
5558 byte digest[SHA256_DIGEST_SIZE]; /* max size */
5559 #ifdef CYASSL_SMALL_STACK
5562 byte encSig[MAX_ENCODED_DIG_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ];
5579 switch (sigAlgoType) {
5582 if ((ret = Md5Hash(buffer, sz, digest)) == 0) {
5584 digestSz = MD5_DIGEST_SIZE;
5591 if ((ret = ShaHash(buffer, sz, digest)) == 0) {
5593 digestSz = SHA_DIGEST_SIZE;
5598 case CTC_SHA256wRSA:
5599 case CTC_SHA256wECDSA:
5600 if ((ret = Sha256Hash(buffer, sz, digest)) == 0) {
5602 digestSz = SHA256_DIGEST_SIZE;
5607 CYASSL_MSG("MakeSignautre called with unsupported type");
5614 #ifdef CYASSL_SMALL_STACK
5615 encSig = (byte*)XMALLOC(MAX_ENCODED_DIG_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ,
5616 NULL, DYNAMIC_TYPE_TMP_BUFFER);
5626 encSigSz = EncodeSignature(encSig, digest, digestSz, typeH);
5627 ret = RsaSSL_Sign(encSig, encSigSz, sig, sigSz, rsaKey, rng);
5632 if (!rsaKey && eccKey) {
5633 word32 outSz = sigSz;
5634 ret = ecc_sign_hash(digest, digestSz, sig, &outSz, rng, eccKey);
5641 #ifdef CYASSL_SMALL_STACK
5642 XFREE(encSig, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5649 /* add signature to end of buffer, size of buffer assumed checked, return
5651 static int AddSignature(byte* buffer, int bodySz, const byte* sig, int sigSz,
5654 byte seq[MAX_SEQ_SZ];
5655 int idx = bodySz, seqSz;
5658 idx += SetAlgoID(sigAlgoType, buffer + idx, sigType, 0);
5660 buffer[idx++] = ASN_BIT_STRING;
5662 idx += SetLength(sigSz + 1, buffer + idx);
5663 buffer[idx++] = 0; /* trailing 0 */
5665 XMEMCPY(buffer + idx, sig, sigSz);
5668 /* make room for overall header */
5669 seqSz = SetSequence(idx, seq);
5670 XMEMMOVE(buffer + seqSz, buffer, idx);
5671 XMEMCPY(buffer, seq, seqSz);
5677 /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
5678 static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
5679 RsaKey* rsaKey, ecc_key* eccKey, RNG* rng,
5680 const byte* ntruKey, word16 ntruSz)
5683 #ifdef CYASSL_SMALL_STACK
5689 cert->keyType = eccKey ? ECC_KEY : (rsaKey ? RSA_KEY : NTRU_KEY);
5691 #ifdef CYASSL_SMALL_STACK
5692 der = (DerCert*)XMALLOC(sizeof(DerCert), NULL, DYNAMIC_TYPE_TMP_BUFFER);
5697 ret = EncodeCert(cert, der, rsaKey, eccKey, rng, ntruKey, ntruSz);
5700 if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
5703 ret = cert->bodySz = WriteCertBody(der, derBuffer);
5706 #ifdef CYASSL_SMALL_STACK
5707 XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5714 /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
5715 int MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,
5716 ecc_key* eccKey, RNG* rng)
5718 return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, 0);
5724 int MakeNtruCert(Cert* cert, byte* derBuffer, word32 derSz,
5725 const byte* ntruKey, word16 keySz, RNG* rng)
5727 return MakeAnyCert(cert, derBuffer, derSz, NULL, NULL, rng, ntruKey, keySz);
5730 #endif /* HAVE_NTRU */
5733 #ifdef CYASSL_CERT_REQ
5735 static int SetReqAttrib(byte* output, char* pw, int extSz)
5737 static const byte cpOid[] =
5738 { ASN_OBJECT_ID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01,
5740 static const byte erOid[] =
5741 { ASN_OBJECT_ID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01,
5744 int sz = 0; /* overall size */
5745 int cpSz = 0; /* Challenge Password section size */
5750 int erSz = 0; /* Extension Request section size */
5753 byte cpSeq[MAX_SEQ_SZ];
5754 byte cpSet[MAX_SET_SZ];
5755 byte cpStr[MAX_PRSTR_SZ];
5756 byte erSeq[MAX_SEQ_SZ];
5757 byte erSet[MAX_SET_SZ];
5763 pwSz = (int)XSTRLEN(pw);
5764 cpStrSz = SetUTF8String(pwSz, cpStr);
5765 cpSetSz = SetSet(cpStrSz + pwSz, cpSet);
5766 cpSeqSz = SetSequence(sizeof(cpOid) + cpSetSz + cpStrSz + pwSz, cpSeq);
5767 cpSz = cpSeqSz + sizeof(cpOid) + cpSetSz + cpStrSz + pwSz;
5771 erSetSz = SetSet(extSz, erSet);
5772 erSeqSz = SetSequence(erSetSz + sizeof(erOid) + extSz, erSeq);
5773 erSz = extSz + erSetSz + erSeqSz + sizeof(erOid);
5776 /* Put the pieces together. */
5777 sz += SetLength(cpSz + erSz, &output[sz]);
5780 XMEMCPY(&output[sz], cpSeq, cpSeqSz);
5782 XMEMCPY(&output[sz], cpOid, sizeof(cpOid));
5783 sz += sizeof(cpOid);
5784 XMEMCPY(&output[sz], cpSet, cpSetSz);
5786 XMEMCPY(&output[sz], cpStr, cpStrSz);
5788 XMEMCPY(&output[sz], pw, pwSz);
5793 XMEMCPY(&output[sz], erSeq, erSeqSz);
5795 XMEMCPY(&output[sz], erOid, sizeof(erOid));
5796 sz += sizeof(erOid);
5797 XMEMCPY(&output[sz], erSet, erSetSz);
5799 /* The actual extension data will be tacked onto the output later. */
5806 /* encode info from cert into DER encoded format */
5807 static int EncodeCertReq(Cert* cert, DerCert* der,
5808 RsaKey* rsaKey, ecc_key* eccKey)
5813 XMEMSET(der, 0, sizeof(DerCert));
5816 der->versionSz = SetMyVersion(cert->version, der->version, FALSE);
5819 der->subjectSz = SetName(der->subject, &cert->subject);
5820 if (der->subjectSz == 0)
5824 if (cert->keyType == RSA_KEY) {
5826 return PUBLIC_KEY_E;
5827 der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey);
5828 if (der->publicKeySz <= 0)
5829 return PUBLIC_KEY_E;
5833 if (cert->keyType == ECC_KEY) {
5835 return PUBLIC_KEY_E;
5836 der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey);
5837 if (der->publicKeySz <= 0)
5838 return PUBLIC_KEY_E;
5840 #endif /* HAVE_ECC */
5844 der->caSz = SetCa(der->ca);
5851 /* extensions, just CA now */
5853 der->extensionsSz = SetExtensions(der->extensions,
5854 der->ca, der->caSz, FALSE);
5855 if (der->extensionsSz == 0)
5856 return EXTENSIONS_E;
5859 der->extensionsSz = 0;
5861 der->attribSz = SetReqAttrib(der->attrib,
5862 cert->challengePw, der->extensionsSz);
5863 if (der->attribSz == 0)
5864 return REQ_ATTRIBUTE_E;
5866 der->total = der->versionSz + der->subjectSz + der->publicKeySz +
5867 der->extensionsSz + der->attribSz;
5873 /* write DER encoded cert req to buffer, size already checked */
5874 static int WriteCertReqBody(DerCert* der, byte* buffer)
5878 /* signed part header */
5879 idx = SetSequence(der->total, buffer);
5881 XMEMCPY(buffer + idx, der->version, der->versionSz);
5882 idx += der->versionSz;
5884 XMEMCPY(buffer + idx, der->subject, der->subjectSz);
5885 idx += der->subjectSz;
5887 XMEMCPY(buffer + idx, der->publicKey, der->publicKeySz);
5888 idx += der->publicKeySz;
5890 XMEMCPY(buffer + idx, der->attrib, der->attribSz);
5891 idx += der->attribSz;
5893 if (der->extensionsSz) {
5894 XMEMCPY(buffer + idx, der->extensions, min(der->extensionsSz,
5895 sizeof(der->extensions)));
5896 idx += der->extensionsSz;
5903 int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
5904 RsaKey* rsaKey, ecc_key* eccKey)
5907 #ifdef CYASSL_SMALL_STACK
5913 cert->keyType = eccKey ? ECC_KEY : RSA_KEY;
5915 #ifdef CYASSL_SMALL_STACK
5916 der = (DerCert*)XMALLOC(sizeof(DerCert), NULL, DYNAMIC_TYPE_TMP_BUFFER);
5921 ret = EncodeCertReq(cert, der, rsaKey, eccKey);
5924 if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
5927 ret = cert->bodySz = WriteCertReqBody(der, derBuffer);
5930 #ifdef CYASSL_SMALL_STACK
5931 XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5937 #endif /* CYASSL_CERT_REQ */
5940 int SignCert(int requestSz, int sType, byte* buffer, word32 buffSz,
5941 RsaKey* rsaKey, ecc_key* eccKey, RNG* rng)
5944 #ifdef CYASSL_SMALL_STACK
5947 byte sig[MAX_ENCODED_SIG_SZ];
5953 #ifdef CYASSL_SMALL_STACK
5954 sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5959 sigSz = MakeSignature(buffer, requestSz, sig, MAX_ENCODED_SIG_SZ, rsaKey,
5960 eccKey, rng, sType);
5963 if (requestSz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
5966 sigSz = AddSignature(buffer, requestSz, sig, sigSz, sType);
5969 #ifdef CYASSL_SMALL_STACK
5970 XFREE(sig, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5977 int MakeSelfCert(Cert* cert, byte* buffer, word32 buffSz, RsaKey* key, RNG* rng)
5979 int ret = MakeCert(cert, buffer, buffSz, key, NULL, rng);
5984 return SignCert(cert->bodySz, cert->sigType, buffer, buffSz, key, NULL,rng);
5988 #ifdef CYASSL_ALT_NAMES
5990 /* Set Alt Names from der cert, return 0 on success */
5991 static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz)
5994 #ifdef CYASSL_SMALL_STACK
5995 DecodedCert* decoded;
5997 DecodedCert decoded[1];
6003 #ifdef CYASSL_SMALL_STACK
6004 decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
6005 DYNAMIC_TYPE_TMP_BUFFER);
6006 if (decoded == NULL)
6010 InitDecodedCert(decoded, (byte*)der, derSz, 0);
6011 ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
6014 CYASSL_MSG("ParseCertRelative error");
6016 else if (decoded->extensions) {
6019 word32 maxExtensionsIdx;
6021 decoded->srcIdx = decoded->extensionsIdx;
6022 b = decoded->source[decoded->srcIdx++];
6024 if (b != ASN_EXTENSIONS) {
6027 else if (GetLength(decoded->source, &decoded->srcIdx, &length,
6028 decoded->maxIdx) < 0) {
6031 else if (GetSequence(decoded->source, &decoded->srcIdx, &length,
6032 decoded->maxIdx) < 0) {
6036 maxExtensionsIdx = decoded->srcIdx + length;
6038 while (decoded->srcIdx < maxExtensionsIdx) {
6040 word32 startIdx = decoded->srcIdx;
6043 if (GetSequence(decoded->source, &decoded->srcIdx, &length,
6044 decoded->maxIdx) < 0) {
6049 tmpIdx = decoded->srcIdx;
6050 decoded->srcIdx = startIdx;
6052 if (GetAlgoId(decoded->source, &decoded->srcIdx, &oid,
6053 decoded->maxIdx) < 0) {
6058 if (oid == ALT_NAMES_OID) {
6059 cert->altNamesSz = length + (tmpIdx - startIdx);
6061 if (cert->altNamesSz < (int)sizeof(cert->altNames))
6062 XMEMCPY(cert->altNames, &decoded->source[startIdx],
6065 cert->altNamesSz = 0;
6066 CYASSL_MSG("AltNames extensions too big");
6071 decoded->srcIdx = tmpIdx + length;
6076 FreeDecodedCert(decoded);
6077 #ifdef CYASSL_SMALL_STACK
6078 XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6081 return ret < 0 ? ret : 0;
6085 /* Set Dates from der cert, return 0 on success */
6086 static int SetDatesFromCert(Cert* cert, const byte* der, int derSz)
6089 #ifdef CYASSL_SMALL_STACK
6090 DecodedCert* decoded;
6092 DecodedCert decoded[1];
6095 CYASSL_ENTER("SetDatesFromCert");
6099 #ifdef CYASSL_SMALL_STACK
6100 decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
6101 DYNAMIC_TYPE_TMP_BUFFER);
6102 if (decoded == NULL)
6106 InitDecodedCert(decoded, (byte*)der, derSz, 0);
6107 ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
6110 CYASSL_MSG("ParseCertRelative error");
6112 else if (decoded->beforeDate == NULL || decoded->afterDate == NULL) {
6113 CYASSL_MSG("Couldn't extract dates");
6116 else if (decoded->beforeDateLen > MAX_DATE_SIZE ||
6117 decoded->afterDateLen > MAX_DATE_SIZE) {
6118 CYASSL_MSG("Bad date size");
6122 XMEMCPY(cert->beforeDate, decoded->beforeDate, decoded->beforeDateLen);
6123 XMEMCPY(cert->afterDate, decoded->afterDate, decoded->afterDateLen);
6125 cert->beforeDateSz = decoded->beforeDateLen;
6126 cert->afterDateSz = decoded->afterDateLen;
6129 FreeDecodedCert(decoded);
6131 #ifdef CYASSL_SMALL_STACK
6132 XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6135 return ret < 0 ? ret : 0;
6139 #endif /* CYASSL_ALT_NAMES && !NO_RSA */
6142 /* Set cn name from der buffer, return 0 on success */
6143 static int SetNameFromCert(CertName* cn, const byte* der, int derSz)
6146 #ifdef CYASSL_SMALL_STACK
6147 DecodedCert* decoded;
6149 DecodedCert decoded[1];
6155 #ifdef CYASSL_SMALL_STACK
6156 decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
6157 DYNAMIC_TYPE_TMP_BUFFER);
6158 if (decoded == NULL)
6162 InitDecodedCert(decoded, (byte*)der, derSz, 0);
6163 ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
6166 CYASSL_MSG("ParseCertRelative error");
6169 if (decoded->subjectCN) {
6170 sz = (decoded->subjectCNLen < CTC_NAME_SIZE) ? decoded->subjectCNLen
6171 : CTC_NAME_SIZE - 1;
6172 strncpy(cn->commonName, decoded->subjectCN, CTC_NAME_SIZE);
6173 cn->commonName[sz] = 0;
6174 cn->commonNameEnc = decoded->subjectCNEnc;
6176 if (decoded->subjectC) {
6177 sz = (decoded->subjectCLen < CTC_NAME_SIZE) ? decoded->subjectCLen
6178 : CTC_NAME_SIZE - 1;
6179 strncpy(cn->country, decoded->subjectC, CTC_NAME_SIZE);
6180 cn->country[sz] = 0;
6181 cn->countryEnc = decoded->subjectCEnc;
6183 if (decoded->subjectST) {
6184 sz = (decoded->subjectSTLen < CTC_NAME_SIZE) ? decoded->subjectSTLen
6185 : CTC_NAME_SIZE - 1;
6186 strncpy(cn->state, decoded->subjectST, CTC_NAME_SIZE);
6188 cn->stateEnc = decoded->subjectSTEnc;
6190 if (decoded->subjectL) {
6191 sz = (decoded->subjectLLen < CTC_NAME_SIZE) ? decoded->subjectLLen
6192 : CTC_NAME_SIZE - 1;
6193 strncpy(cn->locality, decoded->subjectL, CTC_NAME_SIZE);
6194 cn->locality[sz] = 0;
6195 cn->localityEnc = decoded->subjectLEnc;
6197 if (decoded->subjectO) {
6198 sz = (decoded->subjectOLen < CTC_NAME_SIZE) ? decoded->subjectOLen
6199 : CTC_NAME_SIZE - 1;
6200 strncpy(cn->org, decoded->subjectO, CTC_NAME_SIZE);
6202 cn->orgEnc = decoded->subjectOEnc;
6204 if (decoded->subjectOU) {
6205 sz = (decoded->subjectOULen < CTC_NAME_SIZE) ? decoded->subjectOULen
6206 : CTC_NAME_SIZE - 1;
6207 strncpy(cn->unit, decoded->subjectOU, CTC_NAME_SIZE);
6209 cn->unitEnc = decoded->subjectOUEnc;
6211 if (decoded->subjectSN) {
6212 sz = (decoded->subjectSNLen < CTC_NAME_SIZE) ? decoded->subjectSNLen
6213 : CTC_NAME_SIZE - 1;
6214 strncpy(cn->sur, decoded->subjectSN, CTC_NAME_SIZE);
6216 cn->surEnc = decoded->subjectSNEnc;
6218 if (decoded->subjectEmail) {
6219 sz = (decoded->subjectEmailLen < CTC_NAME_SIZE)
6220 ? decoded->subjectEmailLen : CTC_NAME_SIZE - 1;
6221 strncpy(cn->email, decoded->subjectEmail, CTC_NAME_SIZE);
6226 FreeDecodedCert(decoded);
6228 #ifdef CYASSL_SMALL_STACK
6229 XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6232 return ret < 0 ? ret : 0;
6236 #ifndef NO_FILESYSTEM
6238 /* forward from CyaSSL */
6239 int CyaSSL_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz);
6241 /* Set cert issuer from issuerFile in PEM */
6242 int SetIssuer(Cert* cert, const char* issuerFile)
6246 byte* der = (byte*)XMALLOC(EIGHTK_BUF, NULL, DYNAMIC_TYPE_CERT);
6249 CYASSL_MSG("SetIssuer OOF Problem");
6252 derSz = CyaSSL_PemCertToDer(issuerFile, der, EIGHTK_BUF);
6253 cert->selfSigned = 0;
6254 ret = SetNameFromCert(&cert->issuer, der, derSz);
6255 XFREE(der, NULL, DYNAMIC_TYPE_CERT);
6261 /* Set cert subject from subjectFile in PEM */
6262 int SetSubject(Cert* cert, const char* subjectFile)
6266 byte* der = (byte*)XMALLOC(EIGHTK_BUF, NULL, DYNAMIC_TYPE_CERT);
6269 CYASSL_MSG("SetSubject OOF Problem");
6272 derSz = CyaSSL_PemCertToDer(subjectFile, der, EIGHTK_BUF);
6273 ret = SetNameFromCert(&cert->subject, der, derSz);
6274 XFREE(der, NULL, DYNAMIC_TYPE_CERT);
6280 #ifdef CYASSL_ALT_NAMES
6282 /* Set atl names from file in PEM */
6283 int SetAltNames(Cert* cert, const char* file)
6287 byte* der = (byte*)XMALLOC(EIGHTK_BUF, NULL, DYNAMIC_TYPE_CERT);
6290 CYASSL_MSG("SetAltNames OOF Problem");
6293 derSz = CyaSSL_PemCertToDer(file, der, EIGHTK_BUF);
6294 ret = SetAltNamesFromCert(cert, der, derSz);
6295 XFREE(der, NULL, DYNAMIC_TYPE_CERT);
6300 #endif /* CYASSL_ALT_NAMES */
6302 #endif /* NO_FILESYSTEM */
6304 /* Set cert issuer from DER buffer */
6305 int SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
6307 cert->selfSigned = 0;
6308 return SetNameFromCert(&cert->issuer, der, derSz);
6312 /* Set cert subject from DER buffer */
6313 int SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
6315 return SetNameFromCert(&cert->subject, der, derSz);
6319 #ifdef CYASSL_ALT_NAMES
6321 /* Set cert alt names from DER buffer */
6322 int SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
6324 return SetAltNamesFromCert(cert, der, derSz);
6327 /* Set cert dates from DER buffer */
6328 int SetDatesBuffer(Cert* cert, const byte* der, int derSz)
6330 return SetDatesFromCert(cert, der, derSz);
6333 #endif /* CYASSL_ALT_NAMES */
6335 #endif /* CYASSL_CERT_GEN */
6340 /* Der Encode r & s ints into out, outLen is (in/out) size */
6341 int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
6344 word32 rSz; /* encoding size */
6346 word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
6348 /* If the leading bit on the INTEGER is a 1, add a leading zero */
6349 int rLeadingZero = mp_leading_bit(r);
6350 int sLeadingZero = mp_leading_bit(s);
6351 int rLen = mp_unsigned_bin_size(r); /* big int size */
6352 int sLen = mp_unsigned_bin_size(s);
6355 if (*outLen < (rLen + rLeadingZero + sLen + sLeadingZero +
6356 headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
6357 return BAD_FUNC_ARG;
6359 idx = SetSequence(rLen+rLeadingZero+sLen+sLeadingZero+headerSz, out);
6362 out[idx++] = ASN_INTEGER;
6363 rSz = SetLength(rLen + rLeadingZero, &out[idx]);
6367 err = mp_to_unsigned_bin(r, &out[idx]);
6368 if (err != MP_OKAY) return err;
6372 out[idx++] = ASN_INTEGER;
6373 sSz = SetLength(sLen + sLeadingZero, &out[idx]);
6377 err = mp_to_unsigned_bin(s, &out[idx]);
6378 if (err != MP_OKAY) return err;
6387 /* Der Decode ECC-DSA Signautre, r & s stored as big ints */
6388 int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
6393 if (GetSequence(sig, &idx, &len, sigLen) < 0)
6394 return ASN_ECC_KEY_E;
6396 if ((word32)len > (sigLen - idx))
6397 return ASN_ECC_KEY_E;
6399 if (GetInt(r, sig, &idx, sigLen) < 0)
6400 return ASN_ECC_KEY_E;
6402 if (GetInt(s, sig, &idx, sigLen) < 0)
6403 return ASN_ECC_KEY_E;
6409 int EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
6413 int version, length;
6417 #ifdef CYASSL_SMALL_STACK
6421 byte priv[ECC_MAXSIZE];
6422 byte pub[ECC_MAXSIZE * 2 + 1]; /* public key has two parts plus header */
6425 if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
6426 return BAD_FUNC_ARG;
6428 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
6431 if (GetMyVersion(input, inOutIdx, &version) < 0)
6434 b = input[*inOutIdx];
6438 if (b != 4 && b != 6 && b != 7)
6441 if (GetLength(input, inOutIdx, &length, inSz) < 0)
6444 #ifdef CYASSL_SMALL_STACK
6445 priv = (byte*)XMALLOC(ECC_MAXSIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6449 pub = (byte*)XMALLOC(ECC_MAXSIZE * 2 + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6451 XFREE(priv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6458 XMEMCPY(priv, &input[*inOutIdx], privSz);
6459 *inOutIdx += length;
6461 /* prefix 0, may have */
6462 b = input[*inOutIdx];
6463 if (b == ECC_PREFIX_0) {
6466 if (GetLength(input, inOutIdx, &length, inSz) < 0)
6470 b = input[*inOutIdx];
6473 if (b != ASN_OBJECT_ID) {
6474 ret = ASN_OBJECT_ID_E;
6476 else if (GetLength(input, inOutIdx, &length, inSz) < 0) {
6481 oid += input[*inOutIdx];
6484 if (CheckCurve(oid) < 0)
6485 ret = ECC_CURVE_OID_E;
6492 b = input[*inOutIdx];
6495 if (b != ECC_PREFIX_1) {
6496 ret = ASN_ECC_KEY_E;
6498 else if (GetLength(input, inOutIdx, &length, inSz) < 0) {
6503 b = input[*inOutIdx];
6506 if (b != ASN_BIT_STRING) {
6509 else if (GetLength(input, inOutIdx, &length, inSz) < 0) {
6513 b = input[*inOutIdx];
6517 ret = ASN_EXPECT_0_E;
6521 pubSz = length - 1; /* null prefix */
6522 XMEMCPY(pub, &input[*inOutIdx], pubSz);
6524 *inOutIdx += length;
6526 ret = ecc_import_private_key(priv, privSz, pub, pubSz, key);
6532 #ifdef CYASSL_SMALL_STACK
6533 XFREE(priv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6534 XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6540 #endif /* HAVE_ECC */
6543 #if defined(HAVE_OCSP) || defined(HAVE_CRL)
6545 /* Get raw Date only, no processing, 0 on success */
6546 static int GetBasicDate(const byte* source, word32* idx, byte* date,
6547 byte* format, int maxIdx)
6551 CYASSL_ENTER("GetBasicDate");
6553 *format = source[*idx];
6555 if (*format != ASN_UTC_TIME && *format != ASN_GENERALIZED_TIME)
6558 if (GetLength(source, idx, &length, maxIdx) < 0)
6561 if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
6562 return ASN_DATE_SZ_E;
6564 XMEMCPY(date, &source[*idx], length);
6575 static int GetEnumerated(const byte* input, word32* inOutIdx, int *value)
6577 word32 idx = *inOutIdx;
6580 CYASSL_ENTER("GetEnumerated");
6584 if (input[idx++] != ASN_ENUMERATED)
6592 *value = *value << 8 | input[idx++];
6601 static int DecodeSingleResponse(byte* source,
6602 word32* ioIndex, OcspResponse* resp, word32 size)
6604 word32 idx = *ioIndex, prevIndex, oid;
6605 int length, wrapperSz;
6606 CertStatus* cs = resp->status;
6608 CYASSL_ENTER("DecodeSingleResponse");
6610 /* Outer wrapper of the SEQUENCE OF Single Responses. */
6611 if (GetSequence(source, &idx, &wrapperSz, size) < 0)
6616 /* When making a request, we only request one status on one certificate
6617 * at a time. There should only be one SingleResponse */
6619 /* Wrapper around the Single Response */
6620 if (GetSequence(source, &idx, &length, size) < 0)
6623 /* Wrapper around the CertID */
6624 if (GetSequence(source, &idx, &length, size) < 0)
6626 /* Skip the hash algorithm */
6627 if (GetAlgoId(source, &idx, &oid, size) < 0)
6629 /* Save reference to the hash of CN */
6630 if (source[idx++] != ASN_OCTET_STRING)
6632 if (GetLength(source, &idx, &length, size) < 0)
6634 resp->issuerHash = source + idx;
6636 /* Save reference to the hash of the issuer public key */
6637 if (source[idx++] != ASN_OCTET_STRING)
6639 if (GetLength(source, &idx, &length, size) < 0)
6641 resp->issuerKeyHash = source + idx;
6644 /* Read the serial number, it is handled as a string, not as a
6645 * proper number. Just XMEMCPY the data over, rather than load it
6647 if (source[idx++] != ASN_INTEGER)
6649 if (GetLength(source, &idx, &length, size) < 0)
6651 if (length <= EXTERNAL_SERIAL_SIZE)
6653 if (source[idx] == 0)
6658 XMEMCPY(cs->serial, source + idx, length);
6659 cs->serialSz = length;
6663 return ASN_GETINT_E;
6668 switch (source[idx++])
6670 case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
6671 cs->status = CERT_GOOD;
6674 case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
6675 cs->status = CERT_REVOKED;
6676 if (GetLength(source, &idx, &length, size) < 0)
6680 case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
6681 cs->status = CERT_UNKNOWN;
6688 if (GetBasicDate(source, &idx, cs->thisDate,
6689 &cs->thisDateFormat, size) < 0)
6691 if (!XVALIDATE_DATE(cs->thisDate, cs->thisDateFormat, BEFORE))
6692 return ASN_BEFORE_DATE_E;
6694 /* The following items are optional. Only check for them if there is more
6695 * unprocessed data in the singleResponse wrapper. */
6697 if (((int)(idx - prevIndex) < wrapperSz) &&
6698 (source[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0)))
6701 if (GetLength(source, &idx, &length, size) < 0)
6703 if (GetBasicDate(source, &idx, cs->nextDate,
6704 &cs->nextDateFormat, size) < 0)
6707 if (((int)(idx - prevIndex) < wrapperSz) &&
6708 (source[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1)))
6711 if (GetLength(source, &idx, &length, size) < 0)
6721 static int DecodeOcspRespExtensions(byte* source,
6722 word32* ioIndex, OcspResponse* resp, word32 sz)
6724 word32 idx = *ioIndex;
6726 int ext_bound; /* boundary index for the sequence of extensions */
6729 CYASSL_ENTER("DecodeOcspRespExtensions");
6731 if (source[idx++] != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
6734 if (GetLength(source, &idx, &length, sz) < 0) return ASN_PARSE_E;
6736 if (GetSequence(source, &idx, &length, sz) < 0) return ASN_PARSE_E;
6738 ext_bound = idx + length;
6740 while (idx < (word32)ext_bound) {
6741 if (GetSequence(source, &idx, &length, sz) < 0) {
6742 CYASSL_MSG("\tfail: should be a SEQUENCE");
6747 if (GetObjectId(source, &idx, &oid, sz) < 0) {
6748 CYASSL_MSG("\tfail: OBJECT ID");
6752 /* check for critical flag */
6753 if (source[idx] == ASN_BOOLEAN) {
6754 CYASSL_MSG("\tfound optional critical flag, moving past");
6755 idx += (ASN_BOOL_SIZE + 1);
6758 /* process the extension based on the OID */
6759 if (source[idx++] != ASN_OCTET_STRING) {
6760 CYASSL_MSG("\tfail: should be an OCTET STRING");
6764 if (GetLength(source, &idx, &length, sz) < 0) {
6765 CYASSL_MSG("\tfail: extension data length");
6769 if (oid == OCSP_NONCE_OID) {
6770 resp->nonce = source + idx;
6771 resp->nonceSz = length;
6782 static int DecodeResponseData(byte* source,
6783 word32* ioIndex, OcspResponse* resp, word32 size)
6785 word32 idx = *ioIndex, prev_idx;
6788 word32 responderId = 0;
6790 CYASSL_ENTER("DecodeResponseData");
6792 resp->response = source + idx;
6794 if (GetSequence(source, &idx, &length, size) < 0)
6796 resp->responseSz = length + idx - prev_idx;
6798 /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
6799 * item isn't an EXPLICIT[0], then set version to zero and move
6800 * onto the next item.
6802 if (source[idx] == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
6804 idx += 2; /* Eat the value and length */
6805 if (GetMyVersion(source, &idx, &version) < 0)
6810 responderId = source[idx++];
6811 if ((responderId == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) ||
6812 (responderId == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)))
6814 if (GetLength(source, &idx, &length, size) < 0)
6821 /* save pointer to the producedAt time */
6822 if (GetBasicDate(source, &idx, resp->producedDate,
6823 &resp->producedDateFormat, size) < 0)
6826 if (DecodeSingleResponse(source, &idx, resp, size) < 0)
6829 if (DecodeOcspRespExtensions(source, &idx, resp, size) < 0)
6837 static int DecodeCerts(byte* source,
6838 word32* ioIndex, OcspResponse* resp, word32 size)
6840 word32 idx = *ioIndex;
6842 CYASSL_ENTER("DecodeCerts");
6844 if (source[idx++] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
6848 if (GetLength(source, &idx, &length, size) < 0)
6851 if (GetSequence(source, &idx, &length, size) < 0)
6854 resp->cert = source + idx;
6855 resp->certSz = length;
6863 static int DecodeBasicOcspResponse(byte* source,
6864 word32* ioIndex, OcspResponse* resp, word32 size)
6867 word32 idx = *ioIndex;
6870 CYASSL_ENTER("DecodeBasicOcspResponse");
6872 if (GetSequence(source, &idx, &length, size) < 0)
6875 if (idx + length > size)
6877 end_index = idx + length;
6879 if (DecodeResponseData(source, &idx, resp, size) < 0)
6882 /* Get the signature algorithm */
6883 if (GetAlgoId(source, &idx, &resp->sigOID, size) < 0)
6886 /* Obtain pointer to the start of the signature, and save the size */
6887 if (source[idx++] == ASN_BIT_STRING)
6890 if (GetLength(source, &idx, &sigLength, size) < 0)
6892 resp->sigSz = sigLength;
6893 resp->sig = source + idx;
6898 * Check the length of the BasicOcspResponse against the current index to
6899 * see if there are certificates, they are optional.
6901 if (idx < end_index)
6906 if (DecodeCerts(source, &idx, resp, size) < 0)
6909 InitDecodedCert(&cert, resp->cert, resp->certSz, 0);
6910 ret = ParseCertRelative(&cert, CA_TYPE, NO_VERIFY, 0);
6914 ret = ConfirmSignature(resp->response, resp->responseSz,
6915 cert.publicKey, cert.pubKeySize, cert.keyOID,
6916 resp->sig, resp->sigSz, resp->sigOID, NULL);
6917 FreeDecodedCert(&cert);
6921 CYASSL_MSG("\tOCSP Confirm signature failed");
6922 return ASN_OCSP_CONFIRM_E;
6931 void InitOcspResponse(OcspResponse* resp, CertStatus* status,
6932 byte* source, word32 inSz)
6934 CYASSL_ENTER("InitOcspResponse");
6936 resp->responseStatus = -1;
6937 resp->response = NULL;
6938 resp->responseSz = 0;
6939 resp->producedDateFormat = 0;
6940 resp->issuerHash = NULL;
6941 resp->issuerKeyHash = NULL;
6945 resp->status = status;
6948 resp->source = source;
6949 resp->maxIdx = inSz;
6953 int OcspResponseDecode(OcspResponse* resp)
6957 byte* source = resp->source;
6958 word32 size = resp->maxIdx;
6961 CYASSL_ENTER("OcspResponseDecode");
6963 /* peel the outer SEQUENCE wrapper */
6964 if (GetSequence(source, &idx, &length, size) < 0)
6967 /* First get the responseStatus, an ENUMERATED */
6968 if (GetEnumerated(source, &idx, &resp->responseStatus) < 0)
6971 if (resp->responseStatus != OCSP_SUCCESSFUL)
6974 /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
6977 if (source[idx++] != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
6979 if (GetLength(source, &idx, &length, size) < 0)
6982 /* Get the responseBytes SEQUENCE */
6983 if (GetSequence(source, &idx, &length, size) < 0)
6986 /* Check ObjectID for the resposeBytes */
6987 if (GetObjectId(source, &idx, &oid, size) < 0)
6989 if (oid != OCSP_BASIC_OID)
6991 if (source[idx++] != ASN_OCTET_STRING)
6994 if (GetLength(source, &idx, &length, size) < 0)
6997 if (DecodeBasicOcspResponse(source, &idx, resp, size) < 0)
7004 static word32 SetOcspReqExtensions(word32 extSz, byte* output,
7005 const byte* nonce, word32 nonceSz)
7007 static const byte NonceObjId[] = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07,
7009 byte seqArray[5][MAX_SEQ_SZ];
7010 word32 seqSz[5], totalSz;
7012 CYASSL_ENTER("SetOcspReqExtensions");
7014 if (nonce == NULL || nonceSz == 0) return 0;
7016 seqArray[0][0] = ASN_OCTET_STRING;
7017 seqSz[0] = 1 + SetLength(nonceSz, &seqArray[0][1]);
7019 seqArray[1][0] = ASN_OBJECT_ID;
7020 seqSz[1] = 1 + SetLength(sizeof(NonceObjId), &seqArray[1][1]);
7022 totalSz = seqSz[0] + seqSz[1] + nonceSz + (word32)sizeof(NonceObjId);
7024 seqSz[2] = SetSequence(totalSz, seqArray[2]);
7025 totalSz += seqSz[2];
7027 seqSz[3] = SetSequence(totalSz, seqArray[3]);
7028 totalSz += seqSz[3];
7030 seqArray[4][0] = (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2);
7031 seqSz[4] = 1 + SetLength(totalSz, &seqArray[4][1]);
7032 totalSz += seqSz[4];
7034 if (totalSz < extSz)
7037 XMEMCPY(output + totalSz, seqArray[4], seqSz[4]);
7038 totalSz += seqSz[4];
7039 XMEMCPY(output + totalSz, seqArray[3], seqSz[3]);
7040 totalSz += seqSz[3];
7041 XMEMCPY(output + totalSz, seqArray[2], seqSz[2]);
7042 totalSz += seqSz[2];
7043 XMEMCPY(output + totalSz, seqArray[1], seqSz[1]);
7044 totalSz += seqSz[1];
7045 XMEMCPY(output + totalSz, NonceObjId, sizeof(NonceObjId));
7046 totalSz += (word32)sizeof(NonceObjId);
7047 XMEMCPY(output + totalSz, seqArray[0], seqSz[0]);
7048 totalSz += seqSz[0];
7049 XMEMCPY(output + totalSz, nonce, nonceSz);
7057 int EncodeOcspRequest(OcspRequest* req)
7059 byte seqArray[5][MAX_SEQ_SZ];
7060 /* The ASN.1 of the OCSP Request is an onion of sequences */
7061 byte algoArray[MAX_ALGO_SZ];
7062 byte issuerArray[MAX_ENCODED_DIG_SZ];
7063 byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
7064 byte snArray[MAX_SN_SZ];
7065 byte extArray[MAX_OCSP_EXT_SZ];
7066 byte* output = req->dest;
7067 word32 seqSz[5], algoSz, issuerSz, issuerKeySz, snSz, extSz, totalSz;
7070 CYASSL_ENTER("EncodeOcspRequest");
7072 algoSz = SetAlgoID(SHAh, algoArray, hashType, 0);
7074 req->issuerHash = req->cert->issuerHash;
7075 issuerSz = SetDigest(req->cert->issuerHash, SHA_SIZE, issuerArray);
7077 req->issuerKeyHash = req->cert->issuerKeyHash;
7078 issuerKeySz = SetDigest(req->cert->issuerKeyHash, SHA_SIZE, issuerKeyArray);
7080 req->serial = req->cert->serial;
7081 req->serialSz = req->cert->serialSz;
7082 snSz = SetSerialNumber(req->cert->serial, req->cert->serialSz, snArray);
7085 if (req->useNonce) {
7087 if (InitRng(&rng) != 0) {
7088 CYASSL_MSG("\tCannot initialize RNG. Skipping the OSCP Nonce.");
7090 if (RNG_GenerateBlock(&rng, req->nonce, MAX_OCSP_NONCE_SZ) != 0)
7091 CYASSL_MSG("\tCannot run RNG. Skipping the OSCP Nonce.");
7093 req->nonceSz = MAX_OCSP_NONCE_SZ;
7094 extSz = SetOcspReqExtensions(MAX_OCSP_EXT_SZ, extArray,
7095 req->nonce, req->nonceSz);
7100 totalSz = algoSz + issuerSz + issuerKeySz + snSz;
7102 for (i = 4; i >= 0; i--) {
7103 seqSz[i] = SetSequence(totalSz, seqArray[i]);
7104 totalSz += seqSz[i];
7105 if (i == 2) totalSz += extSz;
7108 for (i = 0; i < 5; i++) {
7109 XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
7110 totalSz += seqSz[i];
7112 XMEMCPY(output + totalSz, algoArray, algoSz);
7114 XMEMCPY(output + totalSz, issuerArray, issuerSz);
7115 totalSz += issuerSz;
7116 XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
7117 totalSz += issuerKeySz;
7118 XMEMCPY(output + totalSz, snArray, snSz);
7121 XMEMCPY(output + totalSz, extArray, extSz);
7129 void InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce,
7130 byte* dest, word32 destSz)
7132 CYASSL_ENTER("InitOcspRequest");
7135 req->useNonce = useNonce;
7137 req->issuerHash = NULL;
7138 req->issuerKeyHash = NULL;
7141 req->destSz = destSz;
7145 int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
7149 CYASSL_ENTER("CompareOcspReqResp");
7153 CYASSL_MSG("\tReq missing");
7159 CYASSL_MSG("\tResp missing");
7163 /* Nonces are not critical. The responder may not necessarily add
7164 * the nonce to the response. */
7165 if (req->useNonce && resp->nonceSz != 0) {
7166 cmp = req->nonceSz - resp->nonceSz;
7169 CYASSL_MSG("\tnonceSz mismatch");
7173 cmp = XMEMCMP(req->nonce, resp->nonce, req->nonceSz);
7176 CYASSL_MSG("\tnonce mismatch");
7181 cmp = XMEMCMP(req->issuerHash, resp->issuerHash, SHA_DIGEST_SIZE);
7184 CYASSL_MSG("\tissuerHash mismatch");
7188 cmp = XMEMCMP(req->issuerKeyHash, resp->issuerKeyHash, SHA_DIGEST_SIZE);
7191 CYASSL_MSG("\tissuerKeyHash mismatch");
7195 cmp = req->serialSz - resp->status->serialSz;
7198 CYASSL_MSG("\tserialSz mismatch");
7202 cmp = XMEMCMP(req->serial, resp->status->serial, req->serialSz);
7205 CYASSL_MSG("\tserial mismatch");
7215 /* store SHA1 hash of NAME */
7216 CYASSL_LOCAL int GetNameHash(const byte* source, word32* idx, byte* hash,
7220 int length; /* length of all distinguished names */
7224 CYASSL_ENTER("GetNameHash");
7226 if (source[*idx] == ASN_OBJECT_ID) {
7227 CYASSL_MSG("Trying optional prefix...");
7229 if (GetLength(source, idx, &length, maxIdx) < 0)
7233 CYASSL_MSG("Got optional prefix");
7236 /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
7237 * calculated over the entire DER encoding of the Name field, including
7238 * the tag and length. */
7240 if (GetSequence(source, idx, &length, maxIdx) < 0)
7243 ret = InitSha(&sha);
7246 ShaUpdate(&sha, source + dummy, length + *idx - dummy);
7247 ShaFinal(&sha, hash);
7257 /* initialize decoded CRL */
7258 void InitDecodedCRL(DecodedCRL* dcrl)
7260 CYASSL_MSG("InitDecodedCRL");
7262 dcrl->certBegin = 0;
7264 dcrl->sigLength = 0;
7265 dcrl->signatureOID = 0;
7267 dcrl->totalCerts = 0;
7271 /* free decoded CRL resources */
7272 void FreeDecodedCRL(DecodedCRL* dcrl)
7274 RevokedCert* tmp = dcrl->certs;
7276 CYASSL_MSG("FreeDecodedCRL");
7279 RevokedCert* next = tmp->next;
7280 XFREE(tmp, NULL, DYNAMIC_TYPE_REVOKED);
7286 /* Get Revoked Cert list, 0 on success */
7287 static int GetRevoked(const byte* buff, word32* idx, DecodedCRL* dcrl,
7295 CYASSL_ENTER("GetRevoked");
7297 if (GetSequence(buff, idx, &len, maxIdx) < 0)
7302 /* get serial number */
7306 if (b != ASN_INTEGER) {
7307 CYASSL_MSG("Expecting Integer");
7311 if (GetLength(buff, idx, &len, maxIdx) < 0)
7314 if (len > EXTERNAL_SERIAL_SIZE) {
7315 CYASSL_MSG("Serial Size too big");
7319 rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), NULL, DYNAMIC_TYPE_CRL);
7321 CYASSL_MSG("Alloc Revoked Cert failed");
7325 XMEMCPY(rc->serialNumber, &buff[*idx], len);
7329 rc->next = dcrl->certs;
7339 if (b != ASN_UTC_TIME && b != ASN_GENERALIZED_TIME) {
7340 CYASSL_MSG("Expecting Date");
7344 if (GetLength(buff, idx, &len, maxIdx) < 0)
7350 if (*idx != end) /* skip extensions */
7357 /* Get CRL Signature, 0 on success */
7358 static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
7364 CYASSL_ENTER("GetCRL_Signature");
7368 if (b != ASN_BIT_STRING)
7369 return ASN_BITSTR_E;
7371 if (GetLength(source, idx, &length, maxIdx) < 0)
7374 dcrl->sigLength = length;
7379 return ASN_EXPECT_0_E;
7382 dcrl->signature = (byte*)&source[*idx];
7384 *idx += dcrl->sigLength;
7390 /* prase crl buffer into decoded state, 0 on success */
7391 int ParseCRL(DecodedCRL* dcrl, const byte* buff, word32 sz, void* cm)
7394 word32 oid, idx = 0;
7397 CYASSL_MSG("ParseCRL");
7400 /* hash here if needed for optimized comparisons
7403 * ShaUpdate(&sha, buff, sz);
7404 * ShaFinal(&sha, dcrl->crlHash); */
7406 if (GetSequence(buff, &idx, &len, sz) < 0)
7409 dcrl->certBegin = idx;
7411 if (GetSequence(buff, &idx, &len, sz) < 0)
7413 dcrl->sigIndex = len + idx;
7415 /* may have version */
7416 if (buff[idx] == ASN_INTEGER) {
7417 if (GetMyVersion(buff, &idx, &version) < 0)
7421 if (GetAlgoId(buff, &idx, &oid, sz) < 0)
7424 if (GetNameHash(buff, &idx, dcrl->issuerHash, sz) < 0)
7427 if (GetBasicDate(buff, &idx, dcrl->lastDate, &dcrl->lastDateFormat, sz) < 0)
7430 if (GetBasicDate(buff, &idx, dcrl->nextDate, &dcrl->nextDateFormat, sz) < 0)
7433 if (!XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
7434 CYASSL_MSG("CRL after date is no longer valid");
7435 return ASN_AFTER_DATE_E;
7438 if (idx != dcrl->sigIndex && buff[idx] != CRL_EXTENSIONS) {
7439 if (GetSequence(buff, &idx, &len, sz) < 0)
7444 while (idx < (word32)len) {
7445 if (GetRevoked(buff, &idx, dcrl, sz) < 0)
7450 if (idx != dcrl->sigIndex)
7451 idx = dcrl->sigIndex; /* skip extensions */
7453 if (GetAlgoId(buff, &idx, &dcrl->signatureOID, sz) < 0)
7456 if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
7459 /* openssl doesn't add skid by default for CRLs cause firefox chokes
7460 we're not assuming it's available yet */
7461 #if !defined(NO_SKID) && defined(CRL_SKID_READY)
7462 if (dcrl->extAuthKeyIdSet)
7463 ca = GetCA(cm, dcrl->extAuthKeyId);
7465 ca = GetCAByName(cm, dcrl->issuerHash);
7467 ca = GetCA(cm, dcrl->issuerHash);
7468 #endif /* NO_SKID */
7469 CYASSL_MSG("About to verify CRL signature");
7472 CYASSL_MSG("Found CRL issuer CA");
7473 /* try to confirm/verify signature */
7474 #ifndef IGNORE_KEY_EXTENSIONS
7475 if ((ca->keyUsage & KEYUSE_CRL_SIGN) == 0) {
7476 CYASSL_MSG("CA cannot sign CRLs");
7477 return ASN_CRL_NO_SIGNER_E;
7479 #endif /* IGNORE_KEY_EXTENSIONS */
7480 if (!ConfirmSignature(buff + dcrl->certBegin,
7481 dcrl->sigIndex - dcrl->certBegin,
7482 ca->publicKey, ca->pubKeySize, ca->keyOID,
7483 dcrl->signature, dcrl->sigLength, dcrl->signatureOID, NULL)) {
7484 CYASSL_MSG("CRL Confirm signature failed");
7485 return ASN_CRL_CONFIRM_E;
7489 CYASSL_MSG("Did NOT find CRL issuer CA");
7490 return ASN_CRL_NO_SIGNER_E;
7496 #endif /* HAVE_CRL */
7503 #endif /* CYASSL_SEP */