asn.c 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866
  1. /* asn.c
  2. *
  3. * Copyright (C) 2006-2011 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 THREADX
  22. #include "os.h" /* dc_rtc_api needs */
  23. #include "dc_rtc_api.h" /* to get current time */
  24. #endif
  25. #include "asn.h"
  26. #include "coding.h"
  27. #include "ctc_sha.h"
  28. #include "ctc_md5.h"
  29. #include "error.h"
  30. #ifdef HAVE_NTRU
  31. #include "crypto_ntru.h"
  32. #endif
  33. #ifdef HAVE_ECC
  34. #include "ctc_ecc.h"
  35. #endif
  36. #ifdef _MSC_VER
  37. /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
  38. #pragma warning(disable: 4996)
  39. #endif
  40. #ifndef TRUE
  41. enum {
  42. FALSE = 0,
  43. TRUE = 1
  44. };
  45. #endif
  46. #ifdef THREADX
  47. /* uses parital <time.h> structures */
  48. #define XTIME(tl) (0)
  49. #define XGMTIME(c) my_gmtime((c))
  50. #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
  51. #elif defined(MICRIUM)
  52. #if (NET_SECURE_MGR_CFG_EN == DEF_ENABLED)
  53. #define XVALIDATE_DATE(d,f,t) NetSecure_ValidateDateHandler((d),(f),(t))
  54. #else
  55. #define XVALIDATE_DATE(d, f, t) (0)
  56. #endif
  57. #define NO_TIME_H
  58. /* since Micrium not defining XTIME or XGMTIME, CERT_GEN not available */
  59. #elif defined(USER_TIME)
  60. /* no <time.h> strucutres used */
  61. #define NO_TIME_H
  62. /* user time, and gmtime compatible functions, there is a gmtime
  63. implementation here that WINCE uses, so really just need some ticks
  64. since the EPOCH
  65. */
  66. #else
  67. /* default */
  68. /* uses complete <time.h> facility */
  69. #include <time.h>
  70. #define XTIME(tl) time((tl))
  71. #define XGMTIME(c) gmtime((c))
  72. #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
  73. #endif
  74. #ifdef _WIN32_WCE
  75. /* no time() or gmtime() even though in time.h header?? */
  76. #include <windows.h>
  77. time_t time(time_t* timer)
  78. {
  79. SYSTEMTIME sysTime;
  80. FILETIME fTime;
  81. ULARGE_INTEGER intTime;
  82. time_t localTime;
  83. if (timer == NULL)
  84. timer = &localTime;
  85. GetSystemTime(&sysTime);
  86. SystemTimeToFileTime(&sysTime, &fTime);
  87. XMEMCPY(&intTime, &fTime, sizeof(FILETIME));
  88. /* subtract EPOCH */
  89. intTime.QuadPart -= 0x19db1ded53e8000;
  90. /* to secs */
  91. intTime.QuadPart /= 10000000;
  92. *timer = (time_t)intTime.QuadPart;
  93. return *timer;
  94. }
  95. struct tm* gmtime(const time_t* timer)
  96. {
  97. #define YEAR0 1900
  98. #define EPOCH_YEAR 1970
  99. #define SECS_DAY (24L * 60L * 60L)
  100. #define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) %400)))
  101. #define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365)
  102. static const int _ytab[2][12] =
  103. {
  104. {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
  105. {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
  106. };
  107. static struct tm st_time;
  108. struct tm* ret = &st_time;
  109. time_t time = *timer;
  110. unsigned long dayclock, dayno;
  111. int year = EPOCH_YEAR;
  112. dayclock = (unsigned long)time % SECS_DAY;
  113. dayno = (unsigned long)time / SECS_DAY;
  114. ret->tm_sec = dayclock % 60;
  115. ret->tm_min = (dayclock % 3600) / 60;
  116. ret->tm_hour = dayclock / 3600;
  117. ret->tm_wday = (dayno + 4) % 7; /* day 0 a Thursday */
  118. while(dayno >= (unsigned long)YEARSIZE(year)) {
  119. dayno -= YEARSIZE(year);
  120. year++;
  121. }
  122. ret->tm_year = year - YEAR0;
  123. ret->tm_yday = dayno;
  124. ret->tm_mon = 0;
  125. while(dayno >= (unsigned long)_ytab[LEAPYEAR(year)][ret->tm_mon]) {
  126. dayno -= _ytab[LEAPYEAR(year)][ret->tm_mon];
  127. ret->tm_mon++;
  128. }
  129. ret->tm_mday = ++dayno;
  130. ret->tm_isdst = 0;
  131. return ret;
  132. }
  133. #endif /* _WIN32_WCE */
  134. #ifdef THREADX
  135. #define YEAR0 1900
  136. struct tm* my_gmtime(const time_t* timer) /* has a gmtime() but hangs */
  137. {
  138. static struct tm st_time;
  139. struct tm* ret = &st_time;
  140. DC_RTC_CALENDAR cal;
  141. dc_rtc_time_get(&cal, TRUE);
  142. ret->tm_year = cal.year - YEAR0; /* gm starts at 1900 */
  143. ret->tm_mon = cal.month - 1; /* gm starts at 0 */
  144. ret->tm_mday = cal.day;
  145. ret->tm_hour = cal.hour;
  146. ret->tm_min = cal.minute;
  147. ret->tm_sec = cal.second;
  148. return ret;
  149. }
  150. #endif /* THREADX */
  151. static INLINE word32 btoi(byte b)
  152. {
  153. return b - 0x30;
  154. }
  155. /* two byte date/time, add to value */
  156. static INLINE void GetTime(int* value, const byte* date, int* idx)
  157. {
  158. int i = *idx;
  159. *value += btoi(date[i++]) * 10;
  160. *value += btoi(date[i++]);
  161. *idx = i;
  162. }
  163. #if defined(MICRIUM)
  164. CPU_INT32S NetSecure_ValidateDateHandler(CPU_INT08U *date, CPU_INT08U format,
  165. CPU_INT08U dateType)
  166. {
  167. CPU_BOOLEAN rtn_code;
  168. CPU_INT32S i;
  169. CPU_INT32S val;
  170. CPU_INT16U year;
  171. CPU_INT08U month;
  172. CPU_INT16U day;
  173. CPU_INT08U hour;
  174. CPU_INT08U min;
  175. CPU_INT08U sec;
  176. i = 0;
  177. year = 0u;
  178. if (format == ASN_UTC_TIME) {
  179. if (btoi(date[0]) >= 5)
  180. year = 1900;
  181. else
  182. year = 2000;
  183. }
  184. else { /* format == GENERALIZED_TIME */
  185. year += btoi(date[i++]) * 1000;
  186. year += btoi(date[i++]) * 100;
  187. }
  188. val = year;
  189. GetTime(&val, date, &i);
  190. year = (CPU_INT16U)val;
  191. val = 0;
  192. GetTime(&val, date, &i);
  193. month = (CPU_INT08U)val;
  194. val = 0;
  195. GetTime(&val, date, &i);
  196. day = (CPU_INT16U)val;
  197. val = 0;
  198. GetTime(&val, date, &i);
  199. hour = (CPU_INT08U)val;
  200. val = 0;
  201. GetTime(&val, date, &i);
  202. min = (CPU_INT08U)val;
  203. val = 0;
  204. GetTime(&val, date, &i);
  205. sec = (CPU_INT08U)val;
  206. return NetSecure_ValidateDate(year, month, day, hour, min, sec, dateType);
  207. }
  208. #endif /* MICRIUM */
  209. int GetLength(const byte* input, word32* inOutIdx, int* len)
  210. {
  211. int length = 0;
  212. word32 i = *inOutIdx;
  213. byte b = input[i++];
  214. if (b >= ASN_LONG_LENGTH) {
  215. word32 bytes = b & 0x7F;
  216. while (bytes--) {
  217. b = input[i++];
  218. length = (length << 8) | b;
  219. }
  220. }
  221. else
  222. length = b;
  223. *inOutIdx = i;
  224. *len = length;
  225. return length;
  226. }
  227. int GetSequence(const byte* input, word32* inOutIdx, int* len)
  228. {
  229. int length = -1;
  230. word32 idx = *inOutIdx;
  231. if (input[idx++] != (ASN_SEQUENCE | ASN_CONSTRUCTED) ||
  232. GetLength(input, &idx, &length) < 0)
  233. return ASN_PARSE_E;
  234. *len = length;
  235. *inOutIdx = idx;
  236. return length;
  237. }
  238. int GetSet(const byte* input, word32* inOutIdx, int* len)
  239. {
  240. int length = -1;
  241. word32 idx = *inOutIdx;
  242. if (input[idx++] != (ASN_SET | ASN_CONSTRUCTED) ||
  243. GetLength(input, &idx, &length) < 0)
  244. return ASN_PARSE_E;
  245. *len = length;
  246. *inOutIdx = idx;
  247. return length;
  248. }
  249. /* winodws header clash for WinCE using GetVersion */
  250. int GetMyVersion(const byte* input, word32* inOutIdx, int* version)
  251. {
  252. word32 idx = *inOutIdx;
  253. if (input[idx++] != ASN_INTEGER)
  254. return ASN_PARSE_E;
  255. if (input[idx++] != 0x01)
  256. return ASN_VERSION_E;
  257. *version = input[idx++];
  258. *inOutIdx = idx;
  259. return *version;
  260. }
  261. /* May not have one, not an error */
  262. int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version)
  263. {
  264. word32 idx = *inOutIdx;
  265. if (input[idx++] == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  266. *inOutIdx = ++idx; /* eat header */
  267. return GetMyVersion(input, inOutIdx, version);
  268. }
  269. /* go back as is */
  270. *version = 0;
  271. return 0;
  272. }
  273. int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx )
  274. {
  275. word32 i = *inOutIdx;
  276. byte b = input[i++];
  277. int length;
  278. if (b != ASN_INTEGER)
  279. return ASN_PARSE_E;
  280. if (GetLength(input, &i, &length) < 0)
  281. return ASN_PARSE_E;
  282. if ( (b = input[i++]) == 0x00)
  283. length--;
  284. else
  285. i--;
  286. mp_init(mpi);
  287. if (mp_read_unsigned_bin(mpi, (byte*)input + i, length) != 0) {
  288. mp_clear(mpi);
  289. return ASN_GETINT_E;
  290. }
  291. *inOutIdx = i + length;
  292. return 0;
  293. }
  294. static int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid)
  295. {
  296. int length;
  297. word32 i = *inOutIdx;
  298. byte b;
  299. *oid = 0;
  300. if (GetSequence(input, &i, &length) < 0)
  301. return ASN_PARSE_E;
  302. b = input[i++];
  303. if (b != ASN_OBJECT_ID)
  304. return ASN_OBJECT_ID_E;
  305. if (GetLength(input, &i, &length) < 0)
  306. return ASN_PARSE_E;
  307. while(length--)
  308. *oid += input[i++];
  309. /* just sum it up for now */
  310. /* could have NULL tag and 0 terminator, but may not */
  311. b = input[i++];
  312. if (b == ASN_TAG_NULL) {
  313. b = input[i++];
  314. if (b != 0)
  315. return ASN_EXPECT_0_E;
  316. }
  317. else
  318. /* go back, didn't have it */
  319. i--;
  320. *inOutIdx = i;
  321. return 0;
  322. }
  323. int RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  324. word32 inSz)
  325. {
  326. word32 begin = *inOutIdx;
  327. int version, length;
  328. if (GetSequence(input, inOutIdx, &length) < 0)
  329. return ASN_PARSE_E;
  330. if ((word32)length > (inSz - (*inOutIdx - begin)))
  331. return ASN_INPUT_E;
  332. if (GetMyVersion(input, inOutIdx, &version) < 0)
  333. return ASN_PARSE_E;
  334. key->type = RSA_PRIVATE;
  335. if (GetInt(&key->n, input, inOutIdx) < 0 ||
  336. GetInt(&key->e, input, inOutIdx) < 0 ||
  337. GetInt(&key->d, input, inOutIdx) < 0 ||
  338. GetInt(&key->p, input, inOutIdx) < 0 ||
  339. GetInt(&key->q, input, inOutIdx) < 0 ||
  340. GetInt(&key->dP, input, inOutIdx) < 0 ||
  341. GetInt(&key->dQ, input, inOutIdx) < 0 ||
  342. GetInt(&key->u, input, inOutIdx) < 0 ) return ASN_RSA_KEY_E;
  343. return 0;
  344. }
  345. /* Remove PKCS8 header, move beginning of traditional to beginning of input */
  346. int ToTraditional(byte* input, word32 sz)
  347. {
  348. word32 inOutIdx = 0, oid;
  349. int version, length;
  350. if (GetSequence(input, &inOutIdx, &length) < 0)
  351. return ASN_PARSE_E;
  352. if ((word32)length > (sz - inOutIdx))
  353. return ASN_INPUT_E;
  354. if (GetMyVersion(input, &inOutIdx, &version) < 0)
  355. return ASN_PARSE_E;
  356. if (GetAlgoId(input, &inOutIdx, &oid) < 0)
  357. return ASN_PARSE_E;
  358. if (input[inOutIdx++] != ASN_OCTET_STRING)
  359. return ASN_PARSE_E;
  360. if (GetLength(input, &inOutIdx, &length) < 0)
  361. return ASN_PARSE_E;
  362. if ((word32)length > (sz - inOutIdx))
  363. return ASN_INPUT_E;
  364. XMEMMOVE(input, input + inOutIdx, length);
  365. return 0;
  366. }
  367. int RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  368. word32 inSz)
  369. {
  370. word32 begin = *inOutIdx;
  371. int length;
  372. byte b;
  373. if (GetSequence(input, inOutIdx, &length) < 0)
  374. return ASN_PARSE_E;
  375. if ((word32)length > (inSz - (*inOutIdx - begin)))
  376. return ASN_INPUT_E;
  377. key->type = RSA_PUBLIC;
  378. b = input[*inOutIdx];
  379. #ifdef OPENSSL_EXTRA
  380. if (b != ASN_INTEGER) {
  381. /* not from decoded cert, will have algo id, skip past */
  382. if (GetSequence(input, inOutIdx, &length) < 0)
  383. return ASN_PARSE_E;
  384. b = input[(*inOutIdx)++];
  385. if (b != ASN_OBJECT_ID)
  386. return ASN_OBJECT_ID_E;
  387. if (GetLength(input, inOutIdx, &length) < 0)
  388. return ASN_PARSE_E;
  389. *inOutIdx += length; /* skip past */
  390. /* could have NULL tag and 0 terminator, but may not */
  391. b = input[(*inOutIdx)++];
  392. if (b == ASN_TAG_NULL) {
  393. b = input[(*inOutIdx)++];
  394. if (b != 0)
  395. return ASN_EXPECT_0_E;
  396. }
  397. else
  398. /* go back, didn't have it */
  399. (*inOutIdx)--;
  400. /* should have bit tag length and seq next */
  401. b = input[(*inOutIdx)++];
  402. if (b != ASN_BIT_STRING)
  403. return ASN_BITSTR_E;
  404. if (GetLength(input, inOutIdx, &length) < 0)
  405. return ASN_PARSE_E;
  406. /* could have 0 */
  407. b = input[(*inOutIdx)++];
  408. if (b != 0)
  409. (*inOutIdx)--;
  410. if (GetSequence(input, inOutIdx, &length) < 0)
  411. return ASN_PARSE_E;
  412. }
  413. #endif /* OPENSSL_EXTRA */
  414. if (GetInt(&key->n, input, inOutIdx) < 0 ||
  415. GetInt(&key->e, input, inOutIdx) < 0 ) return ASN_RSA_KEY_E;
  416. return 0;
  417. }
  418. #ifndef NO_DH
  419. int DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
  420. {
  421. word32 begin = *inOutIdx;
  422. int length;
  423. if (GetSequence(input, inOutIdx, &length) < 0)
  424. return ASN_PARSE_E;
  425. if ((word32)length > (inSz - (*inOutIdx - begin)))
  426. return ASN_INPUT_E;
  427. if (GetInt(&key->p, input, inOutIdx) < 0 ||
  428. GetInt(&key->g, input, inOutIdx) < 0 ) return ASN_DH_KEY_E;
  429. return 0;
  430. }
  431. int DhSetKey(DhKey* key, const byte* p, word32 pSz, const byte* g, word32 gSz)
  432. {
  433. /* may have leading 0 */
  434. if (p[0] == 0) {
  435. pSz--; p++;
  436. }
  437. if (g[0] == 0) {
  438. gSz--; g++;
  439. }
  440. mp_init(&key->p);
  441. if (mp_read_unsigned_bin(&key->p, p, pSz) != 0) {
  442. mp_clear(&key->p);
  443. return ASN_DH_KEY_E;
  444. }
  445. mp_init(&key->g);
  446. if (mp_read_unsigned_bin(&key->g, g, gSz) != 0) {
  447. mp_clear(&key->p);
  448. return ASN_DH_KEY_E;
  449. }
  450. return 0;
  451. }
  452. #endif /* NO_DH */
  453. #ifndef NO_DSA
  454. int DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  455. word32 inSz)
  456. {
  457. word32 begin = *inOutIdx;
  458. int length;
  459. if (GetSequence(input, inOutIdx, &length) < 0)
  460. return ASN_PARSE_E;
  461. if ((word32)length > (inSz - (*inOutIdx - begin)))
  462. return ASN_INPUT_E;
  463. if (GetInt(&key->p, input, inOutIdx) < 0 ||
  464. GetInt(&key->q, input, inOutIdx) < 0 ||
  465. GetInt(&key->g, input, inOutIdx) < 0 ||
  466. GetInt(&key->y, input, inOutIdx) < 0 ) return ASN_DH_KEY_E;
  467. key->type = DSA_PUBLIC;
  468. return 0;
  469. }
  470. int DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  471. word32 inSz)
  472. {
  473. word32 begin = *inOutIdx;
  474. int length, version;
  475. if (GetSequence(input, inOutIdx, &length) < 0)
  476. return ASN_PARSE_E;
  477. if ((word32)length > (inSz - (*inOutIdx - begin)))
  478. return ASN_INPUT_E;
  479. if (GetMyVersion(input, inOutIdx, &version) < 0)
  480. return ASN_PARSE_E;
  481. if (GetInt(&key->p, input, inOutIdx) < 0 ||
  482. GetInt(&key->q, input, inOutIdx) < 0 ||
  483. GetInt(&key->g, input, inOutIdx) < 0 ||
  484. GetInt(&key->y, input, inOutIdx) < 0 ||
  485. GetInt(&key->x, input, inOutIdx) < 0 ) return ASN_DH_KEY_E;
  486. key->type = DSA_PRIVATE;
  487. return 0;
  488. }
  489. #endif /* NO_DSA */
  490. void InitDecodedCert(DecodedCert* cert, byte* source, void* heap)
  491. {
  492. cert->publicKey = 0;
  493. cert->pubKeyStored = 0;
  494. cert->signature = 0;
  495. cert->subjectCN = 0;
  496. cert->subjectCNLen = 0;
  497. cert->source = source; /* don't own */
  498. cert->srcIdx = 0;
  499. cert->heap = heap;
  500. #ifdef CYASSL_CERT_GEN
  501. cert->subjectSN = 0;
  502. cert->subjectSNLen = 0;
  503. cert->subjectC = 0;
  504. cert->subjectCLen = 0;
  505. cert->subjectL = 0;
  506. cert->subjectLLen = 0;
  507. cert->subjectST = 0;
  508. cert->subjectSTLen = 0;
  509. cert->subjectO = 0;
  510. cert->subjectOLen = 0;
  511. cert->subjectOU = 0;
  512. cert->subjectOULen = 0;
  513. cert->subjectEmail = 0;
  514. cert->subjectEmailLen = 0;
  515. #endif /* CYASSL_CERT_GEN */
  516. }
  517. void FreeDecodedCert(DecodedCert* cert)
  518. {
  519. if (cert->subjectCNLen == 0) /* 0 means no longer pointer to raw, we own */
  520. XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
  521. if (cert->pubKeyStored == 1)
  522. XFREE(cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  523. }
  524. static int GetCertHeader(DecodedCert* cert, word32 inSz)
  525. {
  526. int ret = 0, version, len;
  527. word32 begin = cert->srcIdx;
  528. mp_int mpi;
  529. if (GetSequence(cert->source, &cert->srcIdx, &len) < 0)
  530. return ASN_PARSE_E;
  531. if ((word32)len > (inSz - (cert->srcIdx - begin))) return ASN_INPUT_E;
  532. cert->certBegin = cert->srcIdx;
  533. GetSequence(cert->source, &cert->srcIdx, &len);
  534. cert->sigIndex = len + cert->srcIdx;
  535. if (GetExplicitVersion(cert->source, &cert->srcIdx, &version) < 0)
  536. return ASN_PARSE_E;
  537. if (GetInt(&mpi, cert->source, &cert->srcIdx) < 0)
  538. ret = ASN_PARSE_E;
  539. mp_clear(&mpi);
  540. return ret;
  541. }
  542. /* Store Rsa Key, may save later, Dsa could use in future */
  543. static int StoreRsaKey(DecodedCert* cert)
  544. {
  545. int length;
  546. word32 read = cert->srcIdx;
  547. if (GetSequence(cert->source, &cert->srcIdx, &length) < 0)
  548. return ASN_PARSE_E;
  549. read = cert->srcIdx - read;
  550. length += read;
  551. while (read--)
  552. cert->srcIdx--;
  553. cert->pubKeySize = length;
  554. cert->publicKey = cert->source + cert->srcIdx;
  555. cert->srcIdx += length;
  556. return 0;
  557. }
  558. #ifdef HAVE_ECC
  559. /* return 0 on sucess if the ECC curve oid sum is supported */
  560. static int CheckCurve(word32 oid)
  561. {
  562. if (oid != ECC_256R1 && oid != ECC_384R1 && oid != ECC_521R1 && oid !=
  563. ECC_160R1 && oid != ECC_192R1 && oid != ECC_224R1)
  564. return -1;
  565. return 0;
  566. }
  567. #endif /* HAVE_ECC */
  568. static int GetKey(DecodedCert* cert)
  569. {
  570. int length;
  571. #ifdef HAVE_NTRU
  572. int tmpIdx = cert->srcIdx;
  573. #endif
  574. if (GetSequence(cert->source, &cert->srcIdx, &length) < 0)
  575. return ASN_PARSE_E;
  576. if (GetAlgoId(cert->source, &cert->srcIdx, &cert->keyOID) < 0)
  577. return ASN_PARSE_E;
  578. if (cert->keyOID == RSAk) {
  579. byte b = cert->source[cert->srcIdx++];
  580. if (b != ASN_BIT_STRING)
  581. return ASN_BITSTR_E;
  582. if (GetLength(cert->source, &cert->srcIdx, &length) < 0)
  583. return ASN_PARSE_E;
  584. b = cert->source[cert->srcIdx++];
  585. if (b != 0x00)
  586. return ASN_EXPECT_0_E;
  587. }
  588. else if (cert->keyOID == DSAk )
  589. ; /* do nothing */
  590. #ifdef HAVE_NTRU
  591. else if (cert->keyOID == NTRUk ) {
  592. const byte* key = &cert->source[tmpIdx];
  593. byte* next = (byte*)key;
  594. word16 keyLen;
  595. byte keyBlob[MAX_NTRU_KEY_SZ];
  596. word32 rc = crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key,
  597. &keyLen, NULL, &next);
  598. if (rc != NTRU_OK)
  599. return ASN_NTRU_KEY_E;
  600. if (keyLen > sizeof(keyBlob))
  601. return ASN_NTRU_KEY_E;
  602. rc = crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key, &keyLen,
  603. keyBlob, &next);
  604. if (rc != NTRU_OK)
  605. return ASN_NTRU_KEY_E;
  606. if ( (next - key) < 0)
  607. return ASN_NTRU_KEY_E;
  608. cert->srcIdx = tmpIdx + (next - key);
  609. cert->publicKey = (byte*) XMALLOC(keyLen, cert->heap,
  610. DYNAMIC_TYPE_PUBLIC_KEY);
  611. if (cert->publicKey == NULL)
  612. return MEMORY_E;
  613. memcpy(cert->publicKey, keyBlob, keyLen);
  614. cert->pubKeyStored = 1;
  615. cert->pubKeySize = keyLen;
  616. }
  617. #endif /* HAVE_NTRU */
  618. #ifdef HAVE_ECC
  619. else if (cert->keyOID == ECDSAk ) {
  620. word32 oid = 0;
  621. int oidSz = 0;
  622. byte b = cert->source[cert->srcIdx++];
  623. if (b != ASN_OBJECT_ID)
  624. return ASN_OBJECT_ID_E;
  625. if (GetLength(cert->source, &cert->srcIdx, &oidSz) < 0)
  626. return ASN_PARSE_E;
  627. while(oidSz--)
  628. oid += cert->source[cert->srcIdx++];
  629. if (CheckCurve(oid) < 0)
  630. return ECC_CURVE_OID_E;
  631. /* key header */
  632. b = cert->source[cert->srcIdx++];
  633. if (b != ASN_BIT_STRING)
  634. return ASN_BITSTR_E;
  635. if (GetLength(cert->source, &cert->srcIdx, &length) < 0)
  636. return ASN_PARSE_E;
  637. b = cert->source[cert->srcIdx++];
  638. if (b != 0x00)
  639. return ASN_EXPECT_0_E;
  640. /* actual key, use length - 1 since preceding 0 */
  641. cert->publicKey = (byte*) XMALLOC(length - 1, cert->heap,
  642. DYNAMIC_TYPE_PUBLIC_KEY);
  643. if (cert->publicKey == NULL)
  644. return MEMORY_E;
  645. memcpy(cert->publicKey, &cert->source[cert->srcIdx], length - 1);
  646. cert->pubKeyStored = 1;
  647. cert->pubKeySize = length - 1;
  648. cert->srcIdx += length;
  649. }
  650. #endif /* HAVE_ECC */
  651. else
  652. return ASN_UNKNOWN_OID_E;
  653. if (cert->keyOID == RSAk)
  654. return StoreRsaKey(cert);
  655. return 0;
  656. }
  657. /* process NAME, either issuer or subject */
  658. static int GetName(DecodedCert* cert, int nameType)
  659. {
  660. Sha sha;
  661. int length; /* length of all distinguished names */
  662. int dummy;
  663. char* full = (nameType == ISSUER) ? cert->issuer : cert->subject;
  664. word32 idx = 0;
  665. InitSha(&sha);
  666. if (GetSequence(cert->source, &cert->srcIdx, &length) < 0)
  667. return ASN_PARSE_E;
  668. length += cert->srcIdx;
  669. while (cert->srcIdx < (word32)length) {
  670. byte b;
  671. byte joint[2];
  672. int oidSz;
  673. if (GetSet(cert->source, &cert->srcIdx, &dummy) < 0)
  674. return ASN_PARSE_E;
  675. if (GetSequence(cert->source, &cert->srcIdx, &dummy) < 0)
  676. return ASN_PARSE_E;
  677. b = cert->source[cert->srcIdx++];
  678. if (b != ASN_OBJECT_ID)
  679. return ASN_OBJECT_ID_E;
  680. if (GetLength(cert->source, &cert->srcIdx, &oidSz) < 0)
  681. return ASN_PARSE_E;
  682. XMEMCPY(joint, &cert->source[cert->srcIdx], sizeof(joint));
  683. /* v1 name types */
  684. if (joint[0] == 0x55 && joint[1] == 0x04) {
  685. byte id;
  686. byte copy = FALSE;
  687. int strLen;
  688. cert->srcIdx += 2;
  689. id = cert->source[cert->srcIdx++];
  690. b = cert->source[cert->srcIdx++]; /* strType */
  691. if (GetLength(cert->source, &cert->srcIdx, &strLen) < 0)
  692. return ASN_PARSE_E;
  693. if (strLen > (int)(ASN_NAME_MAX - idx))
  694. return ASN_PARSE_E;
  695. if (4 > (ASN_NAME_MAX - idx)) /* make sure room for biggest */
  696. return ASN_PARSE_E; /* pre fix header too "/CN=" */
  697. if (id == ASN_COMMON_NAME) {
  698. if (nameType == SUBJECT) {
  699. cert->subjectCN = (char *)&cert->source[cert->srcIdx];
  700. cert->subjectCNLen = strLen;
  701. }
  702. XMEMCPY(&full[idx], "/CN=", 4);
  703. idx += 4;
  704. copy = TRUE;
  705. }
  706. else if (id == ASN_SUR_NAME) {
  707. XMEMCPY(&full[idx], "/SN=", 4);
  708. idx += 4;
  709. copy = TRUE;
  710. #ifdef CYASSL_CERT_GEN
  711. if (nameType == SUBJECT) {
  712. cert->subjectSN = (char*)&cert->source[cert->srcIdx];
  713. cert->subjectSNLen = strLen;
  714. }
  715. #endif /* CYASSL_CERT_GEN */
  716. }
  717. else if (id == ASN_COUNTRY_NAME) {
  718. XMEMCPY(&full[idx], "/C=", 3);
  719. idx += 3;
  720. copy = TRUE;
  721. #ifdef CYASSL_CERT_GEN
  722. if (nameType == SUBJECT) {
  723. cert->subjectC = (char*)&cert->source[cert->srcIdx];
  724. cert->subjectCLen = strLen;
  725. }
  726. #endif /* CYASSL_CERT_GEN */
  727. }
  728. else if (id == ASN_LOCALITY_NAME) {
  729. XMEMCPY(&full[idx], "/L=", 3);
  730. idx += 3;
  731. copy = TRUE;
  732. #ifdef CYASSL_CERT_GEN
  733. if (nameType == SUBJECT) {
  734. cert->subjectL = (char*)&cert->source[cert->srcIdx];
  735. cert->subjectLLen = strLen;
  736. }
  737. #endif /* CYASSL_CERT_GEN */
  738. }
  739. else if (id == ASN_STATE_NAME) {
  740. XMEMCPY(&full[idx], "/ST=", 4);
  741. idx += 4;
  742. copy = TRUE;
  743. #ifdef CYASSL_CERT_GEN
  744. if (nameType == SUBJECT) {
  745. cert->subjectST = (char*)&cert->source[cert->srcIdx];
  746. cert->subjectSTLen = strLen;
  747. }
  748. #endif /* CYASSL_CERT_GEN */
  749. }
  750. else if (id == ASN_ORG_NAME) {
  751. XMEMCPY(&full[idx], "/O=", 3);
  752. idx += 3;
  753. copy = TRUE;
  754. #ifdef CYASSL_CERT_GEN
  755. if (nameType == SUBJECT) {
  756. cert->subjectO = (char*)&cert->source[cert->srcIdx];
  757. cert->subjectOLen = strLen;
  758. }
  759. #endif /* CYASSL_CERT_GEN */
  760. }
  761. else if (id == ASN_ORGUNIT_NAME) {
  762. XMEMCPY(&full[idx], "/OU=", 4);
  763. idx += 4;
  764. copy = TRUE;
  765. #ifdef CYASSL_CERT_GEN
  766. if (nameType == SUBJECT) {
  767. cert->subjectOU = (char*)&cert->source[cert->srcIdx];
  768. cert->subjectOULen = strLen;
  769. }
  770. #endif /* CYASSL_CERT_GEN */
  771. }
  772. if (copy) {
  773. XMEMCPY(&full[idx], &cert->source[cert->srcIdx], strLen);
  774. idx += strLen;
  775. }
  776. ShaUpdate(&sha, &cert->source[cert->srcIdx], strLen);
  777. cert->srcIdx += strLen;
  778. }
  779. else {
  780. /* skip */
  781. byte email = FALSE;
  782. int adv;
  783. if (joint[0] == 0x2a && joint[1] == 0x86) /* email id hdr */
  784. email = TRUE;
  785. cert->srcIdx += oidSz + 1;
  786. if (GetLength(cert->source, &cert->srcIdx, &adv) < 0)
  787. return ASN_PARSE_E;
  788. if (adv > (int)(ASN_NAME_MAX - idx))
  789. return ASN_PARSE_E;
  790. if (email) {
  791. if (14 > (ASN_NAME_MAX - idx))
  792. return ASN_PARSE_E;
  793. XMEMCPY(&full[idx], "/emailAddress=", 14);
  794. idx += 14;
  795. #ifdef CYASSL_CERT_GEN
  796. if (nameType == SUBJECT) {
  797. cert->subjectEmail = (char*)&cert->source[cert->srcIdx];
  798. cert->subjectEmailLen = adv;
  799. }
  800. #endif /* CYASSL_CERT_GEN */
  801. XMEMCPY(&full[idx], &cert->source[cert->srcIdx], adv);
  802. idx += adv;
  803. }
  804. cert->srcIdx += adv;
  805. }
  806. }
  807. full[idx++] = 0;
  808. if (nameType == ISSUER)
  809. ShaFinal(&sha, cert->issuerHash);
  810. else
  811. ShaFinal(&sha, cert->subjectHash);
  812. return 0;
  813. }
  814. #ifndef NO_TIME_H
  815. /* to the second */
  816. static int DateGreaterThan(const struct tm* a, const struct tm* b)
  817. {
  818. if (a->tm_year > b->tm_year)
  819. return 1;
  820. if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
  821. return 1;
  822. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  823. a->tm_mday > b->tm_mday)
  824. return 1;
  825. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  826. a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
  827. return 1;
  828. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  829. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  830. a->tm_min > b->tm_min)
  831. return 1;
  832. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  833. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  834. a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
  835. return 1;
  836. return 0; /* false */
  837. }
  838. static INLINE int DateLessThan(const struct tm* a, const struct tm* b)
  839. {
  840. return !DateGreaterThan(a,b);
  841. }
  842. /* like atoi but only use first byte */
  843. /* Make sure before and after dates are valid */
  844. static int ValidateDate(const byte* date, byte format, int dateType)
  845. {
  846. time_t ltime;
  847. struct tm certTime;
  848. struct tm* localTime;
  849. int i = 0;
  850. ltime = XTIME(0);
  851. XMEMSET(&certTime, 0, sizeof(certTime));
  852. if (format == ASN_UTC_TIME) {
  853. if (btoi(date[0]) >= 5)
  854. certTime.tm_year = 1900;
  855. else
  856. certTime.tm_year = 2000;
  857. }
  858. else { /* format == GENERALIZED_TIME */
  859. certTime.tm_year += btoi(date[i++]) * 1000;
  860. certTime.tm_year += btoi(date[i++]) * 100;
  861. }
  862. GetTime(&certTime.tm_year, date, &i); certTime.tm_year -= 1900; /* adjust */
  863. GetTime(&certTime.tm_mon, date, &i); certTime.tm_mon -= 1; /* adjust */
  864. GetTime(&certTime.tm_mday, date, &i);
  865. GetTime(&certTime.tm_hour, date, &i);
  866. GetTime(&certTime.tm_min, date, &i);
  867. GetTime(&certTime.tm_sec, date, &i);
  868. if (date[i] != 'Z') /* only Zulu supported for this profile */
  869. return 0;
  870. localTime = XGMTIME(&ltime);
  871. if (dateType == BEFORE) {
  872. if (DateLessThan(localTime, &certTime))
  873. return 0;
  874. }
  875. else
  876. if (DateGreaterThan(localTime, &certTime))
  877. return 0;
  878. return 1;
  879. }
  880. #endif /* NO_TIME_H */
  881. static int GetDate(DecodedCert* cert, int dateType)
  882. {
  883. int length;
  884. byte date[MAX_DATE_SIZE];
  885. byte b = cert->source[cert->srcIdx++];
  886. if (b != ASN_UTC_TIME && b != ASN_GENERALIZED_TIME)
  887. return ASN_TIME_E;
  888. if (GetLength(cert->source, &cert->srcIdx, &length) < 0)
  889. return ASN_PARSE_E;
  890. if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
  891. return ASN_DATE_SZ_E;
  892. XMEMCPY(date, &cert->source[cert->srcIdx], length);
  893. cert->srcIdx += length;
  894. if (!XVALIDATE_DATE(date, b, dateType)) {
  895. if (dateType == BEFORE)
  896. return ASN_BEFORE_DATE_E;
  897. else
  898. return ASN_AFTER_DATE_E;
  899. }
  900. return 0;
  901. }
  902. static int GetValidity(DecodedCert* cert, int verify)
  903. {
  904. int length;
  905. int badDate = 0;
  906. if (GetSequence(cert->source, &cert->srcIdx, &length) < 0)
  907. return ASN_PARSE_E;
  908. if (GetDate(cert, BEFORE) < 0 && verify)
  909. badDate = ASN_BEFORE_DATE_E; /* continue parsing */
  910. if (GetDate(cert, AFTER) < 0 && verify)
  911. return ASN_AFTER_DATE_E;
  912. if (badDate != 0)
  913. return badDate;
  914. return 0;
  915. }
  916. static int DecodeToKey(DecodedCert* cert, word32 inSz, int verify)
  917. {
  918. int badDate = 0;
  919. int ret;
  920. if ( (ret = GetCertHeader(cert, inSz)) < 0)
  921. return ret;
  922. if ( (ret = GetAlgoId(cert->source, &cert->srcIdx,&cert->signatureOID)) < 0)
  923. return ret;
  924. if ( (ret = GetName(cert, ISSUER)) < 0)
  925. return ret;
  926. if ( (ret = GetValidity(cert, verify)) < 0)
  927. badDate = ret;
  928. if ( (ret = GetName(cert, SUBJECT)) < 0)
  929. return ret;
  930. if ( (ret = GetKey(cert)) < 0)
  931. return ret;
  932. if (badDate != 0)
  933. return badDate;
  934. return ret;
  935. }
  936. static int GetSignature(DecodedCert* cert)
  937. {
  938. int length;
  939. byte b = cert->source[cert->srcIdx++];
  940. if (b != ASN_BIT_STRING)
  941. return ASN_BITSTR_E;
  942. if (GetLength(cert->source, &cert->srcIdx, &length) < 0)
  943. return ASN_PARSE_E;
  944. cert->sigLength = length;
  945. b = cert->source[cert->srcIdx++];
  946. if (b != 0x00)
  947. return ASN_EXPECT_0_E;
  948. cert->sigLength--;
  949. cert->signature = &cert->source[cert->srcIdx];
  950. cert->srcIdx += cert->sigLength;
  951. return 0;
  952. }
  953. static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
  954. {
  955. output[0] = ASN_OCTET_STRING;
  956. output[1] = digSz;
  957. XMEMCPY(&output[2], digest, digSz);
  958. return digSz + 2;
  959. }
  960. static word32 BytePrecision(word32 value)
  961. {
  962. word32 i;
  963. for (i = sizeof(value); i; --i)
  964. if (value >> (i - 1) * 8)
  965. break;
  966. return i;
  967. }
  968. static word32 SetLength(word32 length, byte* output)
  969. {
  970. word32 i = 0, j;
  971. if (length < ASN_LONG_LENGTH)
  972. output[i++] = length;
  973. else {
  974. output[i++] = BytePrecision(length) | ASN_LONG_LENGTH;
  975. for (j = BytePrecision(length); j; --j) {
  976. output[i] = length >> (j - 1) * 8;
  977. i++;
  978. }
  979. }
  980. return i;
  981. }
  982. static word32 SetSequence(word32 len, byte* output)
  983. {
  984. output[0] = ASN_SEQUENCE | ASN_CONSTRUCTED;
  985. return SetLength(len, output + 1) + 1;
  986. }
  987. static word32 SetAlgoID(int algoOID, byte* output, int type)
  988. {
  989. /* adding TAG_NULL and 0 to end */
  990. /* hashTypes */
  991. static const byte shaAlgoID[] = { 0x2b, 0x0e, 0x03, 0x02, 0x1a,
  992. 0x05, 0x00 };
  993. static const byte md5AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  994. 0x02, 0x05, 0x05, 0x00 };
  995. static const byte md2AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  996. 0x02, 0x02, 0x05, 0x00};
  997. /* sigTypes */
  998. static const byte md5wRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  999. 0x01, 0x01, 0x04, 0x05, 0x00};
  1000. /* keyTypes */
  1001. static const byte RSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  1002. 0x01, 0x01, 0x01, 0x05, 0x00};
  1003. int algoSz = 0;
  1004. word32 idSz, seqSz;
  1005. const byte* algoName = 0;
  1006. byte ID_Length[MAX_LENGTH_SZ];
  1007. byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
  1008. if (type == hashType) {
  1009. switch (algoOID) {
  1010. case SHAh:
  1011. algoSz = sizeof(shaAlgoID);
  1012. algoName = shaAlgoID;
  1013. break;
  1014. case MD2h:
  1015. algoSz = sizeof(md2AlgoID);
  1016. algoName = md2AlgoID;
  1017. break;
  1018. case MD5h:
  1019. algoSz = sizeof(md5AlgoID);
  1020. algoName = md5AlgoID;
  1021. break;
  1022. default:
  1023. return 0; /* UNKOWN_HASH_E; */
  1024. }
  1025. }
  1026. else if (type == sigType) { /* sigType */
  1027. switch (algoOID) {
  1028. case MD5wRSA:
  1029. algoSz = sizeof(md5wRSA_AlgoID);
  1030. algoName = md5wRSA_AlgoID;
  1031. break;
  1032. default:
  1033. return 0; /* UNKOWN_HASH_E; */
  1034. }
  1035. }
  1036. else if (type == keyType) { /* keyType */
  1037. switch (algoOID) {
  1038. case RSAk:
  1039. algoSz = sizeof(RSA_AlgoID);
  1040. algoName = RSA_AlgoID;
  1041. break;
  1042. default:
  1043. return 0; /* UNKOWN_HASH_E; */
  1044. }
  1045. }
  1046. else
  1047. return 0; /* UNKNOWN_TYPE */
  1048. idSz = SetLength(algoSz - 2, ID_Length); /* don't include TAG_NULL/0 */
  1049. seqSz = SetSequence(idSz + algoSz + 1, seqArray);
  1050. seqArray[seqSz++] = ASN_OBJECT_ID;
  1051. XMEMCPY(output, seqArray, seqSz);
  1052. XMEMCPY(output + seqSz, ID_Length, idSz);
  1053. XMEMCPY(output + seqSz + idSz, algoName, algoSz);
  1054. return seqSz + idSz + algoSz;
  1055. }
  1056. word32 EncodeSignature(byte* out, const byte* digest, word32 digSz, int hashOID)
  1057. {
  1058. byte digArray[MAX_ENCODED_DIG_SZ];
  1059. byte algoArray[MAX_ALGO_SZ];
  1060. byte seqArray[MAX_SEQ_SZ];
  1061. word32 encDigSz, algoSz, seqSz;
  1062. encDigSz = SetDigest(digest, digSz, digArray);
  1063. algoSz = SetAlgoID(hashOID, algoArray, hashType);
  1064. seqSz = SetSequence(encDigSz + algoSz, seqArray);
  1065. XMEMCPY(out, seqArray, seqSz);
  1066. XMEMCPY(out + seqSz, algoArray, algoSz);
  1067. XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
  1068. return encDigSz + algoSz + seqSz;
  1069. }
  1070. /* return true (1) for Confirmation */
  1071. static int ConfirmSignature(DecodedCert* cert, const byte* key, word32 keySz,
  1072. word32 keyOID)
  1073. {
  1074. byte digest[SHA_DIGEST_SIZE]; /* max size */
  1075. int hashType, digestSz, ret;
  1076. if (cert->signatureOID == MD5wRSA) {
  1077. Md5 md5;
  1078. InitMd5(&md5);
  1079. Md5Update(&md5, cert->source + cert->certBegin,
  1080. cert->sigIndex - cert->certBegin);
  1081. Md5Final(&md5, digest);
  1082. hashType = MD5h;
  1083. digestSz = MD5_DIGEST_SIZE;
  1084. }
  1085. else if (cert->signatureOID == SHAwRSA || cert->signatureOID == SHAwDSA ||
  1086. cert->signatureOID == SHAwECDSA) {
  1087. Sha sha;
  1088. InitSha(&sha);
  1089. ShaUpdate(&sha, cert->source + cert->certBegin,
  1090. cert->sigIndex - cert->certBegin);
  1091. ShaFinal(&sha, digest);
  1092. hashType = SHAh;
  1093. digestSz = SHA_DIGEST_SIZE;
  1094. }
  1095. else
  1096. return 0; /* ASN_SIG_HASH_E; */
  1097. if (keyOID == RSAk) {
  1098. RsaKey pubKey;
  1099. byte encodedSig[MAX_ENCODED_SIG_SZ];
  1100. byte plain[MAX_ENCODED_SIG_SZ];
  1101. word32 idx = 0;
  1102. int sigSz, verifySz;
  1103. byte* out;
  1104. if (cert->sigLength > MAX_ENCODED_SIG_SZ)
  1105. return 0; /* the key is too big */
  1106. InitRsaKey(&pubKey, cert->heap);
  1107. if (RsaPublicKeyDecode(key, &idx, &pubKey, keySz) < 0)
  1108. ret = 0; /* ASN_KEY_DECODE_E; */
  1109. else {
  1110. XMEMCPY(plain, cert->signature, cert->sigLength);
  1111. if ( (verifySz = RsaSSL_VerifyInline(plain, cert->sigLength, &out,
  1112. &pubKey)) < 0)
  1113. ret = 0; /* ASN_VERIFY_E; */
  1114. else {
  1115. /* make sure we're right justified */
  1116. sigSz = EncodeSignature(encodedSig, digest, digestSz, hashType);
  1117. if (sigSz != verifySz || XMEMCMP(out, encodedSig, sigSz) != 0)
  1118. ret = 0; /* ASN_VERIFY_MATCH_E; */
  1119. else
  1120. ret = 1; /* match */
  1121. }
  1122. }
  1123. FreeRsaKey(&pubKey);
  1124. return ret;
  1125. }
  1126. #ifdef HAVE_ECC
  1127. else if (keyOID == ECDSAk) {
  1128. ecc_key pubKey;
  1129. int verify = 0;
  1130. if (ecc_import_x963(key, keySz, &pubKey) < 0)
  1131. return 0; /* ASN_KEY_DECODE_E */
  1132. ret = ecc_verify_hash(cert->signature, cert->sigLength, digest,
  1133. digestSz, &verify, &pubKey);
  1134. ecc_free(&pubKey);
  1135. if (ret == 0 && verify == 1)
  1136. return 1; /* match */
  1137. return 0; /* ASN_VERIFY_E */
  1138. }
  1139. #endif /* HAVE_ECC */
  1140. else
  1141. return 0; /* ASN_SIG_KEY_E; */
  1142. }
  1143. int ParseCert(DecodedCert* cert, word32 inSz, int type, int verify,
  1144. Signer* signers)
  1145. {
  1146. int ret;
  1147. char* ptr;
  1148. ret = ParseCertRelative(cert, inSz, type, verify, signers);
  1149. if (ret < 0)
  1150. return ret;
  1151. if (cert->subjectCNLen > 0) {
  1152. ptr = (char*) XMALLOC(cert->subjectCNLen + 1, cert->heap,
  1153. DYNAMIC_TYPE_SUBJECT_CN);
  1154. if (ptr == NULL)
  1155. return MEMORY_E;
  1156. XMEMCPY(ptr, cert->subjectCN, cert->subjectCNLen);
  1157. ptr[cert->subjectCNLen] = '\0';
  1158. cert->subjectCN = ptr;
  1159. cert->subjectCNLen = 0;
  1160. }
  1161. if (cert->keyOID == RSAk && cert->pubKeySize > 0) {
  1162. ptr = (char*) XMALLOC(cert->pubKeySize, cert->heap,
  1163. DYNAMIC_TYPE_PUBLIC_KEY);
  1164. if (ptr == NULL)
  1165. return MEMORY_E;
  1166. XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
  1167. cert->publicKey = (byte *)ptr;
  1168. cert->pubKeyStored = 1;
  1169. }
  1170. return ret;
  1171. }
  1172. int ParseCertRelative(DecodedCert* cert, word32 inSz, int type, int verify,
  1173. Signer* signers)
  1174. {
  1175. word32 confirmOID;
  1176. int ret;
  1177. int badDate = 0;
  1178. int confirm = 0;
  1179. if ((ret = DecodeToKey(cert, inSz, verify)) < 0) {
  1180. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E)
  1181. badDate = ret;
  1182. else
  1183. return ret;
  1184. }
  1185. if (cert->srcIdx != cert->sigIndex)
  1186. cert->srcIdx = cert->sigIndex;
  1187. if ((ret = GetAlgoId(cert->source, &cert->srcIdx, &confirmOID)) < 0)
  1188. return ret;
  1189. if ((ret = GetSignature(cert)) < 0)
  1190. return ret;
  1191. if (confirmOID != cert->signatureOID)
  1192. return ASN_SIG_OID_E;
  1193. if (verify && type != CA_TYPE) {
  1194. while (signers) {
  1195. if (XMEMCMP(cert->issuerHash, signers->hash, SHA_DIGEST_SIZE)
  1196. == 0) {
  1197. /* other confirm */
  1198. if (!ConfirmSignature(cert, signers->publicKey,
  1199. signers->pubKeySize, signers->keyOID))
  1200. return ASN_SIG_CONFIRM_E;
  1201. else {
  1202. confirm = 1;
  1203. break;
  1204. }
  1205. }
  1206. signers = signers->next;
  1207. }
  1208. if (!confirm)
  1209. return ASN_SIG_CONFIRM_E;
  1210. }
  1211. if (badDate != 0)
  1212. return badDate;
  1213. return 0;
  1214. }
  1215. Signer* MakeSigner(void* heap)
  1216. {
  1217. Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
  1218. DYNAMIC_TYPE_SIGNER);
  1219. if (signer) {
  1220. signer->name = 0;
  1221. signer->publicKey = 0;
  1222. signer->next = 0;
  1223. }
  1224. return signer;
  1225. }
  1226. void FreeSigners(Signer* signer, void* heap)
  1227. {
  1228. Signer* next = signer;
  1229. while( (signer = next) ) {
  1230. next = signer->next;
  1231. XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  1232. XFREE(signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  1233. XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
  1234. }
  1235. }
  1236. void CTaoCryptErrorString(int error, char* buffer)
  1237. {
  1238. const int max = MAX_ERROR_SZ; /* shorthand */
  1239. #ifdef NO_ERROR_STRINGS
  1240. XSTRNCPY(buffer, "no support for error strings built in", max);
  1241. #else
  1242. switch (error) {
  1243. case OPEN_RAN_E :
  1244. XSTRNCPY(buffer, "opening random device error", max);
  1245. break;
  1246. case READ_RAN_E :
  1247. XSTRNCPY(buffer, "reading random device error", max);
  1248. break;
  1249. case WINCRYPT_E :
  1250. XSTRNCPY(buffer, "windows crypt init error", max);
  1251. break;
  1252. case CRYPTGEN_E :
  1253. XSTRNCPY(buffer, "windows crypt generation error", max);
  1254. break;
  1255. case RAN_BLOCK_E :
  1256. XSTRNCPY(buffer, "random device read would block error", max);
  1257. break;
  1258. case MP_INIT_E :
  1259. XSTRNCPY(buffer, "mp_init error state", max);
  1260. break;
  1261. case MP_READ_E :
  1262. XSTRNCPY(buffer, "mp_read error state", max);
  1263. break;
  1264. case MP_EXPTMOD_E :
  1265. XSTRNCPY(buffer, "mp_exptmod error state", max);
  1266. break;
  1267. case MP_TO_E :
  1268. XSTRNCPY(buffer, "mp_to_xxx error state, can't convert", max);
  1269. break;
  1270. case MP_SUB_E :
  1271. XSTRNCPY(buffer, "mp_sub error state, can't subtract", max);
  1272. break;
  1273. case MP_ADD_E :
  1274. XSTRNCPY(buffer, "mp_add error state, can't add", max);
  1275. break;
  1276. case MP_MUL_E :
  1277. XSTRNCPY(buffer, "mp_mul error state, can't multiply", max);
  1278. break;
  1279. case MP_MULMOD_E :
  1280. XSTRNCPY(buffer, "mp_mulmod error state, can't multiply mod", max);
  1281. break;
  1282. case MP_MOD_E :
  1283. XSTRNCPY(buffer, "mp_mod error state, can't mod", max);
  1284. break;
  1285. case MP_INVMOD_E :
  1286. XSTRNCPY(buffer, "mp_invmod error state, can't inv mod", max);
  1287. break;
  1288. case MP_CMP_E :
  1289. XSTRNCPY(buffer, "mp_cmp error state", max);
  1290. break;
  1291. case MEMORY_E :
  1292. XSTRNCPY(buffer, "out of memory error", max);
  1293. break;
  1294. case RSA_WRONG_TYPE_E :
  1295. XSTRNCPY(buffer, "RSA wrong block type for RSA function", max);
  1296. break;
  1297. case RSA_BUFFER_E :
  1298. XSTRNCPY(buffer, "RSA buffer error, output too small or input too big",
  1299. max);
  1300. break;
  1301. case BUFFER_E :
  1302. XSTRNCPY(buffer, "Buffer error, output too small or input too big", max);
  1303. break;
  1304. case ALGO_ID_E :
  1305. XSTRNCPY(buffer, "Setting Cert AlogID error", max);
  1306. break;
  1307. case PUBLIC_KEY_E :
  1308. XSTRNCPY(buffer, "Setting Cert Public Key error", max);
  1309. break;
  1310. case DATE_E :
  1311. XSTRNCPY(buffer, "Setting Cert Date validity error", max);
  1312. break;
  1313. case SUBJECT_E :
  1314. XSTRNCPY(buffer, "Setting Cert Subject name error", max);
  1315. break;
  1316. case ISSUER_E :
  1317. XSTRNCPY(buffer, "Setting Cert Issuer name error", max);
  1318. break;
  1319. case ASN_PARSE_E :
  1320. XSTRNCPY(buffer, "ASN parsing error, invalid input", max);
  1321. break;
  1322. case ASN_VERSION_E :
  1323. XSTRNCPY(buffer, "ASN version error, invalid number", max);
  1324. break;
  1325. case ASN_GETINT_E :
  1326. XSTRNCPY(buffer, "ASN get big int error, invalid data", max);
  1327. break;
  1328. case ASN_RSA_KEY_E :
  1329. XSTRNCPY(buffer, "ASN key init error, invalid input", max);
  1330. break;
  1331. case ASN_OBJECT_ID_E :
  1332. XSTRNCPY(buffer, "ASN object id error, invalid id", max);
  1333. break;
  1334. case ASN_TAG_NULL_E :
  1335. XSTRNCPY(buffer, "ASN tag error, not null", max);
  1336. break;
  1337. case ASN_EXPECT_0_E :
  1338. XSTRNCPY(buffer, "ASN expect error, not zero", max);
  1339. break;
  1340. case ASN_BITSTR_E :
  1341. XSTRNCPY(buffer, "ASN bit string error, wrong id", max);
  1342. break;
  1343. case ASN_UNKNOWN_OID_E :
  1344. XSTRNCPY(buffer, "ASN oid error, unknown sum id", max);
  1345. break;
  1346. case ASN_DATE_SZ_E :
  1347. XSTRNCPY(buffer, "ASN date error, bad size", max);
  1348. break;
  1349. case ASN_BEFORE_DATE_E :
  1350. XSTRNCPY(buffer, "ASN date error, current date before", max);
  1351. break;
  1352. case ASN_AFTER_DATE_E :
  1353. XSTRNCPY(buffer, "ASN date error, current date after", max);
  1354. break;
  1355. case ASN_SIG_OID_E :
  1356. XSTRNCPY(buffer, "ASN signature error, mismatched oid", max);
  1357. break;
  1358. case ASN_TIME_E :
  1359. XSTRNCPY(buffer, "ASN time error, unkown time type", max);
  1360. break;
  1361. case ASN_INPUT_E :
  1362. XSTRNCPY(buffer, "ASN input error, not enough data", max);
  1363. break;
  1364. case ASN_SIG_CONFIRM_E :
  1365. XSTRNCPY(buffer, "ASN sig error, confirm failure", max);
  1366. break;
  1367. case ASN_SIG_HASH_E :
  1368. XSTRNCPY(buffer, "ASN sig error, unsupported hash type", max);
  1369. break;
  1370. case ASN_SIG_KEY_E :
  1371. XSTRNCPY(buffer, "ASN sig error, unsupported key type", max);
  1372. break;
  1373. case ASN_DH_KEY_E :
  1374. XSTRNCPY(buffer, "ASN key init error, invalid input", max);
  1375. break;
  1376. case ASN_NTRU_KEY_E :
  1377. XSTRNCPY(buffer, "ASN NTRU key decode error, invalid input", max);
  1378. break;
  1379. case ECC_BAD_ARG_E :
  1380. XSTRNCPY(buffer, "ECC input argument wrong type, invalid input", max);
  1381. break;
  1382. case ASN_ECC_KEY_E :
  1383. XSTRNCPY(buffer, "ECC ASN1 bad key data, invalid input", max);
  1384. break;
  1385. case ECC_CURVE_OID_E :
  1386. XSTRNCPY(buffer, "ECC curve sum OID unsupported, invalid input", max);
  1387. break;
  1388. default:
  1389. XSTRNCPY(buffer, "unknown error number", max);
  1390. }
  1391. #endif /* NO_ERROR_STRINGS */
  1392. }
  1393. #if defined(CYASSL_KEY_GEN) || defined(CYASSL_CERT_GEN)
  1394. static int SetMyVersion(word32 version, byte* output, int header)
  1395. {
  1396. int i = 0;
  1397. if (header) {
  1398. output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  1399. output[i++] = ASN_BIT_STRING;
  1400. }
  1401. output[i++] = ASN_INTEGER;
  1402. output[i++] = 0x01;
  1403. output[i++] = version;
  1404. return i;
  1405. }
  1406. int DerToPem(const byte* der, word32 derSz, byte* output, word32 outSz,
  1407. int type)
  1408. {
  1409. char header[80];
  1410. char footer[80];
  1411. int headerLen;
  1412. int footerLen;
  1413. int i;
  1414. int outLen; /* return length or error */
  1415. if (type == CERT_TYPE) {
  1416. XSTRNCPY(header, "-----BEGIN CERTIFICATE-----\n", sizeof(header));
  1417. XSTRNCPY(footer, "-----END CERTIFICATE-----\n", sizeof(footer));
  1418. } else {
  1419. XSTRNCPY(header, "-----BEGIN RSA PRIVATE KEY-----\n", sizeof(header));
  1420. XSTRNCPY(footer, "-----END RSA PRIVATE KEY-----\n", sizeof(footer));
  1421. }
  1422. headerLen = XSTRLEN(header);
  1423. footerLen = XSTRLEN(footer);
  1424. if (!der || !output)
  1425. return -1;
  1426. /* don't even try if outSz too short */
  1427. if (outSz < headerLen + footerLen + derSz)
  1428. return -1;
  1429. /* header */
  1430. XMEMCPY(output, header, headerLen);
  1431. i = headerLen;
  1432. /* body */
  1433. outLen = outSz; /* input to Base64Encode */
  1434. if (Base64Encode(der, derSz, output + i, (word32*)&outLen) < 0)
  1435. return -1;
  1436. i += outLen;
  1437. /* footer */
  1438. if ( (i + footerLen) > (int)outSz)
  1439. return -1;
  1440. XMEMCPY(output + i, footer, footerLen);
  1441. return outLen + headerLen + footerLen;
  1442. }
  1443. #endif /* CYASSL_KEY_GEN || CYASSL_CERT_GEN */
  1444. #ifdef CYASSL_KEY_GEN
  1445. static mp_int* GetRsaInt(RsaKey* key, int index)
  1446. {
  1447. if (index == 0)
  1448. return &key->n;
  1449. if (index == 1)
  1450. return &key->e;
  1451. if (index == 2)
  1452. return &key->d;
  1453. if (index == 3)
  1454. return &key->p;
  1455. if (index == 4)
  1456. return &key->q;
  1457. if (index == 5)
  1458. return &key->dP;
  1459. if (index == 6)
  1460. return &key->dQ;
  1461. if (index == 7)
  1462. return &key->u;
  1463. return NULL;
  1464. }
  1465. /* Convert RsaKey key to DER format, write to output (inLen), return bytes
  1466. written */
  1467. int RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
  1468. {
  1469. word32 seqSz, verSz, rawLen, intTotalLen = 0;
  1470. word32 sizes[RSA_INTS];
  1471. int i, j, outLen;
  1472. byte seq[MAX_SEQ_SZ];
  1473. byte ver[MAX_VERSION_SZ];
  1474. byte tmps[RSA_INTS][MAX_RSA_INT_SZ];
  1475. if (!key || !output)
  1476. return -1;
  1477. if (key->type != RSA_PRIVATE)
  1478. return -1;
  1479. /* write all big ints from key to DER tmps */
  1480. for (i = 0; i < RSA_INTS; i++) {
  1481. mp_int* keyInt = GetRsaInt(key, i);
  1482. rawLen = mp_unsigned_bin_size(keyInt);
  1483. tmps[i][0] = ASN_INTEGER;
  1484. sizes[i] = SetLength(rawLen, tmps[i] + 1) + 1; /* int tag */
  1485. if ( (sizes[i] + rawLen) < sizeof(tmps[i])) {
  1486. int err = mp_to_unsigned_bin(keyInt, tmps[i] + sizes[i]);
  1487. if (err == MP_OKAY) {
  1488. sizes[i] += rawLen;
  1489. intTotalLen += sizes[i];
  1490. }
  1491. else
  1492. return err;
  1493. }
  1494. else
  1495. return -1;
  1496. }
  1497. /* make headers */
  1498. verSz = SetMyVersion(0, ver, FALSE);
  1499. seqSz = SetSequence(verSz + intTotalLen, seq);
  1500. outLen = seqSz + verSz + intTotalLen;
  1501. if (outLen > (int)inLen)
  1502. return -1;
  1503. /* write to output */
  1504. XMEMCPY(output, seq, seqSz);
  1505. j = seqSz;
  1506. XMEMCPY(output + j, ver, verSz);
  1507. j += verSz;
  1508. for (i = 0; i < RSA_INTS; i++) {
  1509. XMEMCPY(output + j, tmps[i], sizes[i]);
  1510. j += sizes[i];
  1511. }
  1512. return outLen;
  1513. }
  1514. #endif /* CYASSL_KEY_GEN */
  1515. #ifdef CYASSL_CERT_GEN
  1516. /* Initialize and Set Certficate defaults:
  1517. version = 3 (0x2)
  1518. serial = 0
  1519. sigType = MD5_WITH_RSA
  1520. issuer = blank
  1521. daysValid = 500
  1522. selfSigned = 1 (true) use subject as issuer
  1523. subject = blank
  1524. */
  1525. void InitCert(Cert* cert)
  1526. {
  1527. cert->version = 2; /* version 3 is hex 2 */
  1528. cert->sigType = MD5wRSA;
  1529. cert->daysValid = 500;
  1530. cert->selfSigned = 1;
  1531. cert->bodySz = 0;
  1532. cert->keyType = RSA_KEY;
  1533. XMEMSET(cert->serial, 0, SERIAL_SIZE);
  1534. cert->issuer.country[0] = '\0';
  1535. cert->issuer.state[0] = '\0';
  1536. cert->issuer.locality[0] = '\0';
  1537. cert->issuer.sur[0] = '\0';
  1538. cert->issuer.org[0] = '\0';
  1539. cert->issuer.unit[0] = '\0';
  1540. cert->issuer.commonName[0] = '\0';
  1541. cert->issuer.email[0] = '\0';
  1542. cert->subject.country[0] = '\0';
  1543. cert->subject.state[0] = '\0';
  1544. cert->subject.locality[0] = '\0';
  1545. cert->subject.sur[0] = '\0';
  1546. cert->subject.org[0] = '\0';
  1547. cert->subject.unit[0] = '\0';
  1548. cert->subject.commonName[0] = '\0';
  1549. cert->subject.email[0] = '\0';
  1550. }
  1551. /* DER encoded x509 Certificate */
  1552. typedef struct DerCert {
  1553. byte size[MAX_LENGTH_SZ]; /* length encoded */
  1554. byte version[MAX_VERSION_SZ]; /* version encoded */
  1555. byte serial[SERIAL_SIZE + MAX_LENGTH_SZ]; /* serial number encoded */
  1556. byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
  1557. byte issuer[ASN_NAME_MAX]; /* issuer encoded */
  1558. byte subject[ASN_NAME_MAX]; /* subject encoded */
  1559. byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
  1560. byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa / ntru public key encoded */
  1561. int sizeSz; /* encoded size length */
  1562. int versionSz; /* encoded version length */
  1563. int serialSz; /* encoded serial length */
  1564. int sigAlgoSz; /* enocded sig alog length */
  1565. int issuerSz; /* encoded issuer length */
  1566. int subjectSz; /* encoded subject length */
  1567. int validitySz; /* encoded validity length */
  1568. int publicKeySz; /* encoded public key length */
  1569. int total; /* total encoded lengths */
  1570. } DerCert;
  1571. /* Write a set header to output */
  1572. static word32 SetSet(word32 len, byte* output)
  1573. {
  1574. output[0] = ASN_SET | ASN_CONSTRUCTED;
  1575. return SetLength(len, output + 1) + 1;
  1576. }
  1577. /* Write a serial number to output */
  1578. static int SetSerial(const byte* serial, byte* output)
  1579. {
  1580. int length = 0;
  1581. output[length++] = ASN_INTEGER;
  1582. length += SetLength(SERIAL_SIZE, &output[length]);
  1583. XMEMCPY(&output[length], serial, SERIAL_SIZE);
  1584. return length + SERIAL_SIZE;
  1585. }
  1586. /* Write a public RSA key to output */
  1587. static int SetPublicKey(byte* output, RsaKey* key)
  1588. {
  1589. byte n[MAX_RSA_INT_SZ];
  1590. byte e[MAX_RSA_E_SZ];
  1591. byte algo[MAX_ALGO_SZ];
  1592. byte seq[MAX_SEQ_SZ];
  1593. byte len[MAX_LENGTH_SZ + 1]; /* trailing 0 */
  1594. int nSz;
  1595. int eSz;
  1596. int algoSz;
  1597. int seqSz;
  1598. int lenSz;
  1599. int idx;
  1600. int rawLen;
  1601. /* n */
  1602. rawLen = mp_unsigned_bin_size(&key->n);
  1603. n[0] = ASN_INTEGER;
  1604. nSz = SetLength(rawLen, n + 1) + 1; /* int tag */
  1605. if ( (nSz + rawLen) < sizeof(n)) {
  1606. int err = mp_to_unsigned_bin(&key->n, n + nSz);
  1607. if (err == MP_OKAY)
  1608. nSz += rawLen;
  1609. else
  1610. return MP_TO_E;
  1611. }
  1612. else
  1613. return BUFFER_E;
  1614. /* e */
  1615. rawLen = mp_unsigned_bin_size(&key->e);
  1616. e[0] = ASN_INTEGER;
  1617. eSz = SetLength(rawLen, e + 1) + 1; /* int tag */
  1618. if ( (eSz + rawLen) < sizeof(e)) {
  1619. int err = mp_to_unsigned_bin(&key->e, e + eSz);
  1620. if (err == MP_OKAY)
  1621. eSz += rawLen;
  1622. else
  1623. return MP_TO_E;
  1624. }
  1625. else
  1626. return BUFFER_E;
  1627. /* headers */
  1628. algoSz = SetAlgoID(RSAk, algo, keyType);
  1629. seqSz = SetSequence(nSz + eSz, seq);
  1630. lenSz = SetLength(seqSz + nSz + eSz + 1, len);
  1631. len[lenSz++] = 0; /* trailing 0 */
  1632. /* write */
  1633. idx = SetSequence(nSz + eSz + seqSz + lenSz + 1 + algoSz, output);
  1634. /* 1 is for ASN_BIT_STRING */
  1635. /* algo */
  1636. XMEMCPY(output + idx, algo, algoSz);
  1637. idx += algoSz;
  1638. /* bit string */
  1639. output[idx++] = ASN_BIT_STRING;
  1640. /* length */
  1641. XMEMCPY(output + idx, len, lenSz);
  1642. idx += lenSz;
  1643. /* seq */
  1644. XMEMCPY(output + idx, seq, seqSz);
  1645. idx += seqSz;
  1646. /* n */
  1647. XMEMCPY(output + idx, n, nSz);
  1648. idx += nSz;
  1649. /* e */
  1650. XMEMCPY(output + idx, e, eSz);
  1651. idx += eSz;
  1652. return idx;
  1653. }
  1654. static INLINE byte itob(int number)
  1655. {
  1656. return (byte)number + 0x30;
  1657. }
  1658. /* write time to output, format */
  1659. static void SetTime(struct tm* date, byte* output)
  1660. {
  1661. int i = 0;
  1662. output[i++] = itob((date->tm_year % 10000) / 1000);
  1663. output[i++] = itob((date->tm_year % 1000) / 100);
  1664. output[i++] = itob((date->tm_year % 100) / 10);
  1665. output[i++] = itob( date->tm_year % 10);
  1666. output[i++] = itob(date->tm_mon / 10);
  1667. output[i++] = itob(date->tm_mon % 10);
  1668. output[i++] = itob(date->tm_mday / 10);
  1669. output[i++] = itob(date->tm_mday % 10);
  1670. output[i++] = itob(date->tm_hour / 10);
  1671. output[i++] = itob(date->tm_hour % 10);
  1672. output[i++] = itob(date->tm_min / 10);
  1673. output[i++] = itob(date->tm_min % 10);
  1674. output[i++] = itob(date->tm_sec / 10);
  1675. output[i++] = itob(date->tm_sec % 10);
  1676. output[i] = 'Z'; /* Zulu profiel */
  1677. }
  1678. /* Set Date validity from now until now + daysValid */
  1679. static int SetValidity(byte* output, int daysValid)
  1680. {
  1681. byte before[MAX_DATE_SIZE];
  1682. byte after[MAX_DATE_SIZE];
  1683. int beforeSz;
  1684. int afterSz;
  1685. int seqSz;
  1686. time_t ticks;
  1687. struct tm* now;
  1688. struct tm local;
  1689. ticks = XTIME(0);
  1690. now = XGMTIME(&ticks);
  1691. /* before now */
  1692. local = *now;
  1693. before[0] = ASN_GENERALIZED_TIME;
  1694. beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
  1695. /* adjust */
  1696. local.tm_year += 1900;
  1697. local.tm_mon += 1;
  1698. SetTime(&local, before + beforeSz);
  1699. beforeSz += ASN_GEN_TIME_SZ;
  1700. /* after now + daysValid */
  1701. local = *now;
  1702. after[0] = ASN_GENERALIZED_TIME;
  1703. afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
  1704. /* add daysValid */
  1705. local.tm_mday += daysValid;
  1706. mktime(&local);
  1707. /* adjust */
  1708. local.tm_year += 1900;
  1709. local.tm_mon += 1;
  1710. SetTime(&local, after + afterSz);
  1711. afterSz += ASN_GEN_TIME_SZ;
  1712. /* headers and output */
  1713. seqSz = SetSequence(beforeSz + afterSz, output);
  1714. XMEMCPY(output + seqSz, before, beforeSz);
  1715. XMEMCPY(output + seqSz + beforeSz, after, afterSz);
  1716. return seqSz + beforeSz + afterSz;
  1717. }
  1718. /* ASN Encoded Name field */
  1719. typedef struct EncodedName {
  1720. int nameLen; /* actual string value length */
  1721. int totalLen; /* total encodeding length */
  1722. int type; /* type of name */
  1723. int used; /* are we actually using this one */
  1724. byte encoded[NAME_SIZE * 2]; /* encoding */
  1725. } EncodedName;
  1726. /* Get Which Name from index */
  1727. static const char* GetOneName(CertName* name, int index)
  1728. {
  1729. switch (index) {
  1730. case 0:
  1731. return name->country;
  1732. break;
  1733. case 1:
  1734. return name->state;
  1735. break;
  1736. case 2:
  1737. return name->locality;
  1738. break;
  1739. case 3:
  1740. return name->sur;
  1741. break;
  1742. case 4:
  1743. return name->org;
  1744. break;
  1745. case 5:
  1746. return name->unit;
  1747. break;
  1748. case 6:
  1749. return name->commonName;
  1750. break;
  1751. case 7:
  1752. return name->email;
  1753. break;
  1754. default:
  1755. return 0;
  1756. }
  1757. return 0;
  1758. }
  1759. /* Get ASN Name from index */
  1760. static byte GetNameId(int index)
  1761. {
  1762. switch (index) {
  1763. case 0:
  1764. return ASN_COUNTRY_NAME;
  1765. break;
  1766. case 1:
  1767. return ASN_STATE_NAME;
  1768. break;
  1769. case 2:
  1770. return ASN_LOCALITY_NAME;
  1771. break;
  1772. case 3:
  1773. return ASN_SUR_NAME;
  1774. break;
  1775. case 4:
  1776. return ASN_ORG_NAME;
  1777. break;
  1778. case 5:
  1779. return ASN_ORGUNIT_NAME;
  1780. break;
  1781. case 6:
  1782. return ASN_COMMON_NAME;
  1783. break;
  1784. case 7:
  1785. /* email uses different id type */
  1786. return 0;
  1787. break;
  1788. default:
  1789. return 0;
  1790. }
  1791. return 0;
  1792. }
  1793. /* encode CertName into output, return total bytes written */
  1794. static int SetName(byte* output, CertName* name)
  1795. {
  1796. int totalBytes = 0, i, idx;
  1797. EncodedName names[NAME_ENTRIES];
  1798. for (i = 0; i < NAME_ENTRIES; i++) {
  1799. const char* nameStr = GetOneName(name, i);
  1800. if (nameStr) {
  1801. /* bottom up */
  1802. byte firstLen[MAX_LENGTH_SZ];
  1803. byte secondLen[MAX_LENGTH_SZ];
  1804. byte sequence[MAX_SEQ_SZ];
  1805. byte set[MAX_SET_SZ];
  1806. int email = i == (NAME_ENTRIES - 1) ? 1 : 0;
  1807. int strLen = XSTRLEN(nameStr);
  1808. int thisLen = strLen;
  1809. int firstSz, secondSz, seqSz, setSz;
  1810. if (strLen == 0) { /* no user data for this item */
  1811. names[i].used = 0;
  1812. continue;
  1813. }
  1814. secondSz = SetLength(strLen, secondLen);
  1815. thisLen += secondSz;
  1816. if (email) {
  1817. thisLen += EMAIL_JOINT_LEN;
  1818. thisLen ++; /* id type */
  1819. firstSz = SetLength(EMAIL_JOINT_LEN, firstLen);
  1820. }
  1821. else {
  1822. thisLen++; /* str type */
  1823. thisLen++; /* id type */
  1824. thisLen += JOINT_LEN;
  1825. firstSz = SetLength(JOINT_LEN + 1, firstLen);
  1826. }
  1827. thisLen += firstSz;
  1828. thisLen++; /* object id */
  1829. seqSz = SetSequence(thisLen, sequence);
  1830. thisLen += seqSz;
  1831. setSz = SetSet(thisLen, set);
  1832. thisLen += setSz;
  1833. if (thisLen > sizeof(names[i].encoded))
  1834. return BUFFER_E;
  1835. /* store it */
  1836. idx = 0;
  1837. /* set */
  1838. XMEMCPY(names[i].encoded, set, setSz);
  1839. idx += setSz;
  1840. /* seq */
  1841. XMEMCPY(names[i].encoded + idx, sequence, seqSz);
  1842. idx += seqSz;
  1843. /* asn object id */
  1844. names[i].encoded[idx++] = ASN_OBJECT_ID;
  1845. /* first length */
  1846. XMEMCPY(names[i].encoded + idx, firstLen, firstSz);
  1847. idx += firstSz;
  1848. if (email) {
  1849. const byte EMAIL_OID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  1850. 0x01, 0x09, 0x01, 0x16 };
  1851. /* email joint id */
  1852. XMEMCPY(names[i].encoded + idx, EMAIL_OID, sizeof(EMAIL_OID));
  1853. idx += sizeof(EMAIL_OID);
  1854. }
  1855. else {
  1856. /* joint id */
  1857. names[i].encoded[idx++] = 0x55;
  1858. names[i].encoded[idx++] = 0x04;
  1859. /* id type */
  1860. names[i].encoded[idx++] = GetNameId(i);
  1861. /* str type */
  1862. names[i].encoded[idx++] = 0x13;
  1863. }
  1864. /* second length */
  1865. XMEMCPY(names[i].encoded + idx, secondLen, secondSz);
  1866. idx += secondSz;
  1867. /* str value */
  1868. XMEMCPY(names[i].encoded + idx, nameStr, strLen);
  1869. idx += strLen;
  1870. totalBytes += idx;
  1871. names[i].totalLen = idx;
  1872. names[i].used = 1;
  1873. }
  1874. else
  1875. names[i].used = 0;
  1876. }
  1877. /* header */
  1878. idx = SetSequence(totalBytes, output);
  1879. totalBytes += idx;
  1880. if (totalBytes > ASN_NAME_MAX)
  1881. return BUFFER_E;
  1882. for (i = 0; i < NAME_ENTRIES; i++) {
  1883. if (names[i].used) {
  1884. XMEMCPY(output + idx, names[i].encoded, names[i].totalLen);
  1885. idx += names[i].totalLen;
  1886. }
  1887. }
  1888. return totalBytes;
  1889. }
  1890. /* encode info from cert into DER enocder format */
  1891. static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, RNG* rng,
  1892. const byte* ntruKey, word16 ntruSz)
  1893. {
  1894. /* version */
  1895. der->versionSz = SetMyVersion(cert->version, der->version, TRUE);
  1896. /* serial number */
  1897. RNG_GenerateBlock(rng, cert->serial, SERIAL_SIZE);
  1898. cert->serial[0] = 0x01; /* ensure positive */
  1899. der->serialSz = SetSerial(cert->serial, der->serial);
  1900. /* signature algo */
  1901. der->sigAlgoSz = SetAlgoID(cert->sigType, der->sigAlgo, sigType);
  1902. if (der->sigAlgoSz == 0)
  1903. return ALGO_ID_E;
  1904. /* public key */
  1905. if (cert->keyType == RSA_KEY) {
  1906. der->publicKeySz = SetPublicKey(der->publicKey, rsaKey);
  1907. if (der->publicKeySz == 0)
  1908. return PUBLIC_KEY_E;
  1909. }
  1910. else {
  1911. #ifdef HAVE_NTRU
  1912. word32 rc;
  1913. word16 encodedSz;
  1914. rc = crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo( ntruSz,
  1915. ntruKey, &encodedSz, NULL);
  1916. if (rc != NTRU_OK)
  1917. return PUBLIC_KEY_E;
  1918. if (encodedSz > MAX_PUBLIC_KEY_SZ)
  1919. return PUBLIC_KEY_E;
  1920. rc = crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo( ntruSz,
  1921. ntruKey, &encodedSz, der->publicKey);
  1922. if (rc != NTRU_OK)
  1923. return PUBLIC_KEY_E;
  1924. der->publicKeySz = encodedSz;
  1925. #endif
  1926. }
  1927. /* date validity */
  1928. der->validitySz = SetValidity(der->validity, cert->daysValid);
  1929. if (der->validitySz == 0)
  1930. return DATE_E;
  1931. /* subject name */
  1932. der->subjectSz = SetName(der->subject, &cert->subject);
  1933. if (der->subjectSz == 0)
  1934. return SUBJECT_E;
  1935. /* issuer name */
  1936. der->issuerSz = SetName(der->issuer, cert->selfSigned ?
  1937. &cert->subject : &cert->issuer);
  1938. if (der->issuerSz == 0)
  1939. return ISSUER_E;
  1940. der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
  1941. der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz;
  1942. return 0;
  1943. }
  1944. /* write DER encoded cert to buffer, size already checked */
  1945. static int WriteCertBody(DerCert* der, byte* buffer)
  1946. {
  1947. int idx;
  1948. /* signed part header */
  1949. idx = SetSequence(der->total, buffer);
  1950. /* version */
  1951. XMEMCPY(buffer + idx, der->version, der->versionSz);
  1952. idx += der->versionSz;
  1953. /* serial */
  1954. XMEMCPY(buffer + idx, der->serial, der->serialSz);
  1955. idx += der->serialSz;
  1956. /* sig algo */
  1957. XMEMCPY(buffer + idx, der->sigAlgo, der->sigAlgoSz);
  1958. idx += der->sigAlgoSz;
  1959. /* issuer */
  1960. XMEMCPY(buffer + idx, der->issuer, der->issuerSz);
  1961. idx += der->issuerSz;
  1962. /* validity */
  1963. XMEMCPY(buffer + idx, der->validity, der->validitySz);
  1964. idx += der->validitySz;
  1965. /* subject */
  1966. XMEMCPY(buffer + idx, der->subject, der->subjectSz);
  1967. idx += der->subjectSz;
  1968. /* public key */
  1969. XMEMCPY(buffer + idx, der->publicKey, der->publicKeySz);
  1970. idx += der->publicKeySz;
  1971. return idx;
  1972. }
  1973. /* Make MD5wRSA signature from buffer (sz), write to sig (sigSz) */
  1974. static int MakeSignature(const byte* buffer, int sz, byte* sig, int sigSz,
  1975. RsaKey* key, RNG* rng)
  1976. {
  1977. byte digest[SHA_DIGEST_SIZE]; /* max size */
  1978. byte encSig[MAX_ENCODED_DIG_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ];
  1979. int encSigSz, digestSz, hashType;
  1980. Md5 md5; /* md5 for now */
  1981. InitMd5(&md5);
  1982. Md5Update(&md5, buffer, sz);
  1983. Md5Final(&md5, digest);
  1984. digestSz = MD5_DIGEST_SIZE;
  1985. hashType = MD5h;
  1986. /* signature */
  1987. encSigSz = EncodeSignature(encSig, digest, digestSz, hashType);
  1988. return RsaSSL_Sign(encSig, encSigSz, sig, sigSz, key, rng);
  1989. }
  1990. /* add signature to end of buffer, size of buffer assumed checked, return
  1991. new length */
  1992. static int AddSignature(byte* buffer, int bodySz, const byte* sig, int sigSz)
  1993. {
  1994. byte seq[MAX_SEQ_SZ];
  1995. int idx = bodySz, seqSz;
  1996. /* algo */
  1997. idx += SetAlgoID(MD5wRSA, buffer + idx, sigType);
  1998. /* bit string */
  1999. buffer[idx++] = ASN_BIT_STRING;
  2000. /* length */
  2001. idx += SetLength(sigSz + 1, buffer + idx);
  2002. buffer[idx++] = 0; /* trailing 0 */
  2003. /* signature */
  2004. XMEMCPY(buffer + idx, sig, sigSz);
  2005. idx += sigSz;
  2006. /* make room for overall header */
  2007. seqSz = SetSequence(idx, seq);
  2008. XMEMMOVE(buffer + seqSz, buffer, idx);
  2009. XMEMCPY(buffer, seq, seqSz);
  2010. return idx + seqSz;
  2011. }
  2012. /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
  2013. static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
  2014. RsaKey* rsaKey, RNG* rng, const byte* ntruKey, word16 ntruSz)
  2015. {
  2016. DerCert der;
  2017. int ret;
  2018. cert->keyType = rsaKey ? RSA_KEY : NTRU_KEY;
  2019. ret = EncodeCert(cert, &der, rsaKey, rng, ntruKey, ntruSz);
  2020. if (ret != 0)
  2021. return ret;
  2022. if (der.total + MAX_SEQ_SZ * 2 > (int)derSz)
  2023. return BUFFER_E;
  2024. return cert->bodySz = WriteCertBody(&der, derBuffer);
  2025. }
  2026. /* Make an x509 Certificate v3 RSA from cert input, write to buffer */
  2027. int MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,RNG* rng)
  2028. {
  2029. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, rng, NULL, 0);
  2030. }
  2031. #ifdef HAVE_NTRU
  2032. int MakeNtruCert(Cert* cert, byte* derBuffer, word32 derSz,
  2033. const byte* ntruKey, word16 keySz, RNG* rng)
  2034. {
  2035. return MakeAnyCert(cert, derBuffer, derSz, NULL, rng, ntruKey, keySz);
  2036. }
  2037. #endif /* HAVE_NTRU */
  2038. int SignCert(Cert* cert, byte* buffer, word32 buffSz, RsaKey* key, RNG* rng)
  2039. {
  2040. byte sig[MAX_ENCODED_SIG_SZ];
  2041. int sigSz;
  2042. int bodySz = cert->bodySz;
  2043. if (bodySz < 0)
  2044. return bodySz;
  2045. sigSz = MakeSignature(buffer, bodySz, sig, sizeof(sig), key, rng);
  2046. if (sigSz < 0)
  2047. return sigSz;
  2048. if (bodySz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
  2049. return BUFFER_E;
  2050. return AddSignature(buffer, bodySz, sig, sigSz);
  2051. }
  2052. int MakeSelfCert(Cert* cert, byte* buffer, word32 buffSz, RsaKey* key, RNG* rng)
  2053. {
  2054. int ret = MakeCert(cert, buffer, buffSz, key, rng);
  2055. if (ret < 0)
  2056. return ret;
  2057. return SignCert(cert, buffer, buffSz, key, rng);
  2058. }
  2059. /* forward from CyaSSL */
  2060. int CyaSSL_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz);
  2061. #ifndef NO_FILESYSTEM
  2062. int SetIssuer(Cert* cert, const char* issuerCertFile)
  2063. {
  2064. DecodedCert decoded;
  2065. byte der[8192];
  2066. int derSz = CyaSSL_PemCertToDer(issuerCertFile, der, sizeof(der));
  2067. int ret;
  2068. int sz;
  2069. if (derSz < 0)
  2070. return derSz;
  2071. cert->selfSigned = 0;
  2072. InitDecodedCert(&decoded, der, 0);
  2073. ret = ParseCertRelative(&decoded, derSz, CA_TYPE, NO_VERIFY, 0);
  2074. if (ret < 0)
  2075. return ret;
  2076. if (decoded.subjectCN) {
  2077. sz = (decoded.subjectCNLen < NAME_SIZE) ? decoded.subjectCNLen :
  2078. NAME_SIZE - 1;
  2079. strncpy(cert->issuer.commonName, decoded.subjectCN, NAME_SIZE);
  2080. cert->issuer.commonName[sz] = 0;
  2081. }
  2082. if (decoded.subjectC) {
  2083. sz = (decoded.subjectCLen < NAME_SIZE) ? decoded.subjectCLen :
  2084. NAME_SIZE - 1;
  2085. strncpy(cert->issuer.country, decoded.subjectC, NAME_SIZE);
  2086. cert->issuer.country[sz] = 0;
  2087. }
  2088. if (decoded.subjectST) {
  2089. sz = (decoded.subjectSTLen < NAME_SIZE) ? decoded.subjectSTLen :
  2090. NAME_SIZE - 1;
  2091. strncpy(cert->issuer.state, decoded.subjectST, NAME_SIZE);
  2092. cert->issuer.state[sz] = 0;
  2093. }
  2094. if (decoded.subjectL) {
  2095. sz = (decoded.subjectLLen < NAME_SIZE) ? decoded.subjectLLen :
  2096. NAME_SIZE - 1;
  2097. strncpy(cert->issuer.locality, decoded.subjectL, NAME_SIZE);
  2098. cert->issuer.locality[sz] = 0;
  2099. }
  2100. if (decoded.subjectO) {
  2101. sz = (decoded.subjectOLen < NAME_SIZE) ? decoded.subjectOLen :
  2102. NAME_SIZE - 1;
  2103. strncpy(cert->issuer.org, decoded.subjectO, NAME_SIZE);
  2104. cert->issuer.org[sz] = 0;
  2105. }
  2106. if (decoded.subjectOU) {
  2107. sz = (decoded.subjectOULen < NAME_SIZE) ? decoded.subjectOULen :
  2108. NAME_SIZE - 1;
  2109. strncpy(cert->issuer.unit, decoded.subjectOU, NAME_SIZE);
  2110. cert->issuer.unit[sz] = 0;
  2111. }
  2112. if (decoded.subjectSN) {
  2113. sz = (decoded.subjectSNLen < NAME_SIZE) ? decoded.subjectSNLen :
  2114. NAME_SIZE - 1;
  2115. strncpy(cert->issuer.sur, decoded.subjectSN, NAME_SIZE);
  2116. cert->issuer.sur[sz] = 0;
  2117. }
  2118. if (decoded.subjectEmail) {
  2119. sz = (decoded.subjectEmailLen < NAME_SIZE) ? decoded.subjectEmailLen :
  2120. NAME_SIZE - 1;
  2121. strncpy(cert->issuer.email, decoded.subjectEmail, NAME_SIZE);
  2122. cert->issuer.email[sz] = 0;
  2123. }
  2124. FreeDecodedCert(&decoded);
  2125. return 0;
  2126. }
  2127. #endif /* NO_FILESYSTEM */
  2128. #endif /* CYASSL_CERT_GEN */
  2129. #ifdef HAVE_ECC
  2130. /* Der Eoncde r & s ints into out, outLen is (in/out) size */
  2131. int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
  2132. {
  2133. word32 idx = 0;
  2134. word32 rSz; /* encoding size */
  2135. word32 sSz;
  2136. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  2137. int rLen = mp_unsigned_bin_size(r); /* big int size */
  2138. int sLen = mp_unsigned_bin_size(s);
  2139. int err;
  2140. if (*outLen < (rLen + sLen + headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
  2141. return -1;
  2142. idx = SetSequence(rLen + sLen + headerSz, out);
  2143. /* store r */
  2144. out[idx++] = ASN_INTEGER;
  2145. rSz = SetLength(rLen, &out[idx]);
  2146. idx += rSz;
  2147. err = mp_to_unsigned_bin(r, &out[idx]);
  2148. if (err != MP_OKAY) return err;
  2149. idx += rLen;
  2150. /* store s */
  2151. out[idx++] = ASN_INTEGER;
  2152. sSz = SetLength(sLen, &out[idx]);
  2153. idx += sSz;
  2154. err = mp_to_unsigned_bin(s, &out[idx]);
  2155. if (err != MP_OKAY) return err;
  2156. idx += sLen;
  2157. *outLen = idx;
  2158. return 0;
  2159. }
  2160. /* Der Decode ECC-DSA Signautre, r & s stored as big ints */
  2161. int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
  2162. {
  2163. word32 idx = 0;
  2164. int len = 0;
  2165. if (GetSequence(sig, &idx, &len) < 0)
  2166. return ASN_ECC_KEY_E;
  2167. if ((word32)len > (sigLen - idx))
  2168. return ASN_ECC_KEY_E;
  2169. if (GetInt(r, sig, &idx) < 0)
  2170. return ASN_ECC_KEY_E;
  2171. if (GetInt(s, sig, &idx) < 0)
  2172. return ASN_ECC_KEY_E;
  2173. return 0;
  2174. }
  2175. int EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
  2176. word32 inSz)
  2177. {
  2178. word32 begin = *inOutIdx;
  2179. word32 oid = 0;
  2180. int version, length;
  2181. int privSz, pubSz;
  2182. byte b;
  2183. byte priv[ECC_MAXSIZE];
  2184. byte pub[ECC_MAXSIZE * 2 + 1]; /* public key has two parts plus header */
  2185. if (GetSequence(input, inOutIdx, &length) < 0)
  2186. return ASN_PARSE_E;
  2187. if ((word32)length > (inSz - (*inOutIdx - begin)))
  2188. return ASN_INPUT_E;
  2189. if (GetMyVersion(input, inOutIdx, &version) < 0)
  2190. return ASN_PARSE_E;
  2191. b = input[*inOutIdx];
  2192. *inOutIdx += 1;
  2193. /* priv type */
  2194. if (b != 4 && b != 6 && b != 7)
  2195. return ASN_PARSE_E;
  2196. if (GetLength(input, inOutIdx, &length) < 0)
  2197. return ASN_PARSE_E;
  2198. /* priv key */
  2199. privSz = length;
  2200. XMEMCPY(priv, &input[*inOutIdx], privSz);
  2201. *inOutIdx += length;
  2202. /* prefix 0 */
  2203. b = input[*inOutIdx];
  2204. *inOutIdx += 1;
  2205. if (GetLength(input, inOutIdx, &length) < 0)
  2206. return ASN_PARSE_E;
  2207. /* object id */
  2208. b = input[*inOutIdx];
  2209. *inOutIdx += 1;
  2210. if (b != ASN_OBJECT_ID)
  2211. return ASN_OBJECT_ID_E;
  2212. if (GetLength(input, inOutIdx, &length) < 0)
  2213. return ASN_PARSE_E;
  2214. while(length--) {
  2215. oid += input[*inOutIdx];
  2216. *inOutIdx += 1;
  2217. }
  2218. if (CheckCurve(oid) < 0)
  2219. return ECC_CURVE_OID_E;
  2220. /* prefix 1 */
  2221. b = input[*inOutIdx];
  2222. *inOutIdx += 1;
  2223. if (GetLength(input, inOutIdx, &length) < 0)
  2224. return ASN_PARSE_E;
  2225. /* key header */
  2226. b = input[*inOutIdx];
  2227. *inOutIdx += 1;
  2228. if (b != ASN_BIT_STRING)
  2229. return ASN_BITSTR_E;
  2230. if (GetLength(input, inOutIdx, &length) < 0)
  2231. return ASN_PARSE_E;
  2232. b = input[*inOutIdx];
  2233. *inOutIdx += 1;
  2234. if (b != 0x00)
  2235. return ASN_EXPECT_0_E;
  2236. pubSz = length - 1; /* null prefix */
  2237. XMEMCPY(pub, &input[*inOutIdx], pubSz);
  2238. *inOutIdx += length;
  2239. return ecc_import_private_key(priv, privSz, pub, pubSz, key);
  2240. }
  2241. #endif /* HAVE_ECC */