PageRenderTime 69ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/ctaocrypt/src/asn.c

https://github.com/andersmalm/cyassl
C | 5110 lines | 3782 code | 1041 blank | 287 comment | 881 complexity | 7ce215fd4d2dff86b6113ab1abcbab72 MD5 | raw file
Possible License(s): GPL-2.0
  1. /* asn.c
  2. *
  3. * Copyright (C) 2006-2012 Sawtooth Consulting Ltd.
  4. *
  5. * This file is part of CyaSSL.
  6. *
  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.
  11. *
  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.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
  20. */
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #ifndef NO_ASN
  25. #ifdef THREADX
  26. #include "os.h" /* dc_rtc_api needs */
  27. #include "dc_rtc_api.h" /* to get current time */
  28. #endif
  29. #include <cyassl/ctaocrypt/integer.h>
  30. #include <cyassl/ctaocrypt/asn.h>
  31. #include <cyassl/ctaocrypt/coding.h>
  32. #include <cyassl/ctaocrypt/sha.h>
  33. #include <cyassl/ctaocrypt/md5.h>
  34. #include <cyassl/ctaocrypt/md2.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>
  41. #include <cyassl/ctaocrypt/random.h>
  42. #ifndef NO_RC4
  43. #include <cyassl/ctaocrypt/arc4.h>
  44. #endif
  45. #ifdef HAVE_NTRU
  46. #include "crypto_ntru.h"
  47. #endif
  48. #ifdef HAVE_ECC
  49. #include <cyassl/ctaocrypt/ecc.h>
  50. #endif
  51. #ifdef CYASSL_DEBUG_ENCODING
  52. #ifdef FREESCALE_MQX
  53. #include <fio.h>
  54. #else
  55. #include <stdio.h>
  56. #endif
  57. #endif
  58. #ifdef _MSC_VER
  59. /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
  60. #pragma warning(disable: 4996)
  61. #endif
  62. #ifndef TRUE
  63. enum {
  64. FALSE = 0,
  65. TRUE = 1
  66. };
  67. #endif
  68. #ifdef THREADX
  69. /* uses parital <time.h> structures */
  70. #define XTIME(tl) (0)
  71. #define XGMTIME(c) my_gmtime((c))
  72. #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
  73. #elif defined(MICRIUM)
  74. #if (NET_SECURE_MGR_CFG_EN == DEF_ENABLED)
  75. #define XVALIDATE_DATE(d,f,t) NetSecure_ValidateDateHandler((d),(f),(t))
  76. #else
  77. #define XVALIDATE_DATE(d, f, t) (0)
  78. #endif
  79. #define NO_TIME_H
  80. /* since Micrium not defining XTIME or XGMTIME, CERT_GEN not available */
  81. #elif defined(USER_TIME)
  82. /* no <time.h> structures used */
  83. #define NO_TIME_H
  84. /* user time, and gmtime compatible functions, there is a gmtime
  85. implementation here that WINCE uses, so really just need some ticks
  86. since the EPOCH
  87. */
  88. #else
  89. /* default */
  90. /* uses complete <time.h> facility */
  91. #include <time.h>
  92. #define XTIME(tl) time((tl))
  93. #define XGMTIME(c) gmtime((c))
  94. #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
  95. #endif
  96. #ifdef _WIN32_WCE
  97. /* no time() or gmtime() even though in time.h header?? */
  98. #include <windows.h>
  99. time_t time(time_t* timer)
  100. {
  101. SYSTEMTIME sysTime;
  102. FILETIME fTime;
  103. ULARGE_INTEGER intTime;
  104. time_t localTime;
  105. if (timer == NULL)
  106. timer = &localTime;
  107. GetSystemTime(&sysTime);
  108. SystemTimeToFileTime(&sysTime, &fTime);
  109. XMEMCPY(&intTime, &fTime, sizeof(FILETIME));
  110. /* subtract EPOCH */
  111. intTime.QuadPart -= 0x19db1ded53e8000;
  112. /* to secs */
  113. intTime.QuadPart /= 10000000;
  114. *timer = (time_t)intTime.QuadPart;
  115. return *timer;
  116. }
  117. struct tm* gmtime(const time_t* timer)
  118. {
  119. #define YEAR0 1900
  120. #define EPOCH_YEAR 1970
  121. #define SECS_DAY (24L * 60L * 60L)
  122. #define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) %400)))
  123. #define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365)
  124. static const int _ytab[2][12] =
  125. {
  126. {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
  127. {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
  128. };
  129. static struct tm st_time;
  130. struct tm* ret = &st_time;
  131. time_t time = *timer;
  132. unsigned long dayclock, dayno;
  133. int year = EPOCH_YEAR;
  134. dayclock = (unsigned long)time % SECS_DAY;
  135. dayno = (unsigned long)time / SECS_DAY;
  136. ret->tm_sec = dayclock % 60;
  137. ret->tm_min = (dayclock % 3600) / 60;
  138. ret->tm_hour = dayclock / 3600;
  139. ret->tm_wday = (dayno + 4) % 7; /* day 0 a Thursday */
  140. while(dayno >= (unsigned long)YEARSIZE(year)) {
  141. dayno -= YEARSIZE(year);
  142. year++;
  143. }
  144. ret->tm_year = year - YEAR0;
  145. ret->tm_yday = dayno;
  146. ret->tm_mon = 0;
  147. while(dayno >= (unsigned long)_ytab[LEAPYEAR(year)][ret->tm_mon]) {
  148. dayno -= _ytab[LEAPYEAR(year)][ret->tm_mon];
  149. ret->tm_mon++;
  150. }
  151. ret->tm_mday = ++dayno;
  152. ret->tm_isdst = 0;
  153. return ret;
  154. }
  155. #endif /* _WIN32_WCE */
  156. #ifdef THREADX
  157. #define YEAR0 1900
  158. struct tm* my_gmtime(const time_t* timer) /* has a gmtime() but hangs */
  159. {
  160. static struct tm st_time;
  161. struct tm* ret = &st_time;
  162. DC_RTC_CALENDAR cal;
  163. dc_rtc_time_get(&cal, TRUE);
  164. ret->tm_year = cal.year - YEAR0; /* gm starts at 1900 */
  165. ret->tm_mon = cal.month - 1; /* gm starts at 0 */
  166. ret->tm_mday = cal.day;
  167. ret->tm_hour = cal.hour;
  168. ret->tm_min = cal.minute;
  169. ret->tm_sec = cal.second;
  170. return ret;
  171. }
  172. #endif /* THREADX */
  173. static INLINE word32 btoi(byte b)
  174. {
  175. return b - 0x30;
  176. }
  177. /* two byte date/time, add to value */
  178. static INLINE void GetTime(int* value, const byte* date, int* idx)
  179. {
  180. int i = *idx;
  181. *value += btoi(date[i++]) * 10;
  182. *value += btoi(date[i++]);
  183. *idx = i;
  184. }
  185. #if defined(MICRIUM)
  186. CPU_INT32S NetSecure_ValidateDateHandler(CPU_INT08U *date, CPU_INT08U format,
  187. CPU_INT08U dateType)
  188. {
  189. CPU_BOOLEAN rtn_code;
  190. CPU_INT32S i;
  191. CPU_INT32S val;
  192. CPU_INT16U year;
  193. CPU_INT08U month;
  194. CPU_INT16U day;
  195. CPU_INT08U hour;
  196. CPU_INT08U min;
  197. CPU_INT08U sec;
  198. i = 0;
  199. year = 0u;
  200. if (format == ASN_UTC_TIME) {
  201. if (btoi(date[0]) >= 5)
  202. year = 1900;
  203. else
  204. year = 2000;
  205. }
  206. else { /* format == GENERALIZED_TIME */
  207. year += btoi(date[i++]) * 1000;
  208. year += btoi(date[i++]) * 100;
  209. }
  210. val = year;
  211. GetTime(&val, date, &i);
  212. year = (CPU_INT16U)val;
  213. val = 0;
  214. GetTime(&val, date, &i);
  215. month = (CPU_INT08U)val;
  216. val = 0;
  217. GetTime(&val, date, &i);
  218. day = (CPU_INT16U)val;
  219. val = 0;
  220. GetTime(&val, date, &i);
  221. hour = (CPU_INT08U)val;
  222. val = 0;
  223. GetTime(&val, date, &i);
  224. min = (CPU_INT08U)val;
  225. val = 0;
  226. GetTime(&val, date, &i);
  227. sec = (CPU_INT08U)val;
  228. return NetSecure_ValidateDate(year, month, day, hour, min, sec, dateType);
  229. }
  230. #endif /* MICRIUM */
  231. static int GetLength(const byte* input, word32* inOutIdx, int* len,
  232. word32 maxIdx)
  233. {
  234. int length = 0;
  235. word32 i = *inOutIdx;
  236. byte b;
  237. if ( (i+1) > maxIdx) { /* for first read */
  238. CYASSL_MSG("GetLength bad index on input");
  239. return BUFFER_E;
  240. }
  241. b = input[i++];
  242. if (b >= ASN_LONG_LENGTH) {
  243. word32 bytes = b & 0x7F;
  244. if ( (i+bytes) > maxIdx) { /* for reading bytes */
  245. CYASSL_MSG("GetLength bad long length");
  246. return BUFFER_E;
  247. }
  248. while (bytes--) {
  249. b = input[i++];
  250. length = (length << 8) | b;
  251. }
  252. }
  253. else
  254. length = b;
  255. if ( (i+length) > maxIdx) { /* for user of length */
  256. CYASSL_MSG("GetLength value exceeds buffer length");
  257. return BUFFER_E;
  258. }
  259. *inOutIdx = i;
  260. *len = length;
  261. return length;
  262. }
  263. static int GetSequence(const byte* input, word32* inOutIdx, int* len,
  264. word32 maxIdx)
  265. {
  266. int length = -1;
  267. word32 idx = *inOutIdx;
  268. if (input[idx++] != (ASN_SEQUENCE | ASN_CONSTRUCTED) ||
  269. GetLength(input, &idx, &length, maxIdx) < 0)
  270. return ASN_PARSE_E;
  271. *len = length;
  272. *inOutIdx = idx;
  273. return length;
  274. }
  275. static int GetSet(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  276. {
  277. int length = -1;
  278. word32 idx = *inOutIdx;
  279. if (input[idx++] != (ASN_SET | ASN_CONSTRUCTED) ||
  280. GetLength(input, &idx, &length, maxIdx) < 0)
  281. return ASN_PARSE_E;
  282. *len = length;
  283. *inOutIdx = idx;
  284. return length;
  285. }
  286. /* winodws header clash for WinCE using GetVersion */
  287. static int GetMyVersion(const byte* input, word32* inOutIdx, int* version)
  288. {
  289. word32 idx = *inOutIdx;
  290. CYASSL_ENTER("GetMyVersion");
  291. if (input[idx++] != ASN_INTEGER)
  292. return ASN_PARSE_E;
  293. if (input[idx++] != 0x01)
  294. return ASN_VERSION_E;
  295. *version = input[idx++];
  296. *inOutIdx = idx;
  297. return *version;
  298. }
  299. /* Get small count integer, 32 bits or less */
  300. static int GetShortInt(const byte* input, word32* inOutIdx, int* number)
  301. {
  302. word32 idx = *inOutIdx;
  303. word32 len;
  304. *number = 0;
  305. if (input[idx++] != ASN_INTEGER)
  306. return ASN_PARSE_E;
  307. len = input[idx++];
  308. if (len > 4)
  309. return ASN_PARSE_E;
  310. while (len--) {
  311. *number = *number << 8 | input[idx++];
  312. }
  313. *inOutIdx = idx;
  314. return *number;
  315. }
  316. /* May not have one, not an error */
  317. static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version)
  318. {
  319. word32 idx = *inOutIdx;
  320. CYASSL_ENTER("GetExplicitVersion");
  321. if (input[idx++] == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  322. *inOutIdx = ++idx; /* eat header */
  323. return GetMyVersion(input, inOutIdx, version);
  324. }
  325. /* go back as is */
  326. *version = 0;
  327. return 0;
  328. }
  329. static int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx,
  330. word32 maxIdx)
  331. {
  332. word32 i = *inOutIdx;
  333. byte b = input[i++];
  334. int length;
  335. if (b != ASN_INTEGER)
  336. return ASN_PARSE_E;
  337. if (GetLength(input, &i, &length, maxIdx) < 0)
  338. return ASN_PARSE_E;
  339. if ( (b = input[i++]) == 0x00)
  340. length--;
  341. else
  342. i--;
  343. if (mp_init(mpi) != MP_OKAY)
  344. return MP_INIT_E;
  345. if (mp_read_unsigned_bin(mpi, (byte*)input + i, length) != 0) {
  346. mp_clear(mpi);
  347. return ASN_GETINT_E;
  348. }
  349. *inOutIdx = i + length;
  350. return 0;
  351. }
  352. static int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
  353. word32 maxIdx)
  354. {
  355. int length;
  356. word32 i = *inOutIdx;
  357. byte b;
  358. *oid = 0;
  359. b = input[i++];
  360. if (b != ASN_OBJECT_ID)
  361. return ASN_OBJECT_ID_E;
  362. if (GetLength(input, &i, &length, maxIdx) < 0)
  363. return ASN_PARSE_E;
  364. while(length--)
  365. *oid += input[i++];
  366. /* just sum it up for now */
  367. *inOutIdx = i;
  368. return 0;
  369. }
  370. static int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
  371. word32 maxIdx)
  372. {
  373. int length;
  374. word32 i = *inOutIdx;
  375. byte b;
  376. *oid = 0;
  377. CYASSL_ENTER("GetAlgoId");
  378. if (GetSequence(input, &i, &length, maxIdx) < 0)
  379. return ASN_PARSE_E;
  380. b = input[i++];
  381. if (b != ASN_OBJECT_ID)
  382. return ASN_OBJECT_ID_E;
  383. if (GetLength(input, &i, &length, maxIdx) < 0)
  384. return ASN_PARSE_E;
  385. while(length--) {
  386. /* odd HC08 compiler behavior here when input[i++] */
  387. *oid += input[i];
  388. i++;
  389. }
  390. /* just sum it up for now */
  391. /* could have NULL tag and 0 terminator, but may not */
  392. b = input[i++];
  393. if (b == ASN_TAG_NULL) {
  394. b = input[i++];
  395. if (b != 0)
  396. return ASN_EXPECT_0_E;
  397. }
  398. else
  399. /* go back, didn't have it */
  400. i--;
  401. *inOutIdx = i;
  402. return 0;
  403. }
  404. #ifndef NO_RSA
  405. #ifdef HAVE_CAVIUM
  406. static int GetCaviumInt(byte** buff, word16* buffSz, const byte* input,
  407. word32* inOutIdx, word32 maxIdx, void* heap)
  408. {
  409. word32 i = *inOutIdx;
  410. byte b = input[i++];
  411. int length;
  412. if (b != ASN_INTEGER)
  413. return ASN_PARSE_E;
  414. if (GetLength(input, &i, &length, maxIdx) < 0)
  415. return ASN_PARSE_E;
  416. if ( (b = input[i++]) == 0x00)
  417. length--;
  418. else
  419. i--;
  420. *buffSz = (word16)length;
  421. *buff = XMALLOC(*buffSz, heap, DYNAMIC_TYPE_CAVIUM_RSA);
  422. if (*buff == NULL)
  423. return MEMORY_E;
  424. XMEMCPY(*buff, input + i, *buffSz);
  425. *inOutIdx = i + length;
  426. return 0;
  427. }
  428. static int CaviumRsaPrivateKeyDecode(const byte* input, word32* inOutIdx,
  429. RsaKey* key, word32 inSz)
  430. {
  431. int version, length;
  432. void* h = key->heap;
  433. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  434. return ASN_PARSE_E;
  435. if (GetMyVersion(input, inOutIdx, &version) < 0)
  436. return ASN_PARSE_E;
  437. key->type = RSA_PRIVATE;
  438. if (GetCaviumInt(&key->c_n, &key->c_nSz, input, inOutIdx, inSz, h) < 0 ||
  439. GetCaviumInt(&key->c_e, &key->c_eSz, input, inOutIdx, inSz, h) < 0 ||
  440. GetCaviumInt(&key->c_d, &key->c_dSz, input, inOutIdx, inSz, h) < 0 ||
  441. GetCaviumInt(&key->c_p, &key->c_pSz, input, inOutIdx, inSz, h) < 0 ||
  442. GetCaviumInt(&key->c_q, &key->c_qSz, input, inOutIdx, inSz, h) < 0 ||
  443. GetCaviumInt(&key->c_dP, &key->c_dP_Sz, input, inOutIdx, inSz, h) < 0 ||
  444. GetCaviumInt(&key->c_dQ, &key->c_dQ_Sz, input, inOutIdx, inSz, h) < 0 ||
  445. GetCaviumInt(&key->c_u, &key->c_uSz, input, inOutIdx, inSz, h) < 0 )
  446. return ASN_RSA_KEY_E;
  447. return 0;
  448. }
  449. #endif /* HAVE_CAVIUM */
  450. int RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  451. word32 inSz)
  452. {
  453. int version, length;
  454. #ifdef HAVE_CAVIUM
  455. if (key->magic == CYASSL_RSA_CAVIUM_MAGIC)
  456. return CaviumRsaPrivateKeyDecode(input, inOutIdx, key, inSz);
  457. #endif
  458. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  459. return ASN_PARSE_E;
  460. if (GetMyVersion(input, inOutIdx, &version) < 0)
  461. return ASN_PARSE_E;
  462. key->type = RSA_PRIVATE;
  463. if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
  464. GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
  465. GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
  466. GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  467. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  468. GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
  469. GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
  470. GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  471. return 0;
  472. }
  473. #endif /* NO_RSA */
  474. /* Remove PKCS8 header, move beginning of traditional to beginning of input */
  475. int ToTraditional(byte* input, word32 sz)
  476. {
  477. word32 inOutIdx = 0, oid;
  478. int version, length;
  479. if (GetSequence(input, &inOutIdx, &length, sz) < 0)
  480. return ASN_PARSE_E;
  481. if (GetMyVersion(input, &inOutIdx, &version) < 0)
  482. return ASN_PARSE_E;
  483. if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
  484. return ASN_PARSE_E;
  485. if (input[inOutIdx] == ASN_OBJECT_ID) {
  486. /* pkcs8 ecc uses slightly different format */
  487. inOutIdx++; /* past id */
  488. if (GetLength(input, &inOutIdx, &length, sz) < 0)
  489. return ASN_PARSE_E;
  490. inOutIdx += length; /* over sub id, key input will verify */
  491. }
  492. if (input[inOutIdx++] != ASN_OCTET_STRING)
  493. return ASN_PARSE_E;
  494. if (GetLength(input, &inOutIdx, &length, sz) < 0)
  495. return ASN_PARSE_E;
  496. XMEMMOVE(input, input + inOutIdx, length);
  497. return 0;
  498. }
  499. #ifndef NO_PWDBASED
  500. /* Check To see if PKCS version algo is supported, set id if it is return 0
  501. < 0 on error */
  502. static int CheckAlgo(int first, int second, int* id, int* version)
  503. {
  504. *id = ALGO_ID_E;
  505. *version = PKCS5; /* default */
  506. if (first == 1) {
  507. switch (second) {
  508. case 1:
  509. *id = PBE_SHA1_RC4_128;
  510. *version = PKCS12;
  511. return 0;
  512. case 3:
  513. *id = PBE_SHA1_DES3;
  514. *version = PKCS12;
  515. return 0;
  516. default:
  517. return ALGO_ID_E;
  518. }
  519. }
  520. if (first != PKCS5)
  521. return ASN_INPUT_E; /* VERSION ERROR */
  522. if (second == PBES2) {
  523. *version = PKCS5v2;
  524. return 0;
  525. }
  526. switch (second) {
  527. case 3: /* see RFC 2898 for ids */
  528. *id = PBE_MD5_DES;
  529. return 0;
  530. case 10:
  531. *id = PBE_SHA1_DES;
  532. return 0;
  533. default:
  534. return ALGO_ID_E;
  535. }
  536. }
  537. /* Check To see if PKCS v2 algo is supported, set id if it is return 0
  538. < 0 on error */
  539. static int CheckAlgoV2(int oid, int* id)
  540. {
  541. switch (oid) {
  542. case 69:
  543. *id = PBE_SHA1_DES;
  544. return 0;
  545. case 652:
  546. *id = PBE_SHA1_DES3;
  547. return 0;
  548. default:
  549. return ALGO_ID_E;
  550. }
  551. }
  552. /* Decrypt intput in place from parameters based on id */
  553. static int DecryptKey(const char* password, int passwordSz, byte* salt,
  554. int saltSz, int iterations, int id, byte* input,
  555. int length, int version, byte* cbcIv)
  556. {
  557. byte key[MAX_KEY_SIZE];
  558. int typeH;
  559. int derivedLen;
  560. int decryptionType;
  561. int ret = 0;
  562. switch (id) {
  563. case PBE_MD5_DES:
  564. typeH = MD5;
  565. derivedLen = 16; /* may need iv for v1.5 */
  566. decryptionType = DES_TYPE;
  567. break;
  568. case PBE_SHA1_DES:
  569. typeH = SHA;
  570. derivedLen = 16; /* may need iv for v1.5 */
  571. decryptionType = DES_TYPE;
  572. break;
  573. case PBE_SHA1_DES3:
  574. typeH = SHA;
  575. derivedLen = 32; /* may need iv for v1.5 */
  576. decryptionType = DES3_TYPE;
  577. break;
  578. case PBE_SHA1_RC4_128:
  579. typeH = SHA;
  580. derivedLen = 16;
  581. decryptionType = RC4_TYPE;
  582. break;
  583. default:
  584. return ALGO_ID_E;
  585. }
  586. if (version == PKCS5v2)
  587. ret = PBKDF2(key, (byte*)password, passwordSz, salt, saltSz, iterations,
  588. derivedLen, typeH);
  589. else if (version == PKCS5)
  590. ret = PBKDF1(key, (byte*)password, passwordSz, salt, saltSz, iterations,
  591. derivedLen, typeH);
  592. else if (version == PKCS12) {
  593. int i, idx = 0;
  594. byte unicodePasswd[MAX_UNICODE_SZ];
  595. if ( (passwordSz * 2 + 2) > (int)sizeof(unicodePasswd))
  596. return UNICODE_SIZE_E;
  597. for (i = 0; i < passwordSz; i++) {
  598. unicodePasswd[idx++] = 0x00;
  599. unicodePasswd[idx++] = (byte)password[i];
  600. }
  601. /* add trailing NULL */
  602. unicodePasswd[idx++] = 0x00;
  603. unicodePasswd[idx++] = 0x00;
  604. ret = PKCS12_PBKDF(key, unicodePasswd, idx, salt, saltSz,
  605. iterations, derivedLen, typeH, 1);
  606. if (decryptionType != RC4_TYPE)
  607. ret += PKCS12_PBKDF(cbcIv, unicodePasswd, idx, salt, saltSz,
  608. iterations, 8, typeH, 2);
  609. }
  610. if (ret != 0)
  611. return ret;
  612. switch (decryptionType) {
  613. #ifndef NO_DES3
  614. case DES_TYPE:
  615. {
  616. Des dec;
  617. byte* desIv = key + 8;
  618. if (version == PKCS5v2 || version == PKCS12)
  619. desIv = cbcIv;
  620. Des_SetKey(&dec, key, desIv, DES_DECRYPTION);
  621. Des_CbcDecrypt(&dec, input, input, length);
  622. break;
  623. }
  624. case DES3_TYPE:
  625. {
  626. Des3 dec;
  627. byte* desIv = key + 24;
  628. if (version == PKCS5v2 || version == PKCS12)
  629. desIv = cbcIv;
  630. Des3_SetKey(&dec, key, desIv, DES_DECRYPTION);
  631. Des3_CbcDecrypt(&dec, input, input, length);
  632. break;
  633. }
  634. #endif
  635. #ifndef NO_RC4
  636. case RC4_TYPE:
  637. {
  638. Arc4 dec;
  639. Arc4SetKey(&dec, key, derivedLen);
  640. Arc4Process(&dec, input, input, length);
  641. break;
  642. }
  643. #endif
  644. default:
  645. return ALGO_ID_E;
  646. }
  647. return 0;
  648. }
  649. /* Remove Encrypted PKCS8 header, move beginning of traditional to beginning
  650. of input */
  651. int ToTraditionalEnc(byte* input, word32 sz,const char* password,int passwordSz)
  652. {
  653. word32 inOutIdx = 0, oid;
  654. int first, second, length, version, saltSz, id;
  655. int iterations = 0;
  656. byte salt[MAX_SALT_SIZE];
  657. byte cbcIv[MAX_IV_SIZE];
  658. if (GetSequence(input, &inOutIdx, &length, sz) < 0)
  659. return ASN_PARSE_E;
  660. if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
  661. return ASN_PARSE_E;
  662. first = input[inOutIdx - 2]; /* PKCS version alwyas 2nd to last byte */
  663. second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
  664. if (CheckAlgo(first, second, &id, &version) < 0)
  665. return ASN_INPUT_E; /* Algo ID error */
  666. if (version == PKCS5v2) {
  667. if (GetSequence(input, &inOutIdx, &length, sz) < 0)
  668. return ASN_PARSE_E;
  669. if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
  670. return ASN_PARSE_E;
  671. if (oid != PBKDF2_OID)
  672. return ASN_PARSE_E;
  673. }
  674. if (GetSequence(input, &inOutIdx, &length, sz) < 0)
  675. return ASN_PARSE_E;
  676. if (input[inOutIdx++] != ASN_OCTET_STRING)
  677. return ASN_PARSE_E;
  678. if (GetLength(input, &inOutIdx, &saltSz, sz) < 0)
  679. return ASN_PARSE_E;
  680. if (saltSz > MAX_SALT_SIZE)
  681. return ASN_PARSE_E;
  682. XMEMCPY(salt, &input[inOutIdx], saltSz);
  683. inOutIdx += saltSz;
  684. if (GetShortInt(input, &inOutIdx, &iterations) < 0)
  685. return ASN_PARSE_E;
  686. if (version == PKCS5v2) {
  687. /* get encryption algo */
  688. if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
  689. return ASN_PARSE_E;
  690. if (CheckAlgoV2(oid, &id) < 0)
  691. return ASN_PARSE_E; /* PKCS v2 algo id error */
  692. if (input[inOutIdx++] != ASN_OCTET_STRING)
  693. return ASN_PARSE_E;
  694. if (GetLength(input, &inOutIdx, &length, sz) < 0)
  695. return ASN_PARSE_E;
  696. XMEMCPY(cbcIv, &input[inOutIdx], length);
  697. inOutIdx += length;
  698. }
  699. if (input[inOutIdx++] != ASN_OCTET_STRING)
  700. return ASN_PARSE_E;
  701. if (GetLength(input, &inOutIdx, &length, sz) < 0)
  702. return ASN_PARSE_E;
  703. if (DecryptKey(password, passwordSz, salt, saltSz, iterations, id,
  704. input + inOutIdx, length, version, cbcIv) < 0)
  705. return ASN_INPUT_E; /* decrypt failure */
  706. XMEMMOVE(input, input + inOutIdx, length);
  707. return ToTraditional(input, length);
  708. }
  709. #endif /* NO_PWDBASED */
  710. #ifndef NO_RSA
  711. int RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  712. word32 inSz)
  713. {
  714. int length;
  715. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  716. return ASN_PARSE_E;
  717. key->type = RSA_PUBLIC;
  718. #ifdef OPENSSL_EXTRA
  719. {
  720. byte b = input[*inOutIdx];
  721. if (b != ASN_INTEGER) {
  722. /* not from decoded cert, will have algo id, skip past */
  723. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  724. return ASN_PARSE_E;
  725. b = input[(*inOutIdx)++];
  726. if (b != ASN_OBJECT_ID)
  727. return ASN_OBJECT_ID_E;
  728. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  729. return ASN_PARSE_E;
  730. *inOutIdx += length; /* skip past */
  731. /* could have NULL tag and 0 terminator, but may not */
  732. b = input[(*inOutIdx)++];
  733. if (b == ASN_TAG_NULL) {
  734. b = input[(*inOutIdx)++];
  735. if (b != 0)
  736. return ASN_EXPECT_0_E;
  737. }
  738. else
  739. /* go back, didn't have it */
  740. (*inOutIdx)--;
  741. /* should have bit tag length and seq next */
  742. b = input[(*inOutIdx)++];
  743. if (b != ASN_BIT_STRING)
  744. return ASN_BITSTR_E;
  745. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  746. return ASN_PARSE_E;
  747. /* could have 0 */
  748. b = input[(*inOutIdx)++];
  749. if (b != 0)
  750. (*inOutIdx)--;
  751. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  752. return ASN_PARSE_E;
  753. } /* end if */
  754. } /* openssl var block */
  755. #endif /* OPENSSL_EXTRA */
  756. if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
  757. GetInt(&key->e, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  758. return 0;
  759. }
  760. #endif
  761. #ifndef NO_DH
  762. int DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
  763. {
  764. int length;
  765. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  766. return ASN_PARSE_E;
  767. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  768. GetInt(&key->g, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
  769. return 0;
  770. }
  771. int DhSetKey(DhKey* key, const byte* p, word32 pSz, const byte* g, word32 gSz)
  772. {
  773. /* may have leading 0 */
  774. if (p[0] == 0) {
  775. pSz--; p++;
  776. }
  777. if (g[0] == 0) {
  778. gSz--; g++;
  779. }
  780. if (mp_init(&key->p) != MP_OKAY)
  781. return MP_INIT_E;
  782. if (mp_read_unsigned_bin(&key->p, p, pSz) != 0) {
  783. mp_clear(&key->p);
  784. return ASN_DH_KEY_E;
  785. }
  786. if (mp_init(&key->g) != MP_OKAY) {
  787. mp_clear(&key->p);
  788. return MP_INIT_E;
  789. }
  790. if (mp_read_unsigned_bin(&key->g, g, gSz) != 0) {
  791. mp_clear(&key->g);
  792. mp_clear(&key->p);
  793. return ASN_DH_KEY_E;
  794. }
  795. return 0;
  796. }
  797. #ifdef OPENSSL_EXTRA
  798. int DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
  799. byte* g, word32* gInOutSz)
  800. {
  801. word32 i = 0;
  802. byte b;
  803. int length;
  804. if (GetSequence(input, &i, &length, inSz) < 0)
  805. return ASN_PARSE_E;
  806. b = input[i++];
  807. if (b != ASN_INTEGER)
  808. return ASN_PARSE_E;
  809. if (GetLength(input, &i, &length, inSz) < 0)
  810. return ASN_PARSE_E;
  811. if ( (b = input[i++]) == 0x00)
  812. length--;
  813. else
  814. i--;
  815. if (length <= (int)*pInOutSz) {
  816. XMEMCPY(p, &input[i], length);
  817. *pInOutSz = length;
  818. }
  819. else
  820. return BUFFER_E;
  821. i += length;
  822. b = input[i++];
  823. if (b != ASN_INTEGER)
  824. return ASN_PARSE_E;
  825. if (GetLength(input, &i, &length, inSz) < 0)
  826. return ASN_PARSE_E;
  827. if (length <= (int)*gInOutSz) {
  828. XMEMCPY(g, &input[i], length);
  829. *gInOutSz = length;
  830. }
  831. else
  832. return BUFFER_E;
  833. return 0;
  834. }
  835. #endif /* OPENSSL_EXTRA */
  836. #endif /* NO_DH */
  837. #ifndef NO_DSA
  838. int DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  839. word32 inSz)
  840. {
  841. int length;
  842. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  843. return ASN_PARSE_E;
  844. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  845. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  846. GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
  847. GetInt(&key->y, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
  848. key->type = DSA_PUBLIC;
  849. return 0;
  850. }
  851. int DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  852. word32 inSz)
  853. {
  854. int length, version;
  855. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  856. return ASN_PARSE_E;
  857. if (GetMyVersion(input, inOutIdx, &version) < 0)
  858. return ASN_PARSE_E;
  859. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  860. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  861. GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
  862. GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
  863. GetInt(&key->x, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
  864. key->type = DSA_PRIVATE;
  865. return 0;
  866. }
  867. #endif /* NO_DSA */
  868. void InitDecodedCert(DecodedCert* cert, byte* source, word32 inSz, void* heap)
  869. {
  870. cert->publicKey = 0;
  871. cert->pubKeyStored = 0;
  872. cert->signature = 0;
  873. cert->subjectCN = 0;
  874. cert->subjectCNLen = 0;
  875. cert->subjectCNStored = 0;
  876. cert->altNames = NULL;
  877. cert->issuer[0] = '\0';
  878. cert->subject[0] = '\0';
  879. cert->source = source; /* don't own */
  880. cert->srcIdx = 0;
  881. cert->maxIdx = inSz; /* can't go over this index */
  882. cert->heap = heap;
  883. XMEMSET(cert->serial, 0, EXTERNAL_SERIAL_SIZE);
  884. cert->serialSz = 0;
  885. cert->extensions = 0;
  886. cert->extensionsSz = 0;
  887. cert->extensionsIdx = 0;
  888. cert->extAuthInfo = NULL;
  889. cert->extAuthInfoSz = 0;
  890. cert->extCrlInfo = NULL;
  891. cert->extCrlInfoSz = 0;
  892. cert->isCA = 0;
  893. #ifdef CYASSL_CERT_GEN
  894. cert->subjectSN = 0;
  895. cert->subjectSNLen = 0;
  896. cert->subjectC = 0;
  897. cert->subjectCLen = 0;
  898. cert->subjectL = 0;
  899. cert->subjectLLen = 0;
  900. cert->subjectST = 0;
  901. cert->subjectSTLen = 0;
  902. cert->subjectO = 0;
  903. cert->subjectOLen = 0;
  904. cert->subjectOU = 0;
  905. cert->subjectOULen = 0;
  906. cert->subjectEmail = 0;
  907. cert->subjectEmailLen = 0;
  908. cert->beforeDate = 0;
  909. cert->beforeDateLen = 0;
  910. cert->afterDate = 0;
  911. cert->afterDateLen = 0;
  912. #endif /* CYASSL_CERT_GEN */
  913. }
  914. void FreeAltNames(DNS_entry* altNames, void* heap)
  915. {
  916. (void)heap;
  917. while (altNames) {
  918. DNS_entry* tmp = altNames->next;
  919. XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
  920. XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME);
  921. altNames = tmp;
  922. }
  923. }
  924. void FreeDecodedCert(DecodedCert* cert)
  925. {
  926. if (cert->subjectCNStored == 1)
  927. XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
  928. if (cert->pubKeyStored == 1)
  929. XFREE(cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  930. if (cert->altNames)
  931. FreeAltNames(cert->altNames, cert->heap);
  932. }
  933. static int GetCertHeader(DecodedCert* cert)
  934. {
  935. int ret = 0, version, len;
  936. byte serialTmp[EXTERNAL_SERIAL_SIZE];
  937. mp_int mpi;
  938. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  939. return ASN_PARSE_E;
  940. cert->certBegin = cert->srcIdx;
  941. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  942. return ASN_PARSE_E;
  943. cert->sigIndex = len + cert->srcIdx;
  944. if (GetExplicitVersion(cert->source, &cert->srcIdx, &version) < 0)
  945. return ASN_PARSE_E;
  946. if (GetInt(&mpi, cert->source, &cert->srcIdx, cert->maxIdx) < 0)
  947. return ASN_PARSE_E;
  948. len = mp_unsigned_bin_size(&mpi);
  949. if (len < (int)sizeof(serialTmp)) {
  950. if (mp_to_unsigned_bin(&mpi, serialTmp) == MP_OKAY) {
  951. if (len > EXTERNAL_SERIAL_SIZE)
  952. len = EXTERNAL_SERIAL_SIZE;
  953. XMEMCPY(cert->serial, serialTmp, len);
  954. cert->serialSz = len;
  955. }
  956. }
  957. mp_clear(&mpi);
  958. return ret;
  959. }
  960. #if !defined(NO_RSA)
  961. /* Store Rsa Key, may save later, Dsa could use in future */
  962. static int StoreRsaKey(DecodedCert* cert)
  963. {
  964. int length;
  965. word32 read = cert->srcIdx;
  966. if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  967. return ASN_PARSE_E;
  968. read = cert->srcIdx - read;
  969. length += read;
  970. while (read--)
  971. cert->srcIdx--;
  972. cert->pubKeySize = length;
  973. cert->publicKey = cert->source + cert->srcIdx;
  974. cert->srcIdx += length;
  975. return 0;
  976. }
  977. #endif
  978. #ifdef HAVE_ECC
  979. /* return 0 on sucess if the ECC curve oid sum is supported */
  980. static int CheckCurve(word32 oid)
  981. {
  982. if (oid != ECC_256R1 && oid != ECC_384R1 && oid != ECC_521R1 && oid !=
  983. ECC_160R1 && oid != ECC_192R1 && oid != ECC_224R1)
  984. return ALGO_ID_E;
  985. return 0;
  986. }
  987. #endif /* HAVE_ECC */
  988. static int GetKey(DecodedCert* cert)
  989. {
  990. int length;
  991. #ifdef HAVE_NTRU
  992. int tmpIdx = cert->srcIdx;
  993. #endif
  994. if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  995. return ASN_PARSE_E;
  996. if (GetAlgoId(cert->source, &cert->srcIdx, &cert->keyOID, cert->maxIdx) < 0)
  997. return ASN_PARSE_E;
  998. switch (cert->keyOID) {
  999. case DSAk:
  1000. /* do nothing */
  1001. break;
  1002. #ifndef NO_RSA
  1003. case RSAk:
  1004. {
  1005. byte b = cert->source[cert->srcIdx++];
  1006. if (b != ASN_BIT_STRING)
  1007. return ASN_BITSTR_E;
  1008. if (GetLength(cert->source,&cert->srcIdx,&length,cert->maxIdx) < 0)
  1009. return ASN_PARSE_E;
  1010. b = cert->source[cert->srcIdx++];
  1011. if (b != 0x00)
  1012. return ASN_EXPECT_0_E;
  1013. return StoreRsaKey(cert);
  1014. }
  1015. break;
  1016. #endif /* NO_RSA */
  1017. #ifdef HAVE_NTRU
  1018. case NTRUk:
  1019. {
  1020. const byte* key = &cert->source[tmpIdx];
  1021. byte* next = (byte*)key;
  1022. word16 keyLen;
  1023. byte keyBlob[MAX_NTRU_KEY_SZ];
  1024. word32 rc = crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key,
  1025. &keyLen, NULL, &next);
  1026. if (rc != NTRU_OK)
  1027. return ASN_NTRU_KEY_E;
  1028. if (keyLen > sizeof(keyBlob))
  1029. return ASN_NTRU_KEY_E;
  1030. rc = crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key,&keyLen,
  1031. keyBlob, &next);
  1032. if (rc != NTRU_OK)
  1033. return ASN_NTRU_KEY_E;
  1034. if ( (next - key) < 0)
  1035. return ASN_NTRU_KEY_E;
  1036. cert->srcIdx = tmpIdx + (int)(next - key);
  1037. cert->publicKey = (byte*) XMALLOC(keyLen, cert->heap,
  1038. DYNAMIC_TYPE_PUBLIC_KEY);
  1039. if (cert->publicKey == NULL)
  1040. return MEMORY_E;
  1041. XMEMCPY(cert->publicKey, keyBlob, keyLen);
  1042. cert->pubKeyStored = 1;
  1043. cert->pubKeySize = keyLen;
  1044. }
  1045. break;
  1046. #endif /* HAVE_NTRU */
  1047. #ifdef HAVE_ECC
  1048. case ECDSAk:
  1049. {
  1050. word32 oid = 0;
  1051. int oidSz = 0;
  1052. byte b = cert->source[cert->srcIdx++];
  1053. if (b != ASN_OBJECT_ID)
  1054. return ASN_OBJECT_ID_E;
  1055. if (GetLength(cert->source,&cert->srcIdx,&oidSz,cert->maxIdx) < 0)
  1056. return ASN_PARSE_E;
  1057. while(oidSz--)
  1058. oid += cert->source[cert->srcIdx++];
  1059. if (CheckCurve(oid) < 0)
  1060. return ECC_CURVE_OID_E;
  1061. /* key header */
  1062. b = cert->source[cert->srcIdx++];
  1063. if (b != ASN_BIT_STRING)
  1064. return ASN_BITSTR_E;
  1065. if (GetLength(cert->source,&cert->srcIdx,&length,cert->maxIdx) < 0)
  1066. return ASN_PARSE_E;
  1067. b = cert->source[cert->srcIdx++];
  1068. if (b != 0x00)
  1069. return ASN_EXPECT_0_E;
  1070. /* actual key, use length - 1 since ate preceding 0 */
  1071. length -= 1;
  1072. cert->publicKey = (byte*) XMALLOC(length, cert->heap,
  1073. DYNAMIC_TYPE_PUBLIC_KEY);
  1074. if (cert->publicKey == NULL)
  1075. return MEMORY_E;
  1076. XMEMCPY(cert->publicKey, &cert->source[cert->srcIdx], length);
  1077. cert->pubKeyStored = 1;
  1078. cert->pubKeySize = length;
  1079. cert->srcIdx += length;
  1080. }
  1081. break;
  1082. #endif /* HAVE_ECC */
  1083. default:
  1084. return ASN_UNKNOWN_OID_E;
  1085. }
  1086. return 0;
  1087. }
  1088. /* process NAME, either issuer or subject */
  1089. static int GetName(DecodedCert* cert, int nameType)
  1090. {
  1091. Sha sha;
  1092. int length; /* length of all distinguished names */
  1093. int dummy;
  1094. char* full = (nameType == ISSUER) ? cert->issuer : cert->subject;
  1095. word32 idx;
  1096. CYASSL_MSG("Getting Cert Name");
  1097. if (cert->source[cert->srcIdx] == ASN_OBJECT_ID) {
  1098. CYASSL_MSG("Trying optional prefix...");
  1099. if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  1100. return ASN_PARSE_E;
  1101. cert->srcIdx += length;
  1102. CYASSL_MSG("Got optional prefix");
  1103. }
  1104. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  1105. * calculated over the entire DER encoding of the Name field, including
  1106. * the tag and length. */
  1107. idx = cert->srcIdx;
  1108. if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  1109. return ASN_PARSE_E;
  1110. InitSha(&sha);
  1111. ShaUpdate(&sha, &cert->source[idx], length + cert->srcIdx - idx);
  1112. if (nameType == ISSUER)
  1113. ShaFinal(&sha, cert->issuerHash);
  1114. else
  1115. ShaFinal(&sha, cert->subjectHash);
  1116. length += cert->srcIdx;
  1117. idx = 0;
  1118. while (cert->srcIdx < (word32)length) {
  1119. byte b;
  1120. byte joint[2];
  1121. byte tooBig = FALSE;
  1122. int oidSz;
  1123. if (GetSet(cert->source, &cert->srcIdx, &dummy, cert->maxIdx) < 0) {
  1124. CYASSL_MSG("Cert name lacks set header, trying sequence");
  1125. }
  1126. if (GetSequence(cert->source, &cert->srcIdx, &dummy, cert->maxIdx) < 0)
  1127. return ASN_PARSE_E;
  1128. b = cert->source[cert->srcIdx++];
  1129. if (b != ASN_OBJECT_ID)
  1130. return ASN_OBJECT_ID_E;
  1131. if (GetLength(cert->source, &cert->srcIdx, &oidSz, cert->maxIdx) < 0)
  1132. return ASN_PARSE_E;
  1133. XMEMCPY(joint, &cert->source[cert->srcIdx], sizeof(joint));
  1134. /* v1 name types */
  1135. if (joint[0] == 0x55 && joint[1] == 0x04) {
  1136. byte id;
  1137. byte copy = FALSE;
  1138. int strLen;
  1139. cert->srcIdx += 2;
  1140. id = cert->source[cert->srcIdx++];
  1141. b = cert->source[cert->srcIdx++]; /* strType */
  1142. (void)b; /* may want to validate? */
  1143. if (GetLength(cert->source, &cert->srcIdx, &strLen,
  1144. cert->maxIdx) < 0)
  1145. return ASN_PARSE_E;
  1146. if ( (strLen + 4) > (int)(ASN_NAME_MAX - idx)) {
  1147. /* include biggest pre fix header too 4 = "/CN=" */
  1148. CYASSL_MSG("ASN Name too big, skipping");
  1149. tooBig = TRUE;
  1150. }
  1151. if (id == ASN_COMMON_NAME) {
  1152. if (nameType == SUBJECT) {
  1153. cert->subjectCN = (char *)&cert->source[cert->srcIdx];
  1154. cert->subjectCNLen = strLen;
  1155. }
  1156. if (!tooBig) {
  1157. XMEMCPY(&full[idx], "/CN=", 4);
  1158. idx += 4;
  1159. copy = TRUE;
  1160. }
  1161. }
  1162. else if (id == ASN_SUR_NAME) {
  1163. if (!tooBig) {
  1164. XMEMCPY(&full[idx], "/SN=", 4);
  1165. idx += 4;
  1166. copy = TRUE;
  1167. }
  1168. #ifdef CYASSL_CERT_GEN
  1169. if (nameType == SUBJECT) {
  1170. cert->subjectSN = (char*)&cert->source[cert->srcIdx];
  1171. cert->subjectSNLen = strLen;
  1172. }
  1173. #endif /* CYASSL_CERT_GEN */
  1174. }
  1175. else if (id == ASN_COUNTRY_NAME) {
  1176. if (!tooBig) {
  1177. XMEMCPY(&full[idx], "/C=", 3);
  1178. idx += 3;
  1179. copy = TRUE;
  1180. }
  1181. #ifdef CYASSL_CERT_GEN
  1182. if (nameType == SUBJECT) {
  1183. cert->subjectC = (char*)&cert->source[cert->srcIdx];
  1184. cert->subjectCLen = strLen;
  1185. }
  1186. #endif /* CYASSL_CERT_GEN */
  1187. }
  1188. else if (id == ASN_LOCALITY_NAME) {
  1189. if (!tooBig) {
  1190. XMEMCPY(&full[idx], "/L=", 3);
  1191. idx += 3;
  1192. copy = TRUE;
  1193. }
  1194. #ifdef CYASSL_CERT_GEN
  1195. if (nameType == SUBJECT) {
  1196. cert->subjectL = (char*)&cert->source[cert->srcIdx];
  1197. cert->subjectLLen = strLen;
  1198. }
  1199. #endif /* CYASSL_CERT_GEN */
  1200. }
  1201. else if (id == ASN_STATE_NAME) {
  1202. if (!tooBig) {
  1203. XMEMCPY(&full[idx], "/ST=", 4);
  1204. idx += 4;
  1205. copy = TRUE;
  1206. }
  1207. #ifdef CYASSL_CERT_GEN
  1208. if (nameType == SUBJECT) {
  1209. cert->subjectST = (char*)&cert->source[cert->srcIdx];
  1210. cert->subjectSTLen = strLen;
  1211. }
  1212. #endif /* CYASSL_CERT_GEN */
  1213. }
  1214. else if (id == ASN_ORG_NAME) {
  1215. if (!tooBig) {
  1216. XMEMCPY(&full[idx], "/O=", 3);
  1217. idx += 3;
  1218. copy = TRUE;
  1219. }
  1220. #ifdef CYASSL_CERT_GEN
  1221. if (nameType == SUBJECT) {
  1222. cert->subjectO = (char*)&cert->source[cert->srcIdx];
  1223. cert->subjectOLen = strLen;
  1224. }
  1225. #endif /* CYASSL_CERT_GEN */
  1226. }
  1227. else if (id == ASN_ORGUNIT_NAME) {
  1228. if (!tooBig) {
  1229. XMEMCPY(&full[idx], "/OU=", 4);
  1230. idx += 4;
  1231. copy = TRUE;
  1232. }
  1233. #ifdef CYASSL_CERT_GEN
  1234. if (nameType == SUBJECT) {
  1235. cert->subjectOU = (char*)&cert->source[cert->srcIdx];
  1236. cert->subjectOULen = strLen;
  1237. }
  1238. #endif /* CYASSL_CERT_GEN */
  1239. }
  1240. if (copy && !tooBig) {
  1241. XMEMCPY(&full[idx], &cert->source[cert->srcIdx], strLen);
  1242. idx += strLen;
  1243. }
  1244. cert->srcIdx += strLen;
  1245. }
  1246. else {
  1247. /* skip */
  1248. byte email = FALSE;
  1249. byte uid = FALSE;
  1250. int adv;
  1251. if (joint[0] == 0x2a && joint[1] == 0x86) /* email id hdr */
  1252. email = TRUE;
  1253. if (joint[0] == 0x9 && joint[1] == 0x92) /* uid id hdr */
  1254. uid = TRUE;
  1255. cert->srcIdx += oidSz + 1;
  1256. if (GetLength(cert->source, &cert->srcIdx, &adv, cert->maxIdx) < 0)
  1257. return ASN_PARSE_E;
  1258. if (adv > (int)(ASN_NAME_MAX - idx)) {
  1259. CYASSL_MSG("ASN name too big, skipping");
  1260. tooBig = TRUE;
  1261. }
  1262. if (email) {
  1263. if (14 > (ASN_NAME_MAX - idx)) {
  1264. CYASSL_MSG("ASN name too big, skipping");
  1265. tooBig = TRUE;
  1266. }
  1267. if (!tooBig) {
  1268. XMEMCPY(&full[idx], "/emailAddress=", 14);
  1269. idx += 14;
  1270. }
  1271. #ifdef CYASSL_CERT_GEN
  1272. if (nameType == SUBJECT) {
  1273. cert->subjectEmail = (char*)&cert->source[cert->srcIdx];
  1274. cert->subjectEmailLen = adv;
  1275. }
  1276. #endif /* CYASSL_CERT_GEN */
  1277. if (!tooBig) {
  1278. XMEMCPY(&full[idx], &cert->source[cert->srcIdx], adv);
  1279. idx += adv;
  1280. }
  1281. }
  1282. if (uid) {
  1283. if (5 > (ASN_NAME_MAX - idx)) {
  1284. CYASSL_MSG("ASN name too big, skipping");
  1285. tooBig = TRUE;
  1286. }
  1287. if (!tooBig) {
  1288. XMEMCPY(&full[idx], "/UID=", 5);
  1289. idx += 5;
  1290. XMEMCPY(&full[idx], &cert->source[cert->srcIdx], adv);
  1291. idx += adv;
  1292. }
  1293. }
  1294. cert->srcIdx += adv;
  1295. }
  1296. }
  1297. full[idx++] = 0;
  1298. return 0;
  1299. }
  1300. #ifndef NO_TIME_H
  1301. /* to the second */
  1302. static int DateGreaterThan(const struct tm* a, const struct tm* b)
  1303. {
  1304. if (a->tm_year > b->tm_year)
  1305. return 1;
  1306. if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
  1307. return 1;
  1308. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  1309. a->tm_mday > b->tm_mday)
  1310. return 1;
  1311. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  1312. a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
  1313. return 1;
  1314. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  1315. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  1316. a->tm_min > b->tm_min)
  1317. return 1;
  1318. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  1319. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  1320. a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
  1321. return 1;
  1322. return 0; /* false */
  1323. }
  1324. static INLINE int DateLessThan(const struct tm* a, const struct tm* b)
  1325. {
  1326. return !DateGreaterThan(a,b);
  1327. }
  1328. /* like atoi but only use first byte */
  1329. /* Make sure before and after dates are valid */
  1330. int ValidateDate(const byte* date, byte format, int dateType)
  1331. {
  1332. time_t ltime;
  1333. struct tm certTime;
  1334. struct tm* localTime;
  1335. int i = 0;
  1336. ltime = XTIME(0);
  1337. XMEMSET(&certTime, 0, sizeof(certTime));
  1338. if (format == ASN_UTC_TIME) {
  1339. if (btoi(date[0]) >= 5)
  1340. certTime.tm_year = 1900;
  1341. else
  1342. certTime.tm_year = 2000;
  1343. }
  1344. else { /* format == GENERALIZED_TIME */
  1345. certTime.tm_year += btoi(date[i++]) * 1000;
  1346. certTime.tm_year += btoi(date[i++]) * 100;
  1347. }
  1348. GetTime(&certTime.tm_year, date, &i); certTime.tm_year -= 1900; /* adjust */
  1349. GetTime(&certTime.tm_mon, date, &i); certTime.tm_mon -= 1; /* adjust */
  1350. GetTime(&certTime.tm_mday, date, &i);
  1351. GetTime(&certTime.tm_hour, date, &i);
  1352. GetTime(&certTime.tm_min, date, &i);
  1353. GetTime(&certTime.tm_sec, date, &i);
  1354. if (date[i] != 'Z') { /* only Zulu supported for this profile */
  1355. CYASSL_MSG("Only Zulu time supported for this profile");
  1356. return 0;
  1357. }
  1358. localTime = XGMTIME(&ltime);
  1359. if (dateType == BEFORE) {
  1360. if (DateLessThan(localTime, &certTime))
  1361. return 0;
  1362. }
  1363. else
  1364. if (DateGreaterThan(localTime, &certTime))
  1365. return 0;
  1366. return 1;
  1367. }
  1368. #endif /* NO_TIME_H */
  1369. static int GetDate(DecodedCert* cert, int dateType)
  1370. {
  1371. int length;
  1372. byte date[MAX_DATE_SIZE];
  1373. byte b;
  1374. #ifdef CYASSL_CERT_GEN
  1375. word32 startIdx = 0;
  1376. if (dateType == BEFORE)
  1377. cert->beforeDate = &cert->source[cert->srcIdx];
  1378. else
  1379. cert->afterDate = &cert->source[cert->srcIdx];
  1380. startIdx = cert->srcIdx;
  1381. #endif
  1382. b = cert->source[cert->srcIdx++];
  1383. if (b != ASN_UTC_TIME && b != ASN_GENERALIZED_TIME)
  1384. return ASN_TIME_E;
  1385. if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  1386. return ASN_PARSE_E;
  1387. if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
  1388. return ASN_DATE_SZ_E;
  1389. XMEMCPY(date, &cert->source[cert->srcIdx], length);
  1390. cert->srcIdx += length;
  1391. #ifdef CYASSL_CERT_GEN
  1392. if (dateType == BEFORE)
  1393. cert->beforeDateLen = cert->srcIdx - startIdx;
  1394. else
  1395. cert->afterDateLen = cert->srcIdx - startIdx;
  1396. #endif
  1397. if (!XVALIDATE_DATE(date, b, dateType)) {
  1398. if (dateType == BEFORE)
  1399. return ASN_BEFORE_DATE_E;
  1400. else
  1401. return ASN_AFTER_DATE_E;
  1402. }
  1403. return 0;
  1404. }
  1405. static int GetValidity(DecodedCert* cert, int verify)
  1406. {
  1407. int length;
  1408. int badDate = 0;
  1409. if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  1410. return ASN_PARSE_E;
  1411. if (GetDate(cert, BEFORE) < 0 && verify)
  1412. badDate = ASN_BEFORE_DATE_E; /* continue parsing */
  1413. if (GetDate(cert, AFTER) < 0 && verify)
  1414. return ASN_AFTER_DATE_E;
  1415. if (badDate != 0)
  1416. return badDate;
  1417. return 0;
  1418. }
  1419. int DecodeToKey(DecodedCert* cert, int verify)
  1420. {
  1421. int badDate = 0;
  1422. int ret;
  1423. if ( (ret = GetCertHeader(cert)) < 0)
  1424. return ret;
  1425. if ( (ret = GetAlgoId(cert->source, &cert->srcIdx, &cert->signatureOID,
  1426. cert->maxIdx)) < 0)
  1427. return ret;
  1428. if ( (ret = GetName(cert, ISSUER)) < 0)
  1429. return ret;
  1430. if ( (ret = GetValidity(cert, verify)) < 0)
  1431. badDate = ret;
  1432. if ( (ret = GetName(cert, SUBJECT)) < 0)
  1433. return ret;
  1434. if ( (ret = GetKey(cert)) < 0)
  1435. return ret;
  1436. if (badDate != 0)
  1437. return badDate;
  1438. return ret;
  1439. }
  1440. static int GetSignature(DecodedCert* cert)
  1441. {
  1442. int length;
  1443. byte b = cert->source[cert->srcIdx++];
  1444. if (b != ASN_BIT_STRING)
  1445. return ASN_BITSTR_E;
  1446. if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  1447. return ASN_PARSE_E;
  1448. cert->sigLength = length;
  1449. b = cert->source[cert->srcIdx++];
  1450. if (b != 0x00)
  1451. return ASN_EXPECT_0_E;
  1452. cert->sigLength--;
  1453. cert->signature = &cert->source[cert->srcIdx];
  1454. cert->srcIdx += cert->sigLength;
  1455. return 0;
  1456. }
  1457. static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
  1458. {
  1459. output[0] = ASN_OCTET_STRING;
  1460. output[1] = (byte)digSz;
  1461. XMEMCPY(&output[2], digest, digSz);
  1462. return digSz + 2;
  1463. }
  1464. static word32 BytePrecision(word32 value)
  1465. {
  1466. word32 i;
  1467. for (i = sizeof(value); i; --i)
  1468. if (value >> ((i - 1) * BIT_SIZE))
  1469. break;
  1470. return i;
  1471. }
  1472. static word32 SetLength(word32 length, byte* output)
  1473. {
  1474. word32 i = 0, j;
  1475. if (length < ASN_LONG_LENGTH)
  1476. output[i++] = (byte)length;
  1477. else {
  1478. output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);
  1479. for (j = BytePrecision(length); j; --j) {
  1480. output[i] = (byte)(length >> ((j - 1) * BIT_SIZE));
  1481. i++;
  1482. }
  1483. }
  1484. return i;
  1485. }
  1486. static word32 SetSequence(word32 len, byte* output)
  1487. {
  1488. output[0] = ASN_SEQUENCE | ASN_CONSTRUCTED;
  1489. return SetLength(len, output + 1) + 1;
  1490. }
  1491. static word32 SetAlgoID(int algoOID, byte* output, int type)
  1492. {
  1493. /* adding TAG_NULL and 0 to end */
  1494. /* hashTypes */
  1495. static const byte shaAlgoID[] = { 0x2b, 0x0e, 0x03, 0x02, 0x1a,
  1496. 0x05, 0x00 };
  1497. static const byte sha256AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
  1498. 0x04, 0x02, 0x01, 0x05, 0x00 };
  1499. static const byte sha384AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
  1500. 0x04, 0x02, 0x02, 0x05, 0x00 };
  1501. static const byte sha512AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
  1502. 0x04, 0x02, 0x03, 0x05, 0x00 };
  1503. static const byte md5AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  1504. 0x02, 0x05, 0x05, 0x00 };
  1505. static const byte md2AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  1506. 0x02, 0x02, 0x05, 0x00};
  1507. /* sigTypes */
  1508. #ifndef NO_RSA
  1509. static const byte md5wRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7,
  1510. 0x0d, 0x01, 0x01, 0x04, 0x05, 0x00};
  1511. static const byte shawRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7,
  1512. 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00};
  1513. static const byte sha256wRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7,
  1514. 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00};
  1515. static const byte sha384wRSA_AlgoID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
  1516. 0x0d, 0x01, 0x01, 0x0c, 0x05, 0x00};
  1517. static const byte sha512wRSA_AlgoID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
  1518. 0x0d, 0x01, 0x01, 0x0d, 0x05, 0x00};
  1519. #endif /* NO_RSA */
  1520. /* keyTypes */
  1521. #ifndef NO_RSA
  1522. static const byte RSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  1523. 0x01, 0x01, 0x01, 0x05, 0x00};
  1524. #endif /* NO_RSA */
  1525. int algoSz = 0;
  1526. word32 idSz, seqSz;
  1527. const byte* algoName = 0;
  1528. byte ID_Length[MAX_LENGTH_SZ];
  1529. byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
  1530. if (type == hashType) {
  1531. switch (algoOID) {
  1532. case SHAh:
  1533. algoSz = sizeof(shaAlgoID);
  1534. algoName = shaAlgoID;
  1535. break;
  1536. case SHA256h:
  1537. algoSz = sizeof(sha256AlgoID);
  1538. algoName = sha256AlgoID;
  1539. break;
  1540. case SHA384h:
  1541. algoSz = sizeof(sha384AlgoID);
  1542. algoName = sha384AlgoID;
  1543. break;
  1544. case SHA512h:
  1545. algoSz = sizeof(sha512AlgoID);
  1546. algoName = sha512AlgoID;
  1547. break;
  1548. case MD2h:
  1549. algoSz = sizeof(md2AlgoID);
  1550. algoName = md2AlgoID;
  1551. break;
  1552. case MD5h:
  1553. algoSz = sizeof(md5AlgoID);
  1554. algoName = md5AlgoID;
  1555. break;
  1556. default:
  1557. CYASSL_MSG("Unknown Hash Algo");
  1558. return 0; /* UNKOWN_HASH_E; */
  1559. }
  1560. }
  1561. else if (type == sigType) { /* sigType */
  1562. switch (algoOID) {
  1563. #ifndef NO_RSA
  1564. case CTC_MD5wRSA:
  1565. algoSz = sizeof(md5wRSA_AlgoID);
  1566. algoName = md5wRSA_AlgoID;
  1567. break;
  1568. case CTC_SHAwRSA:
  1569. algoSz = sizeof(shawRSA_AlgoID);
  1570. algoName = shawRSA_AlgoID;
  1571. break;
  1572. case CTC_SHA256wRSA:
  1573. algoSz = sizeof(sha256wRSA_AlgoID);
  1574. algoName = sha256wRSA_AlgoID;
  1575. break;
  1576. case CTC_SHA384wRSA:
  1577. algoSz = sizeof(sha384wRSA_AlgoID);
  1578. algoName = sha384wRSA_AlgoID;
  1579. break;
  1580. case CTC_SHA512wRSA:
  1581. algoSz = sizeof(sha512wRSA_AlgoID);
  1582. algoName = sha512wRSA_AlgoID;
  1583. break;
  1584. #endif /* NO_RSA */
  1585. default:
  1586. CYASSL_MSG("Unknown Signature Algo");
  1587. return 0;
  1588. }
  1589. }
  1590. else if (type == keyType) { /* keyType */
  1591. switch (algoOID) {
  1592. #ifndef NO_RSA
  1593. case RSAk:
  1594. algoSz = sizeof(RSA_AlgoID);
  1595. algoName = RSA_AlgoID;
  1596. break;
  1597. #endif /* NO_RSA */
  1598. default:
  1599. CYASSL_MSG("Unknown Key Algo");
  1600. return 0;
  1601. }
  1602. }
  1603. else {
  1604. CYASSL_MSG("Unknown Algo type");
  1605. return 0;
  1606. }
  1607. idSz = SetLength(algoSz - 2, ID_Length); /* don't include TAG_NULL/0 */
  1608. seqSz = SetSequence(idSz + algoSz + 1, seqArray);
  1609. seqArray[seqSz++] = ASN_OBJECT_ID;
  1610. XMEMCPY(output, seqArray, seqSz);
  1611. XMEMCPY(output + seqSz, ID_Length, idSz);
  1612. XMEMCPY(output + seqSz + idSz, algoName, algoSz);
  1613. return seqSz + idSz + algoSz;
  1614. }
  1615. word32 EncodeSignature(byte* out, const byte* digest, word32 digSz, int hashOID)
  1616. {
  1617. byte digArray[MAX_ENCODED_DIG_SZ];
  1618. byte algoArray[MAX_ALGO_SZ];
  1619. byte seqArray[MAX_SEQ_SZ];
  1620. word32 encDigSz, algoSz, seqSz;
  1621. encDigSz = SetDigest(digest, digSz, digArray);
  1622. algoSz = SetAlgoID(hashOID, algoArray, hashType);
  1623. seqSz = SetSequence(encDigSz + algoSz, seqArray);
  1624. XMEMCPY(out, seqArray, seqSz);
  1625. XMEMCPY(out + seqSz, algoArray, algoSz);
  1626. XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
  1627. return encDigSz + algoSz + seqSz;
  1628. }
  1629. /* return true (1) for Confirmation */
  1630. static int ConfirmSignature(const byte* buf, word32 bufSz,
  1631. const byte* key, word32 keySz, word32 keyOID,
  1632. const byte* sig, word32 sigSz, word32 sigOID,
  1633. void* heap)
  1634. {
  1635. #ifdef CYASSL_SHA512
  1636. byte digest[SHA512_DIGEST_SIZE]; /* max size */
  1637. #elif !defined(NO_SHA256)
  1638. byte digest[SHA256_DIGEST_SIZE]; /* max size */
  1639. #else
  1640. byte digest[SHA_DIGEST_SIZE]; /* max size */
  1641. #endif
  1642. int typeH, digestSz, ret = 0;
  1643. (void)key;
  1644. (void)keySz;
  1645. (void)sig;
  1646. (void)sigSz;
  1647. (void)heap;
  1648. switch (sigOID) {
  1649. case CTC_MD5wRSA:
  1650. {
  1651. Md5 md5;
  1652. InitMd5(&md5);
  1653. Md5Update(&md5, buf, bufSz);
  1654. Md5Final(&md5, digest);
  1655. typeH = MD5h;
  1656. digestSz = MD5_DIGEST_SIZE;
  1657. }
  1658. break;
  1659. #if defined(CYASSL_MD2)
  1660. case CTC_MD2wRSA:
  1661. {
  1662. Md2 md2;
  1663. InitMd2(&md2);
  1664. Md2Update(&md2, buf, bufSz);
  1665. Md2Final(&md2, digest);
  1666. typeH = MD2h;
  1667. digestSz = MD2_DIGEST_SIZE;
  1668. }
  1669. break;
  1670. #endif
  1671. case CTC_SHAwRSA:
  1672. case CTC_SHAwDSA:
  1673. case CTC_SHAwECDSA:
  1674. {
  1675. Sha sha;
  1676. InitSha(&sha);
  1677. ShaUpdate(&sha, buf, bufSz);
  1678. ShaFinal(&sha, digest);
  1679. typeH = SHAh;
  1680. digestSz = SHA_DIGEST_SIZE;
  1681. }
  1682. break;
  1683. #ifndef NO_SHA256
  1684. case CTC_SHA256wRSA:
  1685. case CTC_SHA256wECDSA:
  1686. {
  1687. Sha256 sha256;
  1688. InitSha256(&sha256);
  1689. Sha256Update(&sha256, buf, bufSz);
  1690. Sha256Final(&sha256, digest);
  1691. typeH = SHA256h;
  1692. digestSz = SHA256_DIGEST_SIZE;
  1693. }
  1694. break;
  1695. #endif
  1696. #ifdef CYASSL_SHA512
  1697. case CTC_SHA512wRSA:
  1698. case CTC_SHA512wECDSA:
  1699. {
  1700. Sha512 sha512;
  1701. InitSha512(&sha512);
  1702. Sha512Update(&sha512, buf, bufSz);
  1703. Sha512Final(&sha512, digest);
  1704. typeH = SHA512h;
  1705. digestSz = SHA512_DIGEST_SIZE;
  1706. }
  1707. break;
  1708. #endif
  1709. #ifdef CYASSL_SHA384
  1710. case CTC_SHA384wRSA:
  1711. case CTC_SHA384wECDSA:
  1712. {
  1713. Sha384 sha384;
  1714. InitSha384(&sha384);
  1715. Sha384Update(&sha384, buf, bufSz);
  1716. Sha384Final(&sha384, digest);
  1717. typeH = SHA384h;
  1718. digestSz = SHA384_DIGEST_SIZE;
  1719. }
  1720. break;
  1721. #endif
  1722. default:
  1723. CYASSL_MSG("Verify Signautre has unsupported type");
  1724. return 0;
  1725. }
  1726. switch (keyOID) {
  1727. #ifndef NO_RSA
  1728. case RSAk:
  1729. {
  1730. RsaKey pubKey;
  1731. byte encodedSig[MAX_ENCODED_SIG_SZ];
  1732. byte plain[MAX_ENCODED_SIG_SZ];
  1733. word32 idx = 0;
  1734. int encodedSigSz, verifySz;
  1735. byte* out;
  1736. if (sigSz > MAX_ENCODED_SIG_SZ) {
  1737. CYASSL_MSG("Verify Signautre is too big");
  1738. return 0;
  1739. }
  1740. InitRsaKey(&pubKey, heap);
  1741. if (RsaPublicKeyDecode(key, &idx, &pubKey, keySz) < 0) {
  1742. CYASSL_MSG("ASN Key decode error RSA");
  1743. ret = 0;
  1744. }
  1745. else {
  1746. XMEMCPY(plain, sig, sigSz);
  1747. if ( (verifySz = RsaSSL_VerifyInline(plain, sigSz, &out,
  1748. &pubKey)) < 0) {
  1749. CYASSL_MSG("Rsa SSL verify error");
  1750. ret = 0;
  1751. }
  1752. else {
  1753. /* make sure we're right justified */
  1754. encodedSigSz =
  1755. EncodeSignature(encodedSig, digest, digestSz, typeH);
  1756. if (encodedSigSz != verifySz ||
  1757. XMEMCMP(out, encodedSig, encodedSigSz) != 0) {
  1758. CYASSL_MSG("Rsa SSL verify match encode error");
  1759. ret = 0;
  1760. }
  1761. else
  1762. ret = 1; /* match */
  1763. #ifdef CYASSL_DEBUG_ENCODING
  1764. {
  1765. int x;
  1766. printf("cyassl encodedSig:\n");
  1767. for (x = 0; x < encodedSigSz; x++) {
  1768. printf("%02x ", encodedSig[x]);
  1769. if ( (x % 16) == 15)
  1770. printf("\n");
  1771. }
  1772. printf("\n");
  1773. printf("actual digest:\n");
  1774. for (x = 0; x < verifySz; x++) {
  1775. printf("%02x ", out[x]);
  1776. if ( (x % 16) == 15)
  1777. printf("\n");
  1778. }
  1779. printf("\n");
  1780. }
  1781. #endif /* CYASSL_DEBUG_ENCODING */
  1782. }
  1783. }
  1784. FreeRsaKey(&pubKey);
  1785. return ret;
  1786. }
  1787. break;
  1788. #endif /* NO_RSA */
  1789. #ifdef HAVE_ECC
  1790. case ECDSAk:
  1791. {
  1792. ecc_key pubKey;
  1793. int verify = 0;
  1794. if (ecc_import_x963(key, keySz, &pubKey) < 0) {
  1795. CYASSL_MSG("ASN Key import error ECC");
  1796. return 0;
  1797. }
  1798. ret = ecc_verify_hash(sig,sigSz,digest,digestSz,&verify,&pubKey);
  1799. ecc_free(&pubKey);
  1800. if (ret == 0 && verify == 1)
  1801. return 1; /* match */
  1802. CYASSL_MSG("ECC Verify didn't match");
  1803. return 0;
  1804. }
  1805. #endif /* HAVE_ECC */
  1806. default:
  1807. CYASSL_MSG("Verify Key type unknown");
  1808. return 0;
  1809. }
  1810. }
  1811. static void DecodeAltNames(byte* input, int sz, DecodedCert* cert)
  1812. {
  1813. word32 idx = 0;
  1814. int length = 0;
  1815. CYASSL_ENTER("DecodeAltNames");
  1816. if (GetSequence(input, &idx, &length, sz) < 0) {
  1817. CYASSL_MSG("\tBad Sequence");
  1818. return;
  1819. }
  1820. while (length > 0) {
  1821. DNS_entry* entry;
  1822. int strLen;
  1823. byte b = input[idx++];
  1824. length--;
  1825. if (b != (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  1826. CYASSL_MSG("\tNot DNS type");
  1827. return;
  1828. }
  1829. if (GetLength(input, &idx, &strLen, sz) < 0) {
  1830. CYASSL_MSG("\tfail: str length");
  1831. return;
  1832. }
  1833. entry = (DNS_entry*)XMALLOC(sizeof(DNS_entry), cert->heap,
  1834. DYNAMIC_TYPE_ALTNAME);
  1835. if (entry == NULL) {
  1836. CYASSL_MSG("\tOut of Memory");
  1837. return;
  1838. }
  1839. entry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  1840. DYNAMIC_TYPE_ALTNAME);
  1841. if (entry->name == NULL) {
  1842. CYASSL_MSG("\tOut of Memory");
  1843. XFREE(entry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  1844. return;
  1845. }
  1846. XMEMCPY(entry->name, &input[idx], strLen);
  1847. entry->name[strLen] = '\0';
  1848. entry->next = cert->altNames;
  1849. cert->altNames = entry;
  1850. length -= strLen;
  1851. idx += strLen;
  1852. }
  1853. }
  1854. static void DecodeBasicCaConstraint(byte* input, int sz, DecodedCert* cert)
  1855. {
  1856. word32 idx = 0;
  1857. int length = 0;
  1858. CYASSL_ENTER("DecodeBasicCaConstraint");
  1859. if (GetSequence(input, &idx, &length, sz) < 0) return;
  1860. if (length == 0) return;
  1861. /* If the basic ca constraint is false, this extension may be named, but
  1862. * left empty. So, if the length is 0, just return. */
  1863. if (input[idx++] != ASN_BOOLEAN)
  1864. {
  1865. CYASSL_MSG("\tfail: constraint not BOOLEAN");
  1866. return;
  1867. }
  1868. if (GetLength(input, &idx, &length, sz) < 0)
  1869. {
  1870. CYASSL_MSG("\tfail: length");
  1871. return;
  1872. }
  1873. if (input[idx])
  1874. cert->isCA = 1;
  1875. }
  1876. #define CRLDP_FULL_NAME 0
  1877. /* From RFC3280 SS4.2.1.14, Distribution Point Name*/
  1878. #define GENERALNAME_URI 6
  1879. /* From RFC3280 SS4.2.1.7, GeneralName */
  1880. static void DecodeCrlDist(byte* input, int sz, DecodedCert* cert)
  1881. {
  1882. word32 idx = 0;
  1883. int length = 0;
  1884. CYASSL_ENTER("DecodeCrlDist");
  1885. /* Unwrap the list of Distribution Points*/
  1886. if (GetSequence(input, &idx, &length, sz) < 0) return;
  1887. /* Unwrap a single Distribution Point */
  1888. if (GetSequence(input, &idx, &length, sz) < 0) return;
  1889. /* The Distribution Point has three explicit optional members
  1890. * First check for a DistributionPointName
  1891. */
  1892. if (input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  1893. {
  1894. idx++;
  1895. if (GetLength(input, &idx, &length, sz) < 0) return;
  1896. if (input[idx] ==
  1897. (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CRLDP_FULL_NAME))
  1898. {
  1899. idx++;
  1900. if (GetLength(input, &idx, &length, sz) < 0) return;
  1901. if (input[idx] == (ASN_CONTEXT_SPECIFIC | GENERALNAME_URI))
  1902. {
  1903. idx++;
  1904. if (GetLength(input, &idx, &length, sz) < 0) return;
  1905. cert->extCrlInfoSz = length;
  1906. cert->extCrlInfo = input + idx;
  1907. idx += length;
  1908. }
  1909. else
  1910. /* This isn't a URI, skip it. */
  1911. idx += length;
  1912. }
  1913. else
  1914. /* This isn't a FULLNAME, skip it. */
  1915. idx += length;
  1916. }
  1917. /* Check for reasonFlags */
  1918. if (idx < (word32)sz &&
  1919. input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  1920. {
  1921. idx++;
  1922. if (GetLength(input, &idx, &length, sz) < 0) return;
  1923. idx += length;
  1924. }
  1925. /* Check for cRLIssuer */
  1926. if (idx < (word32)sz &&
  1927. input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
  1928. {
  1929. idx++;
  1930. if (GetLength(input, &idx, &length, sz) < 0) return;
  1931. idx += length;
  1932. }
  1933. if (idx < (word32)sz)
  1934. {
  1935. CYASSL_MSG("\tThere are more CRL Distribution Point records, "
  1936. "but we only use the first one.");
  1937. }
  1938. return;
  1939. }
  1940. static void DecodeAuthInfo(byte* input, int sz, DecodedCert* cert)
  1941. /*
  1942. * Read the first of the Authority Information Access records. If there are
  1943. * any issues, return without saving the record.
  1944. */
  1945. {
  1946. word32 idx = 0;
  1947. int length = 0;
  1948. word32 oid;
  1949. /* Unwrap the list of AIAs */
  1950. if (GetSequence(input, &idx, &length, sz) < 0) return;
  1951. /* Unwrap a single AIA */
  1952. if (GetSequence(input, &idx, &length, sz) < 0) return;
  1953. oid = 0;
  1954. if (GetObjectId(input, &idx, &oid, sz) < 0) return;
  1955. /* Only supporting URIs right now. */
  1956. if (input[idx] == (ASN_CONTEXT_SPECIFIC | GENERALNAME_URI))
  1957. {
  1958. idx++;
  1959. if (GetLength(input, &idx, &length, sz) < 0) return;
  1960. cert->extAuthInfoSz = length;
  1961. cert->extAuthInfo = input + idx;
  1962. idx += length;
  1963. }
  1964. else
  1965. {
  1966. /* Skip anything else. */
  1967. idx++;
  1968. if (GetLength(input, &idx, &length, sz) < 0) return;
  1969. idx += length;
  1970. }
  1971. if (idx < (word32)sz)
  1972. {
  1973. CYASSL_MSG("\tThere are more Authority Information Access records, "
  1974. "but we only use first one.");
  1975. }
  1976. return;
  1977. }
  1978. static void DecodeCertExtensions(DecodedCert* cert)
  1979. /*
  1980. * Processing the Certificate Extensions. This does not modify the current
  1981. * index. It is works starting with the recorded extensions pointer.
  1982. */
  1983. {
  1984. word32 idx = 0;
  1985. int sz = cert->extensionsSz;
  1986. byte* input = cert->extensions;
  1987. int length;
  1988. word32 oid;
  1989. CYASSL_ENTER("DecodeCertExtensions");
  1990. if (input == NULL || sz == 0) return;
  1991. if (input[idx++] != ASN_EXTENSIONS) return;
  1992. if (GetLength(input, &idx, &length, sz) < 0) return;
  1993. if (GetSequence(input, &idx, &length, sz) < 0) return;
  1994. while (idx < (word32)sz) {
  1995. if (GetSequence(input, &idx, &length, sz) < 0) {
  1996. CYASSL_MSG("\tfail: should be a SEQUENCE");
  1997. return;
  1998. }
  1999. oid = 0;
  2000. if (GetObjectId(input, &idx, &oid, sz) < 0) {
  2001. CYASSL_MSG("\tfail: OBJECT ID");
  2002. return;
  2003. }
  2004. /* check for critical flag */
  2005. if (input[idx] == ASN_BOOLEAN) {
  2006. CYASSL_MSG("\tfound optional critical flag, moving past");
  2007. idx += (ASN_BOOL_SIZE + 1);
  2008. }
  2009. /* process the extension based on the OID */
  2010. if (input[idx++] != ASN_OCTET_STRING) {
  2011. CYASSL_MSG("\tfail: should be an OCTET STRING");
  2012. return;
  2013. }
  2014. if (GetLength(input, &idx, &length, sz) < 0) {
  2015. CYASSL_MSG("\tfail: extension data length");
  2016. return;
  2017. }
  2018. switch (oid) {
  2019. case BASIC_CA_OID:
  2020. DecodeBasicCaConstraint(&input[idx], length, cert);
  2021. break;
  2022. case CRL_DIST_OID:
  2023. DecodeCrlDist(&input[idx], length, cert);
  2024. break;
  2025. case AUTH_INFO_OID:
  2026. DecodeAuthInfo(&input[idx], length, cert);
  2027. break;
  2028. case ALT_NAMES_OID:
  2029. DecodeAltNames(&input[idx], length, cert);
  2030. default:
  2031. CYASSL_MSG("\tExtension type not handled, skipping");
  2032. break;
  2033. }
  2034. idx += length;
  2035. }
  2036. return;
  2037. }
  2038. int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  2039. {
  2040. int ret;
  2041. char* ptr;
  2042. ret = ParseCertRelative(cert, type, verify, cm);
  2043. if (ret < 0)
  2044. return ret;
  2045. if (cert->subjectCNLen > 0) {
  2046. ptr = (char*) XMALLOC(cert->subjectCNLen + 1, cert->heap,
  2047. DYNAMIC_TYPE_SUBJECT_CN);
  2048. if (ptr == NULL)
  2049. return MEMORY_E;
  2050. XMEMCPY(ptr, cert->subjectCN, cert->subjectCNLen);
  2051. ptr[cert->subjectCNLen] = '\0';
  2052. cert->subjectCN = ptr;
  2053. cert->subjectCNStored = 1;
  2054. }
  2055. if (cert->keyOID == RSAk && cert->pubKeySize > 0) {
  2056. ptr = (char*) XMALLOC(cert->pubKeySize, cert->heap,
  2057. DYNAMIC_TYPE_PUBLIC_KEY);
  2058. if (ptr == NULL)
  2059. return MEMORY_E;
  2060. XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
  2061. cert->publicKey = (byte *)ptr;
  2062. cert->pubKeyStored = 1;
  2063. }
  2064. return ret;
  2065. }
  2066. /* from SSL proper, for locking can't do find here anymore */
  2067. #ifdef __cplusplus
  2068. extern "C" {
  2069. #endif
  2070. CYASSL_LOCAL Signer* GetCA(void* signers, byte* hash);
  2071. #ifdef __cplusplus
  2072. }
  2073. #endif
  2074. int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
  2075. {
  2076. word32 confirmOID;
  2077. int ret;
  2078. int badDate = 0;
  2079. if ((ret = DecodeToKey(cert, verify)) < 0) {
  2080. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E)
  2081. badDate = ret;
  2082. else
  2083. return ret;
  2084. }
  2085. if (cert->srcIdx != cert->sigIndex) {
  2086. if (cert->srcIdx < cert->sigIndex) {
  2087. /* save extensions */
  2088. cert->extensions = &cert->source[cert->srcIdx];
  2089. cert->extensionsSz = cert->sigIndex - cert->srcIdx;
  2090. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  2091. }
  2092. DecodeCertExtensions(cert);
  2093. /* advance past extensions */
  2094. cert->srcIdx = cert->sigIndex;
  2095. }
  2096. if ((ret = GetAlgoId(cert->source, &cert->srcIdx, &confirmOID,
  2097. cert->maxIdx)) < 0)
  2098. return ret;
  2099. if ((ret = GetSignature(cert)) < 0)
  2100. return ret;
  2101. if (confirmOID != cert->signatureOID)
  2102. return ASN_SIG_OID_E;
  2103. if (verify && type != CA_TYPE) {
  2104. Signer* ca = GetCA(cm, cert->issuerHash);
  2105. CYASSL_MSG("About to verify certificate signature");
  2106. if (ca) {
  2107. #ifdef HAVE_OCSP
  2108. /* Need the ca's public key hash for OCSP */
  2109. {
  2110. Sha sha;
  2111. InitSha(&sha);
  2112. ShaUpdate(&sha, ca->publicKey, ca->pubKeySize);
  2113. ShaFinal(&sha, cert->issuerKeyHash);
  2114. }
  2115. #endif /* HAVE_OCSP */
  2116. /* try to confirm/verify signature */
  2117. if (!ConfirmSignature(cert->source + cert->certBegin,
  2118. cert->sigIndex - cert->certBegin,
  2119. ca->publicKey, ca->pubKeySize, ca->keyOID,
  2120. cert->signature, cert->sigLength, cert->signatureOID,
  2121. cert->heap)) {
  2122. CYASSL_MSG("Confirm signature failed");
  2123. return ASN_SIG_CONFIRM_E;
  2124. }
  2125. }
  2126. else {
  2127. /* no signer */
  2128. CYASSL_MSG("No CA signer to verify with");
  2129. return ASN_SIG_CONFIRM_E;
  2130. }
  2131. }
  2132. if (badDate != 0)
  2133. return badDate;
  2134. return 0;
  2135. }
  2136. Signer* MakeSigner(void* heap)
  2137. {
  2138. Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
  2139. DYNAMIC_TYPE_SIGNER);
  2140. if (signer) {
  2141. signer->name = 0;
  2142. signer->publicKey = 0;
  2143. signer->next = 0;
  2144. }
  2145. (void)heap;
  2146. return signer;
  2147. }
  2148. void FreeSigners(Signer* signer, void* heap)
  2149. {
  2150. while (signer) {
  2151. Signer* next = signer->next;
  2152. XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  2153. XFREE(signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  2154. XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
  2155. signer = next;
  2156. }
  2157. (void)heap;
  2158. }
  2159. #if defined(CYASSL_KEY_GEN) || defined(CYASSL_CERT_GEN)
  2160. static int SetMyVersion(word32 version, byte* output, int header)
  2161. {
  2162. int i = 0;
  2163. if (header) {
  2164. output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  2165. output[i++] = ASN_BIT_STRING;
  2166. }
  2167. output[i++] = ASN_INTEGER;
  2168. output[i++] = 0x01;
  2169. output[i++] = (byte)version;
  2170. return i;
  2171. }
  2172. int DerToPem(const byte* der, word32 derSz, byte* output, word32 outSz,
  2173. int type)
  2174. {
  2175. char header[80];
  2176. char footer[80];
  2177. int headerLen;
  2178. int footerLen;
  2179. int i;
  2180. int err;
  2181. int outLen; /* return length or error */
  2182. if (type == CERT_TYPE) {
  2183. XSTRNCPY(header, "-----BEGIN CERTIFICATE-----\n", sizeof(header));
  2184. XSTRNCPY(footer, "-----END CERTIFICATE-----\n", sizeof(footer));
  2185. } else {
  2186. XSTRNCPY(header, "-----BEGIN RSA PRIVATE KEY-----\n", sizeof(header));
  2187. XSTRNCPY(footer, "-----END RSA PRIVATE KEY-----\n", sizeof(footer));
  2188. }
  2189. headerLen = (int)XSTRLEN(header);
  2190. footerLen = (int)XSTRLEN(footer);
  2191. if (!der || !output)
  2192. return BAD_FUNC_ARG;
  2193. /* don't even try if outSz too short */
  2194. if (outSz < headerLen + footerLen + derSz)
  2195. return BAD_FUNC_ARG;
  2196. /* header */
  2197. XMEMCPY(output, header, headerLen);
  2198. i = headerLen;
  2199. /* body */
  2200. outLen = outSz; /* input to Base64_Encode */
  2201. if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0)
  2202. return err;
  2203. i += outLen;
  2204. /* footer */
  2205. if ( (i + footerLen) > (int)outSz)
  2206. return BAD_FUNC_ARG;
  2207. XMEMCPY(output + i, footer, footerLen);
  2208. return outLen + headerLen + footerLen;
  2209. }
  2210. #endif /* CYASSL_KEY_GEN || CYASSL_CERT_GEN */
  2211. #if defined(CYASSL_KEY_GEN) && !defined(NO_RSA)
  2212. static mp_int* GetRsaInt(RsaKey* key, int idx)
  2213. {
  2214. if (idx == 0)
  2215. return &key->n;
  2216. if (idx == 1)
  2217. return &key->e;
  2218. if (idx == 2)
  2219. return &key->d;
  2220. if (idx == 3)
  2221. return &key->p;
  2222. if (idx == 4)
  2223. return &key->q;
  2224. if (idx == 5)
  2225. return &key->dP;
  2226. if (idx == 6)
  2227. return &key->dQ;
  2228. if (idx == 7)
  2229. return &key->u;
  2230. return NULL;
  2231. }
  2232. /* Release Tmp RSA resources */
  2233. static INLINE void FreeTmpRsas(byte** tmps, void* heap)
  2234. {
  2235. int i;
  2236. (void)heap;
  2237. for (i = 0; i < RSA_INTS; i++)
  2238. XFREE(tmps[i], heap, DYNAMIC_TYPE_RSA);
  2239. }
  2240. /* Convert RsaKey key to DER format, write to output (inLen), return bytes
  2241. written */
  2242. int RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
  2243. {
  2244. word32 seqSz, verSz, rawLen, intTotalLen = 0;
  2245. word32 sizes[RSA_INTS];
  2246. int i, j, outLen, ret = 0;
  2247. byte seq[MAX_SEQ_SZ];
  2248. byte ver[MAX_VERSION_SZ];
  2249. byte* tmps[RSA_INTS];
  2250. if (!key || !output)
  2251. return BAD_FUNC_ARG;
  2252. if (key->type != RSA_PRIVATE)
  2253. return BAD_FUNC_ARG;
  2254. for (i = 0; i < RSA_INTS; i++)
  2255. tmps[i] = NULL;
  2256. /* write all big ints from key to DER tmps */
  2257. for (i = 0; i < RSA_INTS; i++) {
  2258. mp_int* keyInt = GetRsaInt(key, i);
  2259. rawLen = mp_unsigned_bin_size(keyInt);
  2260. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  2261. DYNAMIC_TYPE_RSA);
  2262. if (tmps[i] == NULL) {
  2263. ret = MEMORY_E;
  2264. break;
  2265. }
  2266. tmps[i][0] = ASN_INTEGER;
  2267. sizes[i] = SetLength(rawLen, tmps[i] + 1) + 1; /* int tag */
  2268. if (sizes[i] <= MAX_SEQ_SZ) {
  2269. int err = mp_to_unsigned_bin(keyInt, tmps[i] + sizes[i]);
  2270. if (err == MP_OKAY) {
  2271. sizes[i] += rawLen;
  2272. intTotalLen += sizes[i];
  2273. }
  2274. else {
  2275. ret = err;
  2276. break;
  2277. }
  2278. }
  2279. else {
  2280. ret = ASN_INPUT_E;
  2281. break;
  2282. }
  2283. }
  2284. if (ret != 0) {
  2285. FreeTmpRsas(tmps, key->heap);
  2286. return ret;
  2287. }
  2288. /* make headers */
  2289. verSz = SetMyVersion(0, ver, FALSE);
  2290. seqSz = SetSequence(verSz + intTotalLen, seq);
  2291. outLen = seqSz + verSz + intTotalLen;
  2292. if (outLen > (int)inLen)
  2293. return BAD_FUNC_ARG;
  2294. /* write to output */
  2295. XMEMCPY(output, seq, seqSz);
  2296. j = seqSz;
  2297. XMEMCPY(output + j, ver, verSz);
  2298. j += verSz;
  2299. for (i = 0; i < RSA_INTS; i++) {
  2300. XMEMCPY(output + j, tmps[i], sizes[i]);
  2301. j += sizes[i];
  2302. }
  2303. FreeTmpRsas(tmps, key->heap);
  2304. return outLen;
  2305. }
  2306. #endif /* CYASSL_KEY_GEN && !NO_RSA */
  2307. #if defined(CYASSL_CERT_GEN) && !defined(NO_RSA)
  2308. #ifndef min
  2309. static INLINE word32 min(word32 a, word32 b)
  2310. {
  2311. return a > b ? b : a;
  2312. }
  2313. #endif /* min */
  2314. /* Initialize and Set Certficate defaults:
  2315. version = 3 (0x2)
  2316. serial = 0
  2317. sigType = SHA_WITH_RSA
  2318. issuer = blank
  2319. daysValid = 500
  2320. selfSigned = 1 (true) use subject as issuer
  2321. subject = blank
  2322. */
  2323. void InitCert(Cert* cert)
  2324. {
  2325. cert->version = 2; /* version 3 is hex 2 */
  2326. cert->sigType = CTC_SHAwRSA;
  2327. cert->daysValid = 500;
  2328. cert->selfSigned = 1;
  2329. cert->isCA = 0;
  2330. cert->bodySz = 0;
  2331. #ifdef CYASSL_ALT_NAMES
  2332. cert->altNamesSz = 0;
  2333. cert->beforeDateSz = 0;
  2334. cert->afterDateSz = 0;
  2335. #endif
  2336. cert->keyType = RSA_KEY;
  2337. XMEMSET(cert->serial, 0, CTC_SERIAL_SIZE);
  2338. cert->issuer.country[0] = '\0';
  2339. cert->issuer.state[0] = '\0';
  2340. cert->issuer.locality[0] = '\0';
  2341. cert->issuer.sur[0] = '\0';
  2342. cert->issuer.org[0] = '\0';
  2343. cert->issuer.unit[0] = '\0';
  2344. cert->issuer.commonName[0] = '\0';
  2345. cert->issuer.email[0] = '\0';
  2346. cert->subject.country[0] = '\0';
  2347. cert->subject.state[0] = '\0';
  2348. cert->subject.locality[0] = '\0';
  2349. cert->subject.sur[0] = '\0';
  2350. cert->subject.org[0] = '\0';
  2351. cert->subject.unit[0] = '\0';
  2352. cert->subject.commonName[0] = '\0';
  2353. cert->subject.email[0] = '\0';
  2354. }
  2355. /* DER encoded x509 Certificate */
  2356. typedef struct DerCert {
  2357. byte size[MAX_LENGTH_SZ]; /* length encoded */
  2358. byte version[MAX_VERSION_SZ]; /* version encoded */
  2359. byte serial[CTC_SERIAL_SIZE + MAX_LENGTH_SZ]; /* serial number encoded */
  2360. byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
  2361. byte issuer[ASN_NAME_MAX]; /* issuer encoded */
  2362. byte subject[ASN_NAME_MAX]; /* subject encoded */
  2363. byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
  2364. byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa / ntru public key encoded */
  2365. byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
  2366. byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
  2367. int sizeSz; /* encoded size length */
  2368. int versionSz; /* encoded version length */
  2369. int serialSz; /* encoded serial length */
  2370. int sigAlgoSz; /* enocded sig alog length */
  2371. int issuerSz; /* encoded issuer length */
  2372. int subjectSz; /* encoded subject length */
  2373. int validitySz; /* encoded validity length */
  2374. int publicKeySz; /* encoded public key length */
  2375. int caSz; /* encoded CA extension length */
  2376. int extensionsSz; /* encoded extensions total length */
  2377. int total; /* total encoded lengths */
  2378. } DerCert;
  2379. /* Write a set header to output */
  2380. static word32 SetSet(word32 len, byte* output)
  2381. {
  2382. output[0] = ASN_SET | ASN_CONSTRUCTED;
  2383. return SetLength(len, output + 1) + 1;
  2384. }
  2385. /* Write a serial number to output */
  2386. static int SetSerial(const byte* serial, byte* output)
  2387. {
  2388. int length = 0;
  2389. output[length++] = ASN_INTEGER;
  2390. length += SetLength(CTC_SERIAL_SIZE, &output[length]);
  2391. XMEMCPY(&output[length], serial, CTC_SERIAL_SIZE);
  2392. return length + CTC_SERIAL_SIZE;
  2393. }
  2394. /* Write a public RSA key to output */
  2395. static int SetPublicKey(byte* output, RsaKey* key)
  2396. {
  2397. byte n[MAX_RSA_INT_SZ];
  2398. byte e[MAX_RSA_E_SZ];
  2399. byte algo[MAX_ALGO_SZ];
  2400. byte seq[MAX_SEQ_SZ];
  2401. byte len[MAX_LENGTH_SZ + 1]; /* trailing 0 */
  2402. int nSz;
  2403. int eSz;
  2404. int algoSz;
  2405. int seqSz;
  2406. int lenSz;
  2407. int idx;
  2408. int rawLen;
  2409. /* n */
  2410. rawLen = mp_unsigned_bin_size(&key->n);
  2411. n[0] = ASN_INTEGER;
  2412. nSz = SetLength(rawLen, n + 1) + 1; /* int tag */
  2413. if ( (nSz + rawLen) < (int)sizeof(n)) {
  2414. int err = mp_to_unsigned_bin(&key->n, n + nSz);
  2415. if (err == MP_OKAY)
  2416. nSz += rawLen;
  2417. else
  2418. return MP_TO_E;
  2419. }
  2420. else
  2421. return BUFFER_E;
  2422. /* e */
  2423. rawLen = mp_unsigned_bin_size(&key->e);
  2424. e[0] = ASN_INTEGER;
  2425. eSz = SetLength(rawLen, e + 1) + 1; /* int tag */
  2426. if ( (eSz + rawLen) < (int)sizeof(e)) {
  2427. int err = mp_to_unsigned_bin(&key->e, e + eSz);
  2428. if (err == MP_OKAY)
  2429. eSz += rawLen;
  2430. else
  2431. return MP_TO_E;
  2432. }
  2433. else
  2434. return BUFFER_E;
  2435. /* headers */
  2436. algoSz = SetAlgoID(RSAk, algo, keyType);
  2437. seqSz = SetSequence(nSz + eSz, seq);
  2438. lenSz = SetLength(seqSz + nSz + eSz + 1, len);
  2439. len[lenSz++] = 0; /* trailing 0 */
  2440. /* write */
  2441. idx = SetSequence(nSz + eSz + seqSz + lenSz + 1 + algoSz, output);
  2442. /* 1 is for ASN_BIT_STRING */
  2443. /* algo */
  2444. XMEMCPY(output + idx, algo, algoSz);
  2445. idx += algoSz;
  2446. /* bit string */
  2447. output[idx++] = ASN_BIT_STRING;
  2448. /* length */
  2449. XMEMCPY(output + idx, len, lenSz);
  2450. idx += lenSz;
  2451. /* seq */
  2452. XMEMCPY(output + idx, seq, seqSz);
  2453. idx += seqSz;
  2454. /* n */
  2455. XMEMCPY(output + idx, n, nSz);
  2456. idx += nSz;
  2457. /* e */
  2458. XMEMCPY(output + idx, e, eSz);
  2459. idx += eSz;
  2460. return idx;
  2461. }
  2462. static INLINE byte itob(int number)
  2463. {
  2464. return (byte)number + 0x30;
  2465. }
  2466. /* write time to output, format */
  2467. static void SetTime(struct tm* date, byte* output)
  2468. {
  2469. int i = 0;
  2470. output[i++] = itob((date->tm_year % 10000) / 1000);
  2471. output[i++] = itob((date->tm_year % 1000) / 100);
  2472. output[i++] = itob((date->tm_year % 100) / 10);
  2473. output[i++] = itob( date->tm_year % 10);
  2474. output[i++] = itob(date->tm_mon / 10);
  2475. output[i++] = itob(date->tm_mon % 10);
  2476. output[i++] = itob(date->tm_mday / 10);
  2477. output[i++] = itob(date->tm_mday % 10);
  2478. output[i++] = itob(date->tm_hour / 10);
  2479. output[i++] = itob(date->tm_hour % 10);
  2480. output[i++] = itob(date->tm_min / 10);
  2481. output[i++] = itob(date->tm_min % 10);
  2482. output[i++] = itob(date->tm_sec / 10);
  2483. output[i++] = itob(date->tm_sec % 10);
  2484. output[i] = 'Z'; /* Zulu profile */
  2485. }
  2486. #ifdef CYASSL_ALT_NAMES
  2487. /* Copy Dates from cert, return bytes written */
  2488. static int CopyValidity(byte* output, Cert* cert)
  2489. {
  2490. int seqSz;
  2491. CYASSL_ENTER("CopyValidity");
  2492. /* headers and output */
  2493. seqSz = SetSequence(cert->beforeDateSz + cert->afterDateSz, output);
  2494. XMEMCPY(output + seqSz, cert->beforeDate, cert->beforeDateSz);
  2495. XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
  2496. cert->afterDateSz);
  2497. return seqSz + cert->beforeDateSz + cert->afterDateSz;
  2498. }
  2499. #endif
  2500. /* Set Date validity from now until now + daysValid */
  2501. static int SetValidity(byte* output, int daysValid)
  2502. {
  2503. byte before[MAX_DATE_SIZE];
  2504. byte after[MAX_DATE_SIZE];
  2505. int beforeSz;
  2506. int afterSz;
  2507. int seqSz;
  2508. time_t ticks;
  2509. struct tm* now;
  2510. struct tm local;
  2511. ticks = XTIME(0);
  2512. now = XGMTIME(&ticks);
  2513. /* before now */
  2514. local = *now;
  2515. before[0] = ASN_GENERALIZED_TIME;
  2516. beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
  2517. /* subtract 1 day for more compliance */
  2518. local.tm_mday -= 1;
  2519. mktime(&local);
  2520. /* adjust */
  2521. local.tm_year += 1900;
  2522. local.tm_mon += 1;
  2523. SetTime(&local, before + beforeSz);
  2524. beforeSz += ASN_GEN_TIME_SZ;
  2525. /* after now + daysValid */
  2526. local = *now;
  2527. after[0] = ASN_GENERALIZED_TIME;
  2528. afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
  2529. /* add daysValid */
  2530. local.tm_mday += daysValid;
  2531. mktime(&local);
  2532. /* adjust */
  2533. local.tm_year += 1900;
  2534. local.tm_mon += 1;
  2535. SetTime(&local, after + afterSz);
  2536. afterSz += ASN_GEN_TIME_SZ;
  2537. /* headers and output */
  2538. seqSz = SetSequence(beforeSz + afterSz, output);
  2539. XMEMCPY(output + seqSz, before, beforeSz);
  2540. XMEMCPY(output + seqSz + beforeSz, after, afterSz);
  2541. return seqSz + beforeSz + afterSz;
  2542. }
  2543. /* ASN Encoded Name field */
  2544. typedef struct EncodedName {
  2545. int nameLen; /* actual string value length */
  2546. int totalLen; /* total encoded length */
  2547. int type; /* type of name */
  2548. int used; /* are we actually using this one */
  2549. byte encoded[CTC_NAME_SIZE * 2]; /* encoding */
  2550. } EncodedName;
  2551. /* Get Which Name from index */
  2552. static const char* GetOneName(CertName* name, int idx)
  2553. {
  2554. switch (idx) {
  2555. case 0:
  2556. return name->country;
  2557. break;
  2558. case 1:
  2559. return name->state;
  2560. break;
  2561. case 2:
  2562. return name->locality;
  2563. break;
  2564. case 3:
  2565. return name->sur;
  2566. break;
  2567. case 4:
  2568. return name->org;
  2569. break;
  2570. case 5:
  2571. return name->unit;
  2572. break;
  2573. case 6:
  2574. return name->commonName;
  2575. break;
  2576. case 7:
  2577. return name->email;
  2578. break;
  2579. default:
  2580. return 0;
  2581. }
  2582. }
  2583. /* Get ASN Name from index */
  2584. static byte GetNameId(int idx)
  2585. {
  2586. switch (idx) {
  2587. case 0:
  2588. return ASN_COUNTRY_NAME;
  2589. break;
  2590. case 1:
  2591. return ASN_STATE_NAME;
  2592. break;
  2593. case 2:
  2594. return ASN_LOCALITY_NAME;
  2595. break;
  2596. case 3:
  2597. return ASN_SUR_NAME;
  2598. break;
  2599. case 4:
  2600. return ASN_ORG_NAME;
  2601. break;
  2602. case 5:
  2603. return ASN_ORGUNIT_NAME;
  2604. break;
  2605. case 6:
  2606. return ASN_COMMON_NAME;
  2607. break;
  2608. case 7:
  2609. /* email uses different id type */
  2610. return 0;
  2611. break;
  2612. default:
  2613. return 0;
  2614. }
  2615. }
  2616. /* encode all extensions, return total bytes written */
  2617. static int SetExtensions(byte* output, const byte* ext, int extSz)
  2618. {
  2619. byte sequence[MAX_SEQ_SZ];
  2620. byte len[MAX_LENGTH_SZ];
  2621. int sz = 0;
  2622. int seqSz = SetSequence(extSz, sequence);
  2623. int lenSz = SetLength(seqSz + extSz, len);
  2624. output[0] = ASN_EXTENSIONS; /* extensions id */
  2625. sz++;
  2626. XMEMCPY(&output[sz], len, lenSz); /* length */
  2627. sz += lenSz;
  2628. XMEMCPY(&output[sz], sequence, seqSz); /* sequence */
  2629. sz += seqSz;
  2630. XMEMCPY(&output[sz], ext, extSz); /* extensions */
  2631. sz += extSz;
  2632. return sz;
  2633. }
  2634. /* encode CA basic constraint true, return total bytes written */
  2635. static int SetCa(byte* output)
  2636. {
  2637. static const byte ca[] = { 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  2638. 0x05, 0x30, 0x03, 0x01, 0x01, 0xff };
  2639. XMEMCPY(output, ca, sizeof(ca));
  2640. return (int)sizeof(ca);
  2641. }
  2642. /* encode CertName into output, return total bytes written */
  2643. static int SetName(byte* output, CertName* name)
  2644. {
  2645. int totalBytes = 0, i, idx;
  2646. EncodedName names[NAME_ENTRIES];
  2647. for (i = 0; i < NAME_ENTRIES; i++) {
  2648. const char* nameStr = GetOneName(name, i);
  2649. if (nameStr) {
  2650. /* bottom up */
  2651. byte firstLen[MAX_LENGTH_SZ];
  2652. byte secondLen[MAX_LENGTH_SZ];
  2653. byte sequence[MAX_SEQ_SZ];
  2654. byte set[MAX_SET_SZ];
  2655. int email = i == (NAME_ENTRIES - 1) ? 1 : 0;
  2656. int strLen = (int)XSTRLEN(nameStr);
  2657. int thisLen = strLen;
  2658. int firstSz, secondSz, seqSz, setSz;
  2659. if (strLen == 0) { /* no user data for this item */
  2660. names[i].used = 0;
  2661. continue;
  2662. }
  2663. secondSz = SetLength(strLen, secondLen);
  2664. thisLen += secondSz;
  2665. if (email) {
  2666. thisLen += EMAIL_JOINT_LEN;
  2667. thisLen ++; /* id type */
  2668. firstSz = SetLength(EMAIL_JOINT_LEN, firstLen);
  2669. }
  2670. else {
  2671. thisLen++; /* str type */
  2672. thisLen++; /* id type */
  2673. thisLen += JOINT_LEN;
  2674. firstSz = SetLength(JOINT_LEN + 1, firstLen);
  2675. }
  2676. thisLen += firstSz;
  2677. thisLen++; /* object id */
  2678. seqSz = SetSequence(thisLen, sequence);
  2679. thisLen += seqSz;
  2680. setSz = SetSet(thisLen, set);
  2681. thisLen += setSz;
  2682. if (thisLen > (int)sizeof(names[i].encoded))
  2683. return BUFFER_E;
  2684. /* store it */
  2685. idx = 0;
  2686. /* set */
  2687. XMEMCPY(names[i].encoded, set, setSz);
  2688. idx += setSz;
  2689. /* seq */
  2690. XMEMCPY(names[i].encoded + idx, sequence, seqSz);
  2691. idx += seqSz;
  2692. /* asn object id */
  2693. names[i].encoded[idx++] = ASN_OBJECT_ID;
  2694. /* first length */
  2695. XMEMCPY(names[i].encoded + idx, firstLen, firstSz);
  2696. idx += firstSz;
  2697. if (email) {
  2698. const byte EMAIL_OID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  2699. 0x01, 0x09, 0x01, 0x16 };
  2700. /* email joint id */
  2701. XMEMCPY(names[i].encoded + idx, EMAIL_OID, sizeof(EMAIL_OID));
  2702. idx += (int)sizeof(EMAIL_OID);
  2703. }
  2704. else {
  2705. /* joint id */
  2706. names[i].encoded[idx++] = 0x55;
  2707. names[i].encoded[idx++] = 0x04;
  2708. /* id type */
  2709. names[i].encoded[idx++] = GetNameId(i);
  2710. /* str type */
  2711. names[i].encoded[idx++] = 0x13;
  2712. }
  2713. /* second length */
  2714. XMEMCPY(names[i].encoded + idx, secondLen, secondSz);
  2715. idx += secondSz;
  2716. /* str value */
  2717. XMEMCPY(names[i].encoded + idx, nameStr, strLen);
  2718. idx += strLen;
  2719. totalBytes += idx;
  2720. names[i].totalLen = idx;
  2721. names[i].used = 1;
  2722. }
  2723. else
  2724. names[i].used = 0;
  2725. }
  2726. /* header */
  2727. idx = SetSequence(totalBytes, output);
  2728. totalBytes += idx;
  2729. if (totalBytes > ASN_NAME_MAX)
  2730. return BUFFER_E;
  2731. for (i = 0; i < NAME_ENTRIES; i++) {
  2732. if (names[i].used) {
  2733. XMEMCPY(output + idx, names[i].encoded, names[i].totalLen);
  2734. idx += names[i].totalLen;
  2735. }
  2736. }
  2737. return totalBytes;
  2738. }
  2739. /* encode info from cert into DER enocder format */
  2740. static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, RNG* rng,
  2741. const byte* ntruKey, word16 ntruSz)
  2742. {
  2743. (void)ntruKey;
  2744. (void)ntruSz;
  2745. /* version */
  2746. der->versionSz = SetMyVersion(cert->version, der->version, TRUE);
  2747. /* serial number */
  2748. RNG_GenerateBlock(rng, cert->serial, CTC_SERIAL_SIZE);
  2749. cert->serial[0] = 0x01; /* ensure positive */
  2750. der->serialSz = SetSerial(cert->serial, der->serial);
  2751. /* signature algo */
  2752. der->sigAlgoSz = SetAlgoID(cert->sigType, der->sigAlgo, sigType);
  2753. if (der->sigAlgoSz == 0)
  2754. return ALGO_ID_E;
  2755. /* public key */
  2756. if (cert->keyType == RSA_KEY) {
  2757. der->publicKeySz = SetPublicKey(der->publicKey, rsaKey);
  2758. if (der->publicKeySz == 0)
  2759. return PUBLIC_KEY_E;
  2760. }
  2761. else {
  2762. #ifdef HAVE_NTRU
  2763. word32 rc;
  2764. word16 encodedSz;
  2765. rc = crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo( ntruSz,
  2766. ntruKey, &encodedSz, NULL);
  2767. if (rc != NTRU_OK)
  2768. return PUBLIC_KEY_E;
  2769. if (encodedSz > MAX_PUBLIC_KEY_SZ)
  2770. return PUBLIC_KEY_E;
  2771. rc = crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo( ntruSz,
  2772. ntruKey, &encodedSz, der->publicKey);
  2773. if (rc != NTRU_OK)
  2774. return PUBLIC_KEY_E;
  2775. der->publicKeySz = encodedSz;
  2776. #endif
  2777. }
  2778. der->validitySz = 0;
  2779. #ifdef CYASSL_ALT_NAMES
  2780. /* date validity copy ? */
  2781. if (cert->beforeDateSz && cert->afterDateSz) {
  2782. der->validitySz = CopyValidity(der->validity, cert);
  2783. if (der->validitySz == 0)
  2784. return DATE_E;
  2785. }
  2786. #endif
  2787. /* date validity */
  2788. if (der->validitySz == 0) {
  2789. der->validitySz = SetValidity(der->validity, cert->daysValid);
  2790. if (der->validitySz == 0)
  2791. return DATE_E;
  2792. }
  2793. /* subject name */
  2794. der->subjectSz = SetName(der->subject, &cert->subject);
  2795. if (der->subjectSz == 0)
  2796. return SUBJECT_E;
  2797. /* issuer name */
  2798. der->issuerSz = SetName(der->issuer, cert->selfSigned ?
  2799. &cert->subject : &cert->issuer);
  2800. if (der->issuerSz == 0)
  2801. return ISSUER_E;
  2802. /* CA */
  2803. if (cert->isCA) {
  2804. der->caSz = SetCa(der->ca);
  2805. if (der->caSz == 0)
  2806. return CA_TRUE_E;
  2807. }
  2808. else
  2809. der->caSz = 0;
  2810. /* extensions, just CA now */
  2811. if (cert->isCA) {
  2812. der->extensionsSz = SetExtensions(der->extensions, der->ca, der->caSz);
  2813. if (der->extensionsSz == 0)
  2814. return EXTENSIONS_E;
  2815. }
  2816. else
  2817. der->extensionsSz = 0;
  2818. #ifdef CYASSL_ALT_NAMES
  2819. if (der->extensionsSz == 0 && cert->altNamesSz) {
  2820. der->extensionsSz = SetExtensions(der->extensions, cert->altNames,
  2821. cert->altNamesSz);
  2822. if (der->extensionsSz == 0)
  2823. return EXTENSIONS_E;
  2824. }
  2825. #endif
  2826. der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
  2827. der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
  2828. der->extensionsSz;
  2829. return 0;
  2830. }
  2831. /* write DER encoded cert to buffer, size already checked */
  2832. static int WriteCertBody(DerCert* der, byte* buffer)
  2833. {
  2834. int idx;
  2835. /* signed part header */
  2836. idx = SetSequence(der->total, buffer);
  2837. /* version */
  2838. XMEMCPY(buffer + idx, der->version, der->versionSz);
  2839. idx += der->versionSz;
  2840. /* serial */
  2841. XMEMCPY(buffer + idx, der->serial, der->serialSz);
  2842. idx += der->serialSz;
  2843. /* sig algo */
  2844. XMEMCPY(buffer + idx, der->sigAlgo, der->sigAlgoSz);
  2845. idx += der->sigAlgoSz;
  2846. /* issuer */
  2847. XMEMCPY(buffer + idx, der->issuer, der->issuerSz);
  2848. idx += der->issuerSz;
  2849. /* validity */
  2850. XMEMCPY(buffer + idx, der->validity, der->validitySz);
  2851. idx += der->validitySz;
  2852. /* subject */
  2853. XMEMCPY(buffer + idx, der->subject, der->subjectSz);
  2854. idx += der->subjectSz;
  2855. /* public key */
  2856. XMEMCPY(buffer + idx, der->publicKey, der->publicKeySz);
  2857. idx += der->publicKeySz;
  2858. if (der->extensionsSz) {
  2859. /* extensions */
  2860. XMEMCPY(buffer + idx, der->extensions, min(der->extensionsSz,
  2861. sizeof(der->extensions)));
  2862. idx += der->extensionsSz;
  2863. }
  2864. return idx;
  2865. }
  2866. /* Make RSA signature from buffer (sz), write to sig (sigSz) */
  2867. static int MakeSignature(const byte* buffer, int sz, byte* sig, int sigSz,
  2868. RsaKey* key, RNG* rng, int sigAlgoType)
  2869. {
  2870. byte digest[SHA256_DIGEST_SIZE]; /* max size */
  2871. byte encSig[MAX_ENCODED_DIG_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ];
  2872. int encSigSz, digestSz, typeH;
  2873. if (sigAlgoType == CTC_MD5wRSA) {
  2874. Md5 md5;
  2875. InitMd5(&md5);
  2876. Md5Update(&md5, buffer, sz);
  2877. Md5Final(&md5, digest);
  2878. digestSz = MD5_DIGEST_SIZE;
  2879. typeH = MD5h;
  2880. }
  2881. else if (sigAlgoType == CTC_SHAwRSA) {
  2882. Sha sha;
  2883. InitSha(&sha);
  2884. ShaUpdate(&sha, buffer, sz);
  2885. ShaFinal(&sha, digest);
  2886. digestSz = SHA_DIGEST_SIZE;
  2887. typeH = SHAh;
  2888. }
  2889. else if (sigAlgoType == CTC_SHA256wRSA) {
  2890. Sha256 sha256;
  2891. InitSha256(&sha256);
  2892. Sha256Update(&sha256, buffer, sz);
  2893. Sha256Final(&sha256, digest);
  2894. digestSz = SHA256_DIGEST_SIZE;
  2895. typeH = SHA256h;
  2896. }
  2897. else
  2898. return ALGO_ID_E;
  2899. /* signature */
  2900. encSigSz = EncodeSignature(encSig, digest, digestSz, typeH);
  2901. return RsaSSL_Sign(encSig, encSigSz, sig, sigSz, key, rng);
  2902. }
  2903. /* add signature to end of buffer, size of buffer assumed checked, return
  2904. new length */
  2905. static int AddSignature(byte* buffer, int bodySz, const byte* sig, int sigSz,
  2906. int sigAlgoType)
  2907. {
  2908. byte seq[MAX_SEQ_SZ];
  2909. int idx = bodySz, seqSz;
  2910. /* algo */
  2911. idx += SetAlgoID(sigAlgoType, buffer + idx, sigType);
  2912. /* bit string */
  2913. buffer[idx++] = ASN_BIT_STRING;
  2914. /* length */
  2915. idx += SetLength(sigSz + 1, buffer + idx);
  2916. buffer[idx++] = 0; /* trailing 0 */
  2917. /* signature */
  2918. XMEMCPY(buffer + idx, sig, sigSz);
  2919. idx += sigSz;
  2920. /* make room for overall header */
  2921. seqSz = SetSequence(idx, seq);
  2922. XMEMMOVE(buffer + seqSz, buffer, idx);
  2923. XMEMCPY(buffer, seq, seqSz);
  2924. return idx + seqSz;
  2925. }
  2926. /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
  2927. static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
  2928. RsaKey* rsaKey, RNG* rng, const byte* ntruKey, word16 ntruSz)
  2929. {
  2930. DerCert der;
  2931. int ret;
  2932. cert->keyType = rsaKey ? RSA_KEY : NTRU_KEY;
  2933. ret = EncodeCert(cert, &der, rsaKey, rng, ntruKey, ntruSz);
  2934. if (ret != 0)
  2935. return ret;
  2936. if (der.total + MAX_SEQ_SZ * 2 > (int)derSz)
  2937. return BUFFER_E;
  2938. return cert->bodySz = WriteCertBody(&der, derBuffer);
  2939. }
  2940. /* Make an x509 Certificate v3 RSA from cert input, write to buffer */
  2941. int MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,RNG* rng)
  2942. {
  2943. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, rng, NULL, 0);
  2944. }
  2945. #ifdef HAVE_NTRU
  2946. int MakeNtruCert(Cert* cert, byte* derBuffer, word32 derSz,
  2947. const byte* ntruKey, word16 keySz, RNG* rng)
  2948. {
  2949. return MakeAnyCert(cert, derBuffer, derSz, NULL, rng, ntruKey, keySz);
  2950. }
  2951. #endif /* HAVE_NTRU */
  2952. int SignCert(Cert* cert, byte* buffer, word32 buffSz, RsaKey* key, RNG* rng)
  2953. {
  2954. byte sig[MAX_ENCODED_SIG_SZ];
  2955. int sigSz;
  2956. int bodySz = cert->bodySz;
  2957. if (bodySz < 0)
  2958. return bodySz;
  2959. sigSz = MakeSignature(buffer, bodySz, sig, sizeof(sig), key, rng,
  2960. cert->sigType);
  2961. if (sigSz < 0)
  2962. return sigSz;
  2963. if (bodySz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
  2964. return BUFFER_E;
  2965. return AddSignature(buffer, bodySz, sig, sigSz, cert->sigType);
  2966. }
  2967. int MakeSelfCert(Cert* cert, byte* buffer, word32 buffSz, RsaKey* key, RNG* rng)
  2968. {
  2969. int ret = MakeCert(cert, buffer, buffSz, key, rng);
  2970. if (ret < 0)
  2971. return ret;
  2972. return SignCert(cert, buffer, buffSz, key, rng);
  2973. }
  2974. #ifdef CYASSL_ALT_NAMES
  2975. /* Set Alt Names from der cert, return 0 on success */
  2976. static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz)
  2977. {
  2978. DecodedCert decoded;
  2979. int ret;
  2980. if (derSz < 0)
  2981. return derSz;
  2982. InitDecodedCert(&decoded, (byte*)der, derSz, 0);
  2983. ret = ParseCertRelative(&decoded, CA_TYPE, NO_VERIFY, 0);
  2984. if (ret < 0) {
  2985. FreeDecodedCert(&decoded);
  2986. return ret;
  2987. }
  2988. if (decoded.extensions) {
  2989. byte b;
  2990. int length;
  2991. word32 maxExtensionsIdx;
  2992. decoded.srcIdx = decoded.extensionsIdx;
  2993. b = decoded.source[decoded.srcIdx++];
  2994. if (b != ASN_EXTENSIONS) {
  2995. FreeDecodedCert(&decoded);
  2996. return ASN_PARSE_E;
  2997. }
  2998. if (GetLength(decoded.source, &decoded.srcIdx, &length,
  2999. decoded.maxIdx) < 0) {
  3000. FreeDecodedCert(&decoded);
  3001. return ASN_PARSE_E;
  3002. }
  3003. if (GetSequence(decoded.source, &decoded.srcIdx, &length,
  3004. decoded.maxIdx) < 0) {
  3005. FreeDecodedCert(&decoded);
  3006. return ASN_PARSE_E;
  3007. }
  3008. maxExtensionsIdx = decoded.srcIdx + length;
  3009. while (decoded.srcIdx < maxExtensionsIdx) {
  3010. word32 oid;
  3011. word32 startIdx = decoded.srcIdx;
  3012. word32 tmpIdx;
  3013. if (GetSequence(decoded.source, &decoded.srcIdx, &length,
  3014. decoded.maxIdx) < 0) {
  3015. FreeDecodedCert(&decoded);
  3016. return ASN_PARSE_E;
  3017. }
  3018. tmpIdx = decoded.srcIdx;
  3019. decoded.srcIdx = startIdx;
  3020. if (GetAlgoId(decoded.source, &decoded.srcIdx, &oid,
  3021. decoded.maxIdx) < 0) {
  3022. FreeDecodedCert(&decoded);
  3023. return ASN_PARSE_E;
  3024. }
  3025. if (oid == ALT_NAMES_OID) {
  3026. cert->altNamesSz = length + (tmpIdx - startIdx);
  3027. if (cert->altNamesSz < (int)sizeof(cert->altNames))
  3028. XMEMCPY(cert->altNames, &decoded.source[startIdx],
  3029. cert->altNamesSz);
  3030. else {
  3031. cert->altNamesSz = 0;
  3032. CYASSL_MSG("AltNames extensions too big");
  3033. FreeDecodedCert(&decoded);
  3034. return ALT_NAME_E;
  3035. }
  3036. }
  3037. decoded.srcIdx = tmpIdx + length;
  3038. }
  3039. }
  3040. FreeDecodedCert(&decoded);
  3041. return 0;
  3042. }
  3043. /* Set Dates from der cert, return 0 on success */
  3044. static int SetDatesFromCert(Cert* cert, const byte* der, int derSz)
  3045. {
  3046. DecodedCert decoded;
  3047. int ret;
  3048. CYASSL_ENTER("SetDatesFromCert");
  3049. if (derSz < 0)
  3050. return derSz;
  3051. InitDecodedCert(&decoded, (byte*)der, derSz, 0);
  3052. ret = ParseCertRelative(&decoded, CA_TYPE, NO_VERIFY, 0);
  3053. if (ret < 0) {
  3054. CYASSL_MSG("ParseCertRelative error");
  3055. FreeDecodedCert(&decoded);
  3056. return ret;
  3057. }
  3058. if (decoded.beforeDate == NULL || decoded.afterDate == NULL) {
  3059. CYASSL_MSG("Couldn't extract dates");
  3060. FreeDecodedCert(&decoded);
  3061. return -1;
  3062. }
  3063. if (decoded.beforeDateLen > MAX_DATE_SIZE || decoded.afterDateLen >
  3064. MAX_DATE_SIZE) {
  3065. CYASSL_MSG("Bad date size");
  3066. FreeDecodedCert(&decoded);
  3067. return -1;
  3068. }
  3069. XMEMCPY(cert->beforeDate, decoded.beforeDate, decoded.beforeDateLen);
  3070. XMEMCPY(cert->afterDate, decoded.afterDate, decoded.afterDateLen);
  3071. cert->beforeDateSz = decoded.beforeDateLen;
  3072. cert->afterDateSz = decoded.afterDateLen;
  3073. return 0;
  3074. }
  3075. #endif /* CYASSL_ALT_NAMES && !NO_RSA */
  3076. /* Set cn name from der buffer, return 0 on success */
  3077. static int SetNameFromCert(CertName* cn, const byte* der, int derSz)
  3078. {
  3079. DecodedCert decoded;
  3080. int ret;
  3081. int sz;
  3082. if (derSz < 0)
  3083. return derSz;
  3084. InitDecodedCert(&decoded, (byte*)der, derSz, 0);
  3085. ret = ParseCertRelative(&decoded, CA_TYPE, NO_VERIFY, 0);
  3086. if (ret < 0)
  3087. return ret;
  3088. if (decoded.subjectCN) {
  3089. sz = (decoded.subjectCNLen < CTC_NAME_SIZE) ? decoded.subjectCNLen :
  3090. CTC_NAME_SIZE - 1;
  3091. strncpy(cn->commonName, decoded.subjectCN, CTC_NAME_SIZE);
  3092. cn->commonName[sz] = 0;
  3093. }
  3094. if (decoded.subjectC) {
  3095. sz = (decoded.subjectCLen < CTC_NAME_SIZE) ? decoded.subjectCLen :
  3096. CTC_NAME_SIZE - 1;
  3097. strncpy(cn->country, decoded.subjectC, CTC_NAME_SIZE);
  3098. cn->country[sz] = 0;
  3099. }
  3100. if (decoded.subjectST) {
  3101. sz = (decoded.subjectSTLen < CTC_NAME_SIZE) ? decoded.subjectSTLen :
  3102. CTC_NAME_SIZE - 1;
  3103. strncpy(cn->state, decoded.subjectST, CTC_NAME_SIZE);
  3104. cn->state[sz] = 0;
  3105. }
  3106. if (decoded.subjectL) {
  3107. sz = (decoded.subjectLLen < CTC_NAME_SIZE) ? decoded.subjectLLen :
  3108. CTC_NAME_SIZE - 1;
  3109. strncpy(cn->locality, decoded.subjectL, CTC_NAME_SIZE);
  3110. cn->locality[sz] = 0;
  3111. }
  3112. if (decoded.subjectO) {
  3113. sz = (decoded.subjectOLen < CTC_NAME_SIZE) ? decoded.subjectOLen :
  3114. CTC_NAME_SIZE - 1;
  3115. strncpy(cn->org, decoded.subjectO, CTC_NAME_SIZE);
  3116. cn->org[sz] = 0;
  3117. }
  3118. if (decoded.subjectOU) {
  3119. sz = (decoded.subjectOULen < CTC_NAME_SIZE) ? decoded.subjectOULen :
  3120. CTC_NAME_SIZE - 1;
  3121. strncpy(cn->unit, decoded.subjectOU, CTC_NAME_SIZE);
  3122. cn->unit[sz] = 0;
  3123. }
  3124. if (decoded.subjectSN) {
  3125. sz = (decoded.subjectSNLen < CTC_NAME_SIZE) ? decoded.subjectSNLen :
  3126. CTC_NAME_SIZE - 1;
  3127. strncpy(cn->sur, decoded.subjectSN, CTC_NAME_SIZE);
  3128. cn->sur[sz] = 0;
  3129. }
  3130. if (decoded.subjectEmail) {
  3131. sz = (decoded.subjectEmailLen < CTC_NAME_SIZE) ?
  3132. decoded.subjectEmailLen : CTC_NAME_SIZE - 1;
  3133. strncpy(cn->email, decoded.subjectEmail, CTC_NAME_SIZE);
  3134. cn->email[sz] = 0;
  3135. }
  3136. FreeDecodedCert(&decoded);
  3137. return 0;
  3138. }
  3139. #ifndef NO_FILESYSTEM
  3140. /* forward from CyaSSL */
  3141. int CyaSSL_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz);
  3142. /* Set cert issuer from issuerFile in PEM */
  3143. int SetIssuer(Cert* cert, const char* issuerFile)
  3144. {
  3145. int ret;
  3146. int derSz;
  3147. byte* der = (byte*)XMALLOC(EIGHTK_BUF, NULL, DYNAMIC_TYPE_CERT);
  3148. if (der == NULL) {
  3149. CYASSL_MSG("SetIssuer OOF Problem");
  3150. return MEMORY_E;
  3151. }
  3152. derSz = CyaSSL_PemCertToDer(issuerFile, der, EIGHTK_BUF);
  3153. cert->selfSigned = 0;
  3154. ret = SetNameFromCert(&cert->issuer, der, derSz);
  3155. XFREE(der, NULL, DYNAMIC_TYPE_CERT);
  3156. return ret;
  3157. }
  3158. /* Set cert subject from subjectFile in PEM */
  3159. int SetSubject(Cert* cert, const char* subjectFile)
  3160. {
  3161. int ret;
  3162. int derSz;
  3163. byte* der = (byte*)XMALLOC(EIGHTK_BUF, NULL, DYNAMIC_TYPE_CERT);
  3164. if (der == NULL) {
  3165. CYASSL_MSG("SetSubject OOF Problem");
  3166. return MEMORY_E;
  3167. }
  3168. derSz = CyaSSL_PemCertToDer(subjectFile, der, EIGHTK_BUF);
  3169. ret = SetNameFromCert(&cert->subject, der, derSz);
  3170. XFREE(der, NULL, DYNAMIC_TYPE_CERT);
  3171. return ret;
  3172. }
  3173. #ifdef CYASSL_ALT_NAMES
  3174. /* Set atl names from file in PEM */
  3175. int SetAltNames(Cert* cert, const char* file)
  3176. {
  3177. int ret;
  3178. int derSz;
  3179. byte* der = (byte*)XMALLOC(EIGHTK_BUF, NULL, DYNAMIC_TYPE_CERT);
  3180. if (der == NULL) {
  3181. CYASSL_MSG("SetAltNames OOF Problem");
  3182. return MEMORY_E;
  3183. }
  3184. derSz = CyaSSL_PemCertToDer(file, der, EIGHTK_BUF);
  3185. ret = SetAltNamesFromCert(cert, der, derSz);
  3186. XFREE(der, NULL, DYNAMIC_TYPE_CERT);
  3187. return ret;
  3188. }
  3189. #endif /* CYASSL_ALT_NAMES */
  3190. #endif /* NO_FILESYSTEM */
  3191. /* Set cert issuer from DER buffer */
  3192. int SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
  3193. {
  3194. cert->selfSigned = 0;
  3195. return SetNameFromCert(&cert->issuer, der, derSz);
  3196. }
  3197. /* Set cert subject from DER buffer */
  3198. int SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
  3199. {
  3200. return SetNameFromCert(&cert->subject, der, derSz);
  3201. }
  3202. #ifdef CYASSL_ALT_NAMES
  3203. /* Set cert alt names from DER buffer */
  3204. int SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
  3205. {
  3206. return SetAltNamesFromCert(cert, der, derSz);
  3207. }
  3208. /* Set cert dates from DER buffer */
  3209. int SetDatesBuffer(Cert* cert, const byte* der, int derSz)
  3210. {
  3211. return SetDatesFromCert(cert, der, derSz);
  3212. }
  3213. #endif /* CYASSL_ALT_NAMES */
  3214. #endif /* CYASSL_CERT_GEN */
  3215. #ifdef HAVE_ECC
  3216. /* Der Encode r & s ints into out, outLen is (in/out) size */
  3217. int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
  3218. {
  3219. word32 idx = 0;
  3220. word32 rSz; /* encoding size */
  3221. word32 sSz;
  3222. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  3223. int rLen = mp_unsigned_bin_size(r); /* big int size */
  3224. int sLen = mp_unsigned_bin_size(s);
  3225. int err;
  3226. if (*outLen < (rLen + sLen + headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
  3227. return BAD_FUNC_ARG;
  3228. idx = SetSequence(rLen + sLen + headerSz, out);
  3229. /* store r */
  3230. out[idx++] = ASN_INTEGER;
  3231. rSz = SetLength(rLen, &out[idx]);
  3232. idx += rSz;
  3233. err = mp_to_unsigned_bin(r, &out[idx]);
  3234. if (err != MP_OKAY) return err;
  3235. idx += rLen;
  3236. /* store s */
  3237. out[idx++] = ASN_INTEGER;
  3238. sSz = SetLength(sLen, &out[idx]);
  3239. idx += sSz;
  3240. err = mp_to_unsigned_bin(s, &out[idx]);
  3241. if (err != MP_OKAY) return err;
  3242. idx += sLen;
  3243. *outLen = idx;
  3244. return 0;
  3245. }
  3246. /* Der Decode ECC-DSA Signautre, r & s stored as big ints */
  3247. int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
  3248. {
  3249. word32 idx = 0;
  3250. int len = 0;
  3251. if (GetSequence(sig, &idx, &len, sigLen) < 0)
  3252. return ASN_ECC_KEY_E;
  3253. if ((word32)len > (sigLen - idx))
  3254. return ASN_ECC_KEY_E;
  3255. if (GetInt(r, sig, &idx, sigLen) < 0)
  3256. return ASN_ECC_KEY_E;
  3257. if (GetInt(s, sig, &idx, sigLen) < 0)
  3258. return ASN_ECC_KEY_E;
  3259. return 0;
  3260. }
  3261. int EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
  3262. word32 inSz)
  3263. {
  3264. word32 oid = 0;
  3265. int version, length;
  3266. int privSz, pubSz;
  3267. byte b;
  3268. byte priv[ECC_MAXSIZE];
  3269. byte pub[ECC_MAXSIZE * 2 + 1]; /* public key has two parts plus header */
  3270. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  3271. return ASN_PARSE_E;
  3272. if (GetMyVersion(input, inOutIdx, &version) < 0)
  3273. return ASN_PARSE_E;
  3274. b = input[*inOutIdx];
  3275. *inOutIdx += 1;
  3276. /* priv type */
  3277. if (b != 4 && b != 6 && b != 7)
  3278. return ASN_PARSE_E;
  3279. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  3280. return ASN_PARSE_E;
  3281. /* priv key */
  3282. privSz = length;
  3283. XMEMCPY(priv, &input[*inOutIdx], privSz);
  3284. *inOutIdx += length;
  3285. /* prefix 0, may have */
  3286. b = input[*inOutIdx];
  3287. if (b == ECC_PREFIX_0) {
  3288. *inOutIdx += 1;
  3289. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  3290. return ASN_PARSE_E;
  3291. /* object id */
  3292. b = input[*inOutIdx];
  3293. *inOutIdx += 1;
  3294. if (b != ASN_OBJECT_ID)
  3295. return ASN_OBJECT_ID_E;
  3296. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  3297. return ASN_PARSE_E;
  3298. while(length--) {
  3299. oid += input[*inOutIdx];
  3300. *inOutIdx += 1;
  3301. }
  3302. if (CheckCurve(oid) < 0)
  3303. return ECC_CURVE_OID_E;
  3304. }
  3305. /* prefix 1 */
  3306. b = input[*inOutIdx];
  3307. *inOutIdx += 1;
  3308. if (b != ECC_PREFIX_1)
  3309. return ASN_ECC_KEY_E;
  3310. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  3311. return ASN_PARSE_E;
  3312. /* key header */
  3313. b = input[*inOutIdx];
  3314. *inOutIdx += 1;
  3315. if (b != ASN_BIT_STRING)
  3316. return ASN_BITSTR_E;
  3317. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  3318. return ASN_PARSE_E;
  3319. b = input[*inOutIdx];
  3320. *inOutIdx += 1;
  3321. if (b != 0x00)
  3322. return ASN_EXPECT_0_E;
  3323. pubSz = length - 1; /* null prefix */
  3324. XMEMCPY(pub, &input[*inOutIdx], pubSz);
  3325. *inOutIdx += length;
  3326. return ecc_import_private_key(priv, privSz, pub, pubSz, key);
  3327. }
  3328. #endif /* HAVE_ECC */
  3329. #if defined(HAVE_OCSP) || defined(HAVE_CRL)
  3330. /* Get raw Date only, no processing, 0 on success */
  3331. static int GetBasicDate(const byte* source, word32* idx, byte* date,
  3332. byte* format, int maxIdx)
  3333. {
  3334. int length;
  3335. CYASSL_ENTER("GetBasicDate");
  3336. *format = source[*idx];
  3337. *idx += 1;
  3338. if (*format != ASN_UTC_TIME && *format != ASN_GENERALIZED_TIME)
  3339. return ASN_TIME_E;
  3340. if (GetLength(source, idx, &length, maxIdx) < 0)
  3341. return ASN_PARSE_E;
  3342. if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
  3343. return ASN_DATE_SZ_E;
  3344. XMEMCPY(date, &source[*idx], length);
  3345. *idx += length;
  3346. return 0;
  3347. }
  3348. #endif
  3349. #ifdef HAVE_OCSP
  3350. static int GetEnumerated(const byte* input, word32* inOutIdx, int *value)
  3351. {
  3352. word32 idx = *inOutIdx;
  3353. word32 len;
  3354. CYASSL_ENTER("GetEnumerated");
  3355. *value = 0;
  3356. if (input[idx++] != ASN_ENUMERATED)
  3357. return ASN_PARSE_E;
  3358. len = input[idx++];
  3359. if (len > 4)
  3360. return ASN_PARSE_E;
  3361. while (len--) {
  3362. *value = *value << 8 | input[idx++];
  3363. }
  3364. *inOutIdx = idx;
  3365. return *value;
  3366. }
  3367. static int DecodeSingleResponse(byte* source,
  3368. word32* ioIndex, OcspResponse* resp, word32 size)
  3369. {
  3370. word32 idx = *ioIndex, prevIndex, oid;
  3371. int length, wrapperSz;
  3372. CertStatus* cs = resp->status;
  3373. CYASSL_ENTER("DecodeSingleResponse");
  3374. /* Outer wrapper of the SEQUENCE OF Single Responses. */
  3375. if (GetSequence(source, &idx, &wrapperSz, size) < 0)
  3376. return ASN_PARSE_E;
  3377. prevIndex = idx;
  3378. /* When making a request, we only request one status on one certificate
  3379. * at a time. There should only be one SingleResponse */
  3380. /* Wrapper around the Single Response */
  3381. if (GetSequence(source, &idx, &length, size) < 0)
  3382. return ASN_PARSE_E;
  3383. /* Wrapper around the CertID */
  3384. if (GetSequence(source, &idx, &length, size) < 0)
  3385. return ASN_PARSE_E;
  3386. /* Skip the hash algorithm */
  3387. if (GetAlgoId(source, &idx, &oid, size) < 0)
  3388. return ASN_PARSE_E;
  3389. /* Save reference to the hash of CN */
  3390. if (source[idx++] != ASN_OCTET_STRING)
  3391. return ASN_PARSE_E;
  3392. if (GetLength(source, &idx, &length, size) < 0)
  3393. return ASN_PARSE_E;
  3394. resp->issuerHash = source + idx;
  3395. idx += length;
  3396. /* Save reference to the hash of the issuer public key */
  3397. if (source[idx++] != ASN_OCTET_STRING)
  3398. return ASN_PARSE_E;
  3399. if (GetLength(source, &idx, &length, size) < 0)
  3400. return ASN_PARSE_E;
  3401. resp->issuerKeyHash = source + idx;
  3402. idx += length;
  3403. /* Read the serial number, it is handled as a string, not as a
  3404. * proper number. Just XMEMCPY the data over, rather than load it
  3405. * as an mp_int. */
  3406. if (source[idx++] != ASN_INTEGER)
  3407. return ASN_PARSE_E;
  3408. if (GetLength(source, &idx, &length, size) < 0)
  3409. return ASN_PARSE_E;
  3410. if (length <= EXTERNAL_SERIAL_SIZE)
  3411. {
  3412. if (source[idx] == 0)
  3413. {
  3414. idx++;
  3415. length--;
  3416. }
  3417. XMEMCPY(cs->serial, source + idx, length);
  3418. cs->serialSz = length;
  3419. }
  3420. else
  3421. {
  3422. return ASN_GETINT_E;
  3423. }
  3424. idx += length;
  3425. /* CertStatus */
  3426. switch (source[idx++])
  3427. {
  3428. case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
  3429. cs->status = CERT_GOOD;
  3430. idx++;
  3431. break;
  3432. case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
  3433. cs->status = CERT_REVOKED;
  3434. GetLength(source, &idx, &length, size);
  3435. idx += length;
  3436. break;
  3437. case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
  3438. cs->status = CERT_UNKNOWN;
  3439. idx++;
  3440. break;
  3441. default:
  3442. return ASN_PARSE_E;
  3443. }
  3444. if (GetBasicDate(source, &idx, cs->thisDate,
  3445. &cs->thisDateFormat, size) < 0)
  3446. return ASN_PARSE_E;
  3447. if (!XVALIDATE_DATE(cs->thisDate, cs->thisDateFormat, BEFORE))
  3448. return ASN_BEFORE_DATE_E;
  3449. /* The following items are optional. Only check for them if there is more
  3450. * unprocessed data in the singleResponse wrapper. */
  3451. if (((int)(idx - prevIndex) < wrapperSz) &&
  3452. (source[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0)))
  3453. {
  3454. idx++;
  3455. if (GetLength(source, &idx, &length, size) < 0)
  3456. return ASN_PARSE_E;
  3457. if (GetBasicDate(source, &idx, cs->nextDate,
  3458. &cs->nextDateFormat, size) < 0)
  3459. return ASN_PARSE_E;
  3460. }
  3461. if (((int)(idx - prevIndex) < wrapperSz) &&
  3462. (source[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1)))
  3463. {
  3464. idx++;
  3465. if (GetLength(source, &idx, &length, size) < 0)
  3466. return ASN_PARSE_E;
  3467. idx += length;
  3468. }
  3469. *ioIndex = idx;
  3470. return 0;
  3471. }
  3472. static int DecodeOcspRespExtensions(byte* source,
  3473. word32* ioIndex, OcspResponse* resp, word32 sz)
  3474. {
  3475. word32 idx = *ioIndex;
  3476. int length;
  3477. int ext_bound; /* boundary index for the sequence of extensions */
  3478. word32 oid;
  3479. CYASSL_ENTER("DecodeOcspRespExtensions");
  3480. if (source[idx++] != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  3481. return ASN_PARSE_E;
  3482. if (GetLength(source, &idx, &length, sz) < 0) return ASN_PARSE_E;
  3483. if (GetSequence(source, &idx, &length, sz) < 0) return ASN_PARSE_E;
  3484. ext_bound = idx + length;
  3485. while (idx < (word32)ext_bound) {
  3486. if (GetSequence(source, &idx, &length, sz) < 0) {
  3487. CYASSL_MSG("\tfail: should be a SEQUENCE");
  3488. return ASN_PARSE_E;
  3489. }
  3490. oid = 0;
  3491. if (GetObjectId(source, &idx, &oid, sz) < 0) {
  3492. CYASSL_MSG("\tfail: OBJECT ID");
  3493. return ASN_PARSE_E;
  3494. }
  3495. /* check for critical flag */
  3496. if (source[idx] == ASN_BOOLEAN) {
  3497. CYASSL_MSG("\tfound optional critical flag, moving past");
  3498. idx += (ASN_BOOL_SIZE + 1);
  3499. }
  3500. /* process the extension based on the OID */
  3501. if (source[idx++] != ASN_OCTET_STRING) {
  3502. CYASSL_MSG("\tfail: should be an OCTET STRING");
  3503. return ASN_PARSE_E;
  3504. }
  3505. if (GetLength(source, &idx, &length, sz) < 0) {
  3506. CYASSL_MSG("\tfail: extension data length");
  3507. return ASN_PARSE_E;
  3508. }
  3509. if (oid == OCSP_NONCE_OID) {
  3510. resp->nonce = source + idx;
  3511. resp->nonceSz = length;
  3512. }
  3513. idx += length;
  3514. }
  3515. *ioIndex = idx;
  3516. return 0;
  3517. }
  3518. static int DecodeResponseData(byte* source,
  3519. word32* ioIndex, OcspResponse* resp, word32 size)
  3520. {
  3521. word32 idx = *ioIndex, prev_idx;
  3522. int length;
  3523. int version;
  3524. word32 responderId = 0;
  3525. CYASSL_ENTER("DecodeResponseData");
  3526. resp->response = source + idx;
  3527. prev_idx = idx;
  3528. if (GetSequence(source, &idx, &length, size) < 0)
  3529. return ASN_PARSE_E;
  3530. resp->responseSz = length + idx - prev_idx;
  3531. /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
  3532. * item isn't an EXPLICIT[0], then set version to zero and move
  3533. * onto the next item.
  3534. */
  3535. if (source[idx] == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
  3536. {
  3537. idx += 2; /* Eat the value and length */
  3538. if (GetMyVersion(source, &idx, &version) < 0)
  3539. return ASN_PARSE_E;
  3540. } else
  3541. version = 0;
  3542. responderId = source[idx++];
  3543. if ((responderId == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) ||
  3544. (responderId == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)))
  3545. {
  3546. if (GetLength(source, &idx, &length, size) < 0)
  3547. return ASN_PARSE_E;
  3548. idx += length;
  3549. }
  3550. else
  3551. return ASN_PARSE_E;
  3552. /* save pointer to the producedAt time */
  3553. if (GetBasicDate(source, &idx, resp->producedDate,
  3554. &resp->producedDateFormat, size) < 0)
  3555. return ASN_PARSE_E;
  3556. if (DecodeSingleResponse(source, &idx, resp, size) < 0)
  3557. return ASN_PARSE_E;
  3558. if (DecodeOcspRespExtensions(source, &idx, resp, size) < 0)
  3559. return ASN_PARSE_E;
  3560. *ioIndex = idx;
  3561. return 0;
  3562. }
  3563. static int DecodeCerts(byte* source,
  3564. word32* ioIndex, OcspResponse* resp, word32 size)
  3565. {
  3566. word32 idx = *ioIndex;
  3567. CYASSL_ENTER("DecodeCerts");
  3568. if (source[idx++] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
  3569. {
  3570. int length;
  3571. if (GetLength(source, &idx, &length, size) < 0)
  3572. return ASN_PARSE_E;
  3573. if (GetSequence(source, &idx, &length, size) < 0)
  3574. return ASN_PARSE_E;
  3575. resp->cert = source + idx;
  3576. resp->certSz = length;
  3577. idx += length;
  3578. }
  3579. *ioIndex = idx;
  3580. return 0;
  3581. }
  3582. static int DecodeBasicOcspResponse(byte* source,
  3583. word32* ioIndex, OcspResponse* resp, word32 size)
  3584. {
  3585. int length;
  3586. word32 idx = *ioIndex;
  3587. word32 end_index;
  3588. CYASSL_ENTER("DecodeBasicOcspResponse");
  3589. if (GetSequence(source, &idx, &length, size) < 0)
  3590. return ASN_PARSE_E;
  3591. if (idx + length > size)
  3592. return ASN_INPUT_E;
  3593. end_index = idx + length;
  3594. if (DecodeResponseData(source, &idx, resp, size) < 0)
  3595. return ASN_PARSE_E;
  3596. /* Get the signature algorithm */
  3597. if (GetAlgoId(source, &idx, &resp->sigOID, size) < 0)
  3598. return ASN_PARSE_E;
  3599. /* Obtain pointer to the start of the signature, and save the size */
  3600. if (source[idx++] == ASN_BIT_STRING)
  3601. {
  3602. int sigLength = 0;
  3603. if (GetLength(source, &idx, &sigLength, size) < 0)
  3604. return ASN_PARSE_E;
  3605. resp->sigSz = sigLength;
  3606. resp->sig = source + idx;
  3607. idx += sigLength;
  3608. }
  3609. /*
  3610. * Check the length of the BasicOcspResponse against the current index to
  3611. * see if there are certificates, they are optional.
  3612. */
  3613. if (idx < end_index)
  3614. {
  3615. DecodedCert cert;
  3616. int ret;
  3617. if (DecodeCerts(source, &idx, resp, size) < 0)
  3618. return ASN_PARSE_E;
  3619. InitDecodedCert(&cert, resp->cert, resp->certSz, 0);
  3620. ret = ParseCertRelative(&cert, CA_TYPE, NO_VERIFY, 0);
  3621. if (ret < 0)
  3622. return ret;
  3623. ret = ConfirmSignature(resp->response, resp->responseSz,
  3624. cert.publicKey, cert.pubKeySize, cert.keyOID,
  3625. resp->sig, resp->sigSz, resp->sigOID, NULL);
  3626. FreeDecodedCert(&cert);
  3627. if (ret == 0)
  3628. {
  3629. CYASSL_MSG("\tConfirm signature failed");
  3630. return ASN_SIG_CONFIRM_E;
  3631. }
  3632. }
  3633. *ioIndex = idx;
  3634. return 0;
  3635. }
  3636. void InitOcspResponse(OcspResponse* resp, CertStatus* status,
  3637. byte* source, word32 inSz)
  3638. {
  3639. CYASSL_ENTER("InitOcspResponse");
  3640. resp->responseStatus = -1;
  3641. resp->response = NULL;
  3642. resp->responseSz = 0;
  3643. resp->producedDateFormat = 0;
  3644. resp->issuerHash = NULL;
  3645. resp->issuerKeyHash = NULL;
  3646. resp->sig = NULL;
  3647. resp->sigSz = 0;
  3648. resp->sigOID = 0;
  3649. resp->status = status;
  3650. resp->nonce = NULL;
  3651. resp->nonceSz = 0;
  3652. resp->source = source;
  3653. resp->maxIdx = inSz;
  3654. }
  3655. int OcspResponseDecode(OcspResponse* resp)
  3656. {
  3657. int length = 0;
  3658. word32 idx = 0;
  3659. byte* source = resp->source;
  3660. word32 size = resp->maxIdx;
  3661. word32 oid;
  3662. CYASSL_ENTER("OcspResponseDecode");
  3663. /* peel the outer SEQUENCE wrapper */
  3664. if (GetSequence(source, &idx, &length, size) < 0)
  3665. return ASN_PARSE_E;
  3666. /* First get the responseStatus, an ENUMERATED */
  3667. if (GetEnumerated(source, &idx, &resp->responseStatus) < 0)
  3668. return ASN_PARSE_E;
  3669. if (resp->responseStatus != OCSP_SUCCESSFUL)
  3670. return 0;
  3671. /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
  3672. if (idx >= size)
  3673. return ASN_INPUT_E;
  3674. if (source[idx++] != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
  3675. return ASN_PARSE_E;
  3676. if (GetLength(source, &idx, &length, size) < 0)
  3677. return ASN_PARSE_E;
  3678. /* Get the responseBytes SEQUENCE */
  3679. if (GetSequence(source, &idx, &length, size) < 0)
  3680. return ASN_PARSE_E;
  3681. /* Check ObjectID for the resposeBytes */
  3682. if (GetObjectId(source, &idx, &oid, size) < 0)
  3683. return ASN_PARSE_E;
  3684. if (oid != OCSP_BASIC_OID)
  3685. return ASN_PARSE_E;
  3686. if (source[idx++] != ASN_OCTET_STRING)
  3687. return ASN_PARSE_E;
  3688. if (GetLength(source, &idx, &length, size) < 0)
  3689. return ASN_PARSE_E;
  3690. if (DecodeBasicOcspResponse(source, &idx, resp, size) < 0)
  3691. return ASN_PARSE_E;
  3692. return 0;
  3693. }
  3694. static int SetSerialNumber(const byte* sn, word32 snSz, byte* output)
  3695. {
  3696. int result = 0;
  3697. CYASSL_ENTER("SetSerialNumber");
  3698. if (snSz <= EXTERNAL_SERIAL_SIZE) {
  3699. output[0] = ASN_INTEGER;
  3700. output[1] = snSz + 1;
  3701. output[2] = 0;
  3702. XMEMCPY(&output[3], sn, snSz);
  3703. result = snSz + 3;
  3704. }
  3705. return result;
  3706. }
  3707. static word32 SetOcspReqExtensions(word32 extSz, byte* output,
  3708. const byte* nonce, word32 nonceSz)
  3709. {
  3710. static const byte NonceObjId[] = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07,
  3711. 0x30, 0x01, 0x02 };
  3712. byte seqArray[5][MAX_SEQ_SZ];
  3713. word32 seqSz[5], totalSz;
  3714. CYASSL_ENTER("SetOcspReqExtensions");
  3715. if (nonce == NULL || nonceSz == 0) return 0;
  3716. seqArray[0][0] = ASN_OCTET_STRING;
  3717. seqSz[0] = 1 + SetLength(nonceSz, &seqArray[0][1]);
  3718. seqArray[1][0] = ASN_OBJECT_ID;
  3719. seqSz[1] = 1 + SetLength(sizeof(NonceObjId), &seqArray[1][1]);
  3720. totalSz = seqSz[0] + seqSz[1] + nonceSz + (word32)sizeof(NonceObjId);
  3721. seqSz[2] = SetSequence(totalSz, seqArray[2]);
  3722. totalSz += seqSz[2];
  3723. seqSz[3] = SetSequence(totalSz, seqArray[3]);
  3724. totalSz += seqSz[3];
  3725. seqArray[4][0] = (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2);
  3726. seqSz[4] = 1 + SetLength(totalSz, &seqArray[4][1]);
  3727. totalSz += seqSz[4];
  3728. if (totalSz < extSz)
  3729. {
  3730. totalSz = 0;
  3731. XMEMCPY(output + totalSz, seqArray[4], seqSz[4]);
  3732. totalSz += seqSz[4];
  3733. XMEMCPY(output + totalSz, seqArray[3], seqSz[3]);
  3734. totalSz += seqSz[3];
  3735. XMEMCPY(output + totalSz, seqArray[2], seqSz[2]);
  3736. totalSz += seqSz[2];
  3737. XMEMCPY(output + totalSz, seqArray[1], seqSz[1]);
  3738. totalSz += seqSz[1];
  3739. XMEMCPY(output + totalSz, NonceObjId, sizeof(NonceObjId));
  3740. totalSz += (word32)sizeof(NonceObjId);
  3741. XMEMCPY(output + totalSz, seqArray[0], seqSz[0]);
  3742. totalSz += seqSz[0];
  3743. XMEMCPY(output + totalSz, nonce, nonceSz);
  3744. totalSz += nonceSz;
  3745. }
  3746. return totalSz;
  3747. }
  3748. int EncodeOcspRequest(OcspRequest* req)
  3749. {
  3750. byte seqArray[5][MAX_SEQ_SZ];
  3751. /* The ASN.1 of the OCSP Request is an onion of sequences */
  3752. byte algoArray[MAX_ALGO_SZ];
  3753. byte issuerArray[MAX_ENCODED_DIG_SZ];
  3754. byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
  3755. byte snArray[MAX_SN_SZ];
  3756. byte extArray[MAX_OCSP_EXT_SZ];
  3757. byte* output = req->dest;
  3758. word32 seqSz[5], algoSz, issuerSz, issuerKeySz, snSz, extSz, totalSz;
  3759. int i;
  3760. CYASSL_ENTER("EncodeOcspRequest");
  3761. algoSz = SetAlgoID(SHAh, algoArray, hashType);
  3762. req->issuerHash = req->cert->issuerHash;
  3763. issuerSz = SetDigest(req->cert->issuerHash, SHA_SIZE, issuerArray);
  3764. req->issuerKeyHash = req->cert->issuerKeyHash;
  3765. issuerKeySz = SetDigest(req->cert->issuerKeyHash, SHA_SIZE, issuerKeyArray);
  3766. req->serial = req->cert->serial;
  3767. req->serialSz = req->cert->serialSz;
  3768. snSz = SetSerialNumber(req->cert->serial, req->cert->serialSz, snArray);
  3769. extSz = 0;
  3770. if (req->useNonce) {
  3771. RNG rng;
  3772. if (InitRng(&rng) != 0) {
  3773. CYASSL_MSG("\tCannot initialize RNG. Skipping the OSCP Nonce.");
  3774. } else {
  3775. req->nonceSz = MAX_OCSP_NONCE_SZ;
  3776. RNG_GenerateBlock(&rng, req->nonce, req->nonceSz);
  3777. extSz = SetOcspReqExtensions(MAX_OCSP_EXT_SZ, extArray,
  3778. req->nonce, req->nonceSz);
  3779. }
  3780. }
  3781. totalSz = algoSz + issuerSz + issuerKeySz + snSz;
  3782. for (i = 4; i >= 0; i--) {
  3783. seqSz[i] = SetSequence(totalSz, seqArray[i]);
  3784. totalSz += seqSz[i];
  3785. if (i == 2) totalSz += extSz;
  3786. }
  3787. totalSz = 0;
  3788. for (i = 0; i < 5; i++) {
  3789. XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
  3790. totalSz += seqSz[i];
  3791. }
  3792. XMEMCPY(output + totalSz, algoArray, algoSz);
  3793. totalSz += algoSz;
  3794. XMEMCPY(output + totalSz, issuerArray, issuerSz);
  3795. totalSz += issuerSz;
  3796. XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
  3797. totalSz += issuerKeySz;
  3798. XMEMCPY(output + totalSz, snArray, snSz);
  3799. totalSz += snSz;
  3800. if (extSz != 0) {
  3801. XMEMCPY(output + totalSz, extArray, extSz);
  3802. totalSz += extSz;
  3803. }
  3804. return totalSz;
  3805. }
  3806. void InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce,
  3807. byte* dest, word32 destSz)
  3808. {
  3809. CYASSL_ENTER("InitOcspRequest");
  3810. req->cert = cert;
  3811. req->useNonce = useNonce;
  3812. req->nonceSz = 0;
  3813. req->issuerHash = NULL;
  3814. req->issuerKeyHash = NULL;
  3815. req->serial = NULL;
  3816. req->dest = dest;
  3817. req->destSz = destSz;
  3818. }
  3819. int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
  3820. {
  3821. int cmp;
  3822. CYASSL_ENTER("CompareOcspReqResp");
  3823. if (req == NULL)
  3824. {
  3825. CYASSL_MSG("\tReq missing");
  3826. return -1;
  3827. }
  3828. if (resp == NULL)
  3829. {
  3830. CYASSL_MSG("\tResp missing");
  3831. return 1;
  3832. }
  3833. if (req->useNonce) {
  3834. cmp = req->nonceSz - resp->nonceSz;
  3835. if (cmp != 0)
  3836. {
  3837. CYASSL_MSG("\tnonceSz mismatch");
  3838. return cmp;
  3839. }
  3840. cmp = XMEMCMP(req->nonce, resp->nonce, req->nonceSz);
  3841. if (cmp != 0)
  3842. {
  3843. CYASSL_MSG("\tnonce mismatch");
  3844. return cmp;
  3845. }
  3846. }
  3847. cmp = XMEMCMP(req->issuerHash, resp->issuerHash, SHA_DIGEST_SIZE);
  3848. if (cmp != 0)
  3849. {
  3850. CYASSL_MSG("\tissuerHash mismatch");
  3851. return cmp;
  3852. }
  3853. cmp = XMEMCMP(req->issuerKeyHash, resp->issuerKeyHash, SHA_DIGEST_SIZE);
  3854. if (cmp != 0)
  3855. {
  3856. CYASSL_MSG("\tissuerKeyHash mismatch");
  3857. return cmp;
  3858. }
  3859. cmp = req->serialSz - resp->status->serialSz;
  3860. if (cmp != 0)
  3861. {
  3862. CYASSL_MSG("\tserialSz mismatch");
  3863. return cmp;
  3864. }
  3865. cmp = XMEMCMP(req->serial, resp->status->serial, req->serialSz);
  3866. if (cmp != 0)
  3867. {
  3868. CYASSL_MSG("\tserial mismatch");
  3869. return cmp;
  3870. }
  3871. return 0;
  3872. }
  3873. #endif
  3874. #ifdef HAVE_CRL
  3875. /* initialize decoded CRL */
  3876. void InitDecodedCRL(DecodedCRL* dcrl)
  3877. {
  3878. CYASSL_MSG("InitDecodedCRL");
  3879. dcrl->certBegin = 0;
  3880. dcrl->sigIndex = 0;
  3881. dcrl->sigLength = 0;
  3882. dcrl->signatureOID = 0;
  3883. dcrl->certs = NULL;
  3884. dcrl->totalCerts = 0;
  3885. }
  3886. /* free decoded CRL resources */
  3887. void FreeDecodedCRL(DecodedCRL* dcrl)
  3888. {
  3889. RevokedCert* tmp = dcrl->certs;
  3890. CYASSL_MSG("FreeDecodedCRL");
  3891. while(tmp) {
  3892. RevokedCert* next = tmp->next;
  3893. XFREE(tmp, NULL, DYNAMIC_TYPE_REVOKED);
  3894. tmp = next;
  3895. }
  3896. }
  3897. /* store SHA1 hash of NAME */
  3898. static int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx)
  3899. {
  3900. Sha sha;
  3901. int length; /* length of all distinguished names */
  3902. word32 dummy;
  3903. CYASSL_ENTER("GetNameHash");
  3904. if (source[*idx] == ASN_OBJECT_ID) {
  3905. CYASSL_MSG("Trying optional prefix...");
  3906. if (GetLength(source, idx, &length, maxIdx) < 0)
  3907. return ASN_PARSE_E;
  3908. *idx += length;
  3909. CYASSL_MSG("Got optional prefix");
  3910. }
  3911. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  3912. * calculated over the entire DER encoding of the Name field, including
  3913. * the tag and length. */
  3914. dummy = *idx;
  3915. if (GetSequence(source, idx, &length, maxIdx) < 0)
  3916. return ASN_PARSE_E;
  3917. InitSha(&sha);
  3918. ShaUpdate(&sha, source + dummy, length + *idx - dummy);
  3919. ShaFinal(&sha, hash);
  3920. *idx += length;
  3921. return 0;
  3922. }
  3923. /* Get Revoked Cert list, 0 on success */
  3924. static int GetRevoked(const byte* buff, word32* idx, DecodedCRL* dcrl,
  3925. int maxIdx)
  3926. {
  3927. int len;
  3928. word32 end;
  3929. byte b;
  3930. RevokedCert* rc;
  3931. CYASSL_ENTER("GetRevoked");
  3932. if (GetSequence(buff, idx, &len, maxIdx) < 0)
  3933. return ASN_PARSE_E;
  3934. end = *idx + len;
  3935. /* get serial number */
  3936. b = buff[*idx];
  3937. *idx += 1;
  3938. if (b != ASN_INTEGER) {
  3939. CYASSL_MSG("Expecting Integer");
  3940. return ASN_PARSE_E;
  3941. }
  3942. if (GetLength(buff, idx, &len, maxIdx) < 0)
  3943. return ASN_PARSE_E;
  3944. if (len > EXTERNAL_SERIAL_SIZE) {
  3945. CYASSL_MSG("Serial Size too big");
  3946. return ASN_PARSE_E;
  3947. }
  3948. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), NULL, DYNAMIC_TYPE_CRL);
  3949. if (rc == NULL) {
  3950. CYASSL_MSG("Alloc Revoked Cert failed");
  3951. return MEMORY_E;
  3952. }
  3953. XMEMCPY(rc->serialNumber, &buff[*idx], len);
  3954. rc->serialSz = len;
  3955. /* add to list */
  3956. rc->next = dcrl->certs;
  3957. dcrl->certs = rc;
  3958. dcrl->totalCerts++;
  3959. *idx += len;
  3960. /* get date */
  3961. b = buff[*idx];
  3962. *idx += 1;
  3963. if (b != ASN_UTC_TIME && b != ASN_GENERALIZED_TIME) {
  3964. CYASSL_MSG("Expecting Date");
  3965. return ASN_PARSE_E;
  3966. }
  3967. if (GetLength(buff, idx, &len, maxIdx) < 0)
  3968. return ASN_PARSE_E;
  3969. /* skip for now */
  3970. *idx += len;
  3971. if (*idx != end) /* skip extensions */
  3972. *idx = end;
  3973. return 0;
  3974. }
  3975. /* Get CRL Signature, 0 on success */
  3976. static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
  3977. int maxIdx)
  3978. {
  3979. int length;
  3980. byte b;
  3981. CYASSL_ENTER("GetCRL_Signature");
  3982. b = source[*idx];
  3983. *idx += 1;
  3984. if (b != ASN_BIT_STRING)
  3985. return ASN_BITSTR_E;
  3986. if (GetLength(source, idx, &length, maxIdx) < 0)
  3987. return ASN_PARSE_E;
  3988. dcrl->sigLength = length;
  3989. b = source[*idx];
  3990. *idx += 1;
  3991. if (b != 0x00)
  3992. return ASN_EXPECT_0_E;
  3993. dcrl->sigLength--;
  3994. dcrl->signature = (byte*)&source[*idx];
  3995. *idx += dcrl->sigLength;
  3996. return 0;
  3997. }
  3998. /* prase crl buffer into decoded state, 0 on success */
  3999. int ParseCRL(DecodedCRL* dcrl, const byte* buff, word32 sz, void* cm)
  4000. {
  4001. int version, len;
  4002. word32 oid, idx = 0;
  4003. Signer* ca;
  4004. CYASSL_MSG("ParseCRL");
  4005. /* raw crl hash */
  4006. /* hash here if needed for optimized comparisons
  4007. * Sha sha;
  4008. * InitSha(&sha);
  4009. * ShaUpdate(&sha, buff, sz);
  4010. * ShaFinal(&sha, dcrl->crlHash); */
  4011. if (GetSequence(buff, &idx, &len, sz) < 0)
  4012. return ASN_PARSE_E;
  4013. dcrl->certBegin = idx;
  4014. if (GetSequence(buff, &idx, &len, sz) < 0)
  4015. return ASN_PARSE_E;
  4016. dcrl->sigIndex = len + idx;
  4017. /* may have version */
  4018. if (buff[idx] == ASN_INTEGER) {
  4019. if (GetMyVersion(buff, &idx, &version) < 0)
  4020. return ASN_PARSE_E;
  4021. }
  4022. if (GetAlgoId(buff, &idx, &oid, sz) < 0)
  4023. return ASN_PARSE_E;
  4024. if (GetNameHash(buff, &idx, dcrl->issuerHash, sz) < 0)
  4025. return ASN_PARSE_E;
  4026. if (GetBasicDate(buff, &idx, dcrl->lastDate, &dcrl->lastDateFormat, sz) < 0)
  4027. return ASN_PARSE_E;
  4028. if (GetBasicDate(buff, &idx, dcrl->nextDate, &dcrl->nextDateFormat, sz) < 0)
  4029. return ASN_PARSE_E;
  4030. if (!XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  4031. CYASSL_MSG("CRL after date is no longer valid");
  4032. return ASN_AFTER_DATE_E;
  4033. }
  4034. if (idx != dcrl->sigIndex && buff[idx] != CRL_EXTENSIONS) {
  4035. if (GetSequence(buff, &idx, &len, sz) < 0)
  4036. return ASN_PARSE_E;
  4037. len += idx;
  4038. while (idx < (word32)len) {
  4039. if (GetRevoked(buff, &idx, dcrl, sz) < 0)
  4040. return ASN_PARSE_E;
  4041. }
  4042. }
  4043. if (idx != dcrl->sigIndex)
  4044. idx = dcrl->sigIndex; /* skip extensions */
  4045. if (GetAlgoId(buff, &idx, &dcrl->signatureOID, sz) < 0)
  4046. return ASN_PARSE_E;
  4047. if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
  4048. return ASN_PARSE_E;
  4049. ca = GetCA(cm, dcrl->issuerHash);
  4050. CYASSL_MSG("About to verify CRL signature");
  4051. if (ca) {
  4052. CYASSL_MSG("Found CRL issuer CA");
  4053. /* try to confirm/verify signature */
  4054. if (!ConfirmSignature(buff + dcrl->certBegin,
  4055. dcrl->sigIndex - dcrl->certBegin,
  4056. ca->publicKey, ca->pubKeySize, ca->keyOID,
  4057. dcrl->signature, dcrl->sigLength, dcrl->signatureOID, NULL)) {
  4058. CYASSL_MSG("CRL Confirm signature failed");
  4059. return ASN_SIG_CONFIRM_E;
  4060. }
  4061. }
  4062. else {
  4063. CYASSL_MSG("Did NOT find CRL issuer CA");
  4064. return ASN_SIG_CONFIRM_E;
  4065. }
  4066. return 0;
  4067. }
  4068. #endif /* HAVE_CRL */
  4069. #endif