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/error.h>
36 #include <cyassl/ctaocrypt/pwdbased.h>
37 #include <cyassl/ctaocrypt/des3.h>
38 #include <cyassl/ctaocrypt/sha256.h>
39 #include <cyassl/ctaocrypt/sha512.h>
40 #include <cyassl/ctaocrypt/logging.h>
43 #include "crypto_ntru.h"
47 #include <cyassl/ctaocrypt/ecc.h>
52 /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
53 #pragma warning(disable: 4996)
66 /* uses parital <time.h> structures */
68 #define XGMTIME(c) my_gmtime((c))
69 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
70 #elif defined(MICRIUM)
71 #if (NET_SECURE_MGR_CFG_EN == DEF_ENABLED)
72 #define XVALIDATE_DATE(d,f,t) NetSecure_ValidateDateHandler((d),(f),(t))
74 #define XVALIDATE_DATE(d, f, t) (0)
77 /* since Micrium not defining XTIME or XGMTIME, CERT_GEN not available */
78 #elif defined(USER_TIME)
79 /* no <time.h> structures used */
81 /* user time, and gmtime compatible functions, there is a gmtime
82 implementation here that WINCE uses, so really just need some ticks
87 /* uses complete <time.h> facility */
89 #define XTIME(tl) time((tl))
90 #define XGMTIME(c) gmtime((c))
91 #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
96 /* no time() or gmtime() even though in time.h header?? */
101 time_t time(time_t* timer)
105 ULARGE_INTEGER intTime;
111 GetSystemTime(&sysTime);
112 SystemTimeToFileTime(&sysTime, &fTime);
114 XMEMCPY(&intTime, &fTime, sizeof(FILETIME));
116 intTime.QuadPart -= 0x19db1ded53e8000;
118 intTime.QuadPart /= 10000000;
119 *timer = (time_t)intTime.QuadPart;
126 struct tm* gmtime(const time_t* timer)
129 #define EPOCH_YEAR 1970
130 #define SECS_DAY (24L * 60L * 60L)
131 #define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) %400)))
132 #define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365)
134 static const int _ytab[2][12] =
136 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
137 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
140 static struct tm st_time;
141 struct tm* ret = &st_time;
142 time_t time = *timer;
143 unsigned long dayclock, dayno;
144 int year = EPOCH_YEAR;
146 dayclock = (unsigned long)time % SECS_DAY;
147 dayno = (unsigned long)time / SECS_DAY;
149 ret->tm_sec = dayclock % 60;
150 ret->tm_min = (dayclock % 3600) / 60;
151 ret->tm_hour = dayclock / 3600;
152 ret->tm_wday = (dayno + 4) % 7; /* day 0 a Thursday */
154 while(dayno >= (unsigned long)YEARSIZE(year)) {
155 dayno -= YEARSIZE(year);
159 ret->tm_year = year - YEAR0;
160 ret->tm_yday = dayno;
163 while(dayno >= (unsigned long)_ytab[LEAPYEAR(year)][ret->tm_mon]) {
164 dayno -= _ytab[LEAPYEAR(year)][ret->tm_mon];
168 ret->tm_mday = ++dayno;
174 #endif /* _WIN32_WCE */
181 struct tm* my_gmtime(const time_t* timer) /* has a gmtime() but hangs */
183 static struct tm st_time;
184 struct tm* ret = &st_time;
187 dc_rtc_time_get(&cal, TRUE);
189 ret->tm_year = cal.year - YEAR0; /* gm starts at 1900 */
190 ret->tm_mon = cal.month - 1; /* gm starts at 0 */
191 ret->tm_mday = cal.day;
192 ret->tm_hour = cal.hour;
193 ret->tm_min = cal.minute;
194 ret->tm_sec = cal.second;
202 static INLINE word32 btoi(byte b)
208 /* two byte date/time, add to value */
209 static INLINE void GetTime(int* value, const byte* date, int* idx)
213 *value += btoi(date[i++]) * 10;
214 *value += btoi(date[i++]);
222 CPU_INT32S NetSecure_ValidateDateHandler(CPU_INT08U *date, CPU_INT08U format,
225 CPU_BOOLEAN rtn_code;
238 if (format == ASN_UTC_TIME) {
239 if (btoi(date[0]) >= 5)
244 else { /* format == GENERALIZED_TIME */
245 year += btoi(date[i++]) * 1000;
246 year += btoi(date[i++]) * 100;
250 GetTime(&val, date, &i);
251 year = (CPU_INT16U)val;
254 GetTime(&val, date, &i);
255 month = (CPU_INT08U)val;
258 GetTime(&val, date, &i);
259 day = (CPU_INT16U)val;
262 GetTime(&val, date, &i);
263 hour = (CPU_INT08U)val;
266 GetTime(&val, date, &i);
267 min = (CPU_INT08U)val;
270 GetTime(&val, date, &i);
271 sec = (CPU_INT08U)val;
273 return NetSecure_ValidateDate(year, month, day, hour, min, sec, dateType);
279 static int GetLength(const byte* input, word32* inOutIdx, int* len,
283 word32 i = *inOutIdx;
286 if ( (i+1) > maxIdx) { /* for first read */
287 CYASSL_MSG("GetLength bad index on input");
292 if (b >= ASN_LONG_LENGTH) {
293 word32 bytes = b & 0x7F;
295 if ( (i+bytes) > maxIdx) { /* for reading bytes */
296 CYASSL_MSG("GetLength bad long length");
302 length = (length << 8) | b;
308 if ( (i+length) > maxIdx) { /* for user of length */
309 CYASSL_MSG("GetLength value exceeds buffer length");
320 static int GetSequence(const byte* input, word32* inOutIdx, int* len,
324 word32 idx = *inOutIdx;
326 if (input[idx++] != (ASN_SEQUENCE | ASN_CONSTRUCTED) ||
327 GetLength(input, &idx, &length, maxIdx) < 0)
337 static int GetSet(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
340 word32 idx = *inOutIdx;
342 if (input[idx++] != (ASN_SET | ASN_CONSTRUCTED) ||
343 GetLength(input, &idx, &length, maxIdx) < 0)
353 /* winodws header clash for WinCE using GetVersion */
354 static int GetMyVersion(const byte* input, word32* inOutIdx, int* version)
356 word32 idx = *inOutIdx;
358 CYASSL_ENTER("GetMyVersion");
360 if (input[idx++] != ASN_INTEGER)
363 if (input[idx++] != 0x01)
364 return ASN_VERSION_E;
366 *version = input[idx++];
373 /* Get small count integer, 32 bits or less */
374 static int GetShortInt(const byte* input, word32* inOutIdx, int* number)
376 word32 idx = *inOutIdx;
381 if (input[idx++] != ASN_INTEGER)
389 *number = *number << 8 | input[idx++];
398 /* May not have one, not an error */
399 static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version)
401 word32 idx = *inOutIdx;
403 CYASSL_ENTER("GetExplicitVersion");
404 if (input[idx++] == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
405 *inOutIdx = ++idx; /* eat header */
406 return GetMyVersion(input, inOutIdx, version);
416 static int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx,
419 word32 i = *inOutIdx;
423 if (b != ASN_INTEGER)
426 if (GetLength(input, &i, &length, maxIdx) < 0)
429 if ( (b = input[i++]) == 0x00)
435 if (mp_read_unsigned_bin(mpi, (byte*)input + i, length) != 0) {
440 *inOutIdx = i + length;
445 static int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
449 word32 i = *inOutIdx;
454 if (b != ASN_OBJECT_ID)
455 return ASN_OBJECT_ID_E;
457 if (GetLength(input, &i, &length, maxIdx) < 0)
462 /* just sum it up for now */
470 static int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
474 word32 i = *inOutIdx;
478 CYASSL_ENTER("GetAlgoId");
480 if (GetSequence(input, &i, &length, maxIdx) < 0)
484 if (b != ASN_OBJECT_ID)
485 return ASN_OBJECT_ID_E;
487 if (GetLength(input, &i, &length, maxIdx) < 0)
492 /* just sum it up for now */
494 /* could have NULL tag and 0 terminator, but may not */
497 if (b == ASN_TAG_NULL) {
500 return ASN_EXPECT_0_E;
503 /* go back, didn't have it */
512 int RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
517 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
520 if (GetMyVersion(input, inOutIdx, &version) < 0)
523 key->type = RSA_PRIVATE;
525 if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
526 GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
527 GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
528 GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
529 GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
530 GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
531 GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
532 GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
538 /* Remove PKCS8 header, move beginning of traditional to beginning of input */
539 int ToTraditional(byte* input, word32 sz)
541 word32 inOutIdx = 0, oid;
544 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
547 if (GetMyVersion(input, &inOutIdx, &version) < 0)
550 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
553 if (input[inOutIdx] == ASN_OBJECT_ID) {
554 /* pkcs8 ecc uses slightly different format */
555 inOutIdx++; /* past id */
556 if (GetLength(input, &inOutIdx, &length, sz) < 0)
558 inOutIdx += length; /* over sub id, key input will verify */
561 if (input[inOutIdx++] != ASN_OCTET_STRING)
564 if (GetLength(input, &inOutIdx, &length, sz) < 0)
567 XMEMMOVE(input, input + inOutIdx, length);
575 /* Check To see if PKCS version algo is supported, set id if it is return 0
577 static int CheckAlgo(int first, int second, int* id, int* version)
580 *version = PKCS5; /* default */
585 *id = PBE_SHA1_RC4_128;
598 return ASN_INPUT_E; /* VERSION ERROR */
600 if (second == PBES2) {
606 case 3: /* see RFC 2898 for ids */
619 /* Check To see if PKCS v2 algo is supported, set id if it is return 0
621 static int CheckAlgoV2(int oid, int* id)
637 /* Decrypt intput in place from parameters based on id */
638 static int DecryptKey(const char* password, int passwordSz, byte* salt,
639 int saltSz, int iterations, int id, byte* input,
640 int length, int version, byte* cbcIv)
642 byte key[MAX_KEY_SIZE];
651 derivedLen = 16; /* may need iv for v1.5 */
652 decryptionType = DES_TYPE;
657 derivedLen = 16; /* may need iv for v1.5 */
658 decryptionType = DES_TYPE;
663 derivedLen = 32; /* may need iv for v1.5 */
664 decryptionType = DES3_TYPE;
667 case PBE_SHA1_RC4_128:
670 decryptionType = RC4_TYPE;
677 if (version == PKCS5v2)
678 ret = PBKDF2(key, (byte*)password, passwordSz, salt, saltSz, iterations,
680 else if (version == PKCS5)
681 ret = PBKDF1(key, (byte*)password, passwordSz, salt, saltSz, iterations,
683 else if (version == PKCS12) {
685 byte unicodePasswd[MAX_UNICODE_SZ];
687 if ( (passwordSz * 2 + 2) > (int)sizeof(unicodePasswd))
688 return UNICODE_SIZE_E;
690 for (i = 0; i < passwordSz; i++) {
691 unicodePasswd[idx++] = 0x00;
692 unicodePasswd[idx++] = (byte)password[i];
694 /* add trailing NULL */
695 unicodePasswd[idx++] = 0x00;
696 unicodePasswd[idx++] = 0x00;
698 ret = PKCS12_PBKDF(key, unicodePasswd, idx, salt, saltSz,
699 iterations, derivedLen, typeH, 1);
700 if (decryptionType != RC4_TYPE)
701 ret += PKCS12_PBKDF(cbcIv, unicodePasswd, idx, salt, saltSz,
702 iterations, 8, typeH, 2);
708 switch (decryptionType) {
713 byte* desIv = key + 8;
715 if (version == PKCS5v2 || version == PKCS12)
717 Des_SetKey(&dec, key, desIv, DES_DECRYPTION);
718 Des_CbcDecrypt(&dec, input, input, length);
725 byte* desIv = key + 24;
727 if (version == PKCS5v2 || version == PKCS12)
729 Des3_SetKey(&dec, key, desIv, DES_DECRYPTION);
730 Des3_CbcDecrypt(&dec, input, input, length);
738 Arc4SetKey(&dec, key, derivedLen);
739 Arc4Process(&dec, input, input, length);
751 /* Remove Encrypted PKCS8 header, move beginning of traditional to beginning
753 int ToTraditionalEnc(byte* input, word32 sz,const char* password,int passwordSz)
755 word32 inOutIdx = 0, oid;
756 int first, second, length, iterations, saltSz, id;
758 byte salt[MAX_SALT_SIZE];
759 byte cbcIv[MAX_IV_SIZE];
761 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
764 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
767 first = input[inOutIdx - 2]; /* PKCS version alwyas 2nd to last byte */
768 second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
770 if (CheckAlgo(first, second, &id, &version) < 0)
771 return ASN_INPUT_E; /* Algo ID error */
773 if (version == PKCS5v2) {
775 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
778 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
781 if (oid != PBKDF2_OID)
785 if (GetSequence(input, &inOutIdx, &length, sz) < 0)
788 if (input[inOutIdx++] != ASN_OCTET_STRING)
791 if (GetLength(input, &inOutIdx, &saltSz, sz) < 0)
794 if (saltSz > MAX_SALT_SIZE)
797 XMEMCPY(salt, &input[inOutIdx], saltSz);
800 if (GetShortInt(input, &inOutIdx, &iterations) < 0)
803 if (version == PKCS5v2) {
804 /* get encryption algo */
805 if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
808 if (CheckAlgoV2(oid, &id) < 0)
809 return ASN_PARSE_E; /* PKCS v2 algo id error */
811 if (input[inOutIdx++] != ASN_OCTET_STRING)
814 if (GetLength(input, &inOutIdx, &length, sz) < 0)
817 XMEMCPY(cbcIv, &input[inOutIdx], length);
821 if (input[inOutIdx++] != ASN_OCTET_STRING)
824 if (GetLength(input, &inOutIdx, &length, sz) < 0)
827 if (DecryptKey(password, passwordSz, salt, saltSz, iterations, id,
828 input + inOutIdx, length, version, cbcIv) < 0)
829 return ASN_INPUT_E; /* decrypt failure */
831 XMEMMOVE(input, input + inOutIdx, length);
832 return ToTraditional(input, length);
835 #endif /* NO_PWDBASED */
838 int RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
843 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
846 key->type = RSA_PUBLIC;
850 byte b = input[*inOutIdx];
851 if (b != ASN_INTEGER) {
852 /* not from decoded cert, will have algo id, skip past */
853 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
856 b = input[(*inOutIdx)++];
857 if (b != ASN_OBJECT_ID)
858 return ASN_OBJECT_ID_E;
860 if (GetLength(input, inOutIdx, &length, inSz) < 0)
863 *inOutIdx += length; /* skip past */
865 /* could have NULL tag and 0 terminator, but may not */
866 b = input[(*inOutIdx)++];
868 if (b == ASN_TAG_NULL) {
869 b = input[(*inOutIdx)++];
871 return ASN_EXPECT_0_E;
874 /* go back, didn't have it */
877 /* should have bit tag length and seq next */
878 b = input[(*inOutIdx)++];
879 if (b != ASN_BIT_STRING)
882 if (GetLength(input, inOutIdx, &length, inSz) < 0)
886 b = input[(*inOutIdx)++];
890 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
893 } /* openssl var block */
894 #endif /* OPENSSL_EXTRA */
896 if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
897 GetInt(&key->e, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
905 int DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
909 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
912 if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
913 GetInt(&key->g, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
918 int DhSetKey(DhKey* key, const byte* p, word32 pSz, const byte* g, word32 gSz)
920 /* may have leading 0 */
930 if (mp_read_unsigned_bin(&key->p, p, pSz) != 0) {
936 if (mp_read_unsigned_bin(&key->g, g, gSz) != 0) {
947 int DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
948 byte* g, word32* gInOutSz)
954 if (GetSequence(input, &i, &length, inSz) < 0)
958 if (b != ASN_INTEGER)
961 if (GetLength(input, &i, &length, inSz) < 0)
964 if ( (b = input[i++]) == 0x00)
969 if (length <= (int)*pInOutSz) {
970 XMEMCPY(p, &input[i], length);
979 if (b != ASN_INTEGER)
982 if (GetLength(input, &i, &length, inSz) < 0)
985 if (length <= (int)*gInOutSz) {
986 XMEMCPY(g, &input[i], length);
995 #endif /* OPENSSL_EXTRA */
1001 int DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
1006 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1009 if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
1010 GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
1011 GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
1012 GetInt(&key->y, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
1014 key->type = DSA_PUBLIC;
1019 int DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
1022 int length, version;
1024 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
1027 if (GetMyVersion(input, inOutIdx, &version) < 0)
1030 if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
1031 GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
1032 GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
1033 GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
1034 GetInt(&key->x, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
1036 key->type = DSA_PRIVATE;
1043 void InitDecodedCert(DecodedCert* cert, byte* source, word32 inSz, void* heap)
1045 cert->publicKey = 0;
1046 cert->pubKeyStored = 0;
1047 cert->signature = 0;
1048 cert->subjectCN = 0;
1049 cert->subjectCNLen = 0;
1050 cert->issuer[0] = '\0';
1051 cert->subject[0] = '\0';
1052 cert->source = source; /* don't own */
1054 cert->maxIdx = inSz; /* can't go over this index */
1056 XMEMSET(cert->serial, 0, EXTERNAL_SERIAL_SIZE);
1058 cert->extensions = 0;
1059 cert->extensionsSz = 0;
1060 cert->extensionsIdx = 0;
1061 cert->extAuthInfo = NULL;
1062 cert->extAuthInfoSz = 0;
1063 cert->extCrlInfo = NULL;
1064 cert->extCrlInfoSz = 0;
1066 #ifdef CYASSL_CERT_GEN
1067 cert->subjectSN = 0;
1068 cert->subjectSNLen = 0;
1070 cert->subjectCLen = 0;
1072 cert->subjectLLen = 0;
1073 cert->subjectST = 0;
1074 cert->subjectSTLen = 0;
1076 cert->subjectOLen = 0;
1077 cert->subjectOU = 0;
1078 cert->subjectOULen = 0;
1079 cert->subjectEmail = 0;
1080 cert->subjectEmailLen = 0;
1081 cert->beforeDate = 0;
1082 cert->beforeDateLen = 0;
1083 cert->afterDate = 0;
1084 cert->afterDateLen = 0;
1085 #endif /* CYASSL_CERT_GEN */
1089 void FreeDecodedCert(DecodedCert* cert)
1091 if (cert->subjectCNLen == 0) /* 0 means no longer pointer to raw, we own */
1092 XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
1093 if (cert->pubKeyStored == 1)
1094 XFREE(cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
1098 static int GetCertHeader(DecodedCert* cert)
1100 int ret = 0, version, len;
1101 byte serialTmp[EXTERNAL_SERIAL_SIZE];
1104 if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
1107 cert->certBegin = cert->srcIdx;
1109 if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
1111 cert->sigIndex = len + cert->srcIdx;
1113 if (GetExplicitVersion(cert->source, &cert->srcIdx, &version) < 0)
1116 if (GetInt(&mpi, cert->source, &cert->srcIdx, cert->maxIdx) < 0)
1119 len = mp_unsigned_bin_size(&mpi);
1120 if (len < (int)sizeof(serialTmp)) {
1121 if (mp_to_unsigned_bin(&mpi, serialTmp) == MP_OKAY) {
1122 if (len > EXTERNAL_SERIAL_SIZE)
1123 len = EXTERNAL_SERIAL_SIZE;
1124 XMEMCPY(cert->serial, serialTmp, len);
1125 cert->serialSz = len;
1133 /* Store Rsa Key, may save later, Dsa could use in future */
1134 static int StoreRsaKey(DecodedCert* cert)
1137 word32 read = cert->srcIdx;
1139 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1142 read = cert->srcIdx - read;
1148 cert->pubKeySize = length;
1149 cert->publicKey = cert->source + cert->srcIdx;
1150 cert->srcIdx += length;
1158 /* return 0 on sucess if the ECC curve oid sum is supported */
1159 static int CheckCurve(word32 oid)
1161 if (oid != ECC_256R1 && oid != ECC_384R1 && oid != ECC_521R1 && oid !=
1162 ECC_160R1 && oid != ECC_192R1 && oid != ECC_224R1)
1168 #endif /* HAVE_ECC */
1171 static int GetKey(DecodedCert* cert)
1175 int tmpIdx = cert->srcIdx;
1178 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1181 if (GetAlgoId(cert->source, &cert->srcIdx, &cert->keyOID, cert->maxIdx) < 0)
1184 if (cert->keyOID == RSAk) {
1185 byte b = cert->source[cert->srcIdx++];
1186 if (b != ASN_BIT_STRING)
1187 return ASN_BITSTR_E;
1189 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1191 b = cert->source[cert->srcIdx++];
1193 return ASN_EXPECT_0_E;
1195 else if (cert->keyOID == DSAk )
1198 else if (cert->keyOID == NTRUk ) {
1199 const byte* key = &cert->source[tmpIdx];
1200 byte* next = (byte*)key;
1202 byte keyBlob[MAX_NTRU_KEY_SZ];
1204 word32 rc = crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key,
1205 &keyLen, NULL, &next);
1208 return ASN_NTRU_KEY_E;
1209 if (keyLen > sizeof(keyBlob))
1210 return ASN_NTRU_KEY_E;
1212 rc = crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key, &keyLen,
1215 return ASN_NTRU_KEY_E;
1217 if ( (next - key) < 0)
1218 return ASN_NTRU_KEY_E;
1220 cert->srcIdx = tmpIdx + (next - key);
1222 cert->publicKey = (byte*) XMALLOC(keyLen, cert->heap,
1223 DYNAMIC_TYPE_PUBLIC_KEY);
1224 if (cert->publicKey == NULL)
1226 XMEMCPY(cert->publicKey, keyBlob, keyLen);
1227 cert->pubKeyStored = 1;
1228 cert->pubKeySize = keyLen;
1230 #endif /* HAVE_NTRU */
1232 else if (cert->keyOID == ECDSAk ) {
1235 byte b = cert->source[cert->srcIdx++];
1237 if (b != ASN_OBJECT_ID)
1238 return ASN_OBJECT_ID_E;
1240 if (GetLength(cert->source, &cert->srcIdx, &oidSz, cert->maxIdx) < 0)
1244 oid += cert->source[cert->srcIdx++];
1245 if (CheckCurve(oid) < 0)
1246 return ECC_CURVE_OID_E;
1249 b = cert->source[cert->srcIdx++];
1250 if (b != ASN_BIT_STRING)
1251 return ASN_BITSTR_E;
1253 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1255 b = cert->source[cert->srcIdx++];
1257 return ASN_EXPECT_0_E;
1259 /* actual key, use length - 1 since ate preceding 0 */
1262 cert->publicKey = (byte*) XMALLOC(length, cert->heap,
1263 DYNAMIC_TYPE_PUBLIC_KEY);
1264 if (cert->publicKey == NULL)
1266 XMEMCPY(cert->publicKey, &cert->source[cert->srcIdx], length);
1267 cert->pubKeyStored = 1;
1268 cert->pubKeySize = length;
1270 cert->srcIdx += length;
1272 #endif /* HAVE_ECC */
1274 return ASN_UNKNOWN_OID_E;
1276 if (cert->keyOID == RSAk)
1277 return StoreRsaKey(cert);
1282 /* process NAME, either issuer or subject */
1283 static int GetName(DecodedCert* cert, int nameType)
1286 int length; /* length of all distinguished names */
1288 char* full = (nameType == ISSUER) ? cert->issuer : cert->subject;
1291 if (cert->source[cert->srcIdx] == ASN_OBJECT_ID) {
1292 CYASSL_MSG("Trying optional prefix...");
1294 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1297 cert->srcIdx += length;
1298 CYASSL_MSG("Got optional prefix");
1301 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1305 ShaUpdate(&sha, &cert->source[cert->srcIdx], length);
1306 if (nameType == ISSUER)
1307 ShaFinal(&sha, cert->issuerHash);
1309 ShaFinal(&sha, cert->subjectHash);
1311 length += cert->srcIdx;
1313 while (cert->srcIdx < (word32)length) {
1318 if (GetSet(cert->source, &cert->srcIdx, &dummy, cert->maxIdx) < 0) {
1319 (void)b; /* empty body warning w/o messages enabled */
1320 CYASSL_MSG("Cert name lacks set header, trying sequence");
1323 if (GetSequence(cert->source, &cert->srcIdx, &dummy, cert->maxIdx) < 0)
1326 b = cert->source[cert->srcIdx++];
1327 if (b != ASN_OBJECT_ID)
1328 return ASN_OBJECT_ID_E;
1330 if (GetLength(cert->source, &cert->srcIdx, &oidSz, cert->maxIdx) < 0)
1333 XMEMCPY(joint, &cert->source[cert->srcIdx], sizeof(joint));
1336 if (joint[0] == 0x55 && joint[1] == 0x04) {
1342 id = cert->source[cert->srcIdx++];
1343 b = cert->source[cert->srcIdx++]; /* strType */
1345 if (GetLength(cert->source, &cert->srcIdx, &strLen,
1350 CYASSL_MSG("Zero length name");
1353 if (strLen > (int)(ASN_NAME_MAX - idx))
1356 if (4 > (ASN_NAME_MAX - idx)) /* make sure room for biggest */
1357 return ASN_PARSE_E; /* pre fix header too "/CN=" */
1359 if (id == ASN_COMMON_NAME) {
1360 if (nameType == SUBJECT) {
1361 cert->subjectCN = (char *)&cert->source[cert->srcIdx];
1362 cert->subjectCNLen = strLen;
1365 XMEMCPY(&full[idx], "/CN=", 4);
1369 else if (id == ASN_SUR_NAME) {
1370 XMEMCPY(&full[idx], "/SN=", 4);
1373 #ifdef CYASSL_CERT_GEN
1374 if (nameType == SUBJECT) {
1375 cert->subjectSN = (char*)&cert->source[cert->srcIdx];
1376 cert->subjectSNLen = strLen;
1378 #endif /* CYASSL_CERT_GEN */
1380 else if (id == ASN_COUNTRY_NAME) {
1381 XMEMCPY(&full[idx], "/C=", 3);
1384 #ifdef CYASSL_CERT_GEN
1385 if (nameType == SUBJECT) {
1386 cert->subjectC = (char*)&cert->source[cert->srcIdx];
1387 cert->subjectCLen = strLen;
1389 #endif /* CYASSL_CERT_GEN */
1391 else if (id == ASN_LOCALITY_NAME) {
1392 XMEMCPY(&full[idx], "/L=", 3);
1395 #ifdef CYASSL_CERT_GEN
1396 if (nameType == SUBJECT) {
1397 cert->subjectL = (char*)&cert->source[cert->srcIdx];
1398 cert->subjectLLen = strLen;
1400 #endif /* CYASSL_CERT_GEN */
1402 else if (id == ASN_STATE_NAME) {
1403 XMEMCPY(&full[idx], "/ST=", 4);
1406 #ifdef CYASSL_CERT_GEN
1407 if (nameType == SUBJECT) {
1408 cert->subjectST = (char*)&cert->source[cert->srcIdx];
1409 cert->subjectSTLen = strLen;
1411 #endif /* CYASSL_CERT_GEN */
1413 else if (id == ASN_ORG_NAME) {
1414 XMEMCPY(&full[idx], "/O=", 3);
1417 #ifdef CYASSL_CERT_GEN
1418 if (nameType == SUBJECT) {
1419 cert->subjectO = (char*)&cert->source[cert->srcIdx];
1420 cert->subjectOLen = strLen;
1422 #endif /* CYASSL_CERT_GEN */
1424 else if (id == ASN_ORGUNIT_NAME) {
1425 XMEMCPY(&full[idx], "/OU=", 4);
1428 #ifdef CYASSL_CERT_GEN
1429 if (nameType == SUBJECT) {
1430 cert->subjectOU = (char*)&cert->source[cert->srcIdx];
1431 cert->subjectOULen = strLen;
1433 #endif /* CYASSL_CERT_GEN */
1437 XMEMCPY(&full[idx], &cert->source[cert->srcIdx], strLen);
1441 cert->srcIdx += strLen;
1449 if (joint[0] == 0x2a && joint[1] == 0x86) /* email id hdr */
1452 if (joint[0] == 0x9 && joint[1] == 0x92) /* uid id hdr */
1455 cert->srcIdx += oidSz + 1;
1457 if (GetLength(cert->source, &cert->srcIdx, &adv, cert->maxIdx) < 0)
1460 if (adv > (int)(ASN_NAME_MAX - idx))
1464 if (14 > (ASN_NAME_MAX - idx))
1466 XMEMCPY(&full[idx], "/emailAddress=", 14);
1469 #ifdef CYASSL_CERT_GEN
1470 if (nameType == SUBJECT) {
1471 cert->subjectEmail = (char*)&cert->source[cert->srcIdx];
1472 cert->subjectEmailLen = adv;
1474 #endif /* CYASSL_CERT_GEN */
1476 XMEMCPY(&full[idx], &cert->source[cert->srcIdx], adv);
1481 if (5 > (ASN_NAME_MAX - idx))
1483 XMEMCPY(&full[idx], "/UID=", 5);
1486 XMEMCPY(&full[idx], &cert->source[cert->srcIdx], adv);
1490 cert->srcIdx += adv;
1502 static int DateGreaterThan(const struct tm* a, const struct tm* b)
1504 if (a->tm_year > b->tm_year)
1507 if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
1510 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
1511 a->tm_mday > b->tm_mday)
1514 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
1515 a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
1518 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
1519 a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
1520 a->tm_min > b->tm_min)
1523 if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
1524 a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
1525 a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
1528 return 0; /* false */
1532 static INLINE int DateLessThan(const struct tm* a, const struct tm* b)
1534 return !DateGreaterThan(a,b);
1538 /* like atoi but only use first byte */
1539 /* Make sure before and after dates are valid */
1540 static int ValidateDate(const byte* date, byte format, int dateType)
1544 struct tm* localTime;
1548 XMEMSET(&certTime, 0, sizeof(certTime));
1550 if (format == ASN_UTC_TIME) {
1551 if (btoi(date[0]) >= 5)
1552 certTime.tm_year = 1900;
1554 certTime.tm_year = 2000;
1556 else { /* format == GENERALIZED_TIME */
1557 certTime.tm_year += btoi(date[i++]) * 1000;
1558 certTime.tm_year += btoi(date[i++]) * 100;
1561 GetTime(&certTime.tm_year, date, &i); certTime.tm_year -= 1900; /* adjust */
1562 GetTime(&certTime.tm_mon, date, &i); certTime.tm_mon -= 1; /* adjust */
1563 GetTime(&certTime.tm_mday, date, &i);
1564 GetTime(&certTime.tm_hour, date, &i);
1565 GetTime(&certTime.tm_min, date, &i);
1566 GetTime(&certTime.tm_sec, date, &i);
1568 if (date[i] != 'Z') { /* only Zulu supported for this profile */
1569 CYASSL_MSG("Only Zulu time supported for this profile");
1573 localTime = XGMTIME(<ime);
1575 if (dateType == BEFORE) {
1576 if (DateLessThan(localTime, &certTime))
1580 if (DateGreaterThan(localTime, &certTime))
1586 #endif /* NO_TIME_H */
1589 static int GetDate(DecodedCert* cert, int dateType)
1592 byte date[MAX_DATE_SIZE];
1595 #ifdef CYASSL_CERT_GEN
1596 word32 startIdx = 0;
1597 if (dateType == BEFORE)
1598 cert->beforeDate = &cert->source[cert->srcIdx];
1600 cert->afterDate = &cert->source[cert->srcIdx];
1601 startIdx = cert->srcIdx;
1604 b = cert->source[cert->srcIdx++];
1605 if (b != ASN_UTC_TIME && b != ASN_GENERALIZED_TIME)
1608 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1611 if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
1612 return ASN_DATE_SZ_E;
1614 XMEMCPY(date, &cert->source[cert->srcIdx], length);
1615 cert->srcIdx += length;
1617 #ifdef CYASSL_CERT_GEN
1618 if (dateType == BEFORE)
1619 cert->beforeDateLen = cert->srcIdx - startIdx;
1621 cert->afterDateLen = cert->srcIdx - startIdx;
1624 if (!XVALIDATE_DATE(date, b, dateType)) {
1625 if (dateType == BEFORE)
1626 return ASN_BEFORE_DATE_E;
1628 return ASN_AFTER_DATE_E;
1635 static int GetValidity(DecodedCert* cert, int verify)
1640 if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1643 if (GetDate(cert, BEFORE) < 0 && verify)
1644 badDate = ASN_BEFORE_DATE_E; /* continue parsing */
1646 if (GetDate(cert, AFTER) < 0 && verify)
1647 return ASN_AFTER_DATE_E;
1656 int DecodeToKey(DecodedCert* cert, int verify)
1661 if ( (ret = GetCertHeader(cert)) < 0)
1664 if ( (ret = GetAlgoId(cert->source, &cert->srcIdx, &cert->signatureOID,
1668 if ( (ret = GetName(cert, ISSUER)) < 0)
1671 if ( (ret = GetValidity(cert, verify)) < 0)
1674 if ( (ret = GetName(cert, SUBJECT)) < 0)
1677 if ( (ret = GetKey(cert)) < 0)
1687 static int GetSignature(DecodedCert* cert)
1690 byte b = cert->source[cert->srcIdx++];
1692 if (b != ASN_BIT_STRING)
1693 return ASN_BITSTR_E;
1695 if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
1698 cert->sigLength = length;
1700 b = cert->source[cert->srcIdx++];
1702 return ASN_EXPECT_0_E;
1705 cert->signature = &cert->source[cert->srcIdx];
1706 cert->srcIdx += cert->sigLength;
1712 static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
1714 output[0] = ASN_OCTET_STRING;
1715 output[1] = (byte)digSz;
1716 XMEMCPY(&output[2], digest, digSz);
1722 static word32 BytePrecision(word32 value)
1725 for (i = sizeof(value); i; --i)
1726 if (value >> (i - 1) * 8)
1733 static word32 SetLength(word32 length, byte* output)
1737 if (length < ASN_LONG_LENGTH)
1738 output[i++] = (byte)length;
1740 output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);
1742 for (j = BytePrecision(length); j; --j) {
1743 output[i] = (byte)(length >> (j - 1) * 8);
1752 static word32 SetSequence(word32 len, byte* output)
1754 output[0] = ASN_SEQUENCE | ASN_CONSTRUCTED;
1755 return SetLength(len, output + 1) + 1;
1759 static word32 SetAlgoID(int algoOID, byte* output, int type)
1761 /* adding TAG_NULL and 0 to end */
1764 static const byte shaAlgoID[] = { 0x2b, 0x0e, 0x03, 0x02, 0x1a,
1766 static const byte sha256AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
1767 0x04, 0x02, 0x01, 0x05, 0x00 };
1768 static const byte sha384AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
1769 0x04, 0x02, 0x02, 0x05, 0x00 };
1770 static const byte sha512AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
1771 0x04, 0x02, 0x03, 0x05, 0x00 };
1772 static const byte md5AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
1773 0x02, 0x05, 0x05, 0x00 };
1774 static const byte md2AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
1775 0x02, 0x02, 0x05, 0x00};
1777 static const byte md5wRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
1778 0x01, 0x01, 0x04, 0x05, 0x00};
1779 static const byte shawRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
1780 0x01, 0x01, 0x05, 0x05, 0x00};
1781 static const byte sha256wRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7,
1782 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00};
1783 static const byte sha384wRSA_AlgoID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
1784 0x0d, 0x01, 0x01, 0x0c, 0x05, 0x00};
1785 static const byte sha512wRSA_AlgoID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
1786 0x0d, 0x01, 0x01, 0x0d, 0x05, 0x00};
1788 static const byte RSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
1789 0x01, 0x01, 0x01, 0x05, 0x00};
1792 const byte* algoName = 0;
1793 byte ID_Length[MAX_LENGTH_SZ];
1794 byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
1796 if (type == hashType) {
1799 algoSz = sizeof(shaAlgoID);
1800 algoName = shaAlgoID;
1804 algoSz = sizeof(sha256AlgoID);
1805 algoName = sha256AlgoID;
1809 algoSz = sizeof(sha384AlgoID);
1810 algoName = sha384AlgoID;
1814 algoSz = sizeof(sha512AlgoID);
1815 algoName = sha512AlgoID;
1819 algoSz = sizeof(md2AlgoID);
1820 algoName = md2AlgoID;
1824 algoSz = sizeof(md5AlgoID);
1825 algoName = md5AlgoID;
1829 CYASSL_MSG("Unknown Hash Algo");
1830 return 0; /* UNKOWN_HASH_E; */
1833 else if (type == sigType) { /* sigType */
1836 algoSz = sizeof(md5wRSA_AlgoID);
1837 algoName = md5wRSA_AlgoID;
1841 algoSz = sizeof(shawRSA_AlgoID);
1842 algoName = shawRSA_AlgoID;
1845 case CTC_SHA256wRSA:
1846 algoSz = sizeof(sha256wRSA_AlgoID);
1847 algoName = sha256wRSA_AlgoID;
1850 case CTC_SHA384wRSA:
1851 algoSz = sizeof(sha384wRSA_AlgoID);
1852 algoName = sha384wRSA_AlgoID;
1855 case CTC_SHA512wRSA:
1856 algoSz = sizeof(sha512wRSA_AlgoID);
1857 algoName = sha512wRSA_AlgoID;
1861 CYASSL_MSG("Unknown Signature Algo");
1865 else if (type == keyType) { /* keyType */
1868 algoSz = sizeof(RSA_AlgoID);
1869 algoName = RSA_AlgoID;
1873 CYASSL_MSG("Unknown Key Algo");
1878 CYASSL_MSG("Unknown Algo type");
1882 idSz = SetLength(algoSz - 2, ID_Length); /* don't include TAG_NULL/0 */
1883 seqSz = SetSequence(idSz + algoSz + 1, seqArray);
1884 seqArray[seqSz++] = ASN_OBJECT_ID;
1886 XMEMCPY(output, seqArray, seqSz);
1887 XMEMCPY(output + seqSz, ID_Length, idSz);
1888 XMEMCPY(output + seqSz + idSz, algoName, algoSz);
1890 return seqSz + idSz + algoSz;
1895 word32 EncodeSignature(byte* out, const byte* digest, word32 digSz, int hashOID)
1897 byte digArray[MAX_ENCODED_DIG_SZ];
1898 byte algoArray[MAX_ALGO_SZ];
1899 byte seqArray[MAX_SEQ_SZ];
1900 word32 encDigSz, algoSz, seqSz;
1902 encDigSz = SetDigest(digest, digSz, digArray);
1903 algoSz = SetAlgoID(hashOID, algoArray, hashType);
1904 seqSz = SetSequence(encDigSz + algoSz, seqArray);
1906 XMEMCPY(out, seqArray, seqSz);
1907 XMEMCPY(out + seqSz, algoArray, algoSz);
1908 XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
1910 return encDigSz + algoSz + seqSz;
1914 /* return true (1) for Confirmation */
1915 static int ConfirmSignature(DecodedCert* cert, const byte* key, word32 keySz,
1918 #ifdef CYASSL_SHA512
1919 byte digest[SHA512_DIGEST_SIZE]; /* max size */
1920 #elif !defined(NO_SHA256)
1921 byte digest[SHA256_DIGEST_SIZE]; /* max size */
1923 byte digest[SHA_DIGEST_SIZE]; /* max size */
1925 int typeH, digestSz, ret;
1927 if (cert->signatureOID == CTC_MD5wRSA) {
1930 Md5Update(&md5, cert->source + cert->certBegin,
1931 cert->sigIndex - cert->certBegin);
1932 Md5Final(&md5, digest);
1934 digestSz = MD5_DIGEST_SIZE;
1936 else if (cert->signatureOID == CTC_SHAwRSA ||
1937 cert->signatureOID == CTC_SHAwDSA ||
1938 cert->signatureOID == CTC_SHAwECDSA) {
1941 ShaUpdate(&sha, cert->source + cert->certBegin,
1942 cert->sigIndex - cert->certBegin);
1943 ShaFinal(&sha, digest);
1945 digestSz = SHA_DIGEST_SIZE;
1948 else if (cert->signatureOID == CTC_SHA256wRSA ||
1949 cert->signatureOID == CTC_SHA256wECDSA) {
1951 InitSha256(&sha256);
1952 Sha256Update(&sha256, cert->source + cert->certBegin,
1953 cert->sigIndex - cert->certBegin);
1954 Sha256Final(&sha256, digest);
1956 digestSz = SHA256_DIGEST_SIZE;
1959 #ifdef CYASSL_SHA512
1960 else if (cert->signatureOID == CTC_SHA512wRSA ||
1961 cert->signatureOID == CTC_SHA512wECDSA) {
1963 InitSha512(&sha512);
1964 Sha512Update(&sha512, cert->source + cert->certBegin,
1965 cert->sigIndex - cert->certBegin);
1966 Sha512Final(&sha512, digest);
1968 digestSz = SHA512_DIGEST_SIZE;
1971 #ifdef CYASSL_SHA384
1972 else if (cert->signatureOID == CTC_SHA384wRSA ||
1973 cert->signatureOID == CTC_SHA384wECDSA) {
1975 InitSha384(&sha384);
1976 Sha384Update(&sha384, cert->source + cert->certBegin,
1977 cert->sigIndex - cert->certBegin);
1978 Sha384Final(&sha384, digest);
1980 digestSz = SHA384_DIGEST_SIZE;
1984 CYASSL_MSG("Verify Signautre has unsupported type");
1988 if (keyOID == RSAk) {
1990 byte encodedSig[MAX_ENCODED_SIG_SZ];
1991 byte plain[MAX_ENCODED_SIG_SZ];
1993 int sigSz, verifySz;
1996 if (cert->sigLength > MAX_ENCODED_SIG_SZ) {
1997 CYASSL_MSG("Verify Signautre is too big");
2001 InitRsaKey(&pubKey, cert->heap);
2002 if (RsaPublicKeyDecode(key, &idx, &pubKey, keySz) < 0) {
2003 CYASSL_MSG("ASN Key decode error RSA");
2007 XMEMCPY(plain, cert->signature, cert->sigLength);
2008 if ( (verifySz = RsaSSL_VerifyInline(plain, cert->sigLength, &out,
2010 CYASSL_MSG("Rsa SSL verify error");
2014 /* make sure we're right justified */
2015 sigSz = EncodeSignature(encodedSig, digest, digestSz, typeH);
2016 if (sigSz != verifySz || XMEMCMP(out, encodedSig, sigSz) != 0){
2017 CYASSL_MSG("Rsa SSL verify match encode error");
2021 ret = 1; /* match */
2023 #ifdef CYASSL_DEBUG_ENCODING
2026 printf("cyassl encodedSig:\n");
2027 for (x = 0; x < sigSz; x++) {
2028 printf("%02x ", encodedSig[x]);
2029 if ( (x % 16) == 15)
2033 printf("actual digest:\n");
2034 for (x = 0; x < verifySz; x++) {
2035 printf("%02x ", out[x]);
2036 if ( (x % 16) == 15)
2041 #endif /* CYASSL_DEBUG_ENCODING */
2044 FreeRsaKey(&pubKey);
2048 else if (keyOID == ECDSAk) {
2052 if (ecc_import_x963(key, keySz, &pubKey) < 0) {
2053 CYASSL_MSG("ASN Key import error ECC");
2057 ret = ecc_verify_hash(cert->signature, cert->sigLength, digest,
2058 digestSz, &verify, &pubKey);
2060 if (ret == 0 && verify == 1)
2061 return 1; /* match */
2063 CYASSL_MSG("ECC Verify didn't match");
2066 #endif /* HAVE_ECC */
2068 CYASSL_MSG("Verify Key type unknown");
2074 static void DecodeBasicCaConstraint(byte* input, int sz, DecodedCert* cert)
2079 CYASSL_ENTER("DecodeBasicCaConstraint");
2080 if (GetSequence(input, &idx, &length, sz) < 0) return;
2082 if (input[idx++] != ASN_BOOLEAN)
2084 CYASSL_MSG("\tfail: constraint not BOOLEAN");
2088 if (GetLength(input, &idx, &length, sz) < 0)
2090 CYASSL_MSG("\tfail: length");
2099 #define CRLDP_FULL_NAME 0
2100 /* From RFC3280 SS4.2.1.14, Distribution Point Name*/
2101 #define GENERALNAME_URI 6
2102 /* From RFC3280 SS4.2.1.7, GeneralName */
2104 static void DecodeCrlDist(byte* input, int sz, DecodedCert* cert)
2109 CYASSL_ENTER("DecodeCrlDist");
2111 /* Unwrap the list of Distribution Points*/
2112 if (GetSequence(input, &idx, &length, sz) < 0) return;
2114 /* Unwrap a single Distribution Point */
2115 if (GetSequence(input, &idx, &length, sz) < 0) return;
2117 /* The Distribution Point has three explicit optional members
2118 * First check for a DistributionPointName
2120 if (input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
2123 if (GetLength(input, &idx, &length, sz) < 0) return;
2126 (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CRLDP_FULL_NAME))
2129 if (GetLength(input, &idx, &length, sz) < 0) return;
2131 if (input[idx] == (ASN_CONTEXT_SPECIFIC | GENERALNAME_URI))
2134 if (GetLength(input, &idx, &length, sz) < 0) return;
2136 cert->extCrlInfoSz = length;
2137 cert->extCrlInfo = input + idx;
2141 /* This isn't a URI, skip it. */
2145 /* This isn't a FULLNAME, skip it. */
2149 /* Check for reasonFlags */
2150 if (idx < (word32)sz &&
2151 input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
2154 if (GetLength(input, &idx, &length, sz) < 0) return;
2158 /* Check for cRLIssuer */
2159 if (idx < (word32)sz &&
2160 input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
2163 if (GetLength(input, &idx, &length, sz) < 0) return;
2167 if (idx < (word32)sz)
2169 CYASSL_MSG("\tThere are more CRL Distribution Point records, "
2170 "but we only use the first one.");
2177 static void DecodeAuthInfo(byte* input, int sz, DecodedCert* cert)
2179 * Read the first of the Authority Information Access records. If there are
2180 * any issues, return without saving the record.
2187 /* Unwrap the list of AIAs */
2188 if (GetSequence(input, &idx, &length, sz) < 0) return;
2190 /* Unwrap a single AIA */
2191 if (GetSequence(input, &idx, &length, sz) < 0) return;
2194 if (GetObjectId(input, &idx, &oid, sz) < 0) return;
2196 /* Only supporting URIs right now. */
2197 if (input[idx] == (ASN_CONTEXT_SPECIFIC | GENERALNAME_URI))
2200 if (GetLength(input, &idx, &length, sz) < 0) return;
2202 cert->extAuthInfoSz = length;
2203 cert->extAuthInfo = input + idx;
2208 /* Skip anything else. */
2210 if (GetLength(input, &idx, &length, sz) < 0) return;
2214 if (idx < (word32)sz)
2216 CYASSL_MSG("\tThere are more Authority Information Access records, "
2217 "but we only use first one.");
2224 static void DecodeCertExtensions(DecodedCert* cert)
2226 * Processing the Certificate Extensions. This does not modify the current
2227 * index. It is works starting with the recorded extensions pointer.
2231 int sz = cert->extensionsSz;
2232 byte* input = cert->extensions;
2236 CYASSL_ENTER("DecodeCertExtensions");
2238 if (input == NULL || sz == 0) return;
2240 if (input[idx++] != ASN_EXTENSIONS)return;
2242 if (GetLength(input, &idx, &length, sz) < 0) return;
2244 if (GetSequence(input, &idx, &length, sz) < 0) return;
2246 while (idx < (word32)sz) {
2247 if (GetSequence(input, &idx, &length, sz) < 0) {
2248 CYASSL_MSG("\tfail: should be a SEQUENCE");
2253 if (GetObjectId(input, &idx, &oid, sz) < 0) {
2254 CYASSL_MSG("\tfail: OBJECT ID");
2258 /* check for critical flag */
2259 if (input[idx] == ASN_BOOLEAN) {
2260 CYASSL_MSG("\tfound optional critical flag, moving past");
2261 idx += (ASN_BOOL_SIZE + 1);
2264 /* process the extension based on the OID */
2265 if (input[idx++] != ASN_OCTET_STRING) {
2266 CYASSL_MSG("\tfail: should be an OCTET STRING");
2270 if (GetLength(input, &idx, &length, sz) < 0) {
2271 CYASSL_MSG("\tfail: extension data length");
2277 DecodeBasicCaConstraint(&input[idx], length, cert);
2281 DecodeCrlDist(&input[idx], length, cert);
2285 DecodeAuthInfo(&input[idx], length, cert);
2289 CYASSL_MSG("\tExtension type not handled, skipping");
2299 int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
2304 ret = ParseCertRelative(cert, type, verify, cm);
2308 if (cert->subjectCNLen > 0) {
2309 ptr = (char*) XMALLOC(cert->subjectCNLen + 1, cert->heap,
2310 DYNAMIC_TYPE_SUBJECT_CN);
2313 XMEMCPY(ptr, cert->subjectCN, cert->subjectCNLen);
2314 ptr[cert->subjectCNLen] = '\0';
2315 cert->subjectCN = ptr;
2316 cert->subjectCNLen = 0;
2319 if (cert->keyOID == RSAk && cert->pubKeySize > 0) {
2320 ptr = (char*) XMALLOC(cert->pubKeySize, cert->heap,
2321 DYNAMIC_TYPE_PUBLIC_KEY);
2324 XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
2325 cert->publicKey = (byte *)ptr;
2326 cert->pubKeyStored = 1;
2333 /* from SSL proper, for locking can't do find here anymore */
2337 CYASSL_LOCAL Signer* GetCA(void* signers, byte* hash);
2343 int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
2349 if ((ret = DecodeToKey(cert, verify)) < 0) {
2350 if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E)
2356 if (cert->srcIdx != cert->sigIndex) {
2357 if (cert->srcIdx < cert->sigIndex) {
2358 /* save extensions */
2359 cert->extensions = &cert->source[cert->srcIdx];
2360 cert->extensionsSz = cert->sigIndex - cert->srcIdx;
2361 cert->extensionsIdx = cert->srcIdx; /* for potential later use */
2363 DecodeCertExtensions(cert);
2364 /* advance past extensions */
2365 cert->srcIdx = cert->sigIndex;
2368 if ((ret = GetAlgoId(cert->source, &cert->srcIdx, &confirmOID,
2372 if ((ret = GetSignature(cert)) < 0)
2375 if (confirmOID != cert->signatureOID)
2376 return ASN_SIG_OID_E;
2378 if (verify && type != CA_TYPE) {
2379 Signer* ca = GetCA(cm, cert->issuerHash);
2380 CYASSL_MSG("About to verify certificate signature");
2384 /* Need the ca's public key hash for OCSP */
2388 ShaUpdate(&sha, ca->publicKey, ca->pubKeySize);
2389 ShaFinal(&sha, cert->issuerKeyHash);
2391 #endif /* HAVE_OCSP */
2392 /* try to confirm/verify signature */
2393 if (!ConfirmSignature(cert, ca->publicKey,
2394 ca->pubKeySize, ca->keyOID)) {
2395 CYASSL_MSG("Confirm signature failed");
2396 return ASN_SIG_CONFIRM_E;
2401 CYASSL_MSG("No CA signer to verify with");
2402 return ASN_SIG_CONFIRM_E;
2413 Signer* MakeSigner(void* heap)
2415 Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
2416 DYNAMIC_TYPE_SIGNER);
2419 signer->publicKey = 0;
2428 void FreeSigners(Signer* signer, void* heap)
2431 Signer* next = signer->next;
2433 XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
2434 XFREE(signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
2435 XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
2443 void CTaoCryptErrorString(int error, char* buffer)
2445 const int max = MAX_ERROR_SZ; /* shorthand */
2447 #ifdef NO_ERROR_STRINGS
2449 XSTRNCPY(buffer, "no support for error strings built in", max);
2456 XSTRNCPY(buffer, "opening random device error", max);
2460 XSTRNCPY(buffer, "reading random device error", max);
2464 XSTRNCPY(buffer, "windows crypt init error", max);
2468 XSTRNCPY(buffer, "windows crypt generation error", max);
2472 XSTRNCPY(buffer, "random device read would block error", max);
2476 XSTRNCPY(buffer, "mp_init error state", max);
2480 XSTRNCPY(buffer, "mp_read error state", max);
2484 XSTRNCPY(buffer, "mp_exptmod error state", max);
2488 XSTRNCPY(buffer, "mp_to_xxx error state, can't convert", max);
2492 XSTRNCPY(buffer, "mp_sub error state, can't subtract", max);
2496 XSTRNCPY(buffer, "mp_add error state, can't add", max);
2500 XSTRNCPY(buffer, "mp_mul error state, can't multiply", max);
2504 XSTRNCPY(buffer, "mp_mulmod error state, can't multiply mod", max);
2508 XSTRNCPY(buffer, "mp_mod error state, can't mod", max);
2512 XSTRNCPY(buffer, "mp_invmod error state, can't inv mod", max);
2516 XSTRNCPY(buffer, "mp_cmp error state", max);
2520 XSTRNCPY(buffer, "mp zero result, not expected", max);
2524 XSTRNCPY(buffer, "out of memory error", max);
2527 case RSA_WRONG_TYPE_E :
2528 XSTRNCPY(buffer, "RSA wrong block type for RSA function", max);
2532 XSTRNCPY(buffer, "RSA buffer error, output too small or input too big",
2537 XSTRNCPY(buffer, "Buffer error, output too small or input too big",max);
2541 XSTRNCPY(buffer, "Setting Cert AlogID error", max);
2545 XSTRNCPY(buffer, "Setting Cert Public Key error", max);
2549 XSTRNCPY(buffer, "Setting Cert Date validity error", max);
2553 XSTRNCPY(buffer, "Setting Cert Subject name error", max);
2557 XSTRNCPY(buffer, "Setting Cert Issuer name error", max);
2561 XSTRNCPY(buffer, "Setting basic constraint CA true error", max);
2565 XSTRNCPY(buffer, "Setting extensions error", max);
2569 XSTRNCPY(buffer, "ASN parsing error, invalid input", max);
2572 case ASN_VERSION_E :
2573 XSTRNCPY(buffer, "ASN version error, invalid number", max);
2577 XSTRNCPY(buffer, "ASN get big int error, invalid data", max);
2580 case ASN_RSA_KEY_E :
2581 XSTRNCPY(buffer, "ASN key init error, invalid input", max);
2584 case ASN_OBJECT_ID_E :
2585 XSTRNCPY(buffer, "ASN object id error, invalid id", max);
2588 case ASN_TAG_NULL_E :
2589 XSTRNCPY(buffer, "ASN tag error, not null", max);
2592 case ASN_EXPECT_0_E :
2593 XSTRNCPY(buffer, "ASN expect error, not zero", max);
2597 XSTRNCPY(buffer, "ASN bit string error, wrong id", max);
2600 case ASN_UNKNOWN_OID_E :
2601 XSTRNCPY(buffer, "ASN oid error, unknown sum id", max);
2604 case ASN_DATE_SZ_E :
2605 XSTRNCPY(buffer, "ASN date error, bad size", max);
2608 case ASN_BEFORE_DATE_E :
2609 XSTRNCPY(buffer, "ASN date error, current date before", max);
2612 case ASN_AFTER_DATE_E :
2613 XSTRNCPY(buffer, "ASN date error, current date after", max);
2616 case ASN_SIG_OID_E :
2617 XSTRNCPY(buffer, "ASN signature error, mismatched oid", max);
2621 XSTRNCPY(buffer, "ASN time error, unkown time type", max);
2625 XSTRNCPY(buffer, "ASN input error, not enough data", max);
2628 case ASN_SIG_CONFIRM_E :
2629 XSTRNCPY(buffer, "ASN sig error, confirm failure", max);
2632 case ASN_SIG_HASH_E :
2633 XSTRNCPY(buffer, "ASN sig error, unsupported hash type", max);
2636 case ASN_SIG_KEY_E :
2637 XSTRNCPY(buffer, "ASN sig error, unsupported key type", max);
2641 XSTRNCPY(buffer, "ASN key init error, invalid input", max);
2644 case ASN_NTRU_KEY_E :
2645 XSTRNCPY(buffer, "ASN NTRU key decode error, invalid input", max);
2648 case ECC_BAD_ARG_E :
2649 XSTRNCPY(buffer, "ECC input argument wrong type, invalid input", max);
2652 case ASN_ECC_KEY_E :
2653 XSTRNCPY(buffer, "ECC ASN1 bad key data, invalid input", max);
2656 case ECC_CURVE_OID_E :
2657 XSTRNCPY(buffer, "ECC curve sum OID unsupported, invalid input", max);
2661 XSTRNCPY(buffer, "Bad function argument", max);
2664 case NOT_COMPILED_IN :
2665 XSTRNCPY(buffer, "Feature not compiled in", max);
2668 case UNICODE_SIZE_E :
2669 XSTRNCPY(buffer, "Unicode password too big", max);
2673 XSTRNCPY(buffer, "No password provided by user", max);
2677 XSTRNCPY(buffer, "Alt Name problem, too big", max);
2681 XSTRNCPY(buffer, "unknown error number", max);
2685 #endif /* NO_ERROR_STRINGS */
2690 #if defined(CYASSL_KEY_GEN) || defined(CYASSL_CERT_GEN)
2692 static int SetMyVersion(word32 version, byte* output, int header)
2697 output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
2698 output[i++] = ASN_BIT_STRING;
2700 output[i++] = ASN_INTEGER;
2702 output[i++] = version;
2708 int DerToPem(const byte* der, word32 derSz, byte* output, word32 outSz,
2718 int outLen; /* return length or error */
2720 if (type == CERT_TYPE) {
2721 XSTRNCPY(header, "-----BEGIN CERTIFICATE-----\n", sizeof(header));
2722 XSTRNCPY(footer, "-----END CERTIFICATE-----\n", sizeof(footer));
2724 XSTRNCPY(header, "-----BEGIN RSA PRIVATE KEY-----\n", sizeof(header));
2725 XSTRNCPY(footer, "-----END RSA PRIVATE KEY-----\n", sizeof(footer));
2728 headerLen = XSTRLEN(header);
2729 footerLen = XSTRLEN(footer);
2731 if (!der || !output)
2732 return BAD_FUNC_ARG;
2734 /* don't even try if outSz too short */
2735 if (outSz < headerLen + footerLen + derSz)
2736 return BAD_FUNC_ARG;
2739 XMEMCPY(output, header, headerLen);
2743 outLen = outSz; /* input to Base64_Encode */
2744 if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0)
2749 if ( (i + footerLen) > (int)outSz)
2750 return BAD_FUNC_ARG;
2751 XMEMCPY(output + i, footer, footerLen);
2753 return outLen + headerLen + footerLen;
2757 #endif /* CYASSL_KEY_GEN || CYASSL_CERT_GEN */
2760 #ifdef CYASSL_KEY_GEN
2763 static mp_int* GetRsaInt(RsaKey* key, int idx)
2786 /* Convert RsaKey key to DER format, write to output (inLen), return bytes
2788 int RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
2790 word32 seqSz, verSz, rawLen, intTotalLen = 0;
2791 word32 sizes[RSA_INTS];
2794 byte seq[MAX_SEQ_SZ];
2795 byte ver[MAX_VERSION_SZ];
2796 byte tmps[RSA_INTS][MAX_RSA_INT_SZ];
2798 if (!key || !output)
2799 return BAD_FUNC_ARG;
2801 if (key->type != RSA_PRIVATE)
2802 return BAD_FUNC_ARG;
2804 /* write all big ints from key to DER tmps */
2805 for (i = 0; i < RSA_INTS; i++) {
2806 mp_int* keyInt = GetRsaInt(key, i);
2807 rawLen = mp_unsigned_bin_size(keyInt);
2809 tmps[i][0] = ASN_INTEGER;
2810 sizes[i] = SetLength(rawLen, tmps[i] + 1) + 1; /* int tag */
2812 if ( (sizes[i] + rawLen) < sizeof(tmps[i])) {
2813 int err = mp_to_unsigned_bin(keyInt, tmps[i] + sizes[i]);
2814 if (err == MP_OKAY) {
2816 intTotalLen += sizes[i];
2826 verSz = SetMyVersion(0, ver, FALSE);
2827 seqSz = SetSequence(verSz + intTotalLen, seq);
2829 outLen = seqSz + verSz + intTotalLen;
2830 if (outLen > (int)inLen)
2831 return BAD_FUNC_ARG;
2833 /* write to output */
2834 XMEMCPY(output, seq, seqSz);
2836 XMEMCPY(output + j, ver, verSz);
2839 for (i = 0; i < RSA_INTS; i++) {
2840 XMEMCPY(output + j, tmps[i], sizes[i]);
2847 #endif /* CYASSL_KEY_GEN */
2850 #ifdef CYASSL_CERT_GEN
2852 /* Initialize and Set Certficate defaults:
2855 sigType = SHA_WITH_RSA
2858 selfSigned = 1 (true) use subject as issuer
2861 void InitCert(Cert* cert)
2863 cert->version = 2; /* version 3 is hex 2 */
2864 cert->sigType = CTC_SHAwRSA;
2865 cert->daysValid = 500;
2866 cert->selfSigned = 1;
2869 #ifdef CYASSL_ALT_NAMES
2870 cert->altNamesSz = 0;
2871 cert->beforeDateSz = 0;
2872 cert->afterDateSz = 0;
2874 cert->keyType = RSA_KEY;
2875 XMEMSET(cert->serial, 0, CTC_SERIAL_SIZE);
2877 cert->issuer.country[0] = '\0';
2878 cert->issuer.state[0] = '\0';
2879 cert->issuer.locality[0] = '\0';
2880 cert->issuer.sur[0] = '\0';
2881 cert->issuer.org[0] = '\0';
2882 cert->issuer.unit[0] = '\0';
2883 cert->issuer.commonName[0] = '\0';
2884 cert->issuer.email[0] = '\0';
2886 cert->subject.country[0] = '\0';
2887 cert->subject.state[0] = '\0';
2888 cert->subject.locality[0] = '\0';
2889 cert->subject.sur[0] = '\0';
2890 cert->subject.org[0] = '\0';
2891 cert->subject.unit[0] = '\0';
2892 cert->subject.commonName[0] = '\0';
2893 cert->subject.email[0] = '\0';
2897 /* DER encoded x509 Certificate */
2898 typedef struct DerCert {
2899 byte size[MAX_LENGTH_SZ]; /* length encoded */
2900 byte version[MAX_VERSION_SZ]; /* version encoded */
2901 byte serial[CTC_SERIAL_SIZE + MAX_LENGTH_SZ]; /* serial number encoded */
2902 byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
2903 byte issuer[ASN_NAME_MAX]; /* issuer encoded */
2904 byte subject[ASN_NAME_MAX]; /* subject encoded */
2905 byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
2906 byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa / ntru public key encoded */
2907 byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
2908 byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
2909 int sizeSz; /* encoded size length */
2910 int versionSz; /* encoded version length */
2911 int serialSz; /* encoded serial length */
2912 int sigAlgoSz; /* enocded sig alog length */
2913 int issuerSz; /* encoded issuer length */
2914 int subjectSz; /* encoded subject length */
2915 int validitySz; /* encoded validity length */
2916 int publicKeySz; /* encoded public key length */
2917 int caSz; /* encoded CA extension length */
2918 int extensionsSz; /* encoded extensions total length */
2919 int total; /* total encoded lengths */
2923 /* Write a set header to output */
2924 static word32 SetSet(word32 len, byte* output)
2926 output[0] = ASN_SET | ASN_CONSTRUCTED;
2927 return SetLength(len, output + 1) + 1;
2931 /* Write a serial number to output */
2932 static int SetSerial(const byte* serial, byte* output)
2936 output[length++] = ASN_INTEGER;
2937 length += SetLength(CTC_SERIAL_SIZE, &output[length]);
2938 XMEMCPY(&output[length], serial, CTC_SERIAL_SIZE);
2940 return length + CTC_SERIAL_SIZE;
2944 /* Write a public RSA key to output */
2945 static int SetPublicKey(byte* output, RsaKey* key)
2947 byte n[MAX_RSA_INT_SZ];
2948 byte e[MAX_RSA_E_SZ];
2949 byte algo[MAX_ALGO_SZ];
2950 byte seq[MAX_SEQ_SZ];
2951 byte len[MAX_LENGTH_SZ + 1]; /* trailing 0 */
2961 rawLen = mp_unsigned_bin_size(&key->n);
2963 nSz = SetLength(rawLen, n + 1) + 1; /* int tag */
2965 if ( (nSz + rawLen) < (int)sizeof(n)) {
2966 int err = mp_to_unsigned_bin(&key->n, n + nSz);
2976 rawLen = mp_unsigned_bin_size(&key->e);
2978 eSz = SetLength(rawLen, e + 1) + 1; /* int tag */
2980 if ( (eSz + rawLen) < (int)sizeof(e)) {
2981 int err = mp_to_unsigned_bin(&key->e, e + eSz);
2991 algoSz = SetAlgoID(RSAk, algo, keyType);
2992 seqSz = SetSequence(nSz + eSz, seq);
2993 lenSz = SetLength(seqSz + nSz + eSz + 1, len);
2994 len[lenSz++] = 0; /* trailing 0 */
2997 idx = SetSequence(nSz + eSz + seqSz + lenSz + 1 + algoSz, output);
2998 /* 1 is for ASN_BIT_STRING */
3000 XMEMCPY(output + idx, algo, algoSz);
3003 output[idx++] = ASN_BIT_STRING;
3005 XMEMCPY(output + idx, len, lenSz);
3008 XMEMCPY(output + idx, seq, seqSz);
3011 XMEMCPY(output + idx, n, nSz);
3014 XMEMCPY(output + idx, e, eSz);
3021 static INLINE byte itob(int number)
3023 return (byte)number + 0x30;
3027 /* write time to output, format */
3028 static void SetTime(struct tm* date, byte* output)
3032 output[i++] = itob((date->tm_year % 10000) / 1000);
3033 output[i++] = itob((date->tm_year % 1000) / 100);
3034 output[i++] = itob((date->tm_year % 100) / 10);
3035 output[i++] = itob( date->tm_year % 10);
3037 output[i++] = itob(date->tm_mon / 10);
3038 output[i++] = itob(date->tm_mon % 10);
3040 output[i++] = itob(date->tm_mday / 10);
3041 output[i++] = itob(date->tm_mday % 10);
3043 output[i++] = itob(date->tm_hour / 10);
3044 output[i++] = itob(date->tm_hour % 10);
3046 output[i++] = itob(date->tm_min / 10);
3047 output[i++] = itob(date->tm_min % 10);
3049 output[i++] = itob(date->tm_sec / 10);
3050 output[i++] = itob(date->tm_sec % 10);
3052 output[i] = 'Z'; /* Zulu profile */
3056 #ifdef CYASSL_ALT_NAMES
3058 /* Copy Dates from cert, return bytes written */
3059 static int CopyValidity(byte* output, Cert* cert)
3063 CYASSL_ENTER("CopyValidity");
3065 /* headers and output */
3066 seqSz = SetSequence(cert->beforeDateSz + cert->afterDateSz, output);
3067 XMEMCPY(output + seqSz, cert->beforeDate, cert->beforeDateSz);
3068 XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
3070 return seqSz + cert->beforeDateSz + cert->afterDateSz;
3076 /* Set Date validity from now until now + daysValid */
3077 static int SetValidity(byte* output, int daysValid)
3079 byte before[MAX_DATE_SIZE];
3080 byte after[MAX_DATE_SIZE];
3091 now = XGMTIME(&ticks);
3095 before[0] = ASN_GENERALIZED_TIME;
3096 beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
3098 /* subtract 1 day for more compliance */
3103 local.tm_year += 1900;
3106 SetTime(&local, before + beforeSz);
3107 beforeSz += ASN_GEN_TIME_SZ;
3109 /* after now + daysValid */
3111 after[0] = ASN_GENERALIZED_TIME;
3112 afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
3115 local.tm_mday += daysValid;
3119 local.tm_year += 1900;
3122 SetTime(&local, after + afterSz);
3123 afterSz += ASN_GEN_TIME_SZ;
3125 /* headers and output */
3126 seqSz = SetSequence(beforeSz + afterSz, output);
3127 XMEMCPY(output + seqSz, before, beforeSz);
3128 XMEMCPY(output + seqSz + beforeSz, after, afterSz);
3130 return seqSz + beforeSz + afterSz;
3134 /* ASN Encoded Name field */
3135 typedef struct EncodedName {
3136 int nameLen; /* actual string value length */
3137 int totalLen; /* total encoded length */
3138 int type; /* type of name */
3139 int used; /* are we actually using this one */
3140 byte encoded[CTC_NAME_SIZE * 2]; /* encoding */
3144 /* Get Which Name from index */
3145 static const char* GetOneName(CertName* name, int idx)
3149 return name->country;
3155 return name->locality;
3167 return name->commonName;
3180 /* Get ASN Name from index */
3181 static byte GetNameId(int idx)
3185 return ASN_COUNTRY_NAME;
3188 return ASN_STATE_NAME;
3191 return ASN_LOCALITY_NAME;
3194 return ASN_SUR_NAME;
3197 return ASN_ORG_NAME;
3200 return ASN_ORGUNIT_NAME;
3203 return ASN_COMMON_NAME;
3206 /* email uses different id type */
3217 /* encode all extensions, return total bytes written */
3218 static int SetExtensions(byte* output, const byte* ext, int extSz)
3220 byte sequence[MAX_SEQ_SZ];
3221 byte len[MAX_LENGTH_SZ];
3224 int seqSz = SetSequence(extSz, sequence);
3225 int lenSz = SetLength(seqSz + extSz, len);
3227 output[0] = ASN_EXTENSIONS; /* extensions id */
3229 XMEMCPY(&output[sz], len, lenSz); /* length */
3231 XMEMCPY(&output[sz], sequence, seqSz); /* sequence */
3233 XMEMCPY(&output[sz], ext, extSz); /* extensions */
3240 /* encode CA basic constraint true, return total bytes written */
3241 static int SetCa(byte* output)
3243 static const byte ca[] = { 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
3244 0x05, 0x30, 0x03, 0x01, 0x01, 0xff };
3246 XMEMCPY(output, ca, sizeof(ca));
3248 return (int)sizeof(ca);
3252 /* encode CertName into output, return total bytes written */
3253 static int SetName(byte* output, CertName* name)
3255 int totalBytes = 0, i, idx;
3256 EncodedName names[NAME_ENTRIES];
3258 for (i = 0; i < NAME_ENTRIES; i++) {
3259 const char* nameStr = GetOneName(name, i);
3262 byte firstLen[MAX_LENGTH_SZ];
3263 byte secondLen[MAX_LENGTH_SZ];
3264 byte sequence[MAX_SEQ_SZ];
3265 byte set[MAX_SET_SZ];
3267 int email = i == (NAME_ENTRIES - 1) ? 1 : 0;
3268 int strLen = XSTRLEN(nameStr);
3269 int thisLen = strLen;
3270 int firstSz, secondSz, seqSz, setSz;
3272 if (strLen == 0) { /* no user data for this item */
3277 secondSz = SetLength(strLen, secondLen);
3278 thisLen += secondSz;
3280 thisLen += EMAIL_JOINT_LEN;
3281 thisLen ++; /* id type */
3282 firstSz = SetLength(EMAIL_JOINT_LEN, firstLen);
3285 thisLen++; /* str type */
3286 thisLen++; /* id type */
3287 thisLen += JOINT_LEN;
3288 firstSz = SetLength(JOINT_LEN + 1, firstLen);
3291 thisLen++; /* object id */
3293 seqSz = SetSequence(thisLen, sequence);
3295 setSz = SetSet(thisLen, set);
3298 if (thisLen > (int)sizeof(names[i].encoded))
3304 XMEMCPY(names[i].encoded, set, setSz);
3307 XMEMCPY(names[i].encoded + idx, sequence, seqSz);
3310 names[i].encoded[idx++] = ASN_OBJECT_ID;
3312 XMEMCPY(names[i].encoded + idx, firstLen, firstSz);
3315 const byte EMAIL_OID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
3316 0x01, 0x09, 0x01, 0x16 };
3317 /* email joint id */
3318 XMEMCPY(names[i].encoded + idx, EMAIL_OID, sizeof(EMAIL_OID));
3319 idx += sizeof(EMAIL_OID);
3323 names[i].encoded[idx++] = 0x55;
3324 names[i].encoded[idx++] = 0x04;
3326 names[i].encoded[idx++] = GetNameId(i);
3328 names[i].encoded[idx++] = 0x13;
3331 XMEMCPY(names[i].encoded + idx, secondLen, secondSz);
3334 XMEMCPY(names[i].encoded + idx, nameStr, strLen);
3338 names[i].totalLen = idx;
3346 idx = SetSequence(totalBytes, output);
3348 if (totalBytes > ASN_NAME_MAX)
3351 for (i = 0; i < NAME_ENTRIES; i++) {
3352 if (names[i].used) {
3353 XMEMCPY(output + idx, names[i].encoded, names[i].totalLen);
3354 idx += names[i].totalLen;
3361 /* encode info from cert into DER enocder format */
3362 static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, RNG* rng,
3363 const byte* ntruKey, word16 ntruSz)
3368 der->versionSz = SetMyVersion(cert->version, der->version, TRUE);
3371 RNG_GenerateBlock(rng, cert->serial, CTC_SERIAL_SIZE);
3372 cert->serial[0] = 0x01; /* ensure positive */
3373 der->serialSz = SetSerial(cert->serial, der->serial);
3375 /* signature algo */
3376 der->sigAlgoSz = SetAlgoID(cert->sigType, der->sigAlgo, sigType);
3377 if (der->sigAlgoSz == 0)
3381 if (cert->keyType == RSA_KEY) {
3382 der->publicKeySz = SetPublicKey(der->publicKey, rsaKey);
3383 if (der->publicKeySz == 0)
3384 return PUBLIC_KEY_E;
3391 rc = crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo( ntruSz,
3392 ntruKey, &encodedSz, NULL);
3394 return PUBLIC_KEY_E;
3395 if (encodedSz > MAX_PUBLIC_KEY_SZ)
3396 return PUBLIC_KEY_E;
3398 rc = crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo( ntruSz,
3399 ntruKey, &encodedSz, der->publicKey);
3401 return PUBLIC_KEY_E;
3403 der->publicKeySz = encodedSz;
3407 der->validitySz = 0;
3408 #ifdef CYASSL_ALT_NAMES
3409 /* date validity copy ? */
3410 if (cert->beforeDateSz && cert->afterDateSz) {
3411 der->validitySz = CopyValidity(der->validity, cert);
3412 if (der->validitySz == 0)
3418 if (der->validitySz == 0) {
3419 der->validitySz = SetValidity(der->validity, cert->daysValid);
3420 if (der->validitySz == 0)
3425 der->subjectSz = SetName(der->subject, &cert->subject);
3426 if (der->subjectSz == 0)
3430 der->issuerSz = SetName(der->issuer, cert->selfSigned ?
3431 &cert->subject : &cert->issuer);
3432 if (der->issuerSz == 0)
3437 der->caSz = SetCa(der->ca);
3444 /* extensions, just CA now */
3446 der->extensionsSz = SetExtensions(der->extensions, der->ca, der->caSz);
3447 if (der->extensionsSz == 0)
3448 return EXTENSIONS_E;
3451 der->extensionsSz = 0;
3453 #ifdef CYASSL_ALT_NAMES
3454 if (der->extensionsSz == 0 && cert->altNamesSz) {
3455 der->extensionsSz = SetExtensions(der->extensions, cert->altNames,
3457 if (der->extensionsSz == 0)
3458 return EXTENSIONS_E;
3462 der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
3463 der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
3470 /* write DER encoded cert to buffer, size already checked */
3471 static int WriteCertBody(DerCert* der, byte* buffer)
3475 /* signed part header */
3476 idx = SetSequence(der->total, buffer);
3478 XMEMCPY(buffer + idx, der->version, der->versionSz);
3479 idx += der->versionSz;
3481 XMEMCPY(buffer + idx, der->serial, der->serialSz);
3482 idx += der->serialSz;
3484 XMEMCPY(buffer + idx, der->sigAlgo, der->sigAlgoSz);
3485 idx += der->sigAlgoSz;
3487 XMEMCPY(buffer + idx, der->issuer, der->issuerSz);
3488 idx += der->issuerSz;
3490 XMEMCPY(buffer + idx, der->validity, der->validitySz);
3491 idx += der->validitySz;
3493 XMEMCPY(buffer + idx, der->subject, der->subjectSz);
3494 idx += der->subjectSz;
3496 XMEMCPY(buffer + idx, der->publicKey, der->publicKeySz);
3497 idx += der->publicKeySz;
3498 if (der->extensionsSz) {
3500 XMEMCPY(buffer + idx, der->extensions, der->extensionsSz);
3501 idx += der->extensionsSz;
3508 /* Make RSA signature from buffer (sz), write to sig (sigSz) */
3509 static int MakeSignature(const byte* buffer, int sz, byte* sig, int sigSz,
3510 RsaKey* key, RNG* rng, int sigAlgoType)
3512 byte digest[SHA256_DIGEST_SIZE]; /* max size */
3513 byte encSig[MAX_ENCODED_DIG_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ];
3514 int encSigSz, digestSz, typeH;
3516 if (sigAlgoType == CTC_MD5wRSA) {
3519 Md5Update(&md5, buffer, sz);
3520 Md5Final(&md5, digest);
3521 digestSz = MD5_DIGEST_SIZE;
3524 else if (sigAlgoType == CTC_SHAwRSA) {
3527 ShaUpdate(&sha, buffer, sz);
3528 ShaFinal(&sha, digest);
3529 digestSz = SHA_DIGEST_SIZE;
3532 else if (sigAlgoType == CTC_SHA256wRSA) {
3534 InitSha256(&sha256);
3535 Sha256Update(&sha256, buffer, sz);
3536 Sha256Final(&sha256, digest);
3537 digestSz = SHA256_DIGEST_SIZE;
3544 encSigSz = EncodeSignature(encSig, digest, digestSz, typeH);
3545 return RsaSSL_Sign(encSig, encSigSz, sig, sigSz, key, rng);
3549 /* add signature to end of buffer, size of buffer assumed checked, return
3551 static int AddSignature(byte* buffer, int bodySz, const byte* sig, int sigSz,
3554 byte seq[MAX_SEQ_SZ];
3555 int idx = bodySz, seqSz;
3558 idx += SetAlgoID(sigAlgoType, buffer + idx, sigType);
3560 buffer[idx++] = ASN_BIT_STRING;
3562 idx += SetLength(sigSz + 1, buffer + idx);
3563 buffer[idx++] = 0; /* trailing 0 */
3565 XMEMCPY(buffer + idx, sig, sigSz);
3568 /* make room for overall header */
3569 seqSz = SetSequence(idx, seq);
3570 XMEMMOVE(buffer + seqSz, buffer, idx);
3571 XMEMCPY(buffer, seq, seqSz);
3577 /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
3578 static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
3579 RsaKey* rsaKey, RNG* rng, const byte* ntruKey, word16 ntruSz)
3584 cert->keyType = rsaKey ? RSA_KEY : NTRU_KEY;
3585 ret = EncodeCert(cert, &der, rsaKey, rng, ntruKey, ntruSz);
3589 if (der.total + MAX_SEQ_SZ * 2 > (int)derSz)
3592 return cert->bodySz = WriteCertBody(&der, derBuffer);
3596 /* Make an x509 Certificate v3 RSA from cert input, write to buffer */
3597 int MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,RNG* rng)
3599 return MakeAnyCert(cert, derBuffer, derSz, rsaKey, rng, NULL, 0);
3605 int MakeNtruCert(Cert* cert, byte* derBuffer, word32 derSz,
3606 const byte* ntruKey, word16 keySz, RNG* rng)
3608 return MakeAnyCert(cert, derBuffer, derSz, NULL, rng, ntruKey, keySz);
3611 #endif /* HAVE_NTRU */
3614 int SignCert(Cert* cert, byte* buffer, word32 buffSz, RsaKey* key, RNG* rng)
3616 byte sig[MAX_ENCODED_SIG_SZ];
3618 int bodySz = cert->bodySz;
3623 sigSz = MakeSignature(buffer, bodySz, sig, sizeof(sig), key, rng,
3628 if (bodySz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
3631 return AddSignature(buffer, bodySz, sig, sigSz, cert->sigType);
3635 int MakeSelfCert(Cert* cert, byte* buffer, word32 buffSz, RsaKey* key, RNG* rng)
3637 int ret = MakeCert(cert, buffer, buffSz, key, rng);
3642 return SignCert(cert, buffer, buffSz, key, rng);
3646 #ifdef CYASSL_ALT_NAMES
3648 /* Set Alt Names from der cert, return 0 on success */
3649 static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz)
3651 DecodedCert decoded;
3657 InitDecodedCert(&decoded, (byte*)der, derSz, 0);
3658 ret = ParseCertRelative(&decoded, CA_TYPE, NO_VERIFY, 0);
3661 FreeDecodedCert(&decoded);
3665 if (decoded.extensions) {
3668 word32 maxExtensionsIdx;
3670 decoded.srcIdx = decoded.extensionsIdx;
3671 b = decoded.source[decoded.srcIdx++];
3672 if (b != ASN_EXTENSIONS) {
3673 FreeDecodedCert(&decoded);
3677 if (GetLength(decoded.source, &decoded.srcIdx, &length,
3678 decoded.maxIdx) < 0) {
3679 FreeDecodedCert(&decoded);
3683 if (GetSequence(decoded.source, &decoded.srcIdx, &length,
3684 decoded.maxIdx) < 0) {
3685 FreeDecodedCert(&decoded);
3689 maxExtensionsIdx = decoded.srcIdx + length;
3691 while (decoded.srcIdx < maxExtensionsIdx) {
3693 word32 startIdx = decoded.srcIdx;
3696 if (GetSequence(decoded.source, &decoded.srcIdx, &length,
3697 decoded.maxIdx) < 0) {
3698 FreeDecodedCert(&decoded);
3702 tmpIdx = decoded.srcIdx;
3703 decoded.srcIdx = startIdx;
3705 if (GetAlgoId(decoded.source, &decoded.srcIdx, &oid,
3706 decoded.maxIdx) < 0) {
3707 FreeDecodedCert(&decoded);
3711 if (oid == ALT_NAMES_OID) {
3712 cert->altNamesSz = length + (tmpIdx - startIdx);
3714 if (cert->altNamesSz < (int)sizeof(cert->altNames))
3715 XMEMCPY(cert->altNames, &decoded.source[startIdx],
3718 cert->altNamesSz = 0;
3719 CYASSL_MSG("AltNames extensions too big");
3720 FreeDecodedCert(&decoded);
3724 decoded.srcIdx = tmpIdx + length;
3727 FreeDecodedCert(&decoded);
3733 /* Set Dates from der cert, return 0 on success */
3734 static int SetDatesFromCert(Cert* cert, const byte* der, int derSz)
3736 DecodedCert decoded;
3739 CYASSL_ENTER("SetDatesFromCert");
3743 InitDecodedCert(&decoded, (byte*)der, derSz, 0);
3744 ret = ParseCertRelative(&decoded, CA_TYPE, NO_VERIFY, 0);
3747 CYASSL_MSG("ParseCertRelative error");
3748 FreeDecodedCert(&decoded);
3752 if (decoded.beforeDate == NULL || decoded.afterDate == NULL) {
3753 CYASSL_MSG("Couldn't extract dates");
3754 FreeDecodedCert(&decoded);
3758 if (decoded.beforeDateLen > MAX_DATE_SIZE || decoded.afterDateLen >
3760 CYASSL_MSG("Bad date size");
3761 FreeDecodedCert(&decoded);
3765 XMEMCPY(cert->beforeDate, decoded.beforeDate, decoded.beforeDateLen);
3766 XMEMCPY(cert->afterDate, decoded.afterDate, decoded.afterDateLen);
3768 cert->beforeDateSz = decoded.beforeDateLen;
3769 cert->afterDateSz = decoded.afterDateLen;
3775 #endif /* CYASSL_ALT_NAMES */
3778 /* Set cn name from der buffer, return 0 on success */
3779 static int SetNameFromCert(CertName* cn, const byte* der, int derSz)
3781 DecodedCert decoded;
3788 InitDecodedCert(&decoded, (byte*)der, derSz, 0);
3789 ret = ParseCertRelative(&decoded, CA_TYPE, NO_VERIFY, 0);
3794 if (decoded.subjectCN) {
3795 sz = (decoded.subjectCNLen < CTC_NAME_SIZE) ? decoded.subjectCNLen :
3797 strncpy(cn->commonName, decoded.subjectCN, CTC_NAME_SIZE);
3798 cn->commonName[sz] = 0;
3800 if (decoded.subjectC) {
3801 sz = (decoded.subjectCLen < CTC_NAME_SIZE) ? decoded.subjectCLen :
3803 strncpy(cn->country, decoded.subjectC, CTC_NAME_SIZE);
3804 cn->country[sz] = 0;
3806 if (decoded.subjectST) {
3807 sz = (decoded.subjectSTLen < CTC_NAME_SIZE) ? decoded.subjectSTLen :
3809 strncpy(cn->state, decoded.subjectST, CTC_NAME_SIZE);
3812 if (decoded.subjectL) {
3813 sz = (decoded.subjectLLen < CTC_NAME_SIZE) ? decoded.subjectLLen :
3815 strncpy(cn->locality, decoded.subjectL, CTC_NAME_SIZE);
3816 cn->locality[sz] = 0;
3818 if (decoded.subjectO) {
3819 sz = (decoded.subjectOLen < CTC_NAME_SIZE) ? decoded.subjectOLen :
3821 strncpy(cn->org, decoded.subjectO, CTC_NAME_SIZE);
3824 if (decoded.subjectOU) {
3825 sz = (decoded.subjectOULen < CTC_NAME_SIZE) ? decoded.subjectOULen :
3827 strncpy(cn->unit, decoded.subjectOU, CTC_NAME_SIZE);
3830 if (decoded.subjectSN) {
3831 sz = (decoded.subjectSNLen < CTC_NAME_SIZE) ? decoded.subjectSNLen :
3833 strncpy(cn->sur, decoded.subjectSN, CTC_NAME_SIZE);
3836 if (decoded.subjectEmail) {
3837 sz = (decoded.subjectEmailLen < CTC_NAME_SIZE) ?
3838 decoded.subjectEmailLen : CTC_NAME_SIZE - 1;
3839 strncpy(cn->email, decoded.subjectEmail, CTC_NAME_SIZE);
3843 FreeDecodedCert(&decoded);
3849 #ifndef NO_FILESYSTEM
3851 /* forward from CyaSSL */
3852 int CyaSSL_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz);
3854 /* Set cert issuer from issuerFile in PEM */
3855 int SetIssuer(Cert* cert, const char* issuerFile)
3858 int derSz = CyaSSL_PemCertToDer(issuerFile, der, sizeof(der));
3860 cert->selfSigned = 0;
3861 return SetNameFromCert(&cert->issuer, der, derSz);
3865 /* Set cert subject from subjectFile in PEM */
3866 int SetSubject(Cert* cert, const char* subjectFile)
3869 int derSz = CyaSSL_PemCertToDer(subjectFile, der, sizeof(der));
3871 return SetNameFromCert(&cert->subject, der, derSz);
3875 #ifdef CYASSL_ALT_NAMES
3877 /* Set atl names from file in PEM */
3878 int SetAltNames(Cert* cert, const char* file)
3881 int derSz = CyaSSL_PemCertToDer(file, der, sizeof(der));
3883 return SetAltNamesFromCert(cert, der, derSz);
3886 #endif /* CYASSL_ALT_NAMES */
3888 #endif /* NO_FILESYSTEM */
3890 /* Set cert issuer from DER buffer */
3891 int SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
3893 cert->selfSigned = 0;
3894 return SetNameFromCert(&cert->issuer, der, derSz);
3898 /* Set cert subject from DER buffer */
3899 int SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
3901 return SetNameFromCert(&cert->subject, der, derSz);
3905 #ifdef CYASSL_ALT_NAMES
3907 /* Set cert alt names from DER buffer */
3908 int SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
3910 return SetAltNamesFromCert(cert, der, derSz);
3913 /* Set cert dates from DER buffer */
3914 int SetDatesBuffer(Cert* cert, const byte* der, int derSz)
3916 return SetDatesFromCert(cert, der, derSz);
3919 #endif /* CYASSL_ALT_NAMES */
3921 #endif /* CYASSL_CERT_GEN */
3926 /* Der Encode r & s ints into out, outLen is (in/out) size */
3927 int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
3930 word32 rSz; /* encoding size */
3932 word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
3934 int rLen = mp_unsigned_bin_size(r); /* big int size */
3935 int sLen = mp_unsigned_bin_size(s);
3938 if (*outLen < (rLen + sLen + headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
3939 return BAD_FUNC_ARG;
3941 idx = SetSequence(rLen + sLen + headerSz, out);
3944 out[idx++] = ASN_INTEGER;
3945 rSz = SetLength(rLen, &out[idx]);
3947 err = mp_to_unsigned_bin(r, &out[idx]);
3948 if (err != MP_OKAY) return err;
3952 out[idx++] = ASN_INTEGER;
3953 sSz = SetLength(sLen, &out[idx]);
3955 err = mp_to_unsigned_bin(s, &out[idx]);
3956 if (err != MP_OKAY) return err;
3965 /* Der Decode ECC-DSA Signautre, r & s stored as big ints */
3966 int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
3971 if (GetSequence(sig, &idx, &len, sigLen) < 0)
3972 return ASN_ECC_KEY_E;
3974 if ((word32)len > (sigLen - idx))
3975 return ASN_ECC_KEY_E;
3977 if (GetInt(r, sig, &idx, sigLen) < 0)
3978 return ASN_ECC_KEY_E;
3980 if (GetInt(s, sig, &idx, sigLen) < 0)
3981 return ASN_ECC_KEY_E;
3987 int EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
3991 int version, length;
3994 byte priv[ECC_MAXSIZE];
3995 byte pub[ECC_MAXSIZE * 2 + 1]; /* public key has two parts plus header */
3997 if (GetSequence(input, inOutIdx, &length, inSz) < 0)
4000 if (GetMyVersion(input, inOutIdx, &version) < 0)
4003 b = input[*inOutIdx];
4007 if (b != 4 && b != 6 && b != 7)
4010 if (GetLength(input, inOutIdx, &length, inSz) < 0)
4015 XMEMCPY(priv, &input[*inOutIdx], privSz);
4016 *inOutIdx += length;
4018 /* prefix 0, may have */
4019 b = input[*inOutIdx];
4020 if (b == ECC_PREFIX_0) {
4023 if (GetLength(input, inOutIdx, &length, inSz) < 0)
4027 b = input[*inOutIdx];
4030 if (b != ASN_OBJECT_ID)
4031 return ASN_OBJECT_ID_E;
4033 if (GetLength(input, inOutIdx, &length, inSz) < 0)
4037 oid += input[*inOutIdx];
4040 if (CheckCurve(oid) < 0)
4041 return ECC_CURVE_OID_E;
4045 b = input[*inOutIdx];
4047 if (b != ECC_PREFIX_1)
4048 return ASN_ECC_KEY_E;
4050 if (GetLength(input, inOutIdx, &length, inSz) < 0)
4054 b = input[*inOutIdx];
4056 if (b != ASN_BIT_STRING)
4057 return ASN_BITSTR_E;
4059 if (GetLength(input, inOutIdx, &length, inSz) < 0)
4061 b = input[*inOutIdx];
4064 return ASN_EXPECT_0_E;
4066 pubSz = length - 1; /* null prefix */
4067 XMEMCPY(pub, &input[*inOutIdx], pubSz);
4069 *inOutIdx += length;
4071 return ecc_import_private_key(priv, privSz, pub, pubSz, key);
4074 #endif /* HAVE_ECC */
4079 static int GetEnumerated(const byte* input, word32* inOutIdx, int *value)
4081 word32 idx = *inOutIdx;
4086 if (input[idx++] != ASN_ENUMERATED)
4094 *value = *value << 8 | input[idx++];
4103 static int DecodeSingleResponse(byte* source,
4104 word32* ioIndex, OcspResponse* resp, word32 size)
4106 word32 index = *ioIndex, prevIndex, oid, mpi_len;
4107 int length, remainder, qty = 0;
4109 byte serialTmp[EXTERNAL_SERIAL_SIZE];
4111 /* Outer wrapper of the SEQUENCE OF Single Responses. */
4112 if (GetSequence(source, &index, &length, size) < 0)
4116 /* First Single Response */
4117 while (remainder != 0 && qty < STATUS_LIST_SIZE)
4120 /* Wrapper around the Single Response */
4121 if (GetSequence(source, &index, &length, size) < 0)
4124 /* Wrapper around the CertID */
4125 if (GetSequence(source, &index, &length, size) < 0)
4127 /* Skip the hash algorithm */
4128 if (GetAlgoId(source, &index, &oid, size) < 0)
4130 /* Skip the hash of CN */
4131 if (source[index++] != ASN_OCTET_STRING)
4133 if (GetLength(source, &index, &length, size) < 0)
4136 /* Skip the hash of the issuer public key */
4137 if (source[index++] != ASN_OCTET_STRING)
4139 if (GetLength(source, &index, &length, size) < 0)
4143 /* Read the serial number */
4144 if (GetInt(&mpi, source, &index, size) < 0)
4146 mpi_len = mp_unsigned_bin_size(&mpi);
4147 if (mpi_len < (int)sizeof(serialTmp)) {
4148 if (mp_to_unsigned_bin(&mpi, serialTmp) == MP_OKAY) {
4149 if (mpi_len > EXTERNAL_SERIAL_SIZE)
4150 mpi_len = EXTERNAL_SERIAL_SIZE;
4151 XMEMCPY(resp->certSN[qty], serialTmp, mpi_len);
4152 resp->certSNsz[qty] = mpi_len;
4158 switch (source[index++])
4160 case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
4161 resp->certStatus[qty] = CERT_GOOD;
4164 case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
4165 resp->certStatus[qty] = CERT_REVOKED;
4166 GetLength(source, &index, &length, size);
4169 case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_UNKNOWN):
4170 resp->certStatus[qty] = CERT_UNKNOWN;
4177 if (source[index++] != ASN_GENERALIZED_TIME)
4180 if (GetLength(source, &index, &length, size) < 0)
4184 remainder = remainder + prevIndex - index;
4187 resp->certStatusCount = qty;
4194 static int DecodeResponseData(byte* source,
4195 word32* ioIndex, OcspResponse* resp, word32 size)
4197 word32 index = *ioIndex;
4200 word32 responderId = 0;
4202 if (GetSequence(source, &index, &length, size) < 0)
4204 resp->respBegin = index;
4205 resp->respLength = length;
4207 /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
4208 * item isn't an EXPLICIT[0], then set version to zero and move
4209 * onto the next item.
4211 if (source[index] == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
4213 index += 2; /* Eat the value and length */
4214 if (GetMyVersion(source, &index, &version) < 0)
4219 responderId = source[index++];
4220 if ((responderId == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) ||
4221 (responderId == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)))
4223 if (GetLength(source, &index, &length, size) < 0)
4230 /* Skip GeneralizedTime */
4231 if (source[index++] != ASN_GENERALIZED_TIME)
4233 if (GetLength(source, &index, &length, size) < 0)
4237 if (DecodeSingleResponse(source, &index, resp, size) < 0)
4240 /* Skip the extensions */
4241 if (source[index++] == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
4243 if (GetLength(source, &index, &length, size) < 0)
4252 static int DecodeCerts(byte* source,
4253 word32* ioIndex, OcspResponse* resp, word32 size)
4255 word32 index = *ioIndex;
4256 if (source[index++] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
4260 if (GetLength(source, &index, &length, size) < 0)
4268 static int DecodeBasicOcspResponse(byte* source,
4269 word32* ioIndex, OcspResponse* resp, word32 size)
4272 word32 index = *ioIndex;
4275 if (GetSequence(source, &index, &length, size) < 0)
4278 if (index + length > size)
4280 end_index = index + length;
4282 if (DecodeResponseData(source, &index, resp, size) < 0)
4285 /* Get the signature algorithm */
4286 if (GetAlgoId(source, &index, &resp->sigOID, size) < 0)
4289 /* Obtain pointer to the start of the signature, and save the size */
4290 if (source[index++] == ASN_BIT_STRING)
4293 if (GetLength(source, &index, &sigLength, size) < 0)
4295 resp->sigLength = sigLength;
4296 resp->sigIndex = index;
4301 * Check the length of the BasicOcspResponse against the current index to
4302 * see if there are certificates, they are optional.
4304 if (index < end_index)
4305 return DecodeCerts(source, &index, resp, size);
4312 void InitOcspResponse(OcspResponse* resp, byte* source, word32 inSz, void* heap)
4314 XMEMSET(resp, 0, sizeof(*resp));
4315 resp->source = source;
4316 resp->maxIdx = inSz;
4321 void FreeOcspResponse(OcspResponse* resp) {}
4324 int OcspResponseDecode(OcspResponse* resp)
4328 byte* source = resp->source;
4329 word32 size = resp->maxIdx;
4332 /* peel the outer SEQUENCE wrapper */
4333 if (GetSequence(source, &index, &length, size) < 0)
4336 /* First get the responseStatus, an ENUMERATED */
4337 if (GetEnumerated(source, &index, &resp->responseStatus) < 0)
4340 if (resp->responseStatus != OCSP_SUCCESSFUL)
4343 /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
4346 if (source[index++] != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
4348 if (GetLength(source, &index, &length, size) < 0)
4351 /* Get the responseBytes SEQUENCE */
4352 if (GetSequence(source, &index, &length, size) < 0)
4355 /* Check ObjectID for the resposeBytes */
4356 if (GetObjectId(source, &index, &oid, size) < 0)
4358 if (oid != OCSP_BASIC_OID)
4360 if (source[index++] != ASN_OCTET_STRING)
4363 if (GetLength(source, &index, &length, size) < 0)
4366 if (DecodeBasicOcspResponse(source, &index, resp, size) < 0)
4373 static int SetSerialNumber(const byte* sn, word32 snSz, byte* output)
4377 if (snSz <= EXTERNAL_SERIAL_SIZE) {
4378 output[0] = ASN_INTEGER;
4379 output[1] = snSz + 1;
4381 XMEMCPY(&output[3], sn, snSz);
4388 int EncodeOcspRequest(DecodedCert* cert, byte* output, word32 outputSz)
4390 byte seqArray[5][MAX_SEQ_SZ];
4391 /* The ASN.1 of the OCSP Request is an onion of sequences */
4392 byte algoArray[MAX_ALGO_SZ];
4393 byte issuerArray[MAX_ENCODED_DIG_SZ];
4394 byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
4395 byte snArray[MAX_SN_SZ];
4397 word32 seqSz[5], algoSz, issuerSz, issuerKeySz, snSz, totalSz;
4400 algoSz = SetAlgoID(SHAh, algoArray, hashType);
4401 issuerSz = SetDigest(cert->issuerHash, SHA_SIZE, issuerArray);
4402 issuerKeySz = SetDigest(cert->issuerKeyHash, SHA_SIZE, issuerKeyArray);
4403 snSz = SetSerialNumber(cert->serial, cert->serialSz, snArray);
4405 totalSz = algoSz + issuerSz + issuerKeySz + snSz;
4407 for (i = 4; i >= 0; i--) {
4408 seqSz[i] = SetSequence(totalSz, seqArray[i]);
4409 totalSz += seqSz[i];
4412 for (i = 0; i < 5; i++) {
4413 XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
4414 totalSz += seqSz[i];
4416 XMEMCPY(output + totalSz, algoArray, algoSz);
4418 XMEMCPY(output + totalSz, issuerArray, issuerSz);
4419 totalSz += issuerSz;
4420 XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
4421 totalSz += issuerKeySz;
4422 XMEMCPY(output + totalSz, snArray, snSz);
4433 /* initialize decoded CRL */
4434 void InitDecodedCRL(DecodedCRL* dcrl)
4436 CYASSL_MSG("InitDecodedCRL");
4438 dcrl->certBegin = 0;
4440 dcrl->sigLength = 0;
4441 dcrl->signatureOID = 0;
4443 dcrl->totalCerts = 0;
4447 /* free decoded CRL resources */
4448 void FreeDecodedCRL(DecodedCRL* dcrl)
4450 RevokedCert* tmp = dcrl->certs;
4452 CYASSL_MSG("FreeDecodedCRL");
4455 RevokedCert* next = tmp->next;
4456 XFREE(tmp, NULL, DYNAMIC_TYPE_REVOKED);
4462 /* store SHA1 hash of NAME */
4463 static int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx)
4466 int length; /* length of all distinguished names */
4468 CYASSL_ENTER("GetNameHash");
4470 if (source[*idx] == ASN_OBJECT_ID) {
4471 CYASSL_MSG("Trying optional prefix...");
4473 if (GetLength(source, idx, &length, maxIdx) < 0)
4477 CYASSL_MSG("Got optional prefix");
4480 if (GetSequence(source, idx, &length, maxIdx) < 0)
4484 ShaUpdate(&sha, &source[*idx], length);
4485 ShaFinal(&sha, hash);
4493 /* Get raw Date only, no processing, 0 on success */
4494 static int GetBasicDate(const byte* source, word32* idx, byte* date, int maxIdx)
4497 byte b = source[*idx];
4499 CYASSL_ENTER("GetBasicDate");
4502 if (b != ASN_UTC_TIME && b != ASN_GENERALIZED_TIME)
4505 if (GetLength(source, idx, &length, maxIdx) < 0)
4508 if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
4509 return ASN_DATE_SZ_E;
4511 XMEMCPY(date, &source[*idx], length);
4518 /* Get Revoked Cert list, 0 on success */
4519 static int GetRevoked(const byte* buff, word32* idx, DecodedCRL* dcrl,
4527 CYASSL_ENTER("GetRevoked");
4529 if (GetSequence(buff, idx, &len, maxIdx) < 0)
4534 /* get serial number */
4538 if (b != ASN_INTEGER) {
4539 CYASSL_MSG("Expecting Integer");
4543 if (GetLength(buff, idx, &len, maxIdx) < 0)
4546 if (len > EXTERNAL_SERIAL_SIZE) {
4547 CYASSL_MSG("Serial Size too big");
4551 rc = XMALLOC(sizeof(RevokedCert), NULL, DYNAMIC_TYPE_CRL);
4553 CYASSL_MSG("Alloc Revoked Cert failed");
4557 XMEMCPY(rc->serialNumber, &buff[*idx], len);
4561 rc->next = dcrl->certs;
4571 if (b != ASN_UTC_TIME && b != ASN_GENERALIZED_TIME) {
4572 CYASSL_MSG("Expecting Date");
4576 if (GetLength(buff, idx, &len, maxIdx) < 0)
4582 if (*idx != end) /* skip extensions */
4589 /* Get CRL Signature, 0 on success */
4590 static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
4596 CYASSL_ENTER("GetCRL_Signature");
4600 if (b != ASN_BIT_STRING)
4601 return ASN_BITSTR_E;
4603 if (GetLength(source, idx, &length, maxIdx) < 0)
4606 dcrl->sigLength = length;
4611 return ASN_EXPECT_0_E;
4614 dcrl->signature = (byte*)&source[*idx];
4616 *idx += dcrl->sigLength;
4622 /* prase crl buffer into decoded state, 0 on success */
4623 int ParseCRL(DecodedCRL* dcrl, const byte* buff, long sz)
4626 word32 oid, idx = 0;
4629 CYASSL_MSG("ParseCRL");
4633 Md5Update(&md5, buff, sz);
4634 Md5Final(&md5, dcrl->crlHash);
4636 if (GetSequence(buff, &idx, &len, sz) < 0)
4639 dcrl->certBegin = idx;
4641 if (GetSequence(buff, &idx, &len, sz) < 0)
4643 dcrl->sigIndex = len + idx;
4645 /* may have version */
4646 if (buff[idx] == ASN_INTEGER) {
4647 if (GetMyVersion(buff, &idx, &version) < 0)
4651 if (GetAlgoId(buff, &idx, &oid, sz) < 0)
4654 if (GetNameHash(buff, &idx, dcrl->issuerHash, sz) < 0)
4657 if (GetBasicDate(buff, &idx, dcrl->lastDate, sz) < 0)
4660 if (GetBasicDate(buff, &idx, dcrl->nextDate, sz) < 0)
4663 if (idx != dcrl->sigIndex && buff[idx] != CRL_EXTENSIONS) {
4664 if (GetSequence(buff, &idx, &len, sz) < 0)
4669 while (idx < (word32)len) {
4670 if (GetRevoked(buff, &idx, dcrl, sz) < 0)
4675 if (idx != dcrl->sigIndex)
4676 idx = dcrl->sigIndex; /* skip extensions */
4678 if (GetAlgoId(buff, &idx, &dcrl->signatureOID, sz) < 0)
4681 if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
4687 #endif /* HAVE_CRL */