3 * Copyright (C) 2006-2012 Sawtooth Consulting Ltd.
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
27 #include "os.h" /* dc_rtc_api needs */
28 #include "dc_rtc_api.h" /* to get current time */
31 #include <cyassl/ctaocrypt/asn.h>
32 #include <cyassl/ctaocrypt/coding.h>
33 #include <cyassl/ctaocrypt/sha.h>
34 #include <cyassl/ctaocrypt/md5.h>
35 #include <cyassl/ctaocrypt/md2.h>
36 #include <cyassl/ctaocrypt/error.h>
37 #include <cyassl/ctaocrypt/pwdbased.h>
38 #include <cyassl/ctaocrypt/des3.h>
39 #include <cyassl/ctaocrypt/sha256.h>
40 #include <cyassl/ctaocrypt/sha512.h>
41 #include <cyassl/ctaocrypt/logging.h>
42 #include <cyassl/ctaocrypt/random.h>
45 #include "crypto_ntru.h"
49 #include <cyassl/ctaocrypt/ecc.h>
54 /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
55 #pragma warning(disable: 4996)
69 static INLINE word32 min(word32 a, word32 b)
78 /* uses parital <time.h> structures */
80 #define XGMTIME(c) my_gmtime((c))
81 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
82 #elif defined(MICRIUM)
83 #if (NET_SECURE_MGR_CFG_EN == DEF_ENABLED)
84 #define XVALIDATE_DATE(d,f,t) NetSecure_ValidateDateHandler((d),(f),(t))
86 #define XVALIDATE_DATE(d, f, t) (0)
89 /* since Micrium not defining XTIME or XGMTIME, CERT_GEN not available */
90 #elif defined(USER_TIME)
91 /* no <time.h> structures used */
93 /* user time, and gmtime compatible functions, there is a gmtime
94 implementation here that WINCE uses, so really just need some ticks
99 /* uses complete <time.h> facility */
101 #define XTIME(tl) time((tl))
102 #define XGMTIME(c) gmtime((c))
103 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
108 /* no time() or gmtime() even though in time.h header?? */
113 time_t time(time_t* timer)
117 ULARGE_INTEGER intTime;
123 GetSystemTime(&sysTime);
124 SystemTimeToFileTime(&sysTime, &fTime);
126 XMEMCPY(&intTime, &fTime, sizeof(FILETIME));
128 intTime.QuadPart -= 0x19db1ded53e8000;
130 intTime.QuadPart /= 10000000;
131 *timer = (time_t)intTime.QuadPart;
138 struct tm* gmtime(const time_t* timer)
141 #define EPOCH_YEAR 1970
142 #define SECS_DAY (24L * 60L * 60L)
143 #define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) %400)))
144 #define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365)
146 static const int _ytab[2][12] =
148 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
149 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
152 static struct tm st_time;
153 struct tm* ret = &st_time;
154 time_t time = *timer;
155 unsigned long dayclock, dayno;
156 int year = EPOCH_YEAR;
158 dayclock = (unsigned long)time % SECS_DAY;
159 dayno = (unsigned long)time / SECS_DAY;
161 ret->tm_sec = dayclock % 60;
162 ret->tm_min = (dayclock % 3600) / 60;
163 ret->tm_hour = dayclock / 3600;
164 ret->tm_wday = (dayno + 4) % 7; /* day 0 a Thursday */
166 while(dayno >= (unsigned long)YEARSIZE(year)) {
167 dayno -= YEARSIZE(year);
171 ret->tm_year = year - YEAR0;
172 ret->tm_yday = dayno;
175 while(dayno >= (unsigned long)_ytab[LEAPYEAR(year)][ret->tm_mon]) {
176 dayno -= _ytab[LEAPYEAR(year)][ret->tm_mon];
180 ret->tm_mday = ++dayno;
186 #endif /* _WIN32_WCE */
193 struct tm* my_gmtime(const time_t* timer) /* has a gmtime() but hangs */
195 static struct tm st_time;
196 struct tm* ret = &st_time;
199 dc_rtc_time_get(&cal, TRUE);
201 ret->tm_year = cal.year - YEAR0; /* gm starts at 1900 */
202 ret->tm_mon = cal.month - 1; /* gm starts at 0 */
203 ret->tm_mday = cal.day;
204 ret->tm_hour = cal.hour;
205 ret->tm_min = cal.minute;
206 ret->tm_sec = cal.second;
214 static INLINE word32 btoi(byte b)
220 /* two byte date/time, add to value */
221 static INLINE void GetTime(int* value, const byte* date, int* idx)
225 *value += btoi(date[i++]) * 10;
226 *value += btoi(date[i++]);
234 CPU_INT32S NetSecure_ValidateDateHandler(CPU_INT08U *date, CPU_INT08U format,
237 CPU_BOOLEAN rtn_code;
250 if (format == ASN_UTC_TIME) {
251 if (btoi(date[0]) >= 5)
256 else { /* format == GENERALIZED_TIME */
257 year += btoi(date[i++]) * 1000;
258 year += btoi(date[i++]) * 100;
262 GetTime(&val, date, &i);
263 year = (CPU_INT16U)val;
266 GetTime(&val, date, &i);
267 month = (CPU_INT08U)val;
270 GetTime(&val, date, &i);
271 day = (CPU_INT16U)val;
274 GetTime(&val, date, &i);
275 hour = (CPU_INT08U)val;
278 GetTime(&val, date, &i);
279 min = (CPU_INT08U)val;
282 GetTime(&val, date, &i);
283 sec = (CPU_INT08U)val;
285 return NetSecure_ValidateDate(year, month, day, hour, min, sec, dateType);
291 static int GetLength(const byte* input, word32* inOutIdx, int* len,
295 word32 i = *inOutIdx;
298 if ( (i+1) > maxIdx) { /* for first read */
299 CYASSL_MSG("GetLength bad index on input");
304 if (b >= ASN_LONG_LENGTH) {
305 word32 bytes = b & 0x7F;
307 if ( (i+bytes) > maxIdx) { /* for reading bytes */
308 CYASSL_MSG("GetLength bad long length");
314 length = (length << 8) | b;
320 if ( (i+length) > maxIdx) { /* for user of length */
321 CYASSL_MSG("GetLength value exceeds buffer length");
332 static int GetSequence(const byte* input, word32* inOutIdx, int* len,
336 word32 idx = *inOutIdx;
338 if (input[idx++] != (ASN_SEQUENCE | ASN_CONSTRUCTED) ||
339 GetLength(input, &idx, &length, maxIdx) < 0)
349 static int GetSet(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
352 word32 idx = *inOutIdx;
354 if (input[idx++] != (ASN_SET | ASN_CONSTRUCTED) ||
355 GetLength(input, &idx, &length, maxIdx) < 0)
365 /* winodws header clash for WinCE using GetVersion */
366 static int GetMyVersion(const byte* input, word32* inOutIdx, int* version)
368 word32 idx = *inOutIdx;
370 CYASSL_ENTER("GetMyVersion");
372 if (input[idx++] != ASN_INTEGER)
375 if (input[idx++] != 0x01)
376 return ASN_VERSION_E;
378 *version = input[idx++];
385 /* Get small count integer, 32 bits or less */
386 static int GetShortInt(const byte* input, word32* inOutIdx, int* number)
388 word32 idx = *inOutIdx;
393 if (input[idx++] != ASN_INTEGER)
401 *number = *number << 8 | input[idx++];
410 /* May not have one, not an error */
411 static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version)
413 word32 idx = *inOutIdx;
415 CYASSL_ENTER("GetExplicitVersion");
416 if (input[idx++] == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
417 *inOutIdx = ++idx; /* eat header */
418 return GetMyVersion(input, inOutIdx, version);
428 static int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx,
431 word32 i = *inOutIdx;
435 if (b != ASN_INTEGER)
438 if (GetLength(input, &i, &length, maxIdx) < 0)
441 if ( (b = input[i++]) == 0x00)
447 if (mp_read_unsigned_bin(mpi, (byte*)input + i, length) != 0) {
452 *inOutIdx = i + length;
457 static int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
461 word32 i = *inOutIdx;
466 if (b != ASN_OBJECT_ID)
467 return ASN_OBJECT_ID_E;
469 if (GetLength(input, &i, &length, maxIdx) < 0)
474 /* just sum it up for now */
482 static int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
486 word32 i = *inOutIdx;
490 CYASSL_ENTER("GetAlgoId");
492 if (GetSequence(input, &i, &length, maxIdx) < 0)
496 if (b != ASN_OBJECT_ID)
497 return ASN_OBJECT_ID_E;
499 if (GetLength(input, &i, &length, maxIdx) < 0)
504 /* just sum it up for now */
506 /* could have NULL tag and 0 terminator, but may not */
509 if (b == ASN_TAG_NULL) {
512 return ASN_EXPECT_0_E;
515 /* go back, didn't have it */
524 int RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
529 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
532 if (GetMyVersion(input, inOutIdx, &version) < 0)
535 key->type = RSA_PRIVATE;
537 if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
538 GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
539 GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
540 GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
541 GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
542 GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
543 GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
544 GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
550 /* Remove PKCS8 header, move beginning of traditional to beginning of input */
551 int ToTraditional(byte* input, word32 sz)
553 word32 inOutIdx = 0, oid;
556 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
559 if (GetMyVersion(input, &inOutIdx, &version) < 0)
562 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
565 if (input[inOutIdx] == ASN_OBJECT_ID) {
566 /* pkcs8 ecc uses slightly different format */
567 inOutIdx++; /* past id */
568 if (GetLength(input, &inOutIdx, &length, sz) < 0)
570 inOutIdx += length; /* over sub id, key input will verify */
573 if (input[inOutIdx++] != ASN_OCTET_STRING)
576 if (GetLength(input, &inOutIdx, &length, sz) < 0)
579 XMEMMOVE(input, input + inOutIdx, length);
587 /* Check To see if PKCS version algo is supported, set id if it is return 0
589 static int CheckAlgo(int first, int second, int* id, int* version)
592 *version = PKCS5; /* default */
597 *id = PBE_SHA1_RC4_128;
610 return ASN_INPUT_E; /* VERSION ERROR */
612 if (second == PBES2) {
618 case 3: /* see RFC 2898 for ids */
631 /* Check To see if PKCS v2 algo is supported, set id if it is return 0
633 static int CheckAlgoV2(int oid, int* id)
649 /* Decrypt intput in place from parameters based on id */
650 static int DecryptKey(const char* password, int passwordSz, byte* salt,
651 int saltSz, int iterations, int id, byte* input,
652 int length, int version, byte* cbcIv)
654 byte key[MAX_KEY_SIZE];
663 derivedLen = 16; /* may need iv for v1.5 */
664 decryptionType = DES_TYPE;
669 derivedLen = 16; /* may need iv for v1.5 */
670 decryptionType = DES_TYPE;
675 derivedLen = 32; /* may need iv for v1.5 */
676 decryptionType = DES3_TYPE;
679 case PBE_SHA1_RC4_128:
682 decryptionType = RC4_TYPE;
689 if (version == PKCS5v2)
690 ret = PBKDF2(key, (byte*)password, passwordSz, salt, saltSz, iterations,
692 else if (version == PKCS5)
693 ret = PBKDF1(key, (byte*)password, passwordSz, salt, saltSz, iterations,
695 else if (version == PKCS12) {
697 byte unicodePasswd[MAX_UNICODE_SZ];
699 if ( (passwordSz * 2 + 2) > (int)sizeof(unicodePasswd))
700 return UNICODE_SIZE_E;
702 for (i = 0; i < passwordSz; i++) {
703 unicodePasswd[idx++] = 0x00;
704 unicodePasswd[idx++] = (byte)password[i];
706 /* add trailing NULL */
707 unicodePasswd[idx++] = 0x00;
708 unicodePasswd[idx++] = 0x00;
710 ret = PKCS12_PBKDF(key, unicodePasswd, idx, salt, saltSz,
711 iterations, derivedLen, typeH, 1);
712 if (decryptionType != RC4_TYPE)
713 ret += PKCS12_PBKDF(cbcIv, unicodePasswd, idx, salt, saltSz,
714 iterations, 8, typeH, 2);
720 switch (decryptionType) {
725 byte* desIv = key + 8;
727 if (version == PKCS5v2 || version == PKCS12)
729 Des_SetKey(&dec, key, desIv, DES_DECRYPTION);
730 Des_CbcDecrypt(&dec, input, input, length);
737 byte* desIv = key + 24;
739 if (version == PKCS5v2 || version == PKCS12)
741 Des3_SetKey(&dec, key, desIv, DES_DECRYPTION);
742 Des3_CbcDecrypt(&dec, input, input, length);
750 Arc4SetKey(&dec, key, derivedLen);
751 Arc4Process(&dec, input, input, length);
763 /* Remove Encrypted PKCS8 header, move beginning of traditional to beginning
765 int ToTraditionalEnc(byte* input, word32 sz,const char* password,int passwordSz)
767 word32 inOutIdx = 0, oid;
768 int first, second, length, iterations, saltSz, id;
770 byte salt[MAX_SALT_SIZE];
771 byte cbcIv[MAX_IV_SIZE];
773 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
776 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
779 first = input[inOutIdx - 2]; /* PKCS version alwyas 2nd to last byte */
780 second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
782 if (CheckAlgo(first, second, &id, &version) < 0)
783 return ASN_INPUT_E; /* Algo ID error */
785 if (version == PKCS5v2) {
787 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
790 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
793 if (oid != PBKDF2_OID)
797 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
800 if (input[inOutIdx++] != ASN_OCTET_STRING)
803 if (GetLength(input, &inOutIdx, &saltSz, sz) < 0)
806 if (saltSz > MAX_SALT_SIZE)
809 XMEMCPY(salt, &input[inOutIdx], saltSz);
812 if (GetShortInt(input, &inOutIdx, &iterations) < 0)
815 if (version == PKCS5v2) {
816 /* get encryption algo */
817 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
820 if (CheckAlgoV2(oid, &id) < 0)
821 return ASN_PARSE_E; /* PKCS v2 algo id error */
823 if (input[inOutIdx++] != ASN_OCTET_STRING)
826 if (GetLength(input, &inOutIdx, &length, sz) < 0)
829 XMEMCPY(cbcIv, &input[inOutIdx], length);
833 if (input[inOutIdx++] != ASN_OCTET_STRING)
836 if (GetLength(input, &inOutIdx, &length, sz) < 0)
839 if (DecryptKey(password, passwordSz, salt, saltSz, iterations, id,
840 input + inOutIdx, length, version, cbcIv) < 0)
841 return ASN_INPUT_E; /* decrypt failure */
843 XMEMMOVE(input, input + inOutIdx, length);
844 return ToTraditional(input, length);
847 #endif /* NO_PWDBASED */
850 int RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
855 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
858 key->type = RSA_PUBLIC;
862 byte b = input[*inOutIdx];
863 if (b != ASN_INTEGER) {
864 /* not from decoded cert, will have algo id, skip past */
865 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
868 b = input[(*inOutIdx)++];
869 if (b != ASN_OBJECT_ID)
870 return ASN_OBJECT_ID_E;
872 if (GetLength(input, inOutIdx, &length, inSz) < 0)
875 *inOutIdx += length; /* skip past */
877 /* could have NULL tag and 0 terminator, but may not */
878 b = input[(*inOutIdx)++];
880 if (b == ASN_TAG_NULL) {
881 b = input[(*inOutIdx)++];
883 return ASN_EXPECT_0_E;
886 /* go back, didn't have it */
889 /* should have bit tag length and seq next */
890 b = input[(*inOutIdx)++];
891 if (b != ASN_BIT_STRING)
894 if (GetLength(input, inOutIdx, &length, inSz) < 0)
898 b = input[(*inOutIdx)++];
902 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
905 } /* openssl var block */
906 #endif /* OPENSSL_EXTRA */
908 if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
909 GetInt(&key->e, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
917 int DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
921 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
924 if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
925 GetInt(&key->g, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
930 int DhSetKey(DhKey* key, const byte* p, word32 pSz, const byte* g, word32 gSz)
932 /* may have leading 0 */
942 if (mp_read_unsigned_bin(&key->p, p, pSz) != 0) {
948 if (mp_read_unsigned_bin(&key->g, g, gSz) != 0) {
959 int DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
960 byte* g, word32* gInOutSz)
966 if (GetSequence(input, &i, &length, inSz) < 0)
970 if (b != ASN_INTEGER)
973 if (GetLength(input, &i, &length, inSz) < 0)
976 if ( (b = input[i++]) == 0x00)
981 if (length <= (int)*pInOutSz) {
982 XMEMCPY(p, &input[i], length);
991 if (b != ASN_INTEGER)
994 if (GetLength(input, &i, &length, inSz) < 0)
997 if (length <= (int)*gInOutSz) {
998 XMEMCPY(g, &input[i], length);
1007 #endif /* OPENSSL_EXTRA */
1013 int DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
1018 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1021 if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
1022 GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
1023 GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
1024 GetInt(&key->y, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
1026 key->type = DSA_PUBLIC;
1031 int DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
1034 int length, version;
1036 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1039 if (GetMyVersion(input, inOutIdx, &version) < 0)
1042 if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
1043 GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
1044 GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
1045 GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
1046 GetInt(&key->x, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
1048 key->type = DSA_PRIVATE;
1055 void InitDecodedCert(DecodedCert* cert, byte* source, word32 inSz, void* heap)
1057 cert->publicKey = 0;
1058 cert->pubKeyStored = 0;
1059 cert->signature = 0;
1060 cert->subjectCN = 0;
1061 cert->subjectCNLen = 0;
1062 cert->subjectCNStored = 0;
1063 cert->altNames = NULL;
1064 cert->issuer[0] = '\0';
1065 cert->subject[0] = '\0';
1066 cert->source = source; /* don't own */
1068 cert->maxIdx = inSz; /* can't go over this index */
1070 XMEMSET(cert->serial, 0, EXTERNAL_SERIAL_SIZE);
1072 cert->extensions = 0;
1073 cert->extensionsSz = 0;
1074 cert->extensionsIdx = 0;
1075 cert->extAuthInfo = NULL;
1076 cert->extAuthInfoSz = 0;
1077 cert->extCrlInfo = NULL;
1078 cert->extCrlInfoSz = 0;
1080 #ifdef CYASSL_CERT_GEN
1081 cert->subjectSN = 0;
1082 cert->subjectSNLen = 0;
1084 cert->subjectCLen = 0;
1086 cert->subjectLLen = 0;
1087 cert->subjectST = 0;
1088 cert->subjectSTLen = 0;
1090 cert->subjectOLen = 0;
1091 cert->subjectOU = 0;
1092 cert->subjectOULen = 0;
1093 cert->subjectEmail = 0;
1094 cert->subjectEmailLen = 0;
1095 cert->beforeDate = 0;
1096 cert->beforeDateLen = 0;
1097 cert->afterDate = 0;
1098 cert->afterDateLen = 0;
1099 #endif /* CYASSL_CERT_GEN */
1103 void FreeAltNames(DNS_entry* altNames, void* heap)
1108 DNS_entry* tmp = altNames->next;
1110 XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
1111 XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME);
1117 void FreeDecodedCert(DecodedCert* cert)
1119 if (cert->subjectCNStored == 1)
1120 XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
1121 if (cert->pubKeyStored == 1)
1122 XFREE(cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
1124 FreeAltNames(cert->altNames, cert->heap);
1128 static int GetCertHeader(DecodedCert* cert)
1130 int ret = 0, version, len;
1131 byte serialTmp[EXTERNAL_SERIAL_SIZE];
1134 if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
1137 cert->certBegin = cert->srcIdx;
1139 if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
1141 cert->sigIndex = len + cert->srcIdx;
1143 if (GetExplicitVersion(cert->source, &cert->srcIdx, &version) < 0)
1146 if (GetInt(&mpi, cert->source, &cert->srcIdx, cert->maxIdx) < 0)
1149 len = mp_unsigned_bin_size(&mpi);
1150 if (len < (int)sizeof(serialTmp)) {
1151 if (mp_to_unsigned_bin(&mpi, serialTmp) == MP_OKAY) {
1152 if (len > EXTERNAL_SERIAL_SIZE)
1153 len = EXTERNAL_SERIAL_SIZE;
1154 XMEMCPY(cert->serial, serialTmp, len);
1155 cert->serialSz = len;
1163 /* Store Rsa Key, may save later, Dsa could use in future */
1164 static int StoreRsaKey(DecodedCert* cert)
1167 word32 read = cert->srcIdx;
1169 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1172 read = cert->srcIdx - read;
1178 cert->pubKeySize = length;
1179 cert->publicKey = cert->source + cert->srcIdx;
1180 cert->srcIdx += length;
1188 /* return 0 on sucess if the ECC curve oid sum is supported */
1189 static int CheckCurve(word32 oid)
1191 if (oid != ECC_256R1 && oid != ECC_384R1 && oid != ECC_521R1 && oid !=
1192 ECC_160R1 && oid != ECC_192R1 && oid != ECC_224R1)
1198 #endif /* HAVE_ECC */
1201 static int GetKey(DecodedCert* cert)
1205 int tmpIdx = cert->srcIdx;
1208 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1211 if (GetAlgoId(cert->source, &cert->srcIdx, &cert->keyOID, cert->maxIdx) < 0)
1214 if (cert->keyOID == RSAk) {
1215 byte b = cert->source[cert->srcIdx++];
1216 if (b != ASN_BIT_STRING)
1217 return ASN_BITSTR_E;
1219 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1221 b = cert->source[cert->srcIdx++];
1223 return ASN_EXPECT_0_E;
1225 else if (cert->keyOID == DSAk )
1228 else if (cert->keyOID == NTRUk ) {
1229 const byte* key = &cert->source[tmpIdx];
1230 byte* next = (byte*)key;
1232 byte keyBlob[MAX_NTRU_KEY_SZ];
1234 word32 rc = crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key,
1235 &keyLen, NULL, &next);
1238 return ASN_NTRU_KEY_E;
1239 if (keyLen > sizeof(keyBlob))
1240 return ASN_NTRU_KEY_E;
1242 rc = crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key, &keyLen,
1245 return ASN_NTRU_KEY_E;
1247 if ( (next - key) < 0)
1248 return ASN_NTRU_KEY_E;
1250 cert->srcIdx = tmpIdx + (next - key);
1252 cert->publicKey = (byte*) XMALLOC(keyLen, cert->heap,
1253 DYNAMIC_TYPE_PUBLIC_KEY);
1254 if (cert->publicKey == NULL)
1256 XMEMCPY(cert->publicKey, keyBlob, keyLen);
1257 cert->pubKeyStored = 1;
1258 cert->pubKeySize = keyLen;
1260 #endif /* HAVE_NTRU */
1262 else if (cert->keyOID == ECDSAk ) {
1265 byte b = cert->source[cert->srcIdx++];
1267 if (b != ASN_OBJECT_ID)
1268 return ASN_OBJECT_ID_E;
1270 if (GetLength(cert->source, &cert->srcIdx, &oidSz, cert->maxIdx) < 0)
1274 oid += cert->source[cert->srcIdx++];
1275 if (CheckCurve(oid) < 0)
1276 return ECC_CURVE_OID_E;
1279 b = cert->source[cert->srcIdx++];
1280 if (b != ASN_BIT_STRING)
1281 return ASN_BITSTR_E;
1283 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1285 b = cert->source[cert->srcIdx++];
1287 return ASN_EXPECT_0_E;
1289 /* actual key, use length - 1 since ate preceding 0 */
1292 cert->publicKey = (byte*) XMALLOC(length, cert->heap,
1293 DYNAMIC_TYPE_PUBLIC_KEY);
1294 if (cert->publicKey == NULL)
1296 XMEMCPY(cert->publicKey, &cert->source[cert->srcIdx], length);
1297 cert->pubKeyStored = 1;
1298 cert->pubKeySize = length;
1300 cert->srcIdx += length;
1302 #endif /* HAVE_ECC */
1304 return ASN_UNKNOWN_OID_E;
1306 if (cert->keyOID == RSAk)
1307 return StoreRsaKey(cert);
1312 /* process NAME, either issuer or subject */
1313 static int GetName(DecodedCert* cert, int nameType)
1316 int length; /* length of all distinguished names */
1318 char* full = (nameType == ISSUER) ? cert->issuer : cert->subject;
1321 if (cert->source[cert->srcIdx] == ASN_OBJECT_ID) {
1322 CYASSL_MSG("Trying optional prefix...");
1324 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1327 cert->srcIdx += length;
1328 CYASSL_MSG("Got optional prefix");
1331 /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
1332 * calculated over the entire DER encoding of the Name field, including
1333 * the tag and length. */
1335 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1339 ShaUpdate(&sha, &cert->source[idx], length + cert->srcIdx - idx);
1340 if (nameType == ISSUER)
1341 ShaFinal(&sha, cert->issuerHash);
1343 ShaFinal(&sha, cert->subjectHash);
1345 length += cert->srcIdx;
1348 while (cert->srcIdx < (word32)length) {
1353 if (GetSet(cert->source, &cert->srcIdx, &dummy, cert->maxIdx) < 0) {
1354 (void)b; /* empty body warning w/o messages enabled */
1355 CYASSL_MSG("Cert name lacks set header, trying sequence");
1358 if (GetSequence(cert->source, &cert->srcIdx, &dummy, cert->maxIdx) < 0)
1361 b = cert->source[cert->srcIdx++];
1362 if (b != ASN_OBJECT_ID)
1363 return ASN_OBJECT_ID_E;
1365 if (GetLength(cert->source, &cert->srcIdx, &oidSz, cert->maxIdx) < 0)
1368 XMEMCPY(joint, &cert->source[cert->srcIdx], sizeof(joint));
1371 if (joint[0] == 0x55 && joint[1] == 0x04) {
1377 id = cert->source[cert->srcIdx++];
1378 b = cert->source[cert->srcIdx++]; /* strType */
1380 if (GetLength(cert->source, &cert->srcIdx, &strLen,
1384 if (strLen > (int)(ASN_NAME_MAX - idx))
1387 if (4 > (ASN_NAME_MAX - idx)) /* make sure room for biggest */
1388 return ASN_PARSE_E; /* pre fix header too "/CN=" */
1390 if (id == ASN_COMMON_NAME) {
1391 if (nameType == SUBJECT) {
1392 cert->subjectCN = (char *)&cert->source[cert->srcIdx];
1393 cert->subjectCNLen = strLen;
1396 XMEMCPY(&full[idx], "/CN=", 4);
1400 else if (id == ASN_SUR_NAME) {
1401 XMEMCPY(&full[idx], "/SN=", 4);
1404 #ifdef CYASSL_CERT_GEN
1405 if (nameType == SUBJECT) {
1406 cert->subjectSN = (char*)&cert->source[cert->srcIdx];
1407 cert->subjectSNLen = strLen;
1409 #endif /* CYASSL_CERT_GEN */
1411 else if (id == ASN_COUNTRY_NAME) {
1412 XMEMCPY(&full[idx], "/C=", 3);
1415 #ifdef CYASSL_CERT_GEN
1416 if (nameType == SUBJECT) {
1417 cert->subjectC = (char*)&cert->source[cert->srcIdx];
1418 cert->subjectCLen = strLen;
1420 #endif /* CYASSL_CERT_GEN */
1422 else if (id == ASN_LOCALITY_NAME) {
1423 XMEMCPY(&full[idx], "/L=", 3);
1426 #ifdef CYASSL_CERT_GEN
1427 if (nameType == SUBJECT) {
1428 cert->subjectL = (char*)&cert->source[cert->srcIdx];
1429 cert->subjectLLen = strLen;
1431 #endif /* CYASSL_CERT_GEN */
1433 else if (id == ASN_STATE_NAME) {
1434 XMEMCPY(&full[idx], "/ST=", 4);
1437 #ifdef CYASSL_CERT_GEN
1438 if (nameType == SUBJECT) {
1439 cert->subjectST = (char*)&cert->source[cert->srcIdx];
1440 cert->subjectSTLen = strLen;
1442 #endif /* CYASSL_CERT_GEN */
1444 else if (id == ASN_ORG_NAME) {
1445 XMEMCPY(&full[idx], "/O=", 3);
1448 #ifdef CYASSL_CERT_GEN
1449 if (nameType == SUBJECT) {
1450 cert->subjectO = (char*)&cert->source[cert->srcIdx];
1451 cert->subjectOLen = strLen;
1453 #endif /* CYASSL_CERT_GEN */
1455 else if (id == ASN_ORGUNIT_NAME) {
1456 XMEMCPY(&full[idx], "/OU=", 4);
1459 #ifdef CYASSL_CERT_GEN
1460 if (nameType == SUBJECT) {
1461 cert->subjectOU = (char*)&cert->source[cert->srcIdx];
1462 cert->subjectOULen = strLen;
1464 #endif /* CYASSL_CERT_GEN */
1468 XMEMCPY(&full[idx], &cert->source[cert->srcIdx], strLen);
1472 cert->srcIdx += strLen;
1480 if (joint[0] == 0x2a && joint[1] == 0x86) /* email id hdr */
1483 if (joint[0] == 0x9 && joint[1] == 0x92) /* uid id hdr */
1486 cert->srcIdx += oidSz + 1;
1488 if (GetLength(cert->source, &cert->srcIdx, &adv, cert->maxIdx) < 0)
1491 if (adv > (int)(ASN_NAME_MAX - idx))
1495 if (14 > (ASN_NAME_MAX - idx))
1497 XMEMCPY(&full[idx], "/emailAddress=", 14);
1500 #ifdef CYASSL_CERT_GEN
1501 if (nameType == SUBJECT) {
1502 cert->subjectEmail = (char*)&cert->source[cert->srcIdx];
1503 cert->subjectEmailLen = adv;
1505 #endif /* CYASSL_CERT_GEN */
1507 XMEMCPY(&full[idx], &cert->source[cert->srcIdx], adv);
1512 if (5 > (ASN_NAME_MAX - idx))
1514 XMEMCPY(&full[idx], "/UID=", 5);
1517 XMEMCPY(&full[idx], &cert->source[cert->srcIdx], adv);
1521 cert->srcIdx += adv;
1533 static int DateGreaterThan(const struct tm* a, const struct tm* b)
1535 if (a->tm_year > b->tm_year)
1538 if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
1541 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
1542 a->tm_mday > b->tm_mday)
1545 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
1546 a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
1549 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
1550 a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
1551 a->tm_min > b->tm_min)
1554 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
1555 a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
1556 a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
1559 return 0; /* false */
1563 static INLINE int DateLessThan(const struct tm* a, const struct tm* b)
1565 return !DateGreaterThan(a,b);
1569 /* like atoi but only use first byte */
1570 /* Make sure before and after dates are valid */
1571 int ValidateDate(const byte* date, byte format, int dateType)
1575 struct tm* localTime;
1579 XMEMSET(&certTime, 0, sizeof(certTime));
1581 if (format == ASN_UTC_TIME) {
1582 if (btoi(date[0]) >= 5)
1583 certTime.tm_year = 1900;
1585 certTime.tm_year = 2000;
1587 else { /* format == GENERALIZED_TIME */
1588 certTime.tm_year += btoi(date[i++]) * 1000;
1589 certTime.tm_year += btoi(date[i++]) * 100;
1592 GetTime(&certTime.tm_year, date, &i); certTime.tm_year -= 1900; /* adjust */
1593 GetTime(&certTime.tm_mon, date, &i); certTime.tm_mon -= 1; /* adjust */
1594 GetTime(&certTime.tm_mday, date, &i);
1595 GetTime(&certTime.tm_hour, date, &i);
1596 GetTime(&certTime.tm_min, date, &i);
1597 GetTime(&certTime.tm_sec, date, &i);
1599 if (date[i] != 'Z') { /* only Zulu supported for this profile */
1600 CYASSL_MSG("Only Zulu time supported for this profile");
1604 localTime = XGMTIME(<ime);
1606 if (dateType == BEFORE) {
1607 if (DateLessThan(localTime, &certTime))
1611 if (DateGreaterThan(localTime, &certTime))
1617 #endif /* NO_TIME_H */
1620 static int GetDate(DecodedCert* cert, int dateType)
1623 byte date[MAX_DATE_SIZE];
1626 #ifdef CYASSL_CERT_GEN
1627 word32 startIdx = 0;
1628 if (dateType == BEFORE)
1629 cert->beforeDate = &cert->source[cert->srcIdx];
1631 cert->afterDate = &cert->source[cert->srcIdx];
1632 startIdx = cert->srcIdx;
1635 b = cert->source[cert->srcIdx++];
1636 if (b != ASN_UTC_TIME && b != ASN_GENERALIZED_TIME)
1639 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1642 if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
1643 return ASN_DATE_SZ_E;
1645 XMEMCPY(date, &cert->source[cert->srcIdx], length);
1646 cert->srcIdx += length;
1648 #ifdef CYASSL_CERT_GEN
1649 if (dateType == BEFORE)
1650 cert->beforeDateLen = cert->srcIdx - startIdx;
1652 cert->afterDateLen = cert->srcIdx - startIdx;
1655 if (!XVALIDATE_DATE(date, b, dateType)) {
1656 if (dateType == BEFORE)
1657 return ASN_BEFORE_DATE_E;
1659 return ASN_AFTER_DATE_E;
1666 static int GetValidity(DecodedCert* cert, int verify)
1671 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1674 if (GetDate(cert, BEFORE) < 0 && verify)
1675 badDate = ASN_BEFORE_DATE_E; /* continue parsing */
1677 if (GetDate(cert, AFTER) < 0 && verify)
1678 return ASN_AFTER_DATE_E;
1687 int DecodeToKey(DecodedCert* cert, int verify)
1692 if ( (ret = GetCertHeader(cert)) < 0)
1695 if ( (ret = GetAlgoId(cert->source, &cert->srcIdx, &cert->signatureOID,
1699 if ( (ret = GetName(cert, ISSUER)) < 0)
1702 if ( (ret = GetValidity(cert, verify)) < 0)
1705 if ( (ret = GetName(cert, SUBJECT)) < 0)
1708 if ( (ret = GetKey(cert)) < 0)
1718 static int GetSignature(DecodedCert* cert)
1721 byte b = cert->source[cert->srcIdx++];
1723 if (b != ASN_BIT_STRING)
1724 return ASN_BITSTR_E;
1726 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1729 cert->sigLength = length;
1731 b = cert->source[cert->srcIdx++];
1733 return ASN_EXPECT_0_E;
1736 cert->signature = &cert->source[cert->srcIdx];
1737 cert->srcIdx += cert->sigLength;
1743 static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
1745 output[0] = ASN_OCTET_STRING;
1746 output[1] = (byte)digSz;
1747 XMEMCPY(&output[2], digest, digSz);
1753 static word32 BytePrecision(word32 value)
1756 for (i = sizeof(value); i; --i)
1757 if (value >> (i - 1) * 8)
1764 static word32 SetLength(word32 length, byte* output)
1768 if (length < ASN_LONG_LENGTH)
1769 output[i++] = (byte)length;
1771 output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);
1773 for (j = BytePrecision(length); j; --j) {
1774 output[i] = (byte)(length >> (j - 1) * 8);
1783 static word32 SetSequence(word32 len, byte* output)
1785 output[0] = ASN_SEQUENCE | ASN_CONSTRUCTED;
1786 return SetLength(len, output + 1) + 1;
1790 static word32 SetAlgoID(int algoOID, byte* output, int type)
1792 /* adding TAG_NULL and 0 to end */
1795 static const byte shaAlgoID[] = { 0x2b, 0x0e, 0x03, 0x02, 0x1a,
1797 static const byte sha256AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
1798 0x04, 0x02, 0x01, 0x05, 0x00 };
1799 static const byte sha384AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
1800 0x04, 0x02, 0x02, 0x05, 0x00 };
1801 static const byte sha512AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
1802 0x04, 0x02, 0x03, 0x05, 0x00 };
1803 static const byte md5AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
1804 0x02, 0x05, 0x05, 0x00 };
1805 static const byte md2AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
1806 0x02, 0x02, 0x05, 0x00};
1808 static const byte md5wRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
1809 0x01, 0x01, 0x04, 0x05, 0x00};
1810 static const byte shawRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
1811 0x01, 0x01, 0x05, 0x05, 0x00};
1812 static const byte sha256wRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7,
1813 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00};
1814 static const byte sha384wRSA_AlgoID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
1815 0x0d, 0x01, 0x01, 0x0c, 0x05, 0x00};
1816 static const byte sha512wRSA_AlgoID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
1817 0x0d, 0x01, 0x01, 0x0d, 0x05, 0x00};
1819 static const byte RSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
1820 0x01, 0x01, 0x01, 0x05, 0x00};
1823 const byte* algoName = 0;
1824 byte ID_Length[MAX_LENGTH_SZ];
1825 byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
1827 if (type == hashType) {
1830 algoSz = sizeof(shaAlgoID);
1831 algoName = shaAlgoID;
1835 algoSz = sizeof(sha256AlgoID);
1836 algoName = sha256AlgoID;
1840 algoSz = sizeof(sha384AlgoID);
1841 algoName = sha384AlgoID;
1845 algoSz = sizeof(sha512AlgoID);
1846 algoName = sha512AlgoID;
1850 algoSz = sizeof(md2AlgoID);
1851 algoName = md2AlgoID;
1855 algoSz = sizeof(md5AlgoID);
1856 algoName = md5AlgoID;
1860 CYASSL_MSG("Unknown Hash Algo");
1861 return 0; /* UNKOWN_HASH_E; */
1864 else if (type == sigType) { /* sigType */
1867 algoSz = sizeof(md5wRSA_AlgoID);
1868 algoName = md5wRSA_AlgoID;
1872 algoSz = sizeof(shawRSA_AlgoID);
1873 algoName = shawRSA_AlgoID;
1876 case CTC_SHA256wRSA:
1877 algoSz = sizeof(sha256wRSA_AlgoID);
1878 algoName = sha256wRSA_AlgoID;
1881 case CTC_SHA384wRSA:
1882 algoSz = sizeof(sha384wRSA_AlgoID);
1883 algoName = sha384wRSA_AlgoID;
1886 case CTC_SHA512wRSA:
1887 algoSz = sizeof(sha512wRSA_AlgoID);
1888 algoName = sha512wRSA_AlgoID;
1892 CYASSL_MSG("Unknown Signature Algo");
1896 else if (type == keyType) { /* keyType */
1899 algoSz = sizeof(RSA_AlgoID);
1900 algoName = RSA_AlgoID;
1904 CYASSL_MSG("Unknown Key Algo");
1909 CYASSL_MSG("Unknown Algo type");
1913 idSz = SetLength(algoSz - 2, ID_Length); /* don't include TAG_NULL/0 */
1914 seqSz = SetSequence(idSz + algoSz + 1, seqArray);
1915 seqArray[seqSz++] = ASN_OBJECT_ID;
1917 XMEMCPY(output, seqArray, seqSz);
1918 XMEMCPY(output + seqSz, ID_Length, idSz);
1919 XMEMCPY(output + seqSz + idSz, algoName, algoSz);
1921 return seqSz + idSz + algoSz;
1926 word32 EncodeSignature(byte* out, const byte* digest, word32 digSz, int hashOID)
1928 byte digArray[MAX_ENCODED_DIG_SZ];
1929 byte algoArray[MAX_ALGO_SZ];
1930 byte seqArray[MAX_SEQ_SZ];
1931 word32 encDigSz, algoSz, seqSz;
1933 encDigSz = SetDigest(digest, digSz, digArray);
1934 algoSz = SetAlgoID(hashOID, algoArray, hashType);
1935 seqSz = SetSequence(encDigSz + algoSz, seqArray);
1937 XMEMCPY(out, seqArray, seqSz);
1938 XMEMCPY(out + seqSz, algoArray, algoSz);
1939 XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
1941 return encDigSz + algoSz + seqSz;
1945 /* return true (1) for Confirmation */
1946 static int ConfirmSignature(const byte* buf, word32 bufSz,
1947 const byte* key, word32 keySz, word32 keyOID,
1948 const byte* sig, word32 sigSz, word32 sigOID,
1951 #ifdef CYASSL_SHA512
1952 byte digest[SHA512_DIGEST_SIZE]; /* max size */
1953 #elif !defined(NO_SHA256)
1954 byte digest[SHA256_DIGEST_SIZE]; /* max size */
1956 byte digest[SHA_DIGEST_SIZE]; /* max size */
1958 int typeH, digestSz, ret;
1960 if (sigOID == CTC_MD5wRSA) {
1963 Md5Update(&md5, buf, bufSz);
1964 Md5Final(&md5, digest);
1966 digestSz = MD5_DIGEST_SIZE;
1969 else if (sigOID == CTC_MD2wRSA) {
1972 Md2Update(&md2, buf, bufSz);
1973 Md2Final(&md2, digest);
1975 digestSz = MD2_DIGEST_SIZE;
1978 else if (sigOID == CTC_SHAwRSA ||
1979 sigOID == CTC_SHAwDSA ||
1980 sigOID == CTC_SHAwECDSA) {
1983 ShaUpdate(&sha, buf, bufSz);
1984 ShaFinal(&sha, digest);
1986 digestSz = SHA_DIGEST_SIZE;
1989 else if (sigOID == CTC_SHA256wRSA ||
1990 sigOID == CTC_SHA256wECDSA) {
1992 InitSha256(&sha256);
1993 Sha256Update(&sha256, buf, bufSz);
1994 Sha256Final(&sha256, digest);
1996 digestSz = SHA256_DIGEST_SIZE;
1999 #ifdef CYASSL_SHA512
2000 else if (sigOID == CTC_SHA512wRSA ||
2001 sigOID == CTC_SHA512wECDSA) {
2003 InitSha512(&sha512);
2004 Sha512Update(&sha512, buf, bufSz);
2005 Sha512Final(&sha512, digest);
2007 digestSz = SHA512_DIGEST_SIZE;
2010 #ifdef CYASSL_SHA384
2011 else if (sigOID == CTC_SHA384wRSA ||
2012 sigOID == CTC_SHA384wECDSA) {
2014 InitSha384(&sha384);
2015 Sha384Update(&sha384, buf, bufSz);
2016 Sha384Final(&sha384, digest);
2018 digestSz = SHA384_DIGEST_SIZE;
2022 CYASSL_MSG("Verify Signautre has unsupported type");
2026 if (keyOID == RSAk) {
2028 byte encodedSig[MAX_ENCODED_SIG_SZ];
2029 byte plain[MAX_ENCODED_SIG_SZ];
2031 int encodedSigSz, verifySz;
2034 if (sigSz > MAX_ENCODED_SIG_SZ) {
2035 CYASSL_MSG("Verify Signautre is too big");
2039 InitRsaKey(&pubKey, heap);
2040 if (RsaPublicKeyDecode(key, &idx, &pubKey, keySz) < 0) {
2041 CYASSL_MSG("ASN Key decode error RSA");
2045 XMEMCPY(plain, sig, sigSz);
2046 if ( (verifySz = RsaSSL_VerifyInline(plain, sigSz, &out,
2048 CYASSL_MSG("Rsa SSL verify error");
2052 /* make sure we're right justified */
2054 EncodeSignature(encodedSig, digest, digestSz, typeH);
2055 if (encodedSigSz != verifySz ||
2056 XMEMCMP(out, encodedSig, encodedSigSz) != 0) {
2057 CYASSL_MSG("Rsa SSL verify match encode error");
2061 ret = 1; /* match */
2063 #ifdef CYASSL_DEBUG_ENCODING
2066 printf("cyassl encodedSig:\n");
2067 for (x = 0; x < encodedSigSz; x++) {
2068 printf("%02x ", encodedSig[x]);
2069 if ( (x % 16) == 15)
2073 printf("actual digest:\n");
2074 for (x = 0; x < verifySz; x++) {
2075 printf("%02x ", out[x]);
2076 if ( (x % 16) == 15)
2081 #endif /* CYASSL_DEBUG_ENCODING */
2084 FreeRsaKey(&pubKey);
2088 else if (keyOID == ECDSAk) {
2092 if (ecc_import_x963(key, keySz, &pubKey) < 0) {
2093 CYASSL_MSG("ASN Key import error ECC");
2097 ret = ecc_verify_hash(sig, sigSz, digest, digestSz, &verify, &pubKey);
2099 if (ret == 0 && verify == 1)
2100 return 1; /* match */
2102 CYASSL_MSG("ECC Verify didn't match");
2105 #endif /* HAVE_ECC */
2107 CYASSL_MSG("Verify Key type unknown");
2113 static void DecodeAltNames(byte* input, int sz, DecodedCert* cert)
2118 CYASSL_ENTER("DecodeAltNames");
2120 if (GetSequence(input, &idx, &length, sz) < 0) {
2121 CYASSL_MSG("\tBad Sequence");
2125 while (length > 0) {
2128 byte b = input[idx++];
2132 if (b != (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
2133 CYASSL_MSG("\tNot DNS type");
2137 if (GetLength(input, &idx, &strLen, sz) < 0) {
2138 CYASSL_MSG("\tfail: str length");
2142 entry = (DNS_entry*)XMALLOC(sizeof(DNS_entry), cert->heap,
2143 DYNAMIC_TYPE_ALTNAME);
2144 if (entry == NULL) {
2145 CYASSL_MSG("\tOut of Memory");
2149 entry->name = (char*)XMALLOC(strLen + 1, cert->heap,
2150 DYNAMIC_TYPE_ALTNAME);
2151 if (entry->name == NULL) {
2152 CYASSL_MSG("\tOut of Memory");
2153 XFREE(entry, cert->heap, DYNAMIC_TYPE_ALTNAME);
2157 XMEMCPY(entry->name, &input[idx], strLen);
2158 entry->name[strLen] = '\0';
2160 entry->next = cert->altNames;
2161 cert->altNames = entry;
2169 static void DecodeBasicCaConstraint(byte* input, int sz, DecodedCert* cert)
2174 CYASSL_ENTER("DecodeBasicCaConstraint");
2175 if (GetSequence(input, &idx, &length, sz) < 0) return;
2177 if (length == 0) return;
2178 /* If the basic ca constraint is false, this extension may be named, but
2179 * left empty. So, if the length is 0, just return. */
2181 if (input[idx++] != ASN_BOOLEAN)
2183 CYASSL_MSG("\tfail: constraint not BOOLEAN");
2187 if (GetLength(input, &idx, &length, sz) < 0)
2189 CYASSL_MSG("\tfail: length");
2198 #define CRLDP_FULL_NAME 0
2199 /* From RFC3280 SS4.2.1.14, Distribution Point Name*/
2200 #define GENERALNAME_URI 6
2201 /* From RFC3280 SS4.2.1.7, GeneralName */
2203 static void DecodeCrlDist(byte* input, int sz, DecodedCert* cert)
2208 CYASSL_ENTER("DecodeCrlDist");
2210 /* Unwrap the list of Distribution Points*/
2211 if (GetSequence(input, &idx, &length, sz) < 0) return;
2213 /* Unwrap a single Distribution Point */
2214 if (GetSequence(input, &idx, &length, sz) < 0) return;
2216 /* The Distribution Point has three explicit optional members
2217 * First check for a DistributionPointName
2219 if (input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
2222 if (GetLength(input, &idx, &length, sz) < 0) return;
2225 (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CRLDP_FULL_NAME))
2228 if (GetLength(input, &idx, &length, sz) < 0) return;
2230 if (input[idx] == (ASN_CONTEXT_SPECIFIC | GENERALNAME_URI))
2233 if (GetLength(input, &idx, &length, sz) < 0) return;
2235 cert->extCrlInfoSz = length;
2236 cert->extCrlInfo = input + idx;
2240 /* This isn't a URI, skip it. */
2244 /* This isn't a FULLNAME, skip it. */
2248 /* Check for reasonFlags */
2249 if (idx < (word32)sz &&
2250 input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
2253 if (GetLength(input, &idx, &length, sz) < 0) return;
2257 /* Check for cRLIssuer */
2258 if (idx < (word32)sz &&
2259 input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
2262 if (GetLength(input, &idx, &length, sz) < 0) return;
2266 if (idx < (word32)sz)
2268 CYASSL_MSG("\tThere are more CRL Distribution Point records, "
2269 "but we only use the first one.");
2276 static void DecodeAuthInfo(byte* input, int sz, DecodedCert* cert)
2278 * Read the first of the Authority Information Access records. If there are
2279 * any issues, return without saving the record.
2286 /* Unwrap the list of AIAs */
2287 if (GetSequence(input, &idx, &length, sz) < 0) return;
2289 /* Unwrap a single AIA */
2290 if (GetSequence(input, &idx, &length, sz) < 0) return;
2293 if (GetObjectId(input, &idx, &oid, sz) < 0) return;
2295 /* Only supporting URIs right now. */
2296 if (input[idx] == (ASN_CONTEXT_SPECIFIC | GENERALNAME_URI))
2299 if (GetLength(input, &idx, &length, sz) < 0) return;
2301 cert->extAuthInfoSz = length;
2302 cert->extAuthInfo = input + idx;
2307 /* Skip anything else. */
2309 if (GetLength(input, &idx, &length, sz) < 0) return;
2313 if (idx < (word32)sz)
2315 CYASSL_MSG("\tThere are more Authority Information Access records, "
2316 "but we only use first one.");
2323 static void DecodeCertExtensions(DecodedCert* cert)
2325 * Processing the Certificate Extensions. This does not modify the current
2326 * index. It is works starting with the recorded extensions pointer.
2330 int sz = cert->extensionsSz;
2331 byte* input = cert->extensions;
2335 CYASSL_ENTER("DecodeCertExtensions");
2337 if (input == NULL || sz == 0) return;
2339 if (input[idx++] != ASN_EXTENSIONS) return;
2341 if (GetLength(input, &idx, &length, sz) < 0) return;
2343 if (GetSequence(input, &idx, &length, sz) < 0) return;
2345 while (idx < (word32)sz) {
2346 if (GetSequence(input, &idx, &length, sz) < 0) {
2347 CYASSL_MSG("\tfail: should be a SEQUENCE");
2352 if (GetObjectId(input, &idx, &oid, sz) < 0) {
2353 CYASSL_MSG("\tfail: OBJECT ID");
2357 /* check for critical flag */
2358 if (input[idx] == ASN_BOOLEAN) {
2359 CYASSL_MSG("\tfound optional critical flag, moving past");
2360 idx += (ASN_BOOL_SIZE + 1);
2363 /* process the extension based on the OID */
2364 if (input[idx++] != ASN_OCTET_STRING) {
2365 CYASSL_MSG("\tfail: should be an OCTET STRING");
2369 if (GetLength(input, &idx, &length, sz) < 0) {
2370 CYASSL_MSG("\tfail: extension data length");
2376 DecodeBasicCaConstraint(&input[idx], length, cert);
2380 DecodeCrlDist(&input[idx], length, cert);
2384 DecodeAuthInfo(&input[idx], length, cert);
2388 DecodeAltNames(&input[idx], length, cert);
2391 CYASSL_MSG("\tExtension type not handled, skipping");
2401 int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
2406 ret = ParseCertRelative(cert, type, verify, cm);
2410 if (cert->subjectCNLen > 0) {
2411 ptr = (char*) XMALLOC(cert->subjectCNLen + 1, cert->heap,
2412 DYNAMIC_TYPE_SUBJECT_CN);
2415 XMEMCPY(ptr, cert->subjectCN, cert->subjectCNLen);
2416 ptr[cert->subjectCNLen] = '\0';
2417 cert->subjectCN = ptr;
2418 cert->subjectCNStored = 1;
2421 if (cert->keyOID == RSAk && cert->pubKeySize > 0) {
2422 ptr = (char*) XMALLOC(cert->pubKeySize, cert->heap,
2423 DYNAMIC_TYPE_PUBLIC_KEY);
2426 XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
2427 cert->publicKey = (byte *)ptr;
2428 cert->pubKeyStored = 1;
2435 /* from SSL proper, for locking can't do find here anymore */
2439 CYASSL_LOCAL Signer* GetCA(void* signers, byte* hash);
2445 int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
2451 if ((ret = DecodeToKey(cert, verify)) < 0) {
2452 if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E)
2458 if (cert->srcIdx != cert->sigIndex) {
2459 if (cert->srcIdx < cert->sigIndex) {
2460 /* save extensions */
2461 cert->extensions = &cert->source[cert->srcIdx];
2462 cert->extensionsSz = cert->sigIndex - cert->srcIdx;
2463 cert->extensionsIdx = cert->srcIdx; /* for potential later use */
2465 DecodeCertExtensions(cert);
2466 /* advance past extensions */
2467 cert->srcIdx = cert->sigIndex;
2470 if ((ret = GetAlgoId(cert->source, &cert->srcIdx, &confirmOID,
2474 if ((ret = GetSignature(cert)) < 0)
2477 if (confirmOID != cert->signatureOID)
2478 return ASN_SIG_OID_E;
2480 if (verify && type != CA_TYPE) {
2481 Signer* ca = GetCA(cm, cert->issuerHash);
2482 CYASSL_MSG("About to verify certificate signature");
2486 /* Need the ca's public key hash for OCSP */
2490 ShaUpdate(&sha, ca->publicKey, ca->pubKeySize);
2491 ShaFinal(&sha, cert->issuerKeyHash);
2493 #endif /* HAVE_OCSP */
2494 /* try to confirm/verify signature */
2495 if (!ConfirmSignature(cert->source + cert->certBegin,
2496 cert->sigIndex - cert->certBegin,
2497 ca->publicKey, ca->pubKeySize, ca->keyOID,
2498 cert->signature, cert->sigLength, cert->signatureOID,
2500 CYASSL_MSG("Confirm signature failed");
2501 return ASN_SIG_CONFIRM_E;
2506 CYASSL_MSG("No CA signer to verify with");
2507 return ASN_SIG_CONFIRM_E;
2518 Signer* MakeSigner(void* heap)
2520 Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
2521 DYNAMIC_TYPE_SIGNER);
2524 signer->publicKey = 0;
2533 void FreeSigners(Signer* signer, void* heap)
2536 Signer* next = signer->next;
2538 XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
2539 XFREE(signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
2540 XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
2548 void CTaoCryptErrorString(int error, char* buffer)
2550 const int max = MAX_ERROR_SZ; /* shorthand */
2552 #ifdef NO_ERROR_STRINGS
2554 XSTRNCPY(buffer, "no support for error strings built in", max);
2561 XSTRNCPY(buffer, "opening random device error", max);
2565 XSTRNCPY(buffer, "reading random device error", max);
2569 XSTRNCPY(buffer, "windows crypt init error", max);
2573 XSTRNCPY(buffer, "windows crypt generation error", max);
2577 XSTRNCPY(buffer, "random device read would block error", max);
2581 XSTRNCPY(buffer, "mp_init error state", max);
2585 XSTRNCPY(buffer, "mp_read error state", max);
2589 XSTRNCPY(buffer, "mp_exptmod error state", max);
2593 XSTRNCPY(buffer, "mp_to_xxx error state, can't convert", max);
2597 XSTRNCPY(buffer, "mp_sub error state, can't subtract", max);
2601 XSTRNCPY(buffer, "mp_add error state, can't add", max);
2605 XSTRNCPY(buffer, "mp_mul error state, can't multiply", max);
2609 XSTRNCPY(buffer, "mp_mulmod error state, can't multiply mod", max);
2613 XSTRNCPY(buffer, "mp_mod error state, can't mod", max);
2617 XSTRNCPY(buffer, "mp_invmod error state, can't inv mod", max);
2621 XSTRNCPY(buffer, "mp_cmp error state", max);
2625 XSTRNCPY(buffer, "mp zero result, not expected", max);
2629 XSTRNCPY(buffer, "out of memory error", max);
2632 case RSA_WRONG_TYPE_E :
2633 XSTRNCPY(buffer, "RSA wrong block type for RSA function", max);
2637 XSTRNCPY(buffer, "RSA buffer error, output too small or input too big",
2642 XSTRNCPY(buffer, "Buffer error, output too small or input too big",max);
2646 XSTRNCPY(buffer, "Setting Cert AlogID error", max);
2650 XSTRNCPY(buffer, "Setting Cert Public Key error", max);
2654 XSTRNCPY(buffer, "Setting Cert Date validity error", max);
2658 XSTRNCPY(buffer, "Setting Cert Subject name error", max);
2662 XSTRNCPY(buffer, "Setting Cert Issuer name error", max);
2666 XSTRNCPY(buffer, "Setting basic constraint CA true error", max);
2670 XSTRNCPY(buffer, "Setting extensions error", max);
2674 XSTRNCPY(buffer, "ASN parsing error, invalid input", max);
2677 case ASN_VERSION_E :
2678 XSTRNCPY(buffer, "ASN version error, invalid number", max);
2682 XSTRNCPY(buffer, "ASN get big int error, invalid data", max);
2685 case ASN_RSA_KEY_E :
2686 XSTRNCPY(buffer, "ASN key init error, invalid input", max);
2689 case ASN_OBJECT_ID_E :
2690 XSTRNCPY(buffer, "ASN object id error, invalid id", max);
2693 case ASN_TAG_NULL_E :
2694 XSTRNCPY(buffer, "ASN tag error, not null", max);
2697 case ASN_EXPECT_0_E :
2698 XSTRNCPY(buffer, "ASN expect error, not zero", max);
2702 XSTRNCPY(buffer, "ASN bit string error, wrong id", max);
2705 case ASN_UNKNOWN_OID_E :
2706 XSTRNCPY(buffer, "ASN oid error, unknown sum id", max);
2709 case ASN_DATE_SZ_E :
2710 XSTRNCPY(buffer, "ASN date error, bad size", max);
2713 case ASN_BEFORE_DATE_E :
2714 XSTRNCPY(buffer, "ASN date error, current date before", max);
2717 case ASN_AFTER_DATE_E :
2718 XSTRNCPY(buffer, "ASN date error, current date after", max);
2721 case ASN_SIG_OID_E :
2722 XSTRNCPY(buffer, "ASN signature error, mismatched oid", max);
2726 XSTRNCPY(buffer, "ASN time error, unkown time type", max);
2730 XSTRNCPY(buffer, "ASN input error, not enough data", max);
2733 case ASN_SIG_CONFIRM_E :
2734 XSTRNCPY(buffer, "ASN sig error, confirm failure", max);
2737 case ASN_SIG_HASH_E :
2738 XSTRNCPY(buffer, "ASN sig error, unsupported hash type", max);
2741 case ASN_SIG_KEY_E :
2742 XSTRNCPY(buffer, "ASN sig error, unsupported key type", max);
2746 XSTRNCPY(buffer, "ASN key init error, invalid input", max);
2749 case ASN_NTRU_KEY_E :
2750 XSTRNCPY(buffer, "ASN NTRU key decode error, invalid input", max);
2753 case ECC_BAD_ARG_E :
2754 XSTRNCPY(buffer, "ECC input argument wrong type, invalid input", max);
2757 case ASN_ECC_KEY_E :
2758 XSTRNCPY(buffer, "ECC ASN1 bad key data, invalid input", max);
2761 case ECC_CURVE_OID_E :
2762 XSTRNCPY(buffer, "ECC curve sum OID unsupported, invalid input", max);
2766 XSTRNCPY(buffer, "Bad function argument", max);
2769 case NOT_COMPILED_IN :
2770 XSTRNCPY(buffer, "Feature not compiled in", max);
2773 case UNICODE_SIZE_E :
2774 XSTRNCPY(buffer, "Unicode password too big", max);
2778 XSTRNCPY(buffer, "No password provided by user", max);
2782 XSTRNCPY(buffer, "Alt Name problem, too big", max);
2785 case AES_GCM_AUTH_E:
2786 XSTRNCPY(buffer, "AES-GCM Authentication check fail", max);
2790 XSTRNCPY(buffer, "unknown error number", max);
2794 #endif /* NO_ERROR_STRINGS */
2799 #if defined(CYASSL_KEY_GEN) || defined(CYASSL_CERT_GEN)
2801 static int SetMyVersion(word32 version, byte* output, int header)
2806 output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
2807 output[i++] = ASN_BIT_STRING;
2809 output[i++] = ASN_INTEGER;
2811 output[i++] = (byte)version;
2817 int DerToPem(const byte* der, word32 derSz, byte* output, word32 outSz,
2827 int outLen; /* return length or error */
2829 if (type == CERT_TYPE) {
2830 XSTRNCPY(header, "-----BEGIN CERTIFICATE-----\n", sizeof(header));
2831 XSTRNCPY(footer, "-----END CERTIFICATE-----\n", sizeof(footer));
2833 XSTRNCPY(header, "-----BEGIN RSA PRIVATE KEY-----\n", sizeof(header));
2834 XSTRNCPY(footer, "-----END RSA PRIVATE KEY-----\n", sizeof(footer));
2837 headerLen = XSTRLEN(header);
2838 footerLen = XSTRLEN(footer);
2840 if (!der || !output)
2841 return BAD_FUNC_ARG;
2843 /* don't even try if outSz too short */
2844 if (outSz < headerLen + footerLen + derSz)
2845 return BAD_FUNC_ARG;
2848 XMEMCPY(output, header, headerLen);
2852 outLen = outSz; /* input to Base64_Encode */
2853 if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0)
2858 if ( (i + footerLen) > (int)outSz)
2859 return BAD_FUNC_ARG;
2860 XMEMCPY(output + i, footer, footerLen);
2862 return outLen + headerLen + footerLen;
2866 #endif /* CYASSL_KEY_GEN || CYASSL_CERT_GEN */
2869 #ifdef CYASSL_KEY_GEN
2872 static mp_int* GetRsaInt(RsaKey* key, int idx)
2895 /* Convert RsaKey key to DER format, write to output (inLen), return bytes
2897 int RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
2899 word32 seqSz, verSz, rawLen, intTotalLen = 0;
2900 word32 sizes[RSA_INTS];
2903 byte seq[MAX_SEQ_SZ];
2904 byte ver[MAX_VERSION_SZ];
2905 byte tmps[RSA_INTS][MAX_RSA_INT_SZ];
2907 if (!key || !output)
2908 return BAD_FUNC_ARG;
2910 if (key->type != RSA_PRIVATE)
2911 return BAD_FUNC_ARG;
2913 /* write all big ints from key to DER tmps */
2914 for (i = 0; i < RSA_INTS; i++) {
2915 mp_int* keyInt = GetRsaInt(key, i);
2916 rawLen = mp_unsigned_bin_size(keyInt);
2918 tmps[i][0] = ASN_INTEGER;
2919 sizes[i] = SetLength(rawLen, tmps[i] + 1) + 1; /* int tag */
2921 if ( (sizes[i] + rawLen) < sizeof(tmps[i])) {
2922 int err = mp_to_unsigned_bin(keyInt, tmps[i] + sizes[i]);
2923 if (err == MP_OKAY) {
2925 intTotalLen += sizes[i];
2935 verSz = SetMyVersion(0, ver, FALSE);
2936 seqSz = SetSequence(verSz + intTotalLen, seq);
2938 outLen = seqSz + verSz + intTotalLen;
2939 if (outLen > (int)inLen)
2940 return BAD_FUNC_ARG;
2942 /* write to output */
2943 XMEMCPY(output, seq, seqSz);
2945 XMEMCPY(output + j, ver, verSz);
2948 for (i = 0; i < RSA_INTS; i++) {
2949 XMEMCPY(output + j, tmps[i], sizes[i]);
2956 #endif /* CYASSL_KEY_GEN */
2959 #ifdef CYASSL_CERT_GEN
2961 /* Initialize and Set Certficate defaults:
2964 sigType = SHA_WITH_RSA
2967 selfSigned = 1 (true) use subject as issuer
2970 void InitCert(Cert* cert)
2972 cert->version = 2; /* version 3 is hex 2 */
2973 cert->sigType = CTC_SHAwRSA;
2974 cert->daysValid = 500;
2975 cert->selfSigned = 1;
2978 #ifdef CYASSL_ALT_NAMES
2979 cert->altNamesSz = 0;
2980 cert->beforeDateSz = 0;
2981 cert->afterDateSz = 0;
2983 cert->keyType = RSA_KEY;
2984 XMEMSET(cert->serial, 0, CTC_SERIAL_SIZE);
2986 cert->issuer.country[0] = '\0';
2987 cert->issuer.state[0] = '\0';
2988 cert->issuer.locality[0] = '\0';
2989 cert->issuer.sur[0] = '\0';
2990 cert->issuer.org[0] = '\0';
2991 cert->issuer.unit[0] = '\0';
2992 cert->issuer.commonName[0] = '\0';
2993 cert->issuer.email[0] = '\0';
2995 cert->subject.country[0] = '\0';
2996 cert->subject.state[0] = '\0';
2997 cert->subject.locality[0] = '\0';
2998 cert->subject.sur[0] = '\0';
2999 cert->subject.org[0] = '\0';
3000 cert->subject.unit[0] = '\0';
3001 cert->subject.commonName[0] = '\0';
3002 cert->subject.email[0] = '\0';
3006 /* DER encoded x509 Certificate */
3007 typedef struct DerCert {
3008 byte size[MAX_LENGTH_SZ]; /* length encoded */
3009 byte version[MAX_VERSION_SZ]; /* version encoded */
3010 byte serial[CTC_SERIAL_SIZE + MAX_LENGTH_SZ]; /* serial number encoded */
3011 byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
3012 byte issuer[ASN_NAME_MAX]; /* issuer encoded */
3013 byte subject[ASN_NAME_MAX]; /* subject encoded */
3014 byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
3015 byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa / ntru public key encoded */
3016 byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
3017 byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
3018 int sizeSz; /* encoded size length */
3019 int versionSz; /* encoded version length */
3020 int serialSz; /* encoded serial length */
3021 int sigAlgoSz; /* enocded sig alog length */
3022 int issuerSz; /* encoded issuer length */
3023 int subjectSz; /* encoded subject length */
3024 int validitySz; /* encoded validity length */
3025 int publicKeySz; /* encoded public key length */
3026 int caSz; /* encoded CA extension length */
3027 int extensionsSz; /* encoded extensions total length */
3028 int total; /* total encoded lengths */
3032 /* Write a set header to output */
3033 static word32 SetSet(word32 len, byte* output)
3035 output[0] = ASN_SET | ASN_CONSTRUCTED;
3036 return SetLength(len, output + 1) + 1;
3040 /* Write a serial number to output */
3041 static int SetSerial(const byte* serial, byte* output)
3045 output[length++] = ASN_INTEGER;
3046 length += SetLength(CTC_SERIAL_SIZE, &output[length]);
3047 XMEMCPY(&output[length], serial, CTC_SERIAL_SIZE);
3049 return length + CTC_SERIAL_SIZE;
3053 /* Write a public RSA key to output */
3054 static int SetPublicKey(byte* output, RsaKey* key)
3056 byte n[MAX_RSA_INT_SZ];
3057 byte e[MAX_RSA_E_SZ];
3058 byte algo[MAX_ALGO_SZ];
3059 byte seq[MAX_SEQ_SZ];
3060 byte len[MAX_LENGTH_SZ + 1]; /* trailing 0 */
3070 rawLen = mp_unsigned_bin_size(&key->n);
3072 nSz = SetLength(rawLen, n + 1) + 1; /* int tag */
3074 if ( (nSz + rawLen) < (int)sizeof(n)) {
3075 int err = mp_to_unsigned_bin(&key->n, n + nSz);
3085 rawLen = mp_unsigned_bin_size(&key->e);
3087 eSz = SetLength(rawLen, e + 1) + 1; /* int tag */
3089 if ( (eSz + rawLen) < (int)sizeof(e)) {
3090 int err = mp_to_unsigned_bin(&key->e, e + eSz);
3100 algoSz = SetAlgoID(RSAk, algo, keyType);
3101 seqSz = SetSequence(nSz + eSz, seq);
3102 lenSz = SetLength(seqSz + nSz + eSz + 1, len);
3103 len[lenSz++] = 0; /* trailing 0 */
3106 idx = SetSequence(nSz + eSz + seqSz + lenSz + 1 + algoSz, output);
3107 /* 1 is for ASN_BIT_STRING */
3109 XMEMCPY(output + idx, algo, algoSz);
3112 output[idx++] = ASN_BIT_STRING;
3114 XMEMCPY(output + idx, len, lenSz);
3117 XMEMCPY(output + idx, seq, seqSz);
3120 XMEMCPY(output + idx, n, nSz);
3123 XMEMCPY(output + idx, e, eSz);
3130 static INLINE byte itob(int number)
3132 return (byte)number + 0x30;
3136 /* write time to output, format */
3137 static void SetTime(struct tm* date, byte* output)
3141 output[i++] = itob((date->tm_year % 10000) / 1000);
3142 output[i++] = itob((date->tm_year % 1000) / 100);
3143 output[i++] = itob((date->tm_year % 100) / 10);
3144 output[i++] = itob( date->tm_year % 10);
3146 output[i++] = itob(date->tm_mon / 10);
3147 output[i++] = itob(date->tm_mon % 10);
3149 output[i++] = itob(date->tm_mday / 10);
3150 output[i++] = itob(date->tm_mday % 10);
3152 output[i++] = itob(date->tm_hour / 10);
3153 output[i++] = itob(date->tm_hour % 10);
3155 output[i++] = itob(date->tm_min / 10);
3156 output[i++] = itob(date->tm_min % 10);
3158 output[i++] = itob(date->tm_sec / 10);
3159 output[i++] = itob(date->tm_sec % 10);
3161 output[i] = 'Z'; /* Zulu profile */
3165 #ifdef CYASSL_ALT_NAMES
3167 /* Copy Dates from cert, return bytes written */
3168 static int CopyValidity(byte* output, Cert* cert)
3172 CYASSL_ENTER("CopyValidity");
3174 /* headers and output */
3175 seqSz = SetSequence(cert->beforeDateSz + cert->afterDateSz, output);
3176 XMEMCPY(output + seqSz, cert->beforeDate, cert->beforeDateSz);
3177 XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
3179 return seqSz + cert->beforeDateSz + cert->afterDateSz;
3185 /* Set Date validity from now until now + daysValid */
3186 static int SetValidity(byte* output, int daysValid)
3188 byte before[MAX_DATE_SIZE];
3189 byte after[MAX_DATE_SIZE];
3200 now = XGMTIME(&ticks);
3204 before[0] = ASN_GENERALIZED_TIME;
3205 beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
3207 /* subtract 1 day for more compliance */
3212 local.tm_year += 1900;
3215 SetTime(&local, before + beforeSz);
3216 beforeSz += ASN_GEN_TIME_SZ;
3218 /* after now + daysValid */
3220 after[0] = ASN_GENERALIZED_TIME;
3221 afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
3224 local.tm_mday += daysValid;
3228 local.tm_year += 1900;
3231 SetTime(&local, after + afterSz);
3232 afterSz += ASN_GEN_TIME_SZ;
3234 /* headers and output */
3235 seqSz = SetSequence(beforeSz + afterSz, output);
3236 XMEMCPY(output + seqSz, before, beforeSz);
3237 XMEMCPY(output + seqSz + beforeSz, after, afterSz);
3239 return seqSz + beforeSz + afterSz;
3243 /* ASN Encoded Name field */
3244 typedef struct EncodedName {
3245 int nameLen; /* actual string value length */
3246 int totalLen; /* total encoded length */
3247 int type; /* type of name */
3248 int used; /* are we actually using this one */
3249 byte encoded[CTC_NAME_SIZE * 2]; /* encoding */
3253 /* Get Which Name from index */
3254 static const char* GetOneName(CertName* name, int idx)
3258 return name->country;
3264 return name->locality;
3276 return name->commonName;
3287 /* Get ASN Name from index */
3288 static byte GetNameId(int idx)
3292 return ASN_COUNTRY_NAME;
3295 return ASN_STATE_NAME;
3298 return ASN_LOCALITY_NAME;
3301 return ASN_SUR_NAME;
3304 return ASN_ORG_NAME;
3307 return ASN_ORGUNIT_NAME;
3310 return ASN_COMMON_NAME;
3313 /* email uses different id type */
3322 /* encode all extensions, return total bytes written */
3323 static int SetExtensions(byte* output, const byte* ext, int extSz)
3325 byte sequence[MAX_SEQ_SZ];
3326 byte len[MAX_LENGTH_SZ];
3329 int seqSz = SetSequence(extSz, sequence);
3330 int lenSz = SetLength(seqSz + extSz, len);
3332 output[0] = ASN_EXTENSIONS; /* extensions id */
3334 XMEMCPY(&output[sz], len, lenSz); /* length */
3336 XMEMCPY(&output[sz], sequence, seqSz); /* sequence */
3338 XMEMCPY(&output[sz], ext, extSz); /* extensions */
3345 /* encode CA basic constraint true, return total bytes written */
3346 static int SetCa(byte* output)
3348 static const byte ca[] = { 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
3349 0x05, 0x30, 0x03, 0x01, 0x01, 0xff };
3351 XMEMCPY(output, ca, sizeof(ca));
3353 return (int)sizeof(ca);
3357 /* encode CertName into output, return total bytes written */
3358 static int SetName(byte* output, CertName* name)
3360 int totalBytes = 0, i, idx;
3361 EncodedName names[NAME_ENTRIES];
3363 for (i = 0; i < NAME_ENTRIES; i++) {
3364 const char* nameStr = GetOneName(name, i);
3367 byte firstLen[MAX_LENGTH_SZ];
3368 byte secondLen[MAX_LENGTH_SZ];
3369 byte sequence[MAX_SEQ_SZ];
3370 byte set[MAX_SET_SZ];
3372 int email = i == (NAME_ENTRIES - 1) ? 1 : 0;
3373 int strLen = XSTRLEN(nameStr);
3374 int thisLen = strLen;
3375 int firstSz, secondSz, seqSz, setSz;
3377 if (strLen == 0) { /* no user data for this item */
3382 secondSz = SetLength(strLen, secondLen);
3383 thisLen += secondSz;
3385 thisLen += EMAIL_JOINT_LEN;
3386 thisLen ++; /* id type */
3387 firstSz = SetLength(EMAIL_JOINT_LEN, firstLen);
3390 thisLen++; /* str type */
3391 thisLen++; /* id type */
3392 thisLen += JOINT_LEN;
3393 firstSz = SetLength(JOINT_LEN + 1, firstLen);
3396 thisLen++; /* object id */
3398 seqSz = SetSequence(thisLen, sequence);
3400 setSz = SetSet(thisLen, set);
3403 if (thisLen > (int)sizeof(names[i].encoded))
3409 XMEMCPY(names[i].encoded, set, setSz);
3412 XMEMCPY(names[i].encoded + idx, sequence, seqSz);
3415 names[i].encoded[idx++] = ASN_OBJECT_ID;
3417 XMEMCPY(names[i].encoded + idx, firstLen, firstSz);
3420 const byte EMAIL_OID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
3421 0x01, 0x09, 0x01, 0x16 };
3422 /* email joint id */
3423 XMEMCPY(names[i].encoded + idx, EMAIL_OID, sizeof(EMAIL_OID));
3424 idx += sizeof(EMAIL_OID);
3428 names[i].encoded[idx++] = 0x55;
3429 names[i].encoded[idx++] = 0x04;
3431 names[i].encoded[idx++] = GetNameId(i);
3433 names[i].encoded[idx++] = 0x13;
3436 XMEMCPY(names[i].encoded + idx, secondLen, secondSz);
3439 XMEMCPY(names[i].encoded + idx, nameStr, strLen);
3443 names[i].totalLen = idx;
3451 idx = SetSequence(totalBytes, output);
3453 if (totalBytes > ASN_NAME_MAX)
3456 for (i = 0; i < NAME_ENTRIES; i++) {
3457 if (names[i].used) {
3458 XMEMCPY(output + idx, names[i].encoded, names[i].totalLen);
3459 idx += names[i].totalLen;
3466 /* encode info from cert into DER enocder format */
3467 static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, RNG* rng,
3468 const byte* ntruKey, word16 ntruSz)
3473 der->versionSz = SetMyVersion(cert->version, der->version, TRUE);
3476 RNG_GenerateBlock(rng, cert->serial, CTC_SERIAL_SIZE);
3477 cert->serial[0] = 0x01; /* ensure positive */
3478 der->serialSz = SetSerial(cert->serial, der->serial);
3480 /* signature algo */
3481 der->sigAlgoSz = SetAlgoID(cert->sigType, der->sigAlgo, sigType);
3482 if (der->sigAlgoSz == 0)
3486 if (cert->keyType == RSA_KEY) {
3487 der->publicKeySz = SetPublicKey(der->publicKey, rsaKey);
3488 if (der->publicKeySz == 0)
3489 return PUBLIC_KEY_E;
3496 rc = crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo( ntruSz,
3497 ntruKey, &encodedSz, NULL);
3499 return PUBLIC_KEY_E;
3500 if (encodedSz > MAX_PUBLIC_KEY_SZ)
3501 return PUBLIC_KEY_E;
3503 rc = crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo( ntruSz,
3504 ntruKey, &encodedSz, der->publicKey);
3506 return PUBLIC_KEY_E;
3508 der->publicKeySz = encodedSz;
3512 der->validitySz = 0;
3513 #ifdef CYASSL_ALT_NAMES
3514 /* date validity copy ? */
3515 if (cert->beforeDateSz && cert->afterDateSz) {
3516 der->validitySz = CopyValidity(der->validity, cert);
3517 if (der->validitySz == 0)
3523 if (der->validitySz == 0) {
3524 der->validitySz = SetValidity(der->validity, cert->daysValid);
3525 if (der->validitySz == 0)
3530 der->subjectSz = SetName(der->subject, &cert->subject);
3531 if (der->subjectSz == 0)
3535 der->issuerSz = SetName(der->issuer, cert->selfSigned ?
3536 &cert->subject : &cert->issuer);
3537 if (der->issuerSz == 0)
3542 der->caSz = SetCa(der->ca);
3549 /* extensions, just CA now */
3551 der->extensionsSz = SetExtensions(der->extensions, der->ca, der->caSz);
3552 if (der->extensionsSz == 0)
3553 return EXTENSIONS_E;
3556 der->extensionsSz = 0;
3558 #ifdef CYASSL_ALT_NAMES
3559 if (der->extensionsSz == 0 && cert->altNamesSz) {
3560 der->extensionsSz = SetExtensions(der->extensions, cert->altNames,
3562 if (der->extensionsSz == 0)
3563 return EXTENSIONS_E;
3567 der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
3568 der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
3575 /* write DER encoded cert to buffer, size already checked */
3576 static int WriteCertBody(DerCert* der, byte* buffer)
3580 /* signed part header */
3581 idx = SetSequence(der->total, buffer);
3583 XMEMCPY(buffer + idx, der->version, der->versionSz);
3584 idx += der->versionSz;
3586 XMEMCPY(buffer + idx, der->serial, der->serialSz);
3587 idx += der->serialSz;
3589 XMEMCPY(buffer + idx, der->sigAlgo, der->sigAlgoSz);
3590 idx += der->sigAlgoSz;
3592 XMEMCPY(buffer + idx, der->issuer, der->issuerSz);
3593 idx += der->issuerSz;
3595 XMEMCPY(buffer + idx, der->validity, der->validitySz);
3596 idx += der->validitySz;
3598 XMEMCPY(buffer + idx, der->subject, der->subjectSz);
3599 idx += der->subjectSz;
3601 XMEMCPY(buffer + idx, der->publicKey, der->publicKeySz);
3602 idx += der->publicKeySz;
3603 if (der->extensionsSz) {
3605 XMEMCPY(buffer + idx, der->extensions, min(der->extensionsSz,
3606 sizeof(der->extensions)));
3607 idx += der->extensionsSz;
3614 /* Make RSA signature from buffer (sz), write to sig (sigSz) */
3615 static int MakeSignature(const byte* buffer, int sz, byte* sig, int sigSz,
3616 RsaKey* key, RNG* rng, int sigAlgoType)
3618 byte digest[SHA256_DIGEST_SIZE]; /* max size */
3619 byte encSig[MAX_ENCODED_DIG_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ];
3620 int encSigSz, digestSz, typeH;
3622 if (sigAlgoType == CTC_MD5wRSA) {
3625 Md5Update(&md5, buffer, sz);
3626 Md5Final(&md5, digest);
3627 digestSz = MD5_DIGEST_SIZE;
3630 else if (sigAlgoType == CTC_SHAwRSA) {
3633 ShaUpdate(&sha, buffer, sz);
3634 ShaFinal(&sha, digest);
3635 digestSz = SHA_DIGEST_SIZE;
3638 else if (sigAlgoType == CTC_SHA256wRSA) {
3640 InitSha256(&sha256);
3641 Sha256Update(&sha256, buffer, sz);
3642 Sha256Final(&sha256, digest);
3643 digestSz = SHA256_DIGEST_SIZE;
3650 encSigSz = EncodeSignature(encSig, digest, digestSz, typeH);
3651 return RsaSSL_Sign(encSig, encSigSz, sig, sigSz, key, rng);
3655 /* add signature to end of buffer, size of buffer assumed checked, return
3657 static int AddSignature(byte* buffer, int bodySz, const byte* sig, int sigSz,
3660 byte seq[MAX_SEQ_SZ];
3661 int idx = bodySz, seqSz;
3664 idx += SetAlgoID(sigAlgoType, buffer + idx, sigType);
3666 buffer[idx++] = ASN_BIT_STRING;
3668 idx += SetLength(sigSz + 1, buffer + idx);
3669 buffer[idx++] = 0; /* trailing 0 */
3671 XMEMCPY(buffer + idx, sig, sigSz);
3674 /* make room for overall header */
3675 seqSz = SetSequence(idx, seq);
3676 XMEMMOVE(buffer + seqSz, buffer, idx);
3677 XMEMCPY(buffer, seq, seqSz);
3683 /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
3684 static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
3685 RsaKey* rsaKey, RNG* rng, const byte* ntruKey, word16 ntruSz)
3690 cert->keyType = rsaKey ? RSA_KEY : NTRU_KEY;
3691 ret = EncodeCert(cert, &der, rsaKey, rng, ntruKey, ntruSz);
3695 if (der.total + MAX_SEQ_SZ * 2 > (int)derSz)
3698 return cert->bodySz = WriteCertBody(&der, derBuffer);
3702 /* Make an x509 Certificate v3 RSA from cert input, write to buffer */
3703 int MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,RNG* rng)
3705 return MakeAnyCert(cert, derBuffer, derSz, rsaKey, rng, NULL, 0);
3711 int MakeNtruCert(Cert* cert, byte* derBuffer, word32 derSz,
3712 const byte* ntruKey, word16 keySz, RNG* rng)
3714 return MakeAnyCert(cert, derBuffer, derSz, NULL, rng, ntruKey, keySz);
3717 #endif /* HAVE_NTRU */
3720 int SignCert(Cert* cert, byte* buffer, word32 buffSz, RsaKey* key, RNG* rng)
3722 byte sig[MAX_ENCODED_SIG_SZ];
3724 int bodySz = cert->bodySz;
3729 sigSz = MakeSignature(buffer, bodySz, sig, sizeof(sig), key, rng,
3734 if (bodySz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
3737 return AddSignature(buffer, bodySz, sig, sigSz, cert->sigType);
3741 int MakeSelfCert(Cert* cert, byte* buffer, word32 buffSz, RsaKey* key, RNG* rng)
3743 int ret = MakeCert(cert, buffer, buffSz, key, rng);
3748 return SignCert(cert, buffer, buffSz, key, rng);
3752 #ifdef CYASSL_ALT_NAMES
3754 /* Set Alt Names from der cert, return 0 on success */
3755 static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz)
3757 DecodedCert decoded;
3763 InitDecodedCert(&decoded, (byte*)der, derSz, 0);
3764 ret = ParseCertRelative(&decoded, CA_TYPE, NO_VERIFY, 0);
3767 FreeDecodedCert(&decoded);
3771 if (decoded.extensions) {
3774 word32 maxExtensionsIdx;
3776 decoded.srcIdx = decoded.extensionsIdx;
3777 b = decoded.source[decoded.srcIdx++];
3778 if (b != ASN_EXTENSIONS) {
3779 FreeDecodedCert(&decoded);
3783 if (GetLength(decoded.source, &decoded.srcIdx, &length,
3784 decoded.maxIdx) < 0) {
3785 FreeDecodedCert(&decoded);
3789 if (GetSequence(decoded.source, &decoded.srcIdx, &length,
3790 decoded.maxIdx) < 0) {
3791 FreeDecodedCert(&decoded);
3795 maxExtensionsIdx = decoded.srcIdx + length;
3797 while (decoded.srcIdx < maxExtensionsIdx) {
3799 word32 startIdx = decoded.srcIdx;
3802 if (GetSequence(decoded.source, &decoded.srcIdx, &length,
3803 decoded.maxIdx) < 0) {
3804 FreeDecodedCert(&decoded);
3808 tmpIdx = decoded.srcIdx;
3809 decoded.srcIdx = startIdx;
3811 if (GetAlgoId(decoded.source, &decoded.srcIdx, &oid,
3812 decoded.maxIdx) < 0) {
3813 FreeDecodedCert(&decoded);
3817 if (oid == ALT_NAMES_OID) {
3818 cert->altNamesSz = length + (tmpIdx - startIdx);
3820 if (cert->altNamesSz < (int)sizeof(cert->altNames))
3821 XMEMCPY(cert->altNames, &decoded.source[startIdx],
3824 cert->altNamesSz = 0;
3825 CYASSL_MSG("AltNames extensions too big");
3826 FreeDecodedCert(&decoded);
3830 decoded.srcIdx = tmpIdx + length;
3833 FreeDecodedCert(&decoded);
3839 /* Set Dates from der cert, return 0 on success */
3840 static int SetDatesFromCert(Cert* cert, const byte* der, int derSz)
3842 DecodedCert decoded;
3845 CYASSL_ENTER("SetDatesFromCert");
3849 InitDecodedCert(&decoded, (byte*)der, derSz, 0);
3850 ret = ParseCertRelative(&decoded, CA_TYPE, NO_VERIFY, 0);
3853 CYASSL_MSG("ParseCertRelative error");
3854 FreeDecodedCert(&decoded);
3858 if (decoded.beforeDate == NULL || decoded.afterDate == NULL) {
3859 CYASSL_MSG("Couldn't extract dates");
3860 FreeDecodedCert(&decoded);
3864 if (decoded.beforeDateLen > MAX_DATE_SIZE || decoded.afterDateLen >
3866 CYASSL_MSG("Bad date size");
3867 FreeDecodedCert(&decoded);
3871 XMEMCPY(cert->beforeDate, decoded.beforeDate, decoded.beforeDateLen);
3872 XMEMCPY(cert->afterDate, decoded.afterDate, decoded.afterDateLen);
3874 cert->beforeDateSz = decoded.beforeDateLen;
3875 cert->afterDateSz = decoded.afterDateLen;
3881 #endif /* CYASSL_ALT_NAMES */
3884 /* Set cn name from der buffer, return 0 on success */
3885 static int SetNameFromCert(CertName* cn, const byte* der, int derSz)
3887 DecodedCert decoded;
3894 InitDecodedCert(&decoded, (byte*)der, derSz, 0);
3895 ret = ParseCertRelative(&decoded, CA_TYPE, NO_VERIFY, 0);
3900 if (decoded.subjectCN) {
3901 sz = (decoded.subjectCNLen < CTC_NAME_SIZE) ? decoded.subjectCNLen :
3903 strncpy(cn->commonName, decoded.subjectCN, CTC_NAME_SIZE);
3904 cn->commonName[sz] = 0;
3906 if (decoded.subjectC) {
3907 sz = (decoded.subjectCLen < CTC_NAME_SIZE) ? decoded.subjectCLen :
3909 strncpy(cn->country, decoded.subjectC, CTC_NAME_SIZE);
3910 cn->country[sz] = 0;
3912 if (decoded.subjectST) {
3913 sz = (decoded.subjectSTLen < CTC_NAME_SIZE) ? decoded.subjectSTLen :
3915 strncpy(cn->state, decoded.subjectST, CTC_NAME_SIZE);
3918 if (decoded.subjectL) {
3919 sz = (decoded.subjectLLen < CTC_NAME_SIZE) ? decoded.subjectLLen :
3921 strncpy(cn->locality, decoded.subjectL, CTC_NAME_SIZE);
3922 cn->locality[sz] = 0;
3924 if (decoded.subjectO) {
3925 sz = (decoded.subjectOLen < CTC_NAME_SIZE) ? decoded.subjectOLen :
3927 strncpy(cn->org, decoded.subjectO, CTC_NAME_SIZE);
3930 if (decoded.subjectOU) {
3931 sz = (decoded.subjectOULen < CTC_NAME_SIZE) ? decoded.subjectOULen :
3933 strncpy(cn->unit, decoded.subjectOU, CTC_NAME_SIZE);
3936 if (decoded.subjectSN) {
3937 sz = (decoded.subjectSNLen < CTC_NAME_SIZE) ? decoded.subjectSNLen :
3939 strncpy(cn->sur, decoded.subjectSN, CTC_NAME_SIZE);
3942 if (decoded.subjectEmail) {
3943 sz = (decoded.subjectEmailLen < CTC_NAME_SIZE) ?
3944 decoded.subjectEmailLen : CTC_NAME_SIZE - 1;
3945 strncpy(cn->email, decoded.subjectEmail, CTC_NAME_SIZE);
3949 FreeDecodedCert(&decoded);
3955 #ifndef NO_FILESYSTEM
3957 /* forward from CyaSSL */
3958 int CyaSSL_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz);
3960 /* Set cert issuer from issuerFile in PEM */
3961 int SetIssuer(Cert* cert, const char* issuerFile)
3964 int derSz = CyaSSL_PemCertToDer(issuerFile, der, sizeof(der));
3966 cert->selfSigned = 0;
3967 return SetNameFromCert(&cert->issuer, der, derSz);
3971 /* Set cert subject from subjectFile in PEM */
3972 int SetSubject(Cert* cert, const char* subjectFile)
3975 int derSz = CyaSSL_PemCertToDer(subjectFile, der, sizeof(der));
3977 return SetNameFromCert(&cert->subject, der, derSz);
3981 #ifdef CYASSL_ALT_NAMES
3983 /* Set atl names from file in PEM */
3984 int SetAltNames(Cert* cert, const char* file)
3987 int derSz = CyaSSL_PemCertToDer(file, der, sizeof(der));
3989 return SetAltNamesFromCert(cert, der, derSz);
3992 #endif /* CYASSL_ALT_NAMES */
3994 #endif /* NO_FILESYSTEM */
3996 /* Set cert issuer from DER buffer */
3997 int SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
3999 cert->selfSigned = 0;
4000 return SetNameFromCert(&cert->issuer, der, derSz);
4004 /* Set cert subject from DER buffer */
4005 int SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
4007 return SetNameFromCert(&cert->subject, der, derSz);
4011 #ifdef CYASSL_ALT_NAMES
4013 /* Set cert alt names from DER buffer */
4014 int SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
4016 return SetAltNamesFromCert(cert, der, derSz);
4019 /* Set cert dates from DER buffer */
4020 int SetDatesBuffer(Cert* cert, const byte* der, int derSz)
4022 return SetDatesFromCert(cert, der, derSz);
4025 #endif /* CYASSL_ALT_NAMES */
4027 #endif /* CYASSL_CERT_GEN */
4032 /* Der Encode r & s ints into out, outLen is (in/out) size */
4033 int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
4036 word32 rSz; /* encoding size */
4038 word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
4040 int rLen = mp_unsigned_bin_size(r); /* big int size */
4041 int sLen = mp_unsigned_bin_size(s);
4044 if (*outLen < (rLen + sLen + headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
4045 return BAD_FUNC_ARG;
4047 idx = SetSequence(rLen + sLen + headerSz, out);
4050 out[idx++] = ASN_INTEGER;
4051 rSz = SetLength(rLen, &out[idx]);
4053 err = mp_to_unsigned_bin(r, &out[idx]);
4054 if (err != MP_OKAY) return err;
4058 out[idx++] = ASN_INTEGER;
4059 sSz = SetLength(sLen, &out[idx]);
4061 err = mp_to_unsigned_bin(s, &out[idx]);
4062 if (err != MP_OKAY) return err;
4071 /* Der Decode ECC-DSA Signautre, r & s stored as big ints */
4072 int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
4077 if (GetSequence(sig, &idx, &len, sigLen) < 0)
4078 return ASN_ECC_KEY_E;
4080 if ((word32)len > (sigLen - idx))
4081 return ASN_ECC_KEY_E;
4083 if (GetInt(r, sig, &idx, sigLen) < 0)
4084 return ASN_ECC_KEY_E;
4086 if (GetInt(s, sig, &idx, sigLen) < 0)
4087 return ASN_ECC_KEY_E;
4093 int EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
4097 int version, length;
4100 byte priv[ECC_MAXSIZE];
4101 byte pub[ECC_MAXSIZE * 2 + 1]; /* public key has two parts plus header */
4103 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
4106 if (GetMyVersion(input, inOutIdx, &version) < 0)
4109 b = input[*inOutIdx];
4113 if (b != 4 && b != 6 && b != 7)
4116 if (GetLength(input, inOutIdx, &length, inSz) < 0)
4121 XMEMCPY(priv, &input[*inOutIdx], privSz);
4122 *inOutIdx += length;
4124 /* prefix 0, may have */
4125 b = input[*inOutIdx];
4126 if (b == ECC_PREFIX_0) {
4129 if (GetLength(input, inOutIdx, &length, inSz) < 0)
4133 b = input[*inOutIdx];
4136 if (b != ASN_OBJECT_ID)
4137 return ASN_OBJECT_ID_E;
4139 if (GetLength(input, inOutIdx, &length, inSz) < 0)
4143 oid += input[*inOutIdx];
4146 if (CheckCurve(oid) < 0)
4147 return ECC_CURVE_OID_E;
4151 b = input[*inOutIdx];
4153 if (b != ECC_PREFIX_1)
4154 return ASN_ECC_KEY_E;
4156 if (GetLength(input, inOutIdx, &length, inSz) < 0)
4160 b = input[*inOutIdx];
4162 if (b != ASN_BIT_STRING)
4163 return ASN_BITSTR_E;
4165 if (GetLength(input, inOutIdx, &length, inSz) < 0)
4167 b = input[*inOutIdx];
4170 return ASN_EXPECT_0_E;
4172 pubSz = length - 1; /* null prefix */
4173 XMEMCPY(pub, &input[*inOutIdx], pubSz);
4175 *inOutIdx += length;
4177 return ecc_import_private_key(priv, privSz, pub, pubSz, key);
4180 #endif /* HAVE_ECC */
4183 #if defined(HAVE_OCSP) || defined(HAVE_CRL)
4185 /* Get raw Date only, no processing, 0 on success */
4186 static int GetBasicDate(const byte* source, word32* idx, byte* date,
4187 byte* format, int maxIdx)
4191 CYASSL_ENTER("GetBasicDate");
4193 *format = source[*idx];
4195 if (*format != ASN_UTC_TIME && *format != ASN_GENERALIZED_TIME)
4198 if (GetLength(source, idx, &length, maxIdx) < 0)
4201 if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
4202 return ASN_DATE_SZ_E;
4204 XMEMCPY(date, &source[*idx], length);
4215 static int GetEnumerated(const byte* input, word32* inOutIdx, int *value)
4217 word32 idx = *inOutIdx;
4220 CYASSL_ENTER("GetEnumerated");
4224 if (input[idx++] != ASN_ENUMERATED)
4232 *value = *value << 8 | input[idx++];
4241 static int DecodeSingleResponse(byte* source,
4242 word32* ioIndex, OcspResponse* resp, word32 size)
4244 word32 index = *ioIndex, prevIndex, oid;
4245 int length, wrapperSz;
4246 CertStatus* cs = resp->status;
4248 CYASSL_ENTER("DecodeSingleResponse");
4250 /* Outer wrapper of the SEQUENCE OF Single Responses. */
4251 if (GetSequence(source, &index, &wrapperSz, size) < 0)
4256 /* When making a request, we only request one status on one certificate
4257 * at a time. There should only be one SingleResponse */
4259 /* Wrapper around the Single Response */
4260 if (GetSequence(source, &index, &length, size) < 0)
4263 /* Wrapper around the CertID */
4264 if (GetSequence(source, &index, &length, size) < 0)
4266 /* Skip the hash algorithm */
4267 if (GetAlgoId(source, &index, &oid, size) < 0)
4269 /* Save reference to the hash of CN */
4270 if (source[index++] != ASN_OCTET_STRING)
4272 if (GetLength(source, &index, &length, size) < 0)
4274 resp->issuerHash = source + index;
4276 /* Save reference to the hash of the issuer public key */
4277 if (source[index++] != ASN_OCTET_STRING)
4279 if (GetLength(source, &index, &length, size) < 0)
4281 resp->issuerKeyHash = source + index;
4284 /* Read the serial number, it is handled as a string, not as a
4285 * proper number. Just XMEMCPY the data over, rather than load it
4287 if (source[index++] != ASN_INTEGER)
4289 if (GetLength(source, &index, &length, size) < 0)
4291 if (length <= EXTERNAL_SERIAL_SIZE)
4293 if (source[index] == 0)
4298 XMEMCPY(cs->serial, source + index, length);
4299 cs->serialSz = length;
4303 return ASN_GETINT_E;
4308 switch (source[index++])
4310 case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
4311 cs->status = CERT_GOOD;
4314 case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
4315 cs->status = CERT_REVOKED;
4316 GetLength(source, &index, &length, size);
4319 case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
4320 cs->status = CERT_UNKNOWN;
4327 if (GetBasicDate(source, &index, cs->thisDate,
4328 &cs->thisDateFormat, size) < 0)
4330 if (!ValidateDate(cs->thisDate, cs->thisDateFormat, BEFORE))
4331 return ASN_BEFORE_DATE_E;
4333 /* The following items are optional. Only check for them if there is more
4334 * unprocessed data in the singleResponse wrapper. */
4336 if ((index - prevIndex < wrapperSz) &&
4337 (source[index] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0)))
4340 if (GetLength(source, &index, &length, size) < 0)
4342 if (GetBasicDate(source, &index, cs->nextDate,
4343 &cs->nextDateFormat, size) < 0)
4346 if ((index - prevIndex < wrapperSz) &&
4347 (source[index] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1)))
4350 if (GetLength(source, &index, &length, size) < 0)
4360 static int DecodeOcspRespExtensions(byte* source,
4361 word32* ioIndex, OcspResponse* resp, word32 sz)
4363 word32 idx = *ioIndex;
4365 int ext_bound; /* boundary index for the sequence of extensions */
4368 CYASSL_ENTER("DecodeOcspRespExtensions");
4370 if (source[idx++] != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
4373 if (GetLength(source, &idx, &length, sz) < 0) return ASN_PARSE_E;
4375 if (GetSequence(source, &idx, &length, sz) < 0) return ASN_PARSE_E;
4377 ext_bound = idx + length;
4379 while (idx < (word32)ext_bound) {
4380 if (GetSequence(source, &idx, &length, sz) < 0) {
4381 CYASSL_MSG("\tfail: should be a SEQUENCE");
4386 if (GetObjectId(source, &idx, &oid, sz) < 0) {
4387 CYASSL_MSG("\tfail: OBJECT ID");
4391 /* check for critical flag */
4392 if (source[idx] == ASN_BOOLEAN) {
4393 CYASSL_MSG("\tfound optional critical flag, moving past");
4394 idx += (ASN_BOOL_SIZE + 1);
4397 /* process the extension based on the OID */
4398 if (source[idx++] != ASN_OCTET_STRING) {
4399 CYASSL_MSG("\tfail: should be an OCTET STRING");
4403 if (GetLength(source, &idx, &length, sz) < 0) {
4404 CYASSL_MSG("\tfail: extension data length");
4408 if (oid == OCSP_NONCE_OID) {
4409 resp->nonce = source + idx;
4410 resp->nonceSz = length;
4421 static int DecodeResponseData(byte* source,
4422 word32* ioIndex, OcspResponse* resp, word32 size)
4424 word32 idx = *ioIndex, prev_idx;
4427 word32 responderId = 0;
4429 CYASSL_ENTER("DecodeResponseData");
4431 resp->response = source + idx;
4433 if (GetSequence(source, &idx, &length, size) < 0)
4435 resp->responseSz = length + idx - prev_idx;
4437 /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
4438 * item isn't an EXPLICIT[0], then set version to zero and move
4439 * onto the next item.
4441 if (source[idx] == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
4443 idx += 2; /* Eat the value and length */
4444 if (GetMyVersion(source, &idx, &version) < 0)
4449 responderId = source[idx++];
4450 if ((responderId == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) ||
4451 (responderId == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)))
4453 if (GetLength(source, &idx, &length, size) < 0)
4460 /* save pointer to the producedAt time */
4461 if (GetBasicDate(source, &idx, resp->producedDate,
4462 &resp->producedDateFormat, size) < 0)
4464 if (!ValidateDate(resp->producedDate, resp->producedDateFormat, BEFORE))
4465 return ASN_BEFORE_DATE_E;
4468 if (DecodeSingleResponse(source, &idx, resp, size) < 0)
4471 if (DecodeOcspRespExtensions(source, &idx, resp, size) < 0)
4479 static int DecodeCerts(byte* source,
4480 word32* ioIndex, OcspResponse* resp, word32 size)
4482 word32 idx = *ioIndex;
4484 CYASSL_ENTER("DecodeCerts");
4486 if (source[idx++] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
4490 if (GetLength(source, &idx, &length, size) < 0)
4493 if (GetSequence(source, &idx, &length, size) < 0)
4496 resp->cert = source + idx;
4497 resp->certSz = length;
4505 static int DecodeBasicOcspResponse(byte* source,
4506 word32* ioIndex, OcspResponse* resp, word32 size)
4509 word32 idx = *ioIndex;
4512 CYASSL_ENTER("DecodeBasicOcspResponse");
4514 if (GetSequence(source, &idx, &length, size) < 0)
4517 if (idx + length > size)
4519 end_index = idx + length;
4521 if (DecodeResponseData(source, &idx, resp, size) < 0)
4524 /* Get the signature algorithm */
4525 if (GetAlgoId(source, &idx, &resp->sigOID, size) < 0)
4528 /* Obtain pointer to the start of the signature, and save the size */
4529 if (source[idx++] == ASN_BIT_STRING)
4532 if (GetLength(source, &idx, &sigLength, size) < 0)
4534 resp->sigSz = sigLength;
4535 resp->sig = source + idx;
4540 * Check the length of the BasicOcspResponse against the current index to
4541 * see if there are certificates, they are optional.
4543 if (idx < end_index)
4548 if (DecodeCerts(source, &idx, resp, size) < 0)
4551 InitDecodedCert(&cert, resp->cert, resp->certSz, 0);
4552 ret = ParseCertRelative(&cert, CA_TYPE, NO_VERIFY, 0);
4556 ret = ConfirmSignature(resp->response, resp->responseSz,
4557 cert.publicKey, cert.pubKeySize, cert.keyOID,
4558 resp->sig, resp->sigSz, resp->sigOID, NULL);
4559 FreeDecodedCert(&cert);
4563 CYASSL_MSG("\tConfirm signature failed");
4564 return ASN_SIG_CONFIRM_E;
4573 void InitOcspResponse(OcspResponse* resp, CertStatus* status,
4574 byte* source, word32 inSz)
4576 CYASSL_ENTER("InitOcspResponse");
4578 resp->responseStatus = -1;
4579 resp->response = NULL;
4580 resp->responseSz = 0;
4581 resp->producedDateFormat = 0;
4582 resp->issuerHash = NULL;
4583 resp->issuerKeyHash = NULL;
4587 resp->status = status;
4590 resp->source = source;
4591 resp->maxIdx = inSz;
4595 int OcspResponseDecode(OcspResponse* resp)
4599 byte* source = resp->source;
4600 word32 size = resp->maxIdx;
4603 CYASSL_ENTER("OcspResponseDecode");
4605 /* peel the outer SEQUENCE wrapper */
4606 if (GetSequence(source, &idx, &length, size) < 0)
4609 /* First get the responseStatus, an ENUMERATED */
4610 if (GetEnumerated(source, &idx, &resp->responseStatus) < 0)
4613 if (resp->responseStatus != OCSP_SUCCESSFUL)
4616 /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
4619 if (source[idx++] != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
4621 if (GetLength(source, &idx, &length, size) < 0)
4624 /* Get the responseBytes SEQUENCE */
4625 if (GetSequence(source, &idx, &length, size) < 0)
4628 /* Check ObjectID for the resposeBytes */
4629 if (GetObjectId(source, &idx, &oid, size) < 0)
4631 if (oid != OCSP_BASIC_OID)
4633 if (source[idx++] != ASN_OCTET_STRING)
4636 if (GetLength(source, &idx, &length, size) < 0)
4639 if (DecodeBasicOcspResponse(source, &idx, resp, size) < 0)
4646 static int SetSerialNumber(const byte* sn, word32 snSz, byte* output)
4650 CYASSL_ENTER("SetSerialNumber");
4652 if (snSz <= EXTERNAL_SERIAL_SIZE) {
4653 output[0] = ASN_INTEGER;
4654 output[1] = snSz + 1;
4656 XMEMCPY(&output[3], sn, snSz);
4663 static word32 SetOcspReqExtensions(word32 extSz, byte* output,
4664 const byte* nonce, word32 nonceSz)
4666 static const byte NonceObjId[] = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07,
4668 byte seqArray[5][MAX_SEQ_SZ];
4669 word32 seqSz[5], totalSz;
4671 CYASSL_ENTER("SetOcspReqExtensions");
4673 if (nonce == NULL || nonceSz == 0) return 0;
4675 seqArray[0][0] = ASN_OCTET_STRING;
4676 seqSz[0] = 1 + SetLength(nonceSz, &seqArray[0][1]);
4678 seqArray[1][0] = ASN_OBJECT_ID;
4679 seqSz[1] = 1 + SetLength(sizeof(NonceObjId), &seqArray[1][1]);
4681 totalSz = seqSz[0] + seqSz[1] + nonceSz + sizeof(NonceObjId);
4683 seqSz[2] = SetSequence(totalSz, seqArray[2]);
4684 totalSz += seqSz[2];
4686 seqSz[3] = SetSequence(totalSz, seqArray[3]);
4687 totalSz += seqSz[3];
4689 seqArray[4][0] = (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2);
4690 seqSz[4] = 1 + SetLength(totalSz, &seqArray[4][1]);
4691 totalSz += seqSz[4];
4693 if (totalSz < extSz)
4696 XMEMCPY(output + totalSz, seqArray[4], seqSz[4]);
4697 totalSz += seqSz[4];
4698 XMEMCPY(output + totalSz, seqArray[3], seqSz[3]);
4699 totalSz += seqSz[3];
4700 XMEMCPY(output + totalSz, seqArray[2], seqSz[2]);
4701 totalSz += seqSz[2];
4702 XMEMCPY(output + totalSz, seqArray[1], seqSz[1]);
4703 totalSz += seqSz[1];
4704 XMEMCPY(output + totalSz, NonceObjId, sizeof(NonceObjId));
4705 totalSz += sizeof(NonceObjId);
4706 XMEMCPY(output + totalSz, seqArray[0], seqSz[0]);
4707 totalSz += seqSz[0];
4708 XMEMCPY(output + totalSz, nonce, nonceSz);
4716 int EncodeOcspRequest(OcspRequest* req)
4718 byte seqArray[5][MAX_SEQ_SZ];
4719 /* The ASN.1 of the OCSP Request is an onion of sequences */
4720 byte algoArray[MAX_ALGO_SZ];
4721 byte issuerArray[MAX_ENCODED_DIG_SZ];
4722 byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
4723 byte snArray[MAX_SN_SZ];
4724 byte extArray[MAX_OCSP_EXT_SZ];
4725 byte* output = req->dest;
4726 word32 outputSz = req->destSz;
4728 word32 seqSz[5], algoSz, issuerSz, issuerKeySz, snSz, extSz, totalSz;
4731 CYASSL_ENTER("EncodeOcspRequest");
4733 algoSz = SetAlgoID(SHAh, algoArray, hashType);
4735 req->issuerHash = req->cert->issuerHash;
4736 issuerSz = SetDigest(req->cert->issuerHash, SHA_SIZE, issuerArray);
4738 req->issuerKeyHash = req->cert->issuerKeyHash;
4739 issuerKeySz = SetDigest(req->cert->issuerKeyHash, SHA_SIZE, issuerKeyArray);
4741 req->serial = req->cert->serial;
4742 req->serialSz = req->cert->serialSz;
4743 snSz = SetSerialNumber(req->cert->serial, req->cert->serialSz, snArray);
4745 if (InitRng(&rng) != 0) {
4746 CYASSL_MSG("\tCannot initialize RNG. Skipping the OSCP Nonce.");
4749 req->nonceSz = MAX_OCSP_NONCE_SZ;
4750 RNG_GenerateBlock(&rng, req->nonce, req->nonceSz);
4751 extSz = SetOcspReqExtensions(MAX_OCSP_EXT_SZ, extArray,
4752 req->nonce, req->nonceSz);
4755 totalSz = algoSz + issuerSz + issuerKeySz + snSz;
4757 for (i = 4; i >= 0; i--) {
4758 seqSz[i] = SetSequence(totalSz, seqArray[i]);
4759 totalSz += seqSz[i];
4760 if (i == 2) totalSz += extSz;
4763 for (i = 0; i < 5; i++) {
4764 XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
4765 totalSz += seqSz[i];
4767 XMEMCPY(output + totalSz, algoArray, algoSz);
4769 XMEMCPY(output + totalSz, issuerArray, issuerSz);
4770 totalSz += issuerSz;
4771 XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
4772 totalSz += issuerKeySz;
4773 XMEMCPY(output + totalSz, snArray, snSz);
4776 XMEMCPY(output + totalSz, extArray, extSz);
4784 void InitOcspRequest(OcspRequest* req, DecodedCert* cert,
4785 byte* dest, word32 destSz)
4787 CYASSL_ENTER("InitOcspRequest");
4791 req->issuerHash = NULL;
4792 req->issuerKeyHash = NULL;
4795 req->destSz = destSz;
4799 int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
4803 CYASSL_ENTER("CompareOcspReqResp");
4807 CYASSL_MSG("\tReq missing");
4813 CYASSL_MSG("\tResp missing");
4817 cmp = req->nonceSz - resp->nonceSz;
4820 CYASSL_MSG("\tnonceSz mismatch");
4824 cmp = XMEMCMP(req->nonce, resp->nonce, req->nonceSz);
4827 CYASSL_MSG("\tnonce mismatch");
4831 cmp = XMEMCMP(req->issuerHash, resp->issuerHash, SHA_DIGEST_SIZE);
4834 CYASSL_MSG("\tissuerHash mismatch");
4838 cmp = XMEMCMP(req->issuerKeyHash, resp->issuerKeyHash, SHA_DIGEST_SIZE);
4841 CYASSL_MSG("\tissuerKeyHash mismatch");
4845 cmp = req->serialSz - resp->status->serialSz;
4848 CYASSL_MSG("\tserialSz mismatch");
4852 cmp = XMEMCMP(req->serial, resp->status->serial, req->serialSz);
4855 CYASSL_MSG("\tserial mismatch");
4867 /* initialize decoded CRL */
4868 void InitDecodedCRL(DecodedCRL* dcrl)
4870 CYASSL_MSG("InitDecodedCRL");
4872 dcrl->certBegin = 0;
4874 dcrl->sigLength = 0;
4875 dcrl->signatureOID = 0;
4877 dcrl->totalCerts = 0;
4881 /* free decoded CRL resources */
4882 void FreeDecodedCRL(DecodedCRL* dcrl)
4884 RevokedCert* tmp = dcrl->certs;
4886 CYASSL_MSG("FreeDecodedCRL");
4889 RevokedCert* next = tmp->next;
4890 XFREE(tmp, NULL, DYNAMIC_TYPE_REVOKED);
4896 /* store SHA1 hash of NAME */
4897 static int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx)
4900 int length; /* length of all distinguished names */
4903 CYASSL_ENTER("GetNameHash");
4905 if (source[*idx] == ASN_OBJECT_ID) {
4906 CYASSL_MSG("Trying optional prefix...");
4908 if (GetLength(source, idx, &length, maxIdx) < 0)
4912 CYASSL_MSG("Got optional prefix");
4915 /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
4916 * calculated over the entire DER encoding of the Name field, including
4917 * the tag and length. */
4919 if (GetSequence(source, idx, &length, maxIdx) < 0)
4923 ShaUpdate(&sha, source + dummy, length + *idx - dummy);
4924 ShaFinal(&sha, hash);
4932 /* Get Revoked Cert list, 0 on success */
4933 static int GetRevoked(const byte* buff, word32* idx, DecodedCRL* dcrl,
4941 CYASSL_ENTER("GetRevoked");
4943 if (GetSequence(buff, idx, &len, maxIdx) < 0)
4948 /* get serial number */
4952 if (b != ASN_INTEGER) {
4953 CYASSL_MSG("Expecting Integer");
4957 if (GetLength(buff, idx, &len, maxIdx) < 0)
4960 if (len > EXTERNAL_SERIAL_SIZE) {
4961 CYASSL_MSG("Serial Size too big");
4965 rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), NULL, DYNAMIC_TYPE_CRL);
4967 CYASSL_MSG("Alloc Revoked Cert failed");
4971 XMEMCPY(rc->serialNumber, &buff[*idx], len);
4975 rc->next = dcrl->certs;
4985 if (b != ASN_UTC_TIME && b != ASN_GENERALIZED_TIME) {
4986 CYASSL_MSG("Expecting Date");
4990 if (GetLength(buff, idx, &len, maxIdx) < 0)
4996 if (*idx != end) /* skip extensions */
5003 /* Get CRL Signature, 0 on success */
5004 static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
5010 CYASSL_ENTER("GetCRL_Signature");
5014 if (b != ASN_BIT_STRING)
5015 return ASN_BITSTR_E;
5017 if (GetLength(source, idx, &length, maxIdx) < 0)
5020 dcrl->sigLength = length;
5025 return ASN_EXPECT_0_E;
5028 dcrl->signature = (byte*)&source[*idx];
5030 *idx += dcrl->sigLength;
5036 /* prase crl buffer into decoded state, 0 on success */
5037 int ParseCRL(DecodedCRL* dcrl, const byte* buff, long sz, void* cm)
5040 word32 oid, idx = 0;
5044 CYASSL_MSG("ParseCRL");
5048 Md5Update(&md5, buff, sz);
5049 Md5Final(&md5, dcrl->crlHash);
5051 if (GetSequence(buff, &idx, &len, sz) < 0)
5054 dcrl->certBegin = idx;
5056 if (GetSequence(buff, &idx, &len, sz) < 0)
5058 dcrl->sigIndex = len + idx;
5060 /* may have version */
5061 if (buff[idx] == ASN_INTEGER) {
5062 if (GetMyVersion(buff, &idx, &version) < 0)
5066 if (GetAlgoId(buff, &idx, &oid, sz) < 0)
5069 if (GetNameHash(buff, &idx, dcrl->issuerHash, sz) < 0)
5072 if (GetBasicDate(buff, &idx, dcrl->lastDate, &dcrl->lastDateFormat, sz) < 0)
5075 if (GetBasicDate(buff, &idx, dcrl->nextDate, &dcrl->nextDateFormat, sz) < 0)
5078 if (!XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
5079 CYASSL_MSG("CRL after date is no longer valid");
5080 return ASN_AFTER_DATE_E;
5083 if (idx != dcrl->sigIndex && buff[idx] != CRL_EXTENSIONS) {
5084 if (GetSequence(buff, &idx, &len, sz) < 0)
5089 while (idx < (word32)len) {
5090 if (GetRevoked(buff, &idx, dcrl, sz) < 0)
5095 if (idx != dcrl->sigIndex)
5096 idx = dcrl->sigIndex; /* skip extensions */
5098 if (GetAlgoId(buff, &idx, &dcrl->signatureOID, sz) < 0)
5101 if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
5104 ca = GetCA(cm, dcrl->issuerHash);
5105 CYASSL_MSG("About to verify CRL signature");
5108 CYASSL_MSG("Found CRL issuer CA");
5109 /* try to confirm/verify signature */
5110 if (!ConfirmSignature(buff + dcrl->certBegin,
5111 dcrl->sigIndex - dcrl->certBegin,
5112 ca->publicKey, ca->pubKeySize, ca->keyOID,
5113 dcrl->signature, dcrl->sigLength, dcrl->signatureOID, NULL)) {
5114 CYASSL_MSG("CRL Confirm signature failed");
5115 return ASN_SIG_CONFIRM_E;
5119 CYASSL_MSG("Did NOT find CRL issuer CA");
5120 return ASN_SIG_CONFIRM_E;
5126 #endif /* HAVE_CRL */