asn.c 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589
  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 HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #ifdef THREADX
  25. #include "os.h" /* dc_rtc_api needs */
  26. #include "dc_rtc_api.h" /* to get current time */
  27. #endif
  28. #include <cyassl/ctaocrypt/asn.h>
  29. #include <cyassl/ctaocrypt/coding.h>
  30. #include <cyassl/ctaocrypt/sha.h>
  31. #include <cyassl/ctaocrypt/md5.h>
  32. #include <cyassl/ctaocrypt/error.h>
  33. #include <cyassl/ctaocrypt/pwdbased.h>
  34. #include <cyassl/ctaocrypt/des3.h>
  35. #include <cyassl/ctaocrypt/sha256.h>
  36. #include <cyassl/ctaocrypt/logging.h>
  37. #ifdef HAVE_NTRU
  38. #include "crypto_ntru.h"
  39. #endif
  40. #ifdef HAVE_ECC
  41. #include <cyassl/ctaocrypt/ecc.h>
  42. #endif
  43. #ifdef _MSC_VER
  44. /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
  45. #pragma warning(disable: 4996)
  46. #endif
  47. #ifndef TRUE
  48. enum {
  49. FALSE = 0,
  50. TRUE = 1
  51. };
  52. #endif
  53. #ifdef THREADX
  54. /* uses parital <time.h> structures */
  55. #define XTIME(tl) (0)
  56. #define XGMTIME(c) my_gmtime((c))
  57. #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
  58. #elif defined(MICRIUM)
  59. #if (NET_SECURE_MGR_CFG_EN == DEF_ENABLED)
  60. #define XVALIDATE_DATE(d,f,t) NetSecure_ValidateDateHandler((d),(f),(t))
  61. #else
  62. #define XVALIDATE_DATE(d, f, t) (0)
  63. #endif
  64. #define NO_TIME_H
  65. /* since Micrium not defining XTIME or XGMTIME, CERT_GEN not available */
  66. #elif defined(USER_TIME)
  67. /* no <time.h> structures used */
  68. #define NO_TIME_H
  69. /* user time, and gmtime compatible functions, there is a gmtime
  70. implementation here that WINCE uses, so really just need some ticks
  71. since the EPOCH
  72. */
  73. #else
  74. /* default */
  75. /* uses complete <time.h> facility */
  76. #include <time.h>
  77. #define XTIME(tl) time((tl))
  78. #define XGMTIME(c) gmtime((c))
  79. #define XVALIDATE_DATE(d, f, t) ValidateDate((d), (f), (t))
  80. #endif
  81. #ifdef _WIN32_WCE
  82. /* no time() or gmtime() even though in time.h header?? */
  83. #include <windows.h>
  84. time_t time(time_t* timer)
  85. {
  86. SYSTEMTIME sysTime;
  87. FILETIME fTime;
  88. ULARGE_INTEGER intTime;
  89. time_t localTime;
  90. if (timer == NULL)
  91. timer = &localTime;
  92. GetSystemTime(&sysTime);
  93. SystemTimeToFileTime(&sysTime, &fTime);
  94. XMEMCPY(&intTime, &fTime, sizeof(FILETIME));
  95. /* subtract EPOCH */
  96. intTime.QuadPart -= 0x19db1ded53e8000;
  97. /* to secs */
  98. intTime.QuadPart /= 10000000;
  99. *timer = (time_t)intTime.QuadPart;
  100. return *timer;
  101. }
  102. struct tm* gmtime(const time_t* timer)
  103. {
  104. #define YEAR0 1900
  105. #define EPOCH_YEAR 1970
  106. #define SECS_DAY (24L * 60L * 60L)
  107. #define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) %400)))
  108. #define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365)
  109. static const int _ytab[2][12] =
  110. {
  111. {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
  112. {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
  113. };
  114. static struct tm st_time;
  115. struct tm* ret = &st_time;
  116. time_t time = *timer;
  117. unsigned long dayclock, dayno;
  118. int year = EPOCH_YEAR;
  119. dayclock = (unsigned long)time % SECS_DAY;
  120. dayno = (unsigned long)time / SECS_DAY;
  121. ret->tm_sec = dayclock % 60;
  122. ret->tm_min = (dayclock % 3600) / 60;
  123. ret->tm_hour = dayclock / 3600;
  124. ret->tm_wday = (dayno + 4) % 7; /* day 0 a Thursday */
  125. while(dayno >= (unsigned long)YEARSIZE(year)) {
  126. dayno -= YEARSIZE(year);
  127. year++;
  128. }
  129. ret->tm_year = year - YEAR0;
  130. ret->tm_yday = dayno;
  131. ret->tm_mon = 0;
  132. while(dayno >= (unsigned long)_ytab[LEAPYEAR(year)][ret->tm_mon]) {
  133. dayno -= _ytab[LEAPYEAR(year)][ret->tm_mon];
  134. ret->tm_mon++;
  135. }
  136. ret->tm_mday = ++dayno;
  137. ret->tm_isdst = 0;
  138. return ret;
  139. }
  140. #endif /* _WIN32_WCE */
  141. #ifdef THREADX
  142. #define YEAR0 1900
  143. struct tm* my_gmtime(const time_t* timer) /* has a gmtime() but hangs */
  144. {
  145. static struct tm st_time;
  146. struct tm* ret = &st_time;
  147. DC_RTC_CALENDAR cal;
  148. dc_rtc_time_get(&cal, TRUE);
  149. ret->tm_year = cal.year - YEAR0; /* gm starts at 1900 */
  150. ret->tm_mon = cal.month - 1; /* gm starts at 0 */
  151. ret->tm_mday = cal.day;
  152. ret->tm_hour = cal.hour;
  153. ret->tm_min = cal.minute;
  154. ret->tm_sec = cal.second;
  155. return ret;
  156. }
  157. #endif /* THREADX */
  158. static INLINE word32 btoi(byte b)
  159. {
  160. return b - 0x30;
  161. }
  162. /* two byte date/time, add to value */
  163. static INLINE void GetTime(int* value, const byte* date, int* idx)
  164. {
  165. int i = *idx;
  166. *value += btoi(date[i++]) * 10;
  167. *value += btoi(date[i++]);
  168. *idx = i;
  169. }
  170. #if defined(MICRIUM)
  171. CPU_INT32S NetSecure_ValidateDateHandler(CPU_INT08U *date, CPU_INT08U format,
  172. CPU_INT08U dateType)
  173. {
  174. CPU_BOOLEAN rtn_code;
  175. CPU_INT32S i;
  176. CPU_INT32S val;
  177. CPU_INT16U year;
  178. CPU_INT08U month;
  179. CPU_INT16U day;
  180. CPU_INT08U hour;
  181. CPU_INT08U min;
  182. CPU_INT08U sec;
  183. i = 0;
  184. year = 0u;
  185. if (format == ASN_UTC_TIME) {
  186. if (btoi(date[0]) >= 5)
  187. year = 1900;
  188. else
  189. year = 2000;
  190. }
  191. else { /* format == GENERALIZED_TIME */
  192. year += btoi(date[i++]) * 1000;
  193. year += btoi(date[i++]) * 100;
  194. }
  195. val = year;
  196. GetTime(&val, date, &i);
  197. year = (CPU_INT16U)val;
  198. val = 0;
  199. GetTime(&val, date, &i);
  200. month = (CPU_INT08U)val;
  201. val = 0;
  202. GetTime(&val, date, &i);
  203. day = (CPU_INT16U)val;
  204. val = 0;
  205. GetTime(&val, date, &i);
  206. hour = (CPU_INT08U)val;
  207. val = 0;
  208. GetTime(&val, date, &i);
  209. min = (CPU_INT08U)val;
  210. val = 0;
  211. GetTime(&val, date, &i);
  212. sec = (CPU_INT08U)val;
  213. return NetSecure_ValidateDate(year, month, day, hour, min, sec, dateType);
  214. }
  215. #endif /* MICRIUM */
  216. static int GetLength(const byte* input, word32* inOutIdx, int* len,
  217. word32 maxIdx)
  218. {
  219. int length = 0;
  220. word32 i = *inOutIdx;
  221. byte b;
  222. if ( (i+1) > maxIdx) { /* for first read */
  223. CYASSL_MSG("GetLength bad index on input");
  224. return BUFFER_E;
  225. }
  226. b = input[i++];
  227. if (b >= ASN_LONG_LENGTH) {
  228. word32 bytes = b & 0x7F;
  229. if ( (i+bytes) > maxIdx) { /* for reading bytes */
  230. CYASSL_MSG("GetLength bad long length");
  231. return BUFFER_E;
  232. }
  233. while (bytes--) {
  234. b = input[i++];
  235. length = (length << 8) | b;
  236. }
  237. }
  238. else
  239. length = b;
  240. if ( (i+length) > maxIdx) { /* for user of length */
  241. CYASSL_MSG("GetLength value exceeds buffer length");
  242. return BUFFER_E;
  243. }
  244. *inOutIdx = i;
  245. *len = length;
  246. return length;
  247. }
  248. static int GetSequence(const byte* input, word32* inOutIdx, int* len,
  249. word32 maxIdx)
  250. {
  251. int length = -1;
  252. word32 idx = *inOutIdx;
  253. if (input[idx++] != (ASN_SEQUENCE | ASN_CONSTRUCTED) ||
  254. GetLength(input, &idx, &length, maxIdx) < 0)
  255. return ASN_PARSE_E;
  256. *len = length;
  257. *inOutIdx = idx;
  258. return length;
  259. }
  260. static int GetSet(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  261. {
  262. int length = -1;
  263. word32 idx = *inOutIdx;
  264. if (input[idx++] != (ASN_SET | ASN_CONSTRUCTED) ||
  265. GetLength(input, &idx, &length, maxIdx) < 0)
  266. return ASN_PARSE_E;
  267. *len = length;
  268. *inOutIdx = idx;
  269. return length;
  270. }
  271. /* winodws header clash for WinCE using GetVersion */
  272. static int GetMyVersion(const byte* input, word32* inOutIdx, int* version)
  273. {
  274. word32 idx = *inOutIdx;
  275. if (input[idx++] != ASN_INTEGER)
  276. return ASN_PARSE_E;
  277. if (input[idx++] != 0x01)
  278. return ASN_VERSION_E;
  279. *version = input[idx++];
  280. *inOutIdx = idx;
  281. return *version;
  282. }
  283. /* Get small count integer, 32 bits or less */
  284. static int GetShortInt(const byte* input, word32* inOutIdx, int* number)
  285. {
  286. word32 idx = *inOutIdx;
  287. word32 len;
  288. *number = 0;
  289. if (input[idx++] != ASN_INTEGER)
  290. return ASN_PARSE_E;
  291. len = input[idx++];
  292. if (len > 4)
  293. return ASN_PARSE_E;
  294. while (len--) {
  295. *number = *number << 8 | input[idx++];
  296. }
  297. *inOutIdx = idx;
  298. return *number;
  299. }
  300. /* May not have one, not an error */
  301. static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version)
  302. {
  303. word32 idx = *inOutIdx;
  304. if (input[idx++] == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  305. *inOutIdx = ++idx; /* eat header */
  306. return GetMyVersion(input, inOutIdx, version);
  307. }
  308. /* go back as is */
  309. *version = 0;
  310. return 0;
  311. }
  312. static int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx,
  313. word32 maxIdx)
  314. {
  315. word32 i = *inOutIdx;
  316. byte b = input[i++];
  317. int length;
  318. if (b != ASN_INTEGER)
  319. return ASN_PARSE_E;
  320. if (GetLength(input, &i, &length, maxIdx) < 0)
  321. return ASN_PARSE_E;
  322. if ( (b = input[i++]) == 0x00)
  323. length--;
  324. else
  325. i--;
  326. mp_init(mpi);
  327. if (mp_read_unsigned_bin(mpi, (byte*)input + i, length) != 0) {
  328. mp_clear(mpi);
  329. return ASN_GETINT_E;
  330. }
  331. *inOutIdx = i + length;
  332. return 0;
  333. }
  334. static int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
  335. word32 maxIdx)
  336. {
  337. int length;
  338. word32 i = *inOutIdx;
  339. byte b;
  340. *oid = 0;
  341. if (GetSequence(input, &i, &length, maxIdx) < 0)
  342. return ASN_PARSE_E;
  343. b = input[i++];
  344. if (b != ASN_OBJECT_ID)
  345. return ASN_OBJECT_ID_E;
  346. if (GetLength(input, &i, &length, maxIdx) < 0)
  347. return ASN_PARSE_E;
  348. while(length--)
  349. *oid += input[i++];
  350. /* just sum it up for now */
  351. /* could have NULL tag and 0 terminator, but may not */
  352. b = input[i++];
  353. if (b == ASN_TAG_NULL) {
  354. b = input[i++];
  355. if (b != 0)
  356. return ASN_EXPECT_0_E;
  357. }
  358. else
  359. /* go back, didn't have it */
  360. i--;
  361. *inOutIdx = i;
  362. return 0;
  363. }
  364. int RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  365. word32 inSz)
  366. {
  367. int version, length;
  368. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  369. return ASN_PARSE_E;
  370. if (GetMyVersion(input, inOutIdx, &version) < 0)
  371. return ASN_PARSE_E;
  372. key->type = RSA_PRIVATE;
  373. if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
  374. GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
  375. GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
  376. GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  377. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  378. GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
  379. GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
  380. GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  381. return 0;
  382. }
  383. /* Remove PKCS8 header, move beginning of traditional to beginning of input */
  384. int ToTraditional(byte* input, word32 sz)
  385. {
  386. word32 inOutIdx = 0, oid;
  387. int version, length;
  388. if (GetSequence(input, &inOutIdx, &length, sz) < 0)
  389. return ASN_PARSE_E;
  390. if (GetMyVersion(input, &inOutIdx, &version) < 0)
  391. return ASN_PARSE_E;
  392. if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
  393. return ASN_PARSE_E;
  394. if (input[inOutIdx++] != ASN_OCTET_STRING)
  395. return ASN_PARSE_E;
  396. if (GetLength(input, &inOutIdx, &length, sz) < 0)
  397. return ASN_PARSE_E;
  398. XMEMMOVE(input, input + inOutIdx, length);
  399. return 0;
  400. }
  401. #ifndef NO_PWDBASED
  402. /* Check To see if PKCS version algo is supported, set id if it is return 0
  403. < 0 on error */
  404. static int CheckAlgo(int first, int second, int* id, int* version)
  405. {
  406. *id = ALGO_ID_E;
  407. *version = PKCS5; /* default */
  408. if (first == 1) {
  409. switch (second) {
  410. case 1:
  411. *id = PBE_SHA1_RC4_128;
  412. *version = PKCS12;
  413. return 0;
  414. case 3:
  415. *id = PBE_SHA1_DES3;
  416. *version = PKCS12;
  417. return 0;
  418. default:
  419. return ALGO_ID_E;
  420. }
  421. }
  422. if (first != PKCS5)
  423. return ASN_INPUT_E; /* VERSION ERROR */
  424. if (second == PBES2) {
  425. *version = PKCS5v2;
  426. return 0;
  427. }
  428. switch (second) {
  429. case 3: /* see RFC 2898 for ids */
  430. *id = PBE_MD5_DES;
  431. return 0;
  432. case 10:
  433. *id = PBE_SHA1_DES;
  434. return 0;
  435. default:
  436. return ALGO_ID_E;
  437. }
  438. }
  439. /* Check To see if PKCS v2 algo is supported, set id if it is return 0
  440. < 0 on error */
  441. static int CheckAlgoV2(int oid, int* id)
  442. {
  443. switch (oid) {
  444. case 69:
  445. *id = PBE_SHA1_DES;
  446. return 0;
  447. case 652:
  448. *id = PBE_SHA1_DES3;
  449. return 0;
  450. default:
  451. return ALGO_ID_E;
  452. }
  453. }
  454. /* Decrypt intput in place from parameters based on id */
  455. static int DecryptKey(const char* password, int passwordSz, byte* salt,
  456. int saltSz, int iterations, int id, byte* input,
  457. int length, int version, byte* cbcIv)
  458. {
  459. byte key[MAX_KEY_SIZE];
  460. int typeH;
  461. int derivedLen;
  462. int decryptionType;
  463. int ret = 0;
  464. switch (id) {
  465. case PBE_MD5_DES:
  466. typeH = MD5;
  467. derivedLen = 16; /* may need iv for v1.5 */
  468. decryptionType = DES_TYPE;
  469. break;
  470. case PBE_SHA1_DES:
  471. typeH = SHA;
  472. derivedLen = 16; /* may need iv for v1.5 */
  473. decryptionType = DES_TYPE;
  474. break;
  475. case PBE_SHA1_DES3:
  476. typeH = SHA;
  477. derivedLen = 32; /* may need iv for v1.5 */
  478. decryptionType = DES3_TYPE;
  479. break;
  480. case PBE_SHA1_RC4_128:
  481. typeH = SHA;
  482. derivedLen = 16;
  483. decryptionType = RC4_TYPE;
  484. break;
  485. default:
  486. return ALGO_ID_E;
  487. }
  488. if (version == PKCS5v2)
  489. ret = PBKDF2(key, (byte*)password, passwordSz, salt, saltSz, iterations,
  490. derivedLen, typeH);
  491. else if (version == PKCS5)
  492. ret = PBKDF1(key, (byte*)password, passwordSz, salt, saltSz, iterations,
  493. derivedLen, typeH);
  494. else if (version == PKCS12) {
  495. int i, idx = 0;
  496. byte unicodePasswd[MAX_UNICODE_SZ];
  497. if ( (passwordSz * 2 + 2) > (int)sizeof(unicodePasswd))
  498. return UNICODE_SIZE_E;
  499. for (i = 0; i < passwordSz; i++) {
  500. unicodePasswd[idx++] = 0x00;
  501. unicodePasswd[idx++] = (byte)password[i];
  502. }
  503. /* add trailing NULL */
  504. unicodePasswd[idx++] = 0x00;
  505. unicodePasswd[idx++] = 0x00;
  506. ret = PKCS12_PBKDF(key, unicodePasswd, idx, salt, saltSz,
  507. iterations, derivedLen, typeH, 1);
  508. if (decryptionType != RC4_TYPE)
  509. ret += PKCS12_PBKDF(cbcIv, unicodePasswd, idx, salt, saltSz,
  510. iterations, 8, typeH, 2);
  511. }
  512. if (ret != 0)
  513. return ret;
  514. switch (decryptionType) {
  515. #ifndef NO_DES3
  516. case DES_TYPE:
  517. {
  518. Des dec;
  519. byte* desIv = key + 8;
  520. if (version == PKCS5v2 || version == PKCS12)
  521. desIv = cbcIv;
  522. Des_SetKey(&dec, key, desIv, DES_DECRYPTION);
  523. Des_CbcDecrypt(&dec, input, input, length);
  524. break;
  525. }
  526. case DES3_TYPE:
  527. {
  528. Des3 dec;
  529. byte* desIv = key + 24;
  530. if (version == PKCS5v2 || version == PKCS12)
  531. desIv = cbcIv;
  532. Des3_SetKey(&dec, key, desIv, DES_DECRYPTION);
  533. Des3_CbcDecrypt(&dec, input, input, length);
  534. break;
  535. }
  536. #endif
  537. case RC4_TYPE:
  538. {
  539. Arc4 dec;
  540. Arc4SetKey(&dec, key, derivedLen);
  541. Arc4Process(&dec, input, input, length);
  542. break;
  543. }
  544. default:
  545. return ALGO_ID_E;
  546. }
  547. return 0;
  548. }
  549. /* Remove Encrypted PKCS8 header, move beginning of traditional to beginning
  550. of input */
  551. int ToTraditionalEnc(byte* input, word32 sz,const char* password,int passwordSz)
  552. {
  553. word32 inOutIdx = 0, oid;
  554. int first, second, length, iterations, saltSz, id;
  555. int version;
  556. byte salt[MAX_SALT_SIZE];
  557. byte cbcIv[MAX_IV_SIZE];
  558. if (GetSequence(input, &inOutIdx, &length, sz) < 0)
  559. return ASN_PARSE_E;
  560. if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
  561. return ASN_PARSE_E;
  562. first = input[inOutIdx - 2]; /* PKCS version alwyas 2nd to last byte */
  563. second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
  564. if (CheckAlgo(first, second, &id, &version) < 0)
  565. return ASN_INPUT_E; /* Algo ID error */
  566. if (version == PKCS5v2) {
  567. if (GetSequence(input, &inOutIdx, &length, sz) < 0)
  568. return ASN_PARSE_E;
  569. if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
  570. return ASN_PARSE_E;
  571. if (oid != PBKDF2_OID)
  572. return ASN_PARSE_E;
  573. }
  574. if (GetSequence(input, &inOutIdx, &length, sz) < 0)
  575. return ASN_PARSE_E;
  576. if (input[inOutIdx++] != ASN_OCTET_STRING)
  577. return ASN_PARSE_E;
  578. if (GetLength(input, &inOutIdx, &saltSz, sz) < 0)
  579. return ASN_PARSE_E;
  580. if (saltSz > MAX_SALT_SIZE)
  581. return ASN_PARSE_E;
  582. XMEMCPY(salt, &input[inOutIdx], saltSz);
  583. inOutIdx += saltSz;
  584. if (GetShortInt(input, &inOutIdx, &iterations) < 0)
  585. return ASN_PARSE_E;
  586. if (version == PKCS5v2) {
  587. /* get encryption algo */
  588. if (GetAlgoId(input, &inOutIdx, &oid, sz) < 0)
  589. return ASN_PARSE_E;
  590. if (CheckAlgoV2(oid, &id) < 0)
  591. return ASN_PARSE_E; /* PKCS v2 algo id error */
  592. if (input[inOutIdx++] != ASN_OCTET_STRING)
  593. return ASN_PARSE_E;
  594. if (GetLength(input, &inOutIdx, &length, sz) < 0)
  595. return ASN_PARSE_E;
  596. XMEMCPY(cbcIv, &input[inOutIdx], length);
  597. inOutIdx += length;
  598. }
  599. if (input[inOutIdx++] != ASN_OCTET_STRING)
  600. return ASN_PARSE_E;
  601. if (GetLength(input, &inOutIdx, &length, sz) < 0)
  602. return ASN_PARSE_E;
  603. if (DecryptKey(password, passwordSz, salt, saltSz, iterations, id,
  604. input + inOutIdx, length, version, cbcIv) < 0)
  605. return ASN_INPUT_E; /* decrypt failure */
  606. XMEMMOVE(input, input + inOutIdx, length);
  607. return ToTraditional(input, length);
  608. }
  609. #endif /* NO_PWDBASED */
  610. int RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  611. word32 inSz)
  612. {
  613. int length;
  614. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  615. return ASN_PARSE_E;
  616. key->type = RSA_PUBLIC;
  617. #ifdef OPENSSL_EXTRA
  618. {
  619. byte b = input[*inOutIdx];
  620. if (b != ASN_INTEGER) {
  621. /* not from decoded cert, will have algo id, skip past */
  622. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  623. return ASN_PARSE_E;
  624. b = input[(*inOutIdx)++];
  625. if (b != ASN_OBJECT_ID)
  626. return ASN_OBJECT_ID_E;
  627. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  628. return ASN_PARSE_E;
  629. *inOutIdx += length; /* skip past */
  630. /* could have NULL tag and 0 terminator, but may not */
  631. b = input[(*inOutIdx)++];
  632. if (b == ASN_TAG_NULL) {
  633. b = input[(*inOutIdx)++];
  634. if (b != 0)
  635. return ASN_EXPECT_0_E;
  636. }
  637. else
  638. /* go back, didn't have it */
  639. (*inOutIdx)--;
  640. /* should have bit tag length and seq next */
  641. b = input[(*inOutIdx)++];
  642. if (b != ASN_BIT_STRING)
  643. return ASN_BITSTR_E;
  644. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  645. return ASN_PARSE_E;
  646. /* could have 0 */
  647. b = input[(*inOutIdx)++];
  648. if (b != 0)
  649. (*inOutIdx)--;
  650. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  651. return ASN_PARSE_E;
  652. } /* end if */
  653. } /* openssl var block */
  654. #endif /* OPENSSL_EXTRA */
  655. if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
  656. GetInt(&key->e, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  657. return 0;
  658. }
  659. #ifndef NO_DH
  660. int DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
  661. {
  662. int length;
  663. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  664. return ASN_PARSE_E;
  665. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  666. GetInt(&key->g, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
  667. return 0;
  668. }
  669. int DhSetKey(DhKey* key, const byte* p, word32 pSz, const byte* g, word32 gSz)
  670. {
  671. /* may have leading 0 */
  672. if (p[0] == 0) {
  673. pSz--; p++;
  674. }
  675. if (g[0] == 0) {
  676. gSz--; g++;
  677. }
  678. mp_init(&key->p);
  679. if (mp_read_unsigned_bin(&key->p, p, pSz) != 0) {
  680. mp_clear(&key->p);
  681. return ASN_DH_KEY_E;
  682. }
  683. mp_init(&key->g);
  684. if (mp_read_unsigned_bin(&key->g, g, gSz) != 0) {
  685. mp_clear(&key->p);
  686. return ASN_DH_KEY_E;
  687. }
  688. return 0;
  689. }
  690. #ifdef OPENSSL_EXTRA
  691. int DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
  692. byte* g, word32* gInOutSz)
  693. {
  694. word32 i = 0;
  695. byte b;
  696. int length;
  697. if (GetSequence(input, &i, &length, inSz) < 0)
  698. return ASN_PARSE_E;
  699. b = input[i++];
  700. if (b != ASN_INTEGER)
  701. return ASN_PARSE_E;
  702. if (GetLength(input, &i, &length, inSz) < 0)
  703. return ASN_PARSE_E;
  704. if ( (b = input[i++]) == 0x00)
  705. length--;
  706. else
  707. i--;
  708. if (length <= *pInOutSz) {
  709. XMEMCPY(p, &input[i], length);
  710. *pInOutSz = length;
  711. }
  712. else
  713. return BUFFER_E;
  714. i += length;
  715. b = input[i++];
  716. if (b != ASN_INTEGER)
  717. return ASN_PARSE_E;
  718. if (GetLength(input, &i, &length, inSz) < 0)
  719. return ASN_PARSE_E;
  720. if (length <= *gInOutSz) {
  721. XMEMCPY(g, &input[i], length);
  722. *gInOutSz = length;
  723. }
  724. else
  725. return BUFFER_E;
  726. return 0;
  727. }
  728. #endif /* OPENSSL_EXTRA */
  729. #endif /* NO_DH */
  730. #ifndef NO_DSA
  731. int DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  732. word32 inSz)
  733. {
  734. int length;
  735. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  736. return ASN_PARSE_E;
  737. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  738. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  739. GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
  740. GetInt(&key->y, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
  741. key->type = DSA_PUBLIC;
  742. return 0;
  743. }
  744. int DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  745. word32 inSz)
  746. {
  747. int length, version;
  748. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  749. return ASN_PARSE_E;
  750. if (GetMyVersion(input, inOutIdx, &version) < 0)
  751. return ASN_PARSE_E;
  752. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  753. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  754. GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
  755. GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
  756. GetInt(&key->x, input, inOutIdx, inSz) < 0 ) return ASN_DH_KEY_E;
  757. key->type = DSA_PRIVATE;
  758. return 0;
  759. }
  760. #endif /* NO_DSA */
  761. void InitDecodedCert(DecodedCert* cert, byte* source, word32 inSz, void* heap)
  762. {
  763. cert->publicKey = 0;
  764. cert->pubKeyStored = 0;
  765. cert->signature = 0;
  766. cert->subjectCN = 0;
  767. cert->subjectCNLen = 0;
  768. cert->source = source; /* don't own */
  769. cert->srcIdx = 0;
  770. cert->maxIdx = inSz; /* can't go over this index */
  771. cert->heap = heap;
  772. XMEMSET(cert->serial, 0, EXTERNAL_SERIAL_SIZE);
  773. cert->serialSz = 0;
  774. cert->extensions = 0;
  775. cert->extensionsSz = 0;
  776. cert->extensionsIdx = 0;
  777. #ifdef CYASSL_CERT_GEN
  778. cert->subjectSN = 0;
  779. cert->subjectSNLen = 0;
  780. cert->subjectC = 0;
  781. cert->subjectCLen = 0;
  782. cert->subjectL = 0;
  783. cert->subjectLLen = 0;
  784. cert->subjectST = 0;
  785. cert->subjectSTLen = 0;
  786. cert->subjectO = 0;
  787. cert->subjectOLen = 0;
  788. cert->subjectOU = 0;
  789. cert->subjectOULen = 0;
  790. cert->subjectEmail = 0;
  791. cert->subjectEmailLen = 0;
  792. #endif /* CYASSL_CERT_GEN */
  793. }
  794. void FreeDecodedCert(DecodedCert* cert)
  795. {
  796. if (cert->subjectCNLen == 0) /* 0 means no longer pointer to raw, we own */
  797. XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
  798. if (cert->pubKeyStored == 1)
  799. XFREE(cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  800. }
  801. static int GetCertHeader(DecodedCert* cert)
  802. {
  803. int ret = 0, version, len;
  804. byte serialTmp[EXTERNAL_SERIAL_SIZE];
  805. mp_int mpi;
  806. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  807. return ASN_PARSE_E;
  808. cert->certBegin = cert->srcIdx;
  809. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  810. return ASN_PARSE_E;
  811. cert->sigIndex = len + cert->srcIdx;
  812. if (GetExplicitVersion(cert->source, &cert->srcIdx, &version) < 0)
  813. return ASN_PARSE_E;
  814. if (GetInt(&mpi, cert->source, &cert->srcIdx, cert->maxIdx) < 0)
  815. return ASN_PARSE_E;
  816. len = mp_unsigned_bin_size(&mpi);
  817. if (len < (int)sizeof(serialTmp)) {
  818. if (mp_to_unsigned_bin(&mpi, serialTmp) == MP_OKAY) {
  819. if (len > EXTERNAL_SERIAL_SIZE)
  820. len = EXTERNAL_SERIAL_SIZE;
  821. XMEMCPY(cert->serial, serialTmp, len);
  822. cert->serialSz = len;
  823. }
  824. }
  825. mp_clear(&mpi);
  826. return ret;
  827. }
  828. /* Store Rsa Key, may save later, Dsa could use in future */
  829. static int StoreRsaKey(DecodedCert* cert)
  830. {
  831. int length;
  832. word32 read = cert->srcIdx;
  833. if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  834. return ASN_PARSE_E;
  835. read = cert->srcIdx - read;
  836. length += read;
  837. while (read--)
  838. cert->srcIdx--;
  839. cert->pubKeySize = length;
  840. cert->publicKey = cert->source + cert->srcIdx;
  841. cert->srcIdx += length;
  842. return 0;
  843. }
  844. #ifdef HAVE_ECC
  845. /* return 0 on sucess if the ECC curve oid sum is supported */
  846. static int CheckCurve(word32 oid)
  847. {
  848. if (oid != ECC_256R1 && oid != ECC_384R1 && oid != ECC_521R1 && oid !=
  849. ECC_160R1 && oid != ECC_192R1 && oid != ECC_224R1)
  850. return ALGO_ID_E;
  851. return 0;
  852. }
  853. #endif /* HAVE_ECC */
  854. static int GetKey(DecodedCert* cert)
  855. {
  856. int length;
  857. #ifdef HAVE_NTRU
  858. int tmpIdx = cert->srcIdx;
  859. #endif
  860. if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  861. return ASN_PARSE_E;
  862. if (GetAlgoId(cert->source, &cert->srcIdx, &cert->keyOID, cert->maxIdx) < 0)
  863. return ASN_PARSE_E;
  864. if (cert->keyOID == RSAk) {
  865. byte b = cert->source[cert->srcIdx++];
  866. if (b != ASN_BIT_STRING)
  867. return ASN_BITSTR_E;
  868. if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  869. return ASN_PARSE_E;
  870. b = cert->source[cert->srcIdx++];
  871. if (b != 0x00)
  872. return ASN_EXPECT_0_E;
  873. }
  874. else if (cert->keyOID == DSAk )
  875. ; /* do nothing */
  876. #ifdef HAVE_NTRU
  877. else if (cert->keyOID == NTRUk ) {
  878. const byte* key = &cert->source[tmpIdx];
  879. byte* next = (byte*)key;
  880. word16 keyLen;
  881. byte keyBlob[MAX_NTRU_KEY_SZ];
  882. word32 rc = crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key,
  883. &keyLen, NULL, &next);
  884. if (rc != NTRU_OK)
  885. return ASN_NTRU_KEY_E;
  886. if (keyLen > sizeof(keyBlob))
  887. return ASN_NTRU_KEY_E;
  888. rc = crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key, &keyLen,
  889. keyBlob, &next);
  890. if (rc != NTRU_OK)
  891. return ASN_NTRU_KEY_E;
  892. if ( (next - key) < 0)
  893. return ASN_NTRU_KEY_E;
  894. cert->srcIdx = tmpIdx + (next - key);
  895. cert->publicKey = (byte*) XMALLOC(keyLen, cert->heap,
  896. DYNAMIC_TYPE_PUBLIC_KEY);
  897. if (cert->publicKey == NULL)
  898. return MEMORY_E;
  899. XMEMCPY(cert->publicKey, keyBlob, keyLen);
  900. cert->pubKeyStored = 1;
  901. cert->pubKeySize = keyLen;
  902. }
  903. #endif /* HAVE_NTRU */
  904. #ifdef HAVE_ECC
  905. else if (cert->keyOID == ECDSAk ) {
  906. word32 oid = 0;
  907. int oidSz = 0;
  908. byte b = cert->source[cert->srcIdx++];
  909. if (b != ASN_OBJECT_ID)
  910. return ASN_OBJECT_ID_E;
  911. if (GetLength(cert->source, &cert->srcIdx, &oidSz, cert->maxIdx) < 0)
  912. return ASN_PARSE_E;
  913. while(oidSz--)
  914. oid += cert->source[cert->srcIdx++];
  915. if (CheckCurve(oid) < 0)
  916. return ECC_CURVE_OID_E;
  917. /* key header */
  918. b = cert->source[cert->srcIdx++];
  919. if (b != ASN_BIT_STRING)
  920. return ASN_BITSTR_E;
  921. if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  922. return ASN_PARSE_E;
  923. b = cert->source[cert->srcIdx++];
  924. if (b != 0x00)
  925. return ASN_EXPECT_0_E;
  926. /* actual key, use length - 1 since preceding 0 */
  927. cert->publicKey = (byte*) XMALLOC(length - 1, cert->heap,
  928. DYNAMIC_TYPE_PUBLIC_KEY);
  929. if (cert->publicKey == NULL)
  930. return MEMORY_E;
  931. XMEMCPY(cert->publicKey, &cert->source[cert->srcIdx], length - 1);
  932. cert->pubKeyStored = 1;
  933. cert->pubKeySize = length - 1;
  934. cert->srcIdx += length;
  935. }
  936. #endif /* HAVE_ECC */
  937. else
  938. return ASN_UNKNOWN_OID_E;
  939. if (cert->keyOID == RSAk)
  940. return StoreRsaKey(cert);
  941. return 0;
  942. }
  943. /* process NAME, either issuer or subject */
  944. static int GetName(DecodedCert* cert, int nameType)
  945. {
  946. Sha sha;
  947. int length; /* length of all distinguished names */
  948. int dummy;
  949. char* full = (nameType == ISSUER) ? cert->issuer : cert->subject;
  950. word32 idx = 0;
  951. InitSha(&sha);
  952. if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  953. return ASN_PARSE_E;
  954. length += cert->srcIdx;
  955. while (cert->srcIdx < (word32)length) {
  956. byte b;
  957. byte joint[2];
  958. int oidSz;
  959. if (GetSet(cert->source, &cert->srcIdx, &dummy, cert->maxIdx) < 0) {
  960. (void)b; /* empty body warning w/o messages enabled */
  961. CYASSL_MSG("Cert name lacks set header, trying sequence");
  962. }
  963. if (GetSequence(cert->source, &cert->srcIdx, &dummy, cert->maxIdx) < 0)
  964. return ASN_PARSE_E;
  965. b = cert->source[cert->srcIdx++];
  966. if (b != ASN_OBJECT_ID)
  967. return ASN_OBJECT_ID_E;
  968. if (GetLength(cert->source, &cert->srcIdx, &oidSz, cert->maxIdx) < 0)
  969. return ASN_PARSE_E;
  970. XMEMCPY(joint, &cert->source[cert->srcIdx], sizeof(joint));
  971. /* v1 name types */
  972. if (joint[0] == 0x55 && joint[1] == 0x04) {
  973. byte id;
  974. byte copy = FALSE;
  975. int strLen;
  976. cert->srcIdx += 2;
  977. id = cert->source[cert->srcIdx++];
  978. b = cert->source[cert->srcIdx++]; /* strType */
  979. if (GetLength(cert->source, &cert->srcIdx, &strLen,
  980. cert->maxIdx) < 0)
  981. return ASN_PARSE_E;
  982. if (strLen > (int)(ASN_NAME_MAX - idx))
  983. return ASN_PARSE_E;
  984. if (4 > (ASN_NAME_MAX - idx)) /* make sure room for biggest */
  985. return ASN_PARSE_E; /* pre fix header too "/CN=" */
  986. if (id == ASN_COMMON_NAME) {
  987. if (nameType == SUBJECT) {
  988. cert->subjectCN = (char *)&cert->source[cert->srcIdx];
  989. cert->subjectCNLen = strLen;
  990. }
  991. XMEMCPY(&full[idx], "/CN=", 4);
  992. idx += 4;
  993. copy = TRUE;
  994. }
  995. else if (id == ASN_SUR_NAME) {
  996. XMEMCPY(&full[idx], "/SN=", 4);
  997. idx += 4;
  998. copy = TRUE;
  999. #ifdef CYASSL_CERT_GEN
  1000. if (nameType == SUBJECT) {
  1001. cert->subjectSN = (char*)&cert->source[cert->srcIdx];
  1002. cert->subjectSNLen = strLen;
  1003. }
  1004. #endif /* CYASSL_CERT_GEN */
  1005. }
  1006. else if (id == ASN_COUNTRY_NAME) {
  1007. XMEMCPY(&full[idx], "/C=", 3);
  1008. idx += 3;
  1009. copy = TRUE;
  1010. #ifdef CYASSL_CERT_GEN
  1011. if (nameType == SUBJECT) {
  1012. cert->subjectC = (char*)&cert->source[cert->srcIdx];
  1013. cert->subjectCLen = strLen;
  1014. }
  1015. #endif /* CYASSL_CERT_GEN */
  1016. }
  1017. else if (id == ASN_LOCALITY_NAME) {
  1018. XMEMCPY(&full[idx], "/L=", 3);
  1019. idx += 3;
  1020. copy = TRUE;
  1021. #ifdef CYASSL_CERT_GEN
  1022. if (nameType == SUBJECT) {
  1023. cert->subjectL = (char*)&cert->source[cert->srcIdx];
  1024. cert->subjectLLen = strLen;
  1025. }
  1026. #endif /* CYASSL_CERT_GEN */
  1027. }
  1028. else if (id == ASN_STATE_NAME) {
  1029. XMEMCPY(&full[idx], "/ST=", 4);
  1030. idx += 4;
  1031. copy = TRUE;
  1032. #ifdef CYASSL_CERT_GEN
  1033. if (nameType == SUBJECT) {
  1034. cert->subjectST = (char*)&cert->source[cert->srcIdx];
  1035. cert->subjectSTLen = strLen;
  1036. }
  1037. #endif /* CYASSL_CERT_GEN */
  1038. }
  1039. else if (id == ASN_ORG_NAME) {
  1040. XMEMCPY(&full[idx], "/O=", 3);
  1041. idx += 3;
  1042. copy = TRUE;
  1043. #ifdef CYASSL_CERT_GEN
  1044. if (nameType == SUBJECT) {
  1045. cert->subjectO = (char*)&cert->source[cert->srcIdx];
  1046. cert->subjectOLen = strLen;
  1047. }
  1048. #endif /* CYASSL_CERT_GEN */
  1049. }
  1050. else if (id == ASN_ORGUNIT_NAME) {
  1051. XMEMCPY(&full[idx], "/OU=", 4);
  1052. idx += 4;
  1053. copy = TRUE;
  1054. #ifdef CYASSL_CERT_GEN
  1055. if (nameType == SUBJECT) {
  1056. cert->subjectOU = (char*)&cert->source[cert->srcIdx];
  1057. cert->subjectOULen = strLen;
  1058. }
  1059. #endif /* CYASSL_CERT_GEN */
  1060. }
  1061. if (copy) {
  1062. XMEMCPY(&full[idx], &cert->source[cert->srcIdx], strLen);
  1063. idx += strLen;
  1064. }
  1065. ShaUpdate(&sha, &cert->source[cert->srcIdx], strLen);
  1066. cert->srcIdx += strLen;
  1067. }
  1068. else {
  1069. /* skip */
  1070. byte email = FALSE;
  1071. byte uid = FALSE;
  1072. int adv;
  1073. if (joint[0] == 0x2a && joint[1] == 0x86) /* email id hdr */
  1074. email = TRUE;
  1075. if (joint[0] == 0x9 && joint[1] == 0x92) /* uid id hdr */
  1076. uid = TRUE;
  1077. cert->srcIdx += oidSz + 1;
  1078. if (GetLength(cert->source, &cert->srcIdx, &adv, cert->maxIdx) < 0)
  1079. return ASN_PARSE_E;
  1080. if (adv > (int)(ASN_NAME_MAX - idx))
  1081. return ASN_PARSE_E;
  1082. if (email) {
  1083. if (14 > (ASN_NAME_MAX - idx))
  1084. return ASN_PARSE_E;
  1085. XMEMCPY(&full[idx], "/emailAddress=", 14);
  1086. idx += 14;
  1087. #ifdef CYASSL_CERT_GEN
  1088. if (nameType == SUBJECT) {
  1089. cert->subjectEmail = (char*)&cert->source[cert->srcIdx];
  1090. cert->subjectEmailLen = adv;
  1091. }
  1092. #endif /* CYASSL_CERT_GEN */
  1093. XMEMCPY(&full[idx], &cert->source[cert->srcIdx], adv);
  1094. idx += adv;
  1095. }
  1096. if (uid) {
  1097. if (5 > (ASN_NAME_MAX - idx))
  1098. return ASN_PARSE_E;
  1099. XMEMCPY(&full[idx], "/UID=", 5);
  1100. idx += 5;
  1101. XMEMCPY(&full[idx], &cert->source[cert->srcIdx], adv);
  1102. idx += adv;
  1103. }
  1104. cert->srcIdx += adv;
  1105. }
  1106. }
  1107. full[idx++] = 0;
  1108. if (nameType == ISSUER)
  1109. ShaFinal(&sha, cert->issuerHash);
  1110. else
  1111. ShaFinal(&sha, cert->subjectHash);
  1112. return 0;
  1113. }
  1114. #ifndef NO_TIME_H
  1115. /* to the second */
  1116. static int DateGreaterThan(const struct tm* a, const struct tm* b)
  1117. {
  1118. if (a->tm_year > b->tm_year)
  1119. return 1;
  1120. if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
  1121. return 1;
  1122. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  1123. a->tm_mday > b->tm_mday)
  1124. return 1;
  1125. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  1126. a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
  1127. return 1;
  1128. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  1129. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  1130. a->tm_min > b->tm_min)
  1131. return 1;
  1132. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  1133. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  1134. a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
  1135. return 1;
  1136. return 0; /* false */
  1137. }
  1138. static INLINE int DateLessThan(const struct tm* a, const struct tm* b)
  1139. {
  1140. return !DateGreaterThan(a,b);
  1141. }
  1142. /* like atoi but only use first byte */
  1143. /* Make sure before and after dates are valid */
  1144. static int ValidateDate(const byte* date, byte format, int dateType)
  1145. {
  1146. time_t ltime;
  1147. struct tm certTime;
  1148. struct tm* localTime;
  1149. int i = 0;
  1150. ltime = XTIME(0);
  1151. XMEMSET(&certTime, 0, sizeof(certTime));
  1152. if (format == ASN_UTC_TIME) {
  1153. if (btoi(date[0]) >= 5)
  1154. certTime.tm_year = 1900;
  1155. else
  1156. certTime.tm_year = 2000;
  1157. }
  1158. else { /* format == GENERALIZED_TIME */
  1159. certTime.tm_year += btoi(date[i++]) * 1000;
  1160. certTime.tm_year += btoi(date[i++]) * 100;
  1161. }
  1162. GetTime(&certTime.tm_year, date, &i); certTime.tm_year -= 1900; /* adjust */
  1163. GetTime(&certTime.tm_mon, date, &i); certTime.tm_mon -= 1; /* adjust */
  1164. GetTime(&certTime.tm_mday, date, &i);
  1165. GetTime(&certTime.tm_hour, date, &i);
  1166. GetTime(&certTime.tm_min, date, &i);
  1167. GetTime(&certTime.tm_sec, date, &i);
  1168. if (date[i] != 'Z') { /* only Zulu supported for this profile */
  1169. CYASSL_MSG("Only Zulu time supported for this profile");
  1170. return 0;
  1171. }
  1172. localTime = XGMTIME(&ltime);
  1173. if (dateType == BEFORE) {
  1174. if (DateLessThan(localTime, &certTime))
  1175. return 0;
  1176. }
  1177. else
  1178. if (DateGreaterThan(localTime, &certTime))
  1179. return 0;
  1180. return 1;
  1181. }
  1182. #endif /* NO_TIME_H */
  1183. static int GetDate(DecodedCert* cert, int dateType)
  1184. {
  1185. int length;
  1186. byte date[MAX_DATE_SIZE];
  1187. byte b = cert->source[cert->srcIdx++];
  1188. if (b != ASN_UTC_TIME && b != ASN_GENERALIZED_TIME)
  1189. return ASN_TIME_E;
  1190. if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  1191. return ASN_PARSE_E;
  1192. if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
  1193. return ASN_DATE_SZ_E;
  1194. XMEMCPY(date, &cert->source[cert->srcIdx], length);
  1195. cert->srcIdx += length;
  1196. if (!XVALIDATE_DATE(date, b, dateType)) {
  1197. if (dateType == BEFORE)
  1198. return ASN_BEFORE_DATE_E;
  1199. else
  1200. return ASN_AFTER_DATE_E;
  1201. }
  1202. return 0;
  1203. }
  1204. static int GetValidity(DecodedCert* cert, int verify)
  1205. {
  1206. int length;
  1207. int badDate = 0;
  1208. if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  1209. return ASN_PARSE_E;
  1210. if (GetDate(cert, BEFORE) < 0 && verify)
  1211. badDate = ASN_BEFORE_DATE_E; /* continue parsing */
  1212. if (GetDate(cert, AFTER) < 0 && verify)
  1213. return ASN_AFTER_DATE_E;
  1214. if (badDate != 0)
  1215. return badDate;
  1216. return 0;
  1217. }
  1218. static int DecodeToKey(DecodedCert* cert, int verify)
  1219. {
  1220. int badDate = 0;
  1221. int ret;
  1222. if ( (ret = GetCertHeader(cert)) < 0)
  1223. return ret;
  1224. if ( (ret = GetAlgoId(cert->source, &cert->srcIdx, &cert->signatureOID,
  1225. cert->maxIdx)) < 0)
  1226. return ret;
  1227. if ( (ret = GetName(cert, ISSUER)) < 0)
  1228. return ret;
  1229. if ( (ret = GetValidity(cert, verify)) < 0)
  1230. badDate = ret;
  1231. if ( (ret = GetName(cert, SUBJECT)) < 0)
  1232. return ret;
  1233. if ( (ret = GetKey(cert)) < 0)
  1234. return ret;
  1235. if (badDate != 0)
  1236. return badDate;
  1237. return ret;
  1238. }
  1239. static int GetSignature(DecodedCert* cert)
  1240. {
  1241. int length;
  1242. byte b = cert->source[cert->srcIdx++];
  1243. if (b != ASN_BIT_STRING)
  1244. return ASN_BITSTR_E;
  1245. if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  1246. return ASN_PARSE_E;
  1247. cert->sigLength = length;
  1248. b = cert->source[cert->srcIdx++];
  1249. if (b != 0x00)
  1250. return ASN_EXPECT_0_E;
  1251. cert->sigLength--;
  1252. cert->signature = &cert->source[cert->srcIdx];
  1253. cert->srcIdx += cert->sigLength;
  1254. return 0;
  1255. }
  1256. static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
  1257. {
  1258. output[0] = ASN_OCTET_STRING;
  1259. output[1] = (byte)digSz;
  1260. XMEMCPY(&output[2], digest, digSz);
  1261. return digSz + 2;
  1262. }
  1263. static word32 BytePrecision(word32 value)
  1264. {
  1265. word32 i;
  1266. for (i = sizeof(value); i; --i)
  1267. if (value >> (i - 1) * 8)
  1268. break;
  1269. return i;
  1270. }
  1271. static word32 SetLength(word32 length, byte* output)
  1272. {
  1273. word32 i = 0, j;
  1274. if (length < ASN_LONG_LENGTH)
  1275. output[i++] = (byte)length;
  1276. else {
  1277. output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);
  1278. for (j = BytePrecision(length); j; --j) {
  1279. output[i] = (byte)(length >> (j - 1) * 8);
  1280. i++;
  1281. }
  1282. }
  1283. return i;
  1284. }
  1285. static word32 SetSequence(word32 len, byte* output)
  1286. {
  1287. output[0] = ASN_SEQUENCE | ASN_CONSTRUCTED;
  1288. return SetLength(len, output + 1) + 1;
  1289. }
  1290. static word32 SetAlgoID(int algoOID, byte* output, int type)
  1291. {
  1292. /* adding TAG_NULL and 0 to end */
  1293. /* hashTypes */
  1294. static const byte shaAlgoID[] = { 0x2b, 0x0e, 0x03, 0x02, 0x1a,
  1295. 0x05, 0x00 };
  1296. static const byte sha256AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
  1297. 0x04, 0x02, 0x01, 0x05, 0x00 };
  1298. static const byte md5AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  1299. 0x02, 0x05, 0x05, 0x00 };
  1300. static const byte md2AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  1301. 0x02, 0x02, 0x05, 0x00};
  1302. /* sigTypes */
  1303. static const byte md5wRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  1304. 0x01, 0x01, 0x04, 0x05, 0x00};
  1305. static const byte shawRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  1306. 0x01, 0x01, 0x05, 0x05, 0x00};
  1307. static const byte sha256wRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7,
  1308. 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00};
  1309. /* keyTypes */
  1310. static const byte RSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  1311. 0x01, 0x01, 0x01, 0x05, 0x00};
  1312. int algoSz = 0;
  1313. word32 idSz, seqSz;
  1314. const byte* algoName = 0;
  1315. byte ID_Length[MAX_LENGTH_SZ];
  1316. byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
  1317. if (type == hashType) {
  1318. switch (algoOID) {
  1319. case SHAh:
  1320. algoSz = sizeof(shaAlgoID);
  1321. algoName = shaAlgoID;
  1322. break;
  1323. case SHA256h:
  1324. algoSz = sizeof(sha256AlgoID);
  1325. algoName = sha256AlgoID;
  1326. break;
  1327. case MD2h:
  1328. algoSz = sizeof(md2AlgoID);
  1329. algoName = md2AlgoID;
  1330. break;
  1331. case MD5h:
  1332. algoSz = sizeof(md5AlgoID);
  1333. algoName = md5AlgoID;
  1334. break;
  1335. default:
  1336. CYASSL_MSG("Unknown Hash Algo");
  1337. return 0; /* UNKOWN_HASH_E; */
  1338. }
  1339. }
  1340. else if (type == sigType) { /* sigType */
  1341. switch (algoOID) {
  1342. case CTC_MD5wRSA:
  1343. algoSz = sizeof(md5wRSA_AlgoID);
  1344. algoName = md5wRSA_AlgoID;
  1345. break;
  1346. case CTC_SHAwRSA:
  1347. algoSz = sizeof(shawRSA_AlgoID);
  1348. algoName = shawRSA_AlgoID;
  1349. break;
  1350. case CTC_SHA256wRSA:
  1351. algoSz = sizeof(sha256wRSA_AlgoID);
  1352. algoName = sha256wRSA_AlgoID;
  1353. break;
  1354. default:
  1355. CYASSL_MSG("Unknown Signature Algo");
  1356. return 0;
  1357. }
  1358. }
  1359. else if (type == keyType) { /* keyType */
  1360. switch (algoOID) {
  1361. case RSAk:
  1362. algoSz = sizeof(RSA_AlgoID);
  1363. algoName = RSA_AlgoID;
  1364. break;
  1365. default:
  1366. CYASSL_MSG("Unknown Key Algo");
  1367. return 0;
  1368. }
  1369. }
  1370. else {
  1371. CYASSL_MSG("Unknown Algo type");
  1372. return 0;
  1373. }
  1374. idSz = SetLength(algoSz - 2, ID_Length); /* don't include TAG_NULL/0 */
  1375. seqSz = SetSequence(idSz + algoSz + 1, seqArray);
  1376. seqArray[seqSz++] = ASN_OBJECT_ID;
  1377. XMEMCPY(output, seqArray, seqSz);
  1378. XMEMCPY(output + seqSz, ID_Length, idSz);
  1379. XMEMCPY(output + seqSz + idSz, algoName, algoSz);
  1380. return seqSz + idSz + algoSz;
  1381. }
  1382. word32 EncodeSignature(byte* out, const byte* digest, word32 digSz, int hashOID)
  1383. {
  1384. byte digArray[MAX_ENCODED_DIG_SZ];
  1385. byte algoArray[MAX_ALGO_SZ];
  1386. byte seqArray[MAX_SEQ_SZ];
  1387. word32 encDigSz, algoSz, seqSz;
  1388. encDigSz = SetDigest(digest, digSz, digArray);
  1389. algoSz = SetAlgoID(hashOID, algoArray, hashType);
  1390. seqSz = SetSequence(encDigSz + algoSz, seqArray);
  1391. XMEMCPY(out, seqArray, seqSz);
  1392. XMEMCPY(out + seqSz, algoArray, algoSz);
  1393. XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
  1394. return encDigSz + algoSz + seqSz;
  1395. }
  1396. /* return true (1) for Confirmation */
  1397. static int ConfirmSignature(DecodedCert* cert, const byte* key, word32 keySz,
  1398. word32 keyOID)
  1399. {
  1400. #ifndef NO_SHA256
  1401. byte digest[SHA256_DIGEST_SIZE]; /* max size */
  1402. #else
  1403. byte digest[SHA_DIGEST_SIZE]; /* max size */
  1404. #endif
  1405. int typeH, digestSz, ret;
  1406. if (cert->signatureOID == CTC_MD5wRSA) {
  1407. Md5 md5;
  1408. InitMd5(&md5);
  1409. Md5Update(&md5, cert->source + cert->certBegin,
  1410. cert->sigIndex - cert->certBegin);
  1411. Md5Final(&md5, digest);
  1412. typeH = MD5h;
  1413. digestSz = MD5_DIGEST_SIZE;
  1414. }
  1415. else if (cert->signatureOID == CTC_SHAwRSA ||
  1416. cert->signatureOID == CTC_SHAwDSA ||
  1417. cert->signatureOID == CTC_SHAwECDSA) {
  1418. Sha sha;
  1419. InitSha(&sha);
  1420. ShaUpdate(&sha, cert->source + cert->certBegin,
  1421. cert->sigIndex - cert->certBegin);
  1422. ShaFinal(&sha, digest);
  1423. typeH = SHAh;
  1424. digestSz = SHA_DIGEST_SIZE;
  1425. }
  1426. #ifndef NO_SHA256
  1427. else if (cert->signatureOID == CTC_SHA256wRSA ||
  1428. cert->signatureOID == CTC_SHA256wECDSA) {
  1429. Sha256 sha256;
  1430. InitSha256(&sha256);
  1431. Sha256Update(&sha256, cert->source + cert->certBegin,
  1432. cert->sigIndex - cert->certBegin);
  1433. Sha256Final(&sha256, digest);
  1434. typeH = SHA256h;
  1435. digestSz = SHA256_DIGEST_SIZE;
  1436. }
  1437. #endif
  1438. else {
  1439. CYASSL_MSG("Verify Signautre has unsupported type");
  1440. return 0;
  1441. }
  1442. if (keyOID == RSAk) {
  1443. RsaKey pubKey;
  1444. byte encodedSig[MAX_ENCODED_SIG_SZ];
  1445. byte plain[MAX_ENCODED_SIG_SZ];
  1446. word32 idx = 0;
  1447. int sigSz, verifySz;
  1448. byte* out;
  1449. if (cert->sigLength > MAX_ENCODED_SIG_SZ) {
  1450. CYASSL_MSG("Verify Signautre is too big");
  1451. return 0;
  1452. }
  1453. InitRsaKey(&pubKey, cert->heap);
  1454. if (RsaPublicKeyDecode(key, &idx, &pubKey, keySz) < 0) {
  1455. CYASSL_MSG("ASN Key decode error RSA");
  1456. ret = 0;
  1457. }
  1458. else {
  1459. XMEMCPY(plain, cert->signature, cert->sigLength);
  1460. if ( (verifySz = RsaSSL_VerifyInline(plain, cert->sigLength, &out,
  1461. &pubKey)) < 0) {
  1462. CYASSL_MSG("Rsa SSL verify error");
  1463. ret = 0;
  1464. }
  1465. else {
  1466. /* make sure we're right justified */
  1467. sigSz = EncodeSignature(encodedSig, digest, digestSz, typeH);
  1468. if (sigSz != verifySz || XMEMCMP(out, encodedSig, sigSz) != 0){
  1469. CYASSL_MSG("Rsa SSL verify match encode error");
  1470. ret = 0;
  1471. }
  1472. else
  1473. ret = 1; /* match */
  1474. #ifdef CYASSL_DEBUG_ENCODING
  1475. {
  1476. int x;
  1477. printf("cyassl encodedSig:\n");
  1478. for (x = 0; x < sigSz; x++) {
  1479. printf("%02x ", encodedSig[x]);
  1480. if ( (x % 16) == 15)
  1481. printf("\n");
  1482. }
  1483. printf("\n");
  1484. printf("actual digest:\n");
  1485. for (x = 0; x < verifySz; x++) {
  1486. printf("%02x ", out[x]);
  1487. if ( (x % 16) == 15)
  1488. printf("\n");
  1489. }
  1490. printf("\n");
  1491. }
  1492. #endif /* CYASSL_DEBUG_ENCODING */
  1493. }
  1494. }
  1495. FreeRsaKey(&pubKey);
  1496. return ret;
  1497. }
  1498. #ifdef HAVE_ECC
  1499. else if (keyOID == ECDSAk) {
  1500. ecc_key pubKey;
  1501. int verify = 0;
  1502. if (ecc_import_x963(key, keySz, &pubKey) < 0) {
  1503. CYASSL_MSG("ASN Key import error ECC");
  1504. return 0;
  1505. }
  1506. ret = ecc_verify_hash(cert->signature, cert->sigLength, digest,
  1507. digestSz, &verify, &pubKey);
  1508. ecc_free(&pubKey);
  1509. if (ret == 0 && verify == 1)
  1510. return 1; /* match */
  1511. CYASSL_MSG("ECC Verify didn't match");
  1512. return 0;
  1513. }
  1514. #endif /* HAVE_ECC */
  1515. else {
  1516. CYASSL_MSG("Verify Key type unknown");
  1517. return 0;
  1518. }
  1519. }
  1520. int ParseCert(DecodedCert* cert, int type, int verify,
  1521. Signer* signers)
  1522. {
  1523. int ret;
  1524. char* ptr;
  1525. ret = ParseCertRelative(cert, type, verify, signers);
  1526. if (ret < 0)
  1527. return ret;
  1528. if (cert->subjectCNLen > 0) {
  1529. ptr = (char*) XMALLOC(cert->subjectCNLen + 1, cert->heap,
  1530. DYNAMIC_TYPE_SUBJECT_CN);
  1531. if (ptr == NULL)
  1532. return MEMORY_E;
  1533. XMEMCPY(ptr, cert->subjectCN, cert->subjectCNLen);
  1534. ptr[cert->subjectCNLen] = '\0';
  1535. cert->subjectCN = ptr;
  1536. cert->subjectCNLen = 0;
  1537. }
  1538. if (cert->keyOID == RSAk && cert->pubKeySize > 0) {
  1539. ptr = (char*) XMALLOC(cert->pubKeySize, cert->heap,
  1540. DYNAMIC_TYPE_PUBLIC_KEY);
  1541. if (ptr == NULL)
  1542. return MEMORY_E;
  1543. XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
  1544. cert->publicKey = (byte *)ptr;
  1545. cert->pubKeyStored = 1;
  1546. }
  1547. return ret;
  1548. }
  1549. /* from SSL proper, for locking can't do find here anymore */
  1550. CYASSL_LOCAL Signer* GetCA(Signer* signers, byte* hash);
  1551. int ParseCertRelative(DecodedCert* cert, int type, int verify,
  1552. Signer* signers)
  1553. {
  1554. word32 confirmOID;
  1555. int ret;
  1556. int badDate = 0;
  1557. if ((ret = DecodeToKey(cert, verify)) < 0) {
  1558. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E)
  1559. badDate = ret;
  1560. else
  1561. return ret;
  1562. }
  1563. if (cert->srcIdx != cert->sigIndex) {
  1564. if (cert->srcIdx < cert->sigIndex) {
  1565. /* save extensions */
  1566. cert->extensions = &cert->source[cert->srcIdx];
  1567. cert->extensionsSz = cert->sigIndex - cert->srcIdx;
  1568. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  1569. }
  1570. /* advance past extensions */
  1571. cert->srcIdx = cert->sigIndex;
  1572. }
  1573. if ((ret = GetAlgoId(cert->source, &cert->srcIdx, &confirmOID,
  1574. cert->maxIdx)) < 0)
  1575. return ret;
  1576. if ((ret = GetSignature(cert)) < 0)
  1577. return ret;
  1578. if (confirmOID != cert->signatureOID)
  1579. return ASN_SIG_OID_E;
  1580. if (verify && type != CA_TYPE) {
  1581. Signer* ca = GetCA(signers, cert->issuerHash);
  1582. CYASSL_MSG("About to verify certificate signature");
  1583. if (ca) {
  1584. /* try to confirm/verify signature */
  1585. if (!ConfirmSignature(cert, ca->publicKey,
  1586. ca->pubKeySize, ca->keyOID)) {
  1587. CYASSL_MSG("Confirm signature failed");
  1588. return ASN_SIG_CONFIRM_E;
  1589. }
  1590. }
  1591. else {
  1592. /* no signer */
  1593. CYASSL_MSG("No CA signer to verify with");
  1594. return ASN_SIG_CONFIRM_E;
  1595. }
  1596. }
  1597. if (badDate != 0)
  1598. return badDate;
  1599. return 0;
  1600. }
  1601. Signer* MakeSigner(void* heap)
  1602. {
  1603. Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
  1604. DYNAMIC_TYPE_SIGNER);
  1605. if (signer) {
  1606. signer->name = 0;
  1607. signer->publicKey = 0;
  1608. signer->next = 0;
  1609. }
  1610. (void)heap;
  1611. return signer;
  1612. }
  1613. void FreeSigners(Signer* signer, void* heap)
  1614. {
  1615. while (signer) {
  1616. Signer* next = signer->next;
  1617. XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  1618. XFREE(signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  1619. XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
  1620. signer = next;
  1621. }
  1622. (void)heap;
  1623. }
  1624. void CTaoCryptErrorString(int error, char* buffer)
  1625. {
  1626. const int max = MAX_ERROR_SZ; /* shorthand */
  1627. #ifdef NO_ERROR_STRINGS
  1628. XSTRNCPY(buffer, "no support for error strings built in", max);
  1629. #else
  1630. switch (error) {
  1631. case OPEN_RAN_E :
  1632. XSTRNCPY(buffer, "opening random device error", max);
  1633. break;
  1634. case READ_RAN_E :
  1635. XSTRNCPY(buffer, "reading random device error", max);
  1636. break;
  1637. case WINCRYPT_E :
  1638. XSTRNCPY(buffer, "windows crypt init error", max);
  1639. break;
  1640. case CRYPTGEN_E :
  1641. XSTRNCPY(buffer, "windows crypt generation error", max);
  1642. break;
  1643. case RAN_BLOCK_E :
  1644. XSTRNCPY(buffer, "random device read would block error", max);
  1645. break;
  1646. case MP_INIT_E :
  1647. XSTRNCPY(buffer, "mp_init error state", max);
  1648. break;
  1649. case MP_READ_E :
  1650. XSTRNCPY(buffer, "mp_read error state", max);
  1651. break;
  1652. case MP_EXPTMOD_E :
  1653. XSTRNCPY(buffer, "mp_exptmod error state", max);
  1654. break;
  1655. case MP_TO_E :
  1656. XSTRNCPY(buffer, "mp_to_xxx error state, can't convert", max);
  1657. break;
  1658. case MP_SUB_E :
  1659. XSTRNCPY(buffer, "mp_sub error state, can't subtract", max);
  1660. break;
  1661. case MP_ADD_E :
  1662. XSTRNCPY(buffer, "mp_add error state, can't add", max);
  1663. break;
  1664. case MP_MUL_E :
  1665. XSTRNCPY(buffer, "mp_mul error state, can't multiply", max);
  1666. break;
  1667. case MP_MULMOD_E :
  1668. XSTRNCPY(buffer, "mp_mulmod error state, can't multiply mod", max);
  1669. break;
  1670. case MP_MOD_E :
  1671. XSTRNCPY(buffer, "mp_mod error state, can't mod", max);
  1672. break;
  1673. case MP_INVMOD_E :
  1674. XSTRNCPY(buffer, "mp_invmod error state, can't inv mod", max);
  1675. break;
  1676. case MP_CMP_E :
  1677. XSTRNCPY(buffer, "mp_cmp error state", max);
  1678. break;
  1679. case MP_ZERO_E :
  1680. XSTRNCPY(buffer, "mp zero result, not expected", max);
  1681. break;
  1682. case MEMORY_E :
  1683. XSTRNCPY(buffer, "out of memory error", max);
  1684. break;
  1685. case RSA_WRONG_TYPE_E :
  1686. XSTRNCPY(buffer, "RSA wrong block type for RSA function", max);
  1687. break;
  1688. case RSA_BUFFER_E :
  1689. XSTRNCPY(buffer, "RSA buffer error, output too small or input too big",
  1690. max);
  1691. break;
  1692. case BUFFER_E :
  1693. XSTRNCPY(buffer, "Buffer error, output too small or input too big",max);
  1694. break;
  1695. case ALGO_ID_E :
  1696. XSTRNCPY(buffer, "Setting Cert AlogID error", max);
  1697. break;
  1698. case PUBLIC_KEY_E :
  1699. XSTRNCPY(buffer, "Setting Cert Public Key error", max);
  1700. break;
  1701. case DATE_E :
  1702. XSTRNCPY(buffer, "Setting Cert Date validity error", max);
  1703. break;
  1704. case SUBJECT_E :
  1705. XSTRNCPY(buffer, "Setting Cert Subject name error", max);
  1706. break;
  1707. case ISSUER_E :
  1708. XSTRNCPY(buffer, "Setting Cert Issuer name error", max);
  1709. break;
  1710. case CA_TRUE_E :
  1711. XSTRNCPY(buffer, "Setting basic constraint CA true error", max);
  1712. break;
  1713. case EXTENSIONS_E :
  1714. XSTRNCPY(buffer, "Setting extensions error", max);
  1715. break;
  1716. case ASN_PARSE_E :
  1717. XSTRNCPY(buffer, "ASN parsing error, invalid input", max);
  1718. break;
  1719. case ASN_VERSION_E :
  1720. XSTRNCPY(buffer, "ASN version error, invalid number", max);
  1721. break;
  1722. case ASN_GETINT_E :
  1723. XSTRNCPY(buffer, "ASN get big int error, invalid data", max);
  1724. break;
  1725. case ASN_RSA_KEY_E :
  1726. XSTRNCPY(buffer, "ASN key init error, invalid input", max);
  1727. break;
  1728. case ASN_OBJECT_ID_E :
  1729. XSTRNCPY(buffer, "ASN object id error, invalid id", max);
  1730. break;
  1731. case ASN_TAG_NULL_E :
  1732. XSTRNCPY(buffer, "ASN tag error, not null", max);
  1733. break;
  1734. case ASN_EXPECT_0_E :
  1735. XSTRNCPY(buffer, "ASN expect error, not zero", max);
  1736. break;
  1737. case ASN_BITSTR_E :
  1738. XSTRNCPY(buffer, "ASN bit string error, wrong id", max);
  1739. break;
  1740. case ASN_UNKNOWN_OID_E :
  1741. XSTRNCPY(buffer, "ASN oid error, unknown sum id", max);
  1742. break;
  1743. case ASN_DATE_SZ_E :
  1744. XSTRNCPY(buffer, "ASN date error, bad size", max);
  1745. break;
  1746. case ASN_BEFORE_DATE_E :
  1747. XSTRNCPY(buffer, "ASN date error, current date before", max);
  1748. break;
  1749. case ASN_AFTER_DATE_E :
  1750. XSTRNCPY(buffer, "ASN date error, current date after", max);
  1751. break;
  1752. case ASN_SIG_OID_E :
  1753. XSTRNCPY(buffer, "ASN signature error, mismatched oid", max);
  1754. break;
  1755. case ASN_TIME_E :
  1756. XSTRNCPY(buffer, "ASN time error, unkown time type", max);
  1757. break;
  1758. case ASN_INPUT_E :
  1759. XSTRNCPY(buffer, "ASN input error, not enough data", max);
  1760. break;
  1761. case ASN_SIG_CONFIRM_E :
  1762. XSTRNCPY(buffer, "ASN sig error, confirm failure", max);
  1763. break;
  1764. case ASN_SIG_HASH_E :
  1765. XSTRNCPY(buffer, "ASN sig error, unsupported hash type", max);
  1766. break;
  1767. case ASN_SIG_KEY_E :
  1768. XSTRNCPY(buffer, "ASN sig error, unsupported key type", max);
  1769. break;
  1770. case ASN_DH_KEY_E :
  1771. XSTRNCPY(buffer, "ASN key init error, invalid input", max);
  1772. break;
  1773. case ASN_NTRU_KEY_E :
  1774. XSTRNCPY(buffer, "ASN NTRU key decode error, invalid input", max);
  1775. break;
  1776. case ECC_BAD_ARG_E :
  1777. XSTRNCPY(buffer, "ECC input argument wrong type, invalid input", max);
  1778. break;
  1779. case ASN_ECC_KEY_E :
  1780. XSTRNCPY(buffer, "ECC ASN1 bad key data, invalid input", max);
  1781. break;
  1782. case ECC_CURVE_OID_E :
  1783. XSTRNCPY(buffer, "ECC curve sum OID unsupported, invalid input", max);
  1784. break;
  1785. case BAD_FUNC_ARG :
  1786. XSTRNCPY(buffer, "Bad function argument", max);
  1787. break;
  1788. case NOT_COMPILED_IN :
  1789. XSTRNCPY(buffer, "Feature not compiled in", max);
  1790. break;
  1791. case UNICODE_SIZE_E :
  1792. XSTRNCPY(buffer, "Unicode password too big", max);
  1793. break;
  1794. case NO_PASSWORD :
  1795. XSTRNCPY(buffer, "No password provided by user", max);
  1796. break;
  1797. default:
  1798. XSTRNCPY(buffer, "unknown error number", max);
  1799. }
  1800. #endif /* NO_ERROR_STRINGS */
  1801. }
  1802. #if defined(CYASSL_KEY_GEN) || defined(CYASSL_CERT_GEN)
  1803. static int SetMyVersion(word32 version, byte* output, int header)
  1804. {
  1805. int i = 0;
  1806. if (header) {
  1807. output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  1808. output[i++] = ASN_BIT_STRING;
  1809. }
  1810. output[i++] = ASN_INTEGER;
  1811. output[i++] = 0x01;
  1812. output[i++] = version;
  1813. return i;
  1814. }
  1815. int DerToPem(const byte* der, word32 derSz, byte* output, word32 outSz,
  1816. int type)
  1817. {
  1818. char header[80];
  1819. char footer[80];
  1820. int headerLen;
  1821. int footerLen;
  1822. int i;
  1823. int err;
  1824. int outLen; /* return length or error */
  1825. if (type == CERT_TYPE) {
  1826. XSTRNCPY(header, "-----BEGIN CERTIFICATE-----\n", sizeof(header));
  1827. XSTRNCPY(footer, "-----END CERTIFICATE-----\n", sizeof(footer));
  1828. } else {
  1829. XSTRNCPY(header, "-----BEGIN RSA PRIVATE KEY-----\n", sizeof(header));
  1830. XSTRNCPY(footer, "-----END RSA PRIVATE KEY-----\n", sizeof(footer));
  1831. }
  1832. headerLen = XSTRLEN(header);
  1833. footerLen = XSTRLEN(footer);
  1834. if (!der || !output)
  1835. return BAD_FUNC_ARG;
  1836. /* don't even try if outSz too short */
  1837. if (outSz < headerLen + footerLen + derSz)
  1838. return BAD_FUNC_ARG;
  1839. /* header */
  1840. XMEMCPY(output, header, headerLen);
  1841. i = headerLen;
  1842. /* body */
  1843. outLen = outSz; /* input to Base64Encode */
  1844. if ( (err = Base64Encode(der, derSz, output + i, (word32*)&outLen)) < 0)
  1845. return err;
  1846. i += outLen;
  1847. /* footer */
  1848. if ( (i + footerLen) > (int)outSz)
  1849. return BAD_FUNC_ARG;
  1850. XMEMCPY(output + i, footer, footerLen);
  1851. return outLen + headerLen + footerLen;
  1852. }
  1853. #endif /* CYASSL_KEY_GEN || CYASSL_CERT_GEN */
  1854. #ifdef CYASSL_KEY_GEN
  1855. static mp_int* GetRsaInt(RsaKey* key, int idx)
  1856. {
  1857. if (idx == 0)
  1858. return &key->n;
  1859. if (idx == 1)
  1860. return &key->e;
  1861. if (idx == 2)
  1862. return &key->d;
  1863. if (idx == 3)
  1864. return &key->p;
  1865. if (idx == 4)
  1866. return &key->q;
  1867. if (idx == 5)
  1868. return &key->dP;
  1869. if (idx == 6)
  1870. return &key->dQ;
  1871. if (idx == 7)
  1872. return &key->u;
  1873. return NULL;
  1874. }
  1875. /* Convert RsaKey key to DER format, write to output (inLen), return bytes
  1876. written */
  1877. int RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
  1878. {
  1879. word32 seqSz, verSz, rawLen, intTotalLen = 0;
  1880. word32 sizes[RSA_INTS];
  1881. int i, j, outLen;
  1882. byte seq[MAX_SEQ_SZ];
  1883. byte ver[MAX_VERSION_SZ];
  1884. byte tmps[RSA_INTS][MAX_RSA_INT_SZ];
  1885. if (!key || !output)
  1886. return BAD_FUNC_ARG;
  1887. if (key->type != RSA_PRIVATE)
  1888. return BAD_FUNC_ARG;
  1889. /* write all big ints from key to DER tmps */
  1890. for (i = 0; i < RSA_INTS; i++) {
  1891. mp_int* keyInt = GetRsaInt(key, i);
  1892. rawLen = mp_unsigned_bin_size(keyInt);
  1893. tmps[i][0] = ASN_INTEGER;
  1894. sizes[i] = SetLength(rawLen, tmps[i] + 1) + 1; /* int tag */
  1895. if ( (sizes[i] + rawLen) < sizeof(tmps[i])) {
  1896. int err = mp_to_unsigned_bin(keyInt, tmps[i] + sizes[i]);
  1897. if (err == MP_OKAY) {
  1898. sizes[i] += rawLen;
  1899. intTotalLen += sizes[i];
  1900. }
  1901. else
  1902. return err;
  1903. }
  1904. else
  1905. return ASN_INPUT_E;
  1906. }
  1907. /* make headers */
  1908. verSz = SetMyVersion(0, ver, FALSE);
  1909. seqSz = SetSequence(verSz + intTotalLen, seq);
  1910. outLen = seqSz + verSz + intTotalLen;
  1911. if (outLen > (int)inLen)
  1912. return BAD_FUNC_ARG;
  1913. /* write to output */
  1914. XMEMCPY(output, seq, seqSz);
  1915. j = seqSz;
  1916. XMEMCPY(output + j, ver, verSz);
  1917. j += verSz;
  1918. for (i = 0; i < RSA_INTS; i++) {
  1919. XMEMCPY(output + j, tmps[i], sizes[i]);
  1920. j += sizes[i];
  1921. }
  1922. return outLen;
  1923. }
  1924. #endif /* CYASSL_KEY_GEN */
  1925. #ifdef CYASSL_CERT_GEN
  1926. /* Initialize and Set Certficate defaults:
  1927. version = 3 (0x2)
  1928. serial = 0
  1929. sigType = SHA_WITH_RSA
  1930. issuer = blank
  1931. daysValid = 500
  1932. selfSigned = 1 (true) use subject as issuer
  1933. subject = blank
  1934. */
  1935. void InitCert(Cert* cert)
  1936. {
  1937. cert->version = 2; /* version 3 is hex 2 */
  1938. cert->sigType = CTC_SHAwRSA;
  1939. cert->daysValid = 500;
  1940. cert->selfSigned = 1;
  1941. cert->isCA = 0;
  1942. cert->bodySz = 0;
  1943. cert->altNamesSz = 0;
  1944. cert->keyType = RSA_KEY;
  1945. XMEMSET(cert->serial, 0, CTC_SERIAL_SIZE);
  1946. cert->issuer.country[0] = '\0';
  1947. cert->issuer.state[0] = '\0';
  1948. cert->issuer.locality[0] = '\0';
  1949. cert->issuer.sur[0] = '\0';
  1950. cert->issuer.org[0] = '\0';
  1951. cert->issuer.unit[0] = '\0';
  1952. cert->issuer.commonName[0] = '\0';
  1953. cert->issuer.email[0] = '\0';
  1954. cert->subject.country[0] = '\0';
  1955. cert->subject.state[0] = '\0';
  1956. cert->subject.locality[0] = '\0';
  1957. cert->subject.sur[0] = '\0';
  1958. cert->subject.org[0] = '\0';
  1959. cert->subject.unit[0] = '\0';
  1960. cert->subject.commonName[0] = '\0';
  1961. cert->subject.email[0] = '\0';
  1962. }
  1963. /* DER encoded x509 Certificate */
  1964. typedef struct DerCert {
  1965. byte size[MAX_LENGTH_SZ]; /* length encoded */
  1966. byte version[MAX_VERSION_SZ]; /* version encoded */
  1967. byte serial[CTC_SERIAL_SIZE + MAX_LENGTH_SZ]; /* serial number encoded */
  1968. byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
  1969. byte issuer[ASN_NAME_MAX]; /* issuer encoded */
  1970. byte subject[ASN_NAME_MAX]; /* subject encoded */
  1971. byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
  1972. byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa / ntru public key encoded */
  1973. byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
  1974. byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
  1975. int sizeSz; /* encoded size length */
  1976. int versionSz; /* encoded version length */
  1977. int serialSz; /* encoded serial length */
  1978. int sigAlgoSz; /* enocded sig alog length */
  1979. int issuerSz; /* encoded issuer length */
  1980. int subjectSz; /* encoded subject length */
  1981. int validitySz; /* encoded validity length */
  1982. int publicKeySz; /* encoded public key length */
  1983. int caSz; /* encoded CA extension length */
  1984. int extensionsSz; /* encoded extensions total length */
  1985. int total; /* total encoded lengths */
  1986. } DerCert;
  1987. /* Write a set header to output */
  1988. static word32 SetSet(word32 len, byte* output)
  1989. {
  1990. output[0] = ASN_SET | ASN_CONSTRUCTED;
  1991. return SetLength(len, output + 1) + 1;
  1992. }
  1993. /* Write a serial number to output */
  1994. static int SetSerial(const byte* serial, byte* output)
  1995. {
  1996. int length = 0;
  1997. output[length++] = ASN_INTEGER;
  1998. length += SetLength(CTC_SERIAL_SIZE, &output[length]);
  1999. XMEMCPY(&output[length], serial, CTC_SERIAL_SIZE);
  2000. return length + CTC_SERIAL_SIZE;
  2001. }
  2002. /* Write a public RSA key to output */
  2003. static int SetPublicKey(byte* output, RsaKey* key)
  2004. {
  2005. byte n[MAX_RSA_INT_SZ];
  2006. byte e[MAX_RSA_E_SZ];
  2007. byte algo[MAX_ALGO_SZ];
  2008. byte seq[MAX_SEQ_SZ];
  2009. byte len[MAX_LENGTH_SZ + 1]; /* trailing 0 */
  2010. int nSz;
  2011. int eSz;
  2012. int algoSz;
  2013. int seqSz;
  2014. int lenSz;
  2015. int idx;
  2016. int rawLen;
  2017. /* n */
  2018. rawLen = mp_unsigned_bin_size(&key->n);
  2019. n[0] = ASN_INTEGER;
  2020. nSz = SetLength(rawLen, n + 1) + 1; /* int tag */
  2021. if ( (nSz + rawLen) < (int)sizeof(n)) {
  2022. int err = mp_to_unsigned_bin(&key->n, n + nSz);
  2023. if (err == MP_OKAY)
  2024. nSz += rawLen;
  2025. else
  2026. return MP_TO_E;
  2027. }
  2028. else
  2029. return BUFFER_E;
  2030. /* e */
  2031. rawLen = mp_unsigned_bin_size(&key->e);
  2032. e[0] = ASN_INTEGER;
  2033. eSz = SetLength(rawLen, e + 1) + 1; /* int tag */
  2034. if ( (eSz + rawLen) < (int)sizeof(e)) {
  2035. int err = mp_to_unsigned_bin(&key->e, e + eSz);
  2036. if (err == MP_OKAY)
  2037. eSz += rawLen;
  2038. else
  2039. return MP_TO_E;
  2040. }
  2041. else
  2042. return BUFFER_E;
  2043. /* headers */
  2044. algoSz = SetAlgoID(RSAk, algo, keyType);
  2045. seqSz = SetSequence(nSz + eSz, seq);
  2046. lenSz = SetLength(seqSz + nSz + eSz + 1, len);
  2047. len[lenSz++] = 0; /* trailing 0 */
  2048. /* write */
  2049. idx = SetSequence(nSz + eSz + seqSz + lenSz + 1 + algoSz, output);
  2050. /* 1 is for ASN_BIT_STRING */
  2051. /* algo */
  2052. XMEMCPY(output + idx, algo, algoSz);
  2053. idx += algoSz;
  2054. /* bit string */
  2055. output[idx++] = ASN_BIT_STRING;
  2056. /* length */
  2057. XMEMCPY(output + idx, len, lenSz);
  2058. idx += lenSz;
  2059. /* seq */
  2060. XMEMCPY(output + idx, seq, seqSz);
  2061. idx += seqSz;
  2062. /* n */
  2063. XMEMCPY(output + idx, n, nSz);
  2064. idx += nSz;
  2065. /* e */
  2066. XMEMCPY(output + idx, e, eSz);
  2067. idx += eSz;
  2068. return idx;
  2069. }
  2070. static INLINE byte itob(int number)
  2071. {
  2072. return (byte)number + 0x30;
  2073. }
  2074. /* write time to output, format */
  2075. static void SetTime(struct tm* date, byte* output)
  2076. {
  2077. int i = 0;
  2078. output[i++] = itob((date->tm_year % 10000) / 1000);
  2079. output[i++] = itob((date->tm_year % 1000) / 100);
  2080. output[i++] = itob((date->tm_year % 100) / 10);
  2081. output[i++] = itob( date->tm_year % 10);
  2082. output[i++] = itob(date->tm_mon / 10);
  2083. output[i++] = itob(date->tm_mon % 10);
  2084. output[i++] = itob(date->tm_mday / 10);
  2085. output[i++] = itob(date->tm_mday % 10);
  2086. output[i++] = itob(date->tm_hour / 10);
  2087. output[i++] = itob(date->tm_hour % 10);
  2088. output[i++] = itob(date->tm_min / 10);
  2089. output[i++] = itob(date->tm_min % 10);
  2090. output[i++] = itob(date->tm_sec / 10);
  2091. output[i++] = itob(date->tm_sec % 10);
  2092. output[i] = 'Z'; /* Zulu profile */
  2093. }
  2094. /* Set Date validity from now until now + daysValid */
  2095. static int SetValidity(byte* output, int daysValid)
  2096. {
  2097. byte before[MAX_DATE_SIZE];
  2098. byte after[MAX_DATE_SIZE];
  2099. int beforeSz;
  2100. int afterSz;
  2101. int seqSz;
  2102. time_t ticks;
  2103. struct tm* now;
  2104. struct tm local;
  2105. ticks = XTIME(0);
  2106. now = XGMTIME(&ticks);
  2107. /* before now */
  2108. local = *now;
  2109. before[0] = ASN_GENERALIZED_TIME;
  2110. beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
  2111. /* subtract 1 day for more compliance */
  2112. local.tm_mday -= 1;
  2113. mktime(&local);
  2114. /* adjust */
  2115. local.tm_year += 1900;
  2116. local.tm_mon += 1;
  2117. SetTime(&local, before + beforeSz);
  2118. beforeSz += ASN_GEN_TIME_SZ;
  2119. /* after now + daysValid */
  2120. local = *now;
  2121. after[0] = ASN_GENERALIZED_TIME;
  2122. afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
  2123. /* add daysValid */
  2124. local.tm_mday += daysValid;
  2125. mktime(&local);
  2126. /* adjust */
  2127. local.tm_year += 1900;
  2128. local.tm_mon += 1;
  2129. SetTime(&local, after + afterSz);
  2130. afterSz += ASN_GEN_TIME_SZ;
  2131. /* headers and output */
  2132. seqSz = SetSequence(beforeSz + afterSz, output);
  2133. XMEMCPY(output + seqSz, before, beforeSz);
  2134. XMEMCPY(output + seqSz + beforeSz, after, afterSz);
  2135. return seqSz + beforeSz + afterSz;
  2136. }
  2137. /* ASN Encoded Name field */
  2138. typedef struct EncodedName {
  2139. int nameLen; /* actual string value length */
  2140. int totalLen; /* total encoded length */
  2141. int type; /* type of name */
  2142. int used; /* are we actually using this one */
  2143. byte encoded[CTC_NAME_SIZE * 2]; /* encoding */
  2144. } EncodedName;
  2145. /* Get Which Name from index */
  2146. static const char* GetOneName(CertName* name, int idx)
  2147. {
  2148. switch (idx) {
  2149. case 0:
  2150. return name->country;
  2151. break;
  2152. case 1:
  2153. return name->state;
  2154. break;
  2155. case 2:
  2156. return name->locality;
  2157. break;
  2158. case 3:
  2159. return name->sur;
  2160. break;
  2161. case 4:
  2162. return name->org;
  2163. break;
  2164. case 5:
  2165. return name->unit;
  2166. break;
  2167. case 6:
  2168. return name->commonName;
  2169. break;
  2170. case 7:
  2171. return name->email;
  2172. break;
  2173. default:
  2174. return 0;
  2175. }
  2176. return 0;
  2177. }
  2178. /* Get ASN Name from index */
  2179. static byte GetNameId(int idx)
  2180. {
  2181. switch (idx) {
  2182. case 0:
  2183. return ASN_COUNTRY_NAME;
  2184. break;
  2185. case 1:
  2186. return ASN_STATE_NAME;
  2187. break;
  2188. case 2:
  2189. return ASN_LOCALITY_NAME;
  2190. break;
  2191. case 3:
  2192. return ASN_SUR_NAME;
  2193. break;
  2194. case 4:
  2195. return ASN_ORG_NAME;
  2196. break;
  2197. case 5:
  2198. return ASN_ORGUNIT_NAME;
  2199. break;
  2200. case 6:
  2201. return ASN_COMMON_NAME;
  2202. break;
  2203. case 7:
  2204. /* email uses different id type */
  2205. return 0;
  2206. break;
  2207. default:
  2208. return 0;
  2209. }
  2210. return 0;
  2211. }
  2212. /* encode all extensions, return total bytes written */
  2213. static int SetExtensions(byte* output, const byte* ext, int extSz)
  2214. {
  2215. byte sequence[MAX_SEQ_SZ];
  2216. byte len[MAX_LENGTH_SZ];
  2217. int sz = 0;
  2218. int seqSz = SetSequence(extSz, sequence);
  2219. int lenSz = SetLength(seqSz + extSz, len);
  2220. output[0] = ASN_EXTENSIONS; /* extensions id */
  2221. sz++;
  2222. XMEMCPY(&output[sz], len, lenSz); /* length */
  2223. sz += lenSz;
  2224. XMEMCPY(&output[sz], sequence, seqSz); /* sequence */
  2225. sz += seqSz;
  2226. XMEMCPY(&output[sz], ext, extSz); /* extensions */
  2227. sz += extSz;
  2228. return sz;
  2229. }
  2230. /* encode CA basic constraint true, return total bytes written */
  2231. static int SetCa(byte* output)
  2232. {
  2233. static const byte ca[] = { 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  2234. 0x05, 0x30, 0x03, 0x01, 0x01, 0xff };
  2235. XMEMCPY(output, ca, sizeof(ca));
  2236. return (int)sizeof(ca);
  2237. }
  2238. /* encode CertName into output, return total bytes written */
  2239. static int SetName(byte* output, CertName* name)
  2240. {
  2241. int totalBytes = 0, i, idx;
  2242. EncodedName names[NAME_ENTRIES];
  2243. for (i = 0; i < NAME_ENTRIES; i++) {
  2244. const char* nameStr = GetOneName(name, i);
  2245. if (nameStr) {
  2246. /* bottom up */
  2247. byte firstLen[MAX_LENGTH_SZ];
  2248. byte secondLen[MAX_LENGTH_SZ];
  2249. byte sequence[MAX_SEQ_SZ];
  2250. byte set[MAX_SET_SZ];
  2251. int email = i == (NAME_ENTRIES - 1) ? 1 : 0;
  2252. int strLen = XSTRLEN(nameStr);
  2253. int thisLen = strLen;
  2254. int firstSz, secondSz, seqSz, setSz;
  2255. if (strLen == 0) { /* no user data for this item */
  2256. names[i].used = 0;
  2257. continue;
  2258. }
  2259. secondSz = SetLength(strLen, secondLen);
  2260. thisLen += secondSz;
  2261. if (email) {
  2262. thisLen += EMAIL_JOINT_LEN;
  2263. thisLen ++; /* id type */
  2264. firstSz = SetLength(EMAIL_JOINT_LEN, firstLen);
  2265. }
  2266. else {
  2267. thisLen++; /* str type */
  2268. thisLen++; /* id type */
  2269. thisLen += JOINT_LEN;
  2270. firstSz = SetLength(JOINT_LEN + 1, firstLen);
  2271. }
  2272. thisLen += firstSz;
  2273. thisLen++; /* object id */
  2274. seqSz = SetSequence(thisLen, sequence);
  2275. thisLen += seqSz;
  2276. setSz = SetSet(thisLen, set);
  2277. thisLen += setSz;
  2278. if (thisLen > (int)sizeof(names[i].encoded))
  2279. return BUFFER_E;
  2280. /* store it */
  2281. idx = 0;
  2282. /* set */
  2283. XMEMCPY(names[i].encoded, set, setSz);
  2284. idx += setSz;
  2285. /* seq */
  2286. XMEMCPY(names[i].encoded + idx, sequence, seqSz);
  2287. idx += seqSz;
  2288. /* asn object id */
  2289. names[i].encoded[idx++] = ASN_OBJECT_ID;
  2290. /* first length */
  2291. XMEMCPY(names[i].encoded + idx, firstLen, firstSz);
  2292. idx += firstSz;
  2293. if (email) {
  2294. const byte EMAIL_OID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  2295. 0x01, 0x09, 0x01, 0x16 };
  2296. /* email joint id */
  2297. XMEMCPY(names[i].encoded + idx, EMAIL_OID, sizeof(EMAIL_OID));
  2298. idx += sizeof(EMAIL_OID);
  2299. }
  2300. else {
  2301. /* joint id */
  2302. names[i].encoded[idx++] = 0x55;
  2303. names[i].encoded[idx++] = 0x04;
  2304. /* id type */
  2305. names[i].encoded[idx++] = GetNameId(i);
  2306. /* str type */
  2307. names[i].encoded[idx++] = 0x13;
  2308. }
  2309. /* second length */
  2310. XMEMCPY(names[i].encoded + idx, secondLen, secondSz);
  2311. idx += secondSz;
  2312. /* str value */
  2313. XMEMCPY(names[i].encoded + idx, nameStr, strLen);
  2314. idx += strLen;
  2315. totalBytes += idx;
  2316. names[i].totalLen = idx;
  2317. names[i].used = 1;
  2318. }
  2319. else
  2320. names[i].used = 0;
  2321. }
  2322. /* header */
  2323. idx = SetSequence(totalBytes, output);
  2324. totalBytes += idx;
  2325. if (totalBytes > ASN_NAME_MAX)
  2326. return BUFFER_E;
  2327. for (i = 0; i < NAME_ENTRIES; i++) {
  2328. if (names[i].used) {
  2329. XMEMCPY(output + idx, names[i].encoded, names[i].totalLen);
  2330. idx += names[i].totalLen;
  2331. }
  2332. }
  2333. return totalBytes;
  2334. }
  2335. /* encode info from cert into DER enocder format */
  2336. static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, RNG* rng,
  2337. const byte* ntruKey, word16 ntruSz)
  2338. {
  2339. (void)ntruKey;
  2340. (void)ntruSz;
  2341. /* version */
  2342. der->versionSz = SetMyVersion(cert->version, der->version, TRUE);
  2343. /* serial number */
  2344. RNG_GenerateBlock(rng, cert->serial, CTC_SERIAL_SIZE);
  2345. cert->serial[0] = 0x01; /* ensure positive */
  2346. der->serialSz = SetSerial(cert->serial, der->serial);
  2347. /* signature algo */
  2348. der->sigAlgoSz = SetAlgoID(cert->sigType, der->sigAlgo, sigType);
  2349. if (der->sigAlgoSz == 0)
  2350. return ALGO_ID_E;
  2351. /* public key */
  2352. if (cert->keyType == RSA_KEY) {
  2353. der->publicKeySz = SetPublicKey(der->publicKey, rsaKey);
  2354. if (der->publicKeySz == 0)
  2355. return PUBLIC_KEY_E;
  2356. }
  2357. else {
  2358. #ifdef HAVE_NTRU
  2359. word32 rc;
  2360. word16 encodedSz;
  2361. rc = crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo( ntruSz,
  2362. ntruKey, &encodedSz, NULL);
  2363. if (rc != NTRU_OK)
  2364. return PUBLIC_KEY_E;
  2365. if (encodedSz > MAX_PUBLIC_KEY_SZ)
  2366. return PUBLIC_KEY_E;
  2367. rc = crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo( ntruSz,
  2368. ntruKey, &encodedSz, der->publicKey);
  2369. if (rc != NTRU_OK)
  2370. return PUBLIC_KEY_E;
  2371. der->publicKeySz = encodedSz;
  2372. #endif
  2373. }
  2374. /* date validity */
  2375. der->validitySz = SetValidity(der->validity, cert->daysValid);
  2376. if (der->validitySz == 0)
  2377. return DATE_E;
  2378. /* subject name */
  2379. der->subjectSz = SetName(der->subject, &cert->subject);
  2380. if (der->subjectSz == 0)
  2381. return SUBJECT_E;
  2382. /* issuer name */
  2383. der->issuerSz = SetName(der->issuer, cert->selfSigned ?
  2384. &cert->subject : &cert->issuer);
  2385. if (der->issuerSz == 0)
  2386. return ISSUER_E;
  2387. /* CA */
  2388. if (cert->isCA) {
  2389. der->caSz = SetCa(der->ca);
  2390. if (der->caSz == 0)
  2391. return CA_TRUE_E;
  2392. }
  2393. else
  2394. der->caSz = 0;
  2395. /* extensions, just CA now */
  2396. if (cert->isCA) {
  2397. der->extensionsSz = SetExtensions(der->extensions, der->ca, der->caSz);
  2398. if (der->extensionsSz == 0)
  2399. return EXTENSIONS_E;
  2400. }
  2401. else
  2402. der->extensionsSz = 0;
  2403. if (der->extensionsSz == 0 && cert->altNamesSz) {
  2404. der->extensionsSz = SetExtensions(der->extensions, cert->altNames,
  2405. cert->altNamesSz);
  2406. if (der->extensionsSz == 0)
  2407. return EXTENSIONS_E;
  2408. }
  2409. der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
  2410. der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
  2411. der->extensionsSz;
  2412. return 0;
  2413. }
  2414. /* write DER encoded cert to buffer, size already checked */
  2415. static int WriteCertBody(DerCert* der, byte* buffer)
  2416. {
  2417. int idx;
  2418. /* signed part header */
  2419. idx = SetSequence(der->total, buffer);
  2420. /* version */
  2421. XMEMCPY(buffer + idx, der->version, der->versionSz);
  2422. idx += der->versionSz;
  2423. /* serial */
  2424. XMEMCPY(buffer + idx, der->serial, der->serialSz);
  2425. idx += der->serialSz;
  2426. /* sig algo */
  2427. XMEMCPY(buffer + idx, der->sigAlgo, der->sigAlgoSz);
  2428. idx += der->sigAlgoSz;
  2429. /* issuer */
  2430. XMEMCPY(buffer + idx, der->issuer, der->issuerSz);
  2431. idx += der->issuerSz;
  2432. /* validity */
  2433. XMEMCPY(buffer + idx, der->validity, der->validitySz);
  2434. idx += der->validitySz;
  2435. /* subject */
  2436. XMEMCPY(buffer + idx, der->subject, der->subjectSz);
  2437. idx += der->subjectSz;
  2438. /* public key */
  2439. XMEMCPY(buffer + idx, der->publicKey, der->publicKeySz);
  2440. idx += der->publicKeySz;
  2441. if (der->extensionsSz) {
  2442. /* extensions */
  2443. XMEMCPY(buffer + idx, der->extensions, der->extensionsSz);
  2444. idx += der->extensionsSz;
  2445. }
  2446. return idx;
  2447. }
  2448. /* Make RSA signature from buffer (sz), write to sig (sigSz) */
  2449. static int MakeSignature(const byte* buffer, int sz, byte* sig, int sigSz,
  2450. RsaKey* key, RNG* rng, int sigAlgoType)
  2451. {
  2452. byte digest[SHA256_DIGEST_SIZE]; /* max size */
  2453. byte encSig[MAX_ENCODED_DIG_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ];
  2454. int encSigSz, digestSz, typeH;
  2455. if (sigAlgoType == CTC_MD5wRSA) {
  2456. Md5 md5;
  2457. InitMd5(&md5);
  2458. Md5Update(&md5, buffer, sz);
  2459. Md5Final(&md5, digest);
  2460. digestSz = MD5_DIGEST_SIZE;
  2461. typeH = MD5h;
  2462. }
  2463. else if (sigAlgoType == CTC_SHAwRSA) {
  2464. Sha sha;
  2465. InitSha(&sha);
  2466. ShaUpdate(&sha, buffer, sz);
  2467. ShaFinal(&sha, digest);
  2468. digestSz = SHA_DIGEST_SIZE;
  2469. typeH = SHAh;
  2470. }
  2471. else if (sigAlgoType == CTC_SHA256wRSA) {
  2472. Sha256 sha256;
  2473. InitSha256(&sha256);
  2474. Sha256Update(&sha256, buffer, sz);
  2475. Sha256Final(&sha256, digest);
  2476. digestSz = SHA256_DIGEST_SIZE;
  2477. typeH = SHA256h;
  2478. }
  2479. else
  2480. return ALGO_ID_E;
  2481. /* signature */
  2482. encSigSz = EncodeSignature(encSig, digest, digestSz, typeH);
  2483. return RsaSSL_Sign(encSig, encSigSz, sig, sigSz, key, rng);
  2484. }
  2485. /* add signature to end of buffer, size of buffer assumed checked, return
  2486. new length */
  2487. static int AddSignature(byte* buffer, int bodySz, const byte* sig, int sigSz,
  2488. int sigAlgoType)
  2489. {
  2490. byte seq[MAX_SEQ_SZ];
  2491. int idx = bodySz, seqSz;
  2492. /* algo */
  2493. idx += SetAlgoID(sigAlgoType, buffer + idx, sigType);
  2494. /* bit string */
  2495. buffer[idx++] = ASN_BIT_STRING;
  2496. /* length */
  2497. idx += SetLength(sigSz + 1, buffer + idx);
  2498. buffer[idx++] = 0; /* trailing 0 */
  2499. /* signature */
  2500. XMEMCPY(buffer + idx, sig, sigSz);
  2501. idx += sigSz;
  2502. /* make room for overall header */
  2503. seqSz = SetSequence(idx, seq);
  2504. XMEMMOVE(buffer + seqSz, buffer, idx);
  2505. XMEMCPY(buffer, seq, seqSz);
  2506. return idx + seqSz;
  2507. }
  2508. /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
  2509. static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
  2510. RsaKey* rsaKey, RNG* rng, const byte* ntruKey, word16 ntruSz)
  2511. {
  2512. DerCert der;
  2513. int ret;
  2514. cert->keyType = rsaKey ? RSA_KEY : NTRU_KEY;
  2515. ret = EncodeCert(cert, &der, rsaKey, rng, ntruKey, ntruSz);
  2516. if (ret != 0)
  2517. return ret;
  2518. if (der.total + MAX_SEQ_SZ * 2 > (int)derSz)
  2519. return BUFFER_E;
  2520. return cert->bodySz = WriteCertBody(&der, derBuffer);
  2521. }
  2522. /* Make an x509 Certificate v3 RSA from cert input, write to buffer */
  2523. int MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,RNG* rng)
  2524. {
  2525. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, rng, NULL, 0);
  2526. }
  2527. #ifdef HAVE_NTRU
  2528. int MakeNtruCert(Cert* cert, byte* derBuffer, word32 derSz,
  2529. const byte* ntruKey, word16 keySz, RNG* rng)
  2530. {
  2531. return MakeAnyCert(cert, derBuffer, derSz, NULL, rng, ntruKey, keySz);
  2532. }
  2533. #endif /* HAVE_NTRU */
  2534. int SignCert(Cert* cert, byte* buffer, word32 buffSz, RsaKey* key, RNG* rng)
  2535. {
  2536. byte sig[MAX_ENCODED_SIG_SZ];
  2537. int sigSz;
  2538. int bodySz = cert->bodySz;
  2539. if (bodySz < 0)
  2540. return bodySz;
  2541. sigSz = MakeSignature(buffer, bodySz, sig, sizeof(sig), key, rng,
  2542. cert->sigType);
  2543. if (sigSz < 0)
  2544. return sigSz;
  2545. if (bodySz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
  2546. return BUFFER_E;
  2547. return AddSignature(buffer, bodySz, sig, sigSz, cert->sigType);
  2548. }
  2549. int MakeSelfCert(Cert* cert, byte* buffer, word32 buffSz, RsaKey* key, RNG* rng)
  2550. {
  2551. int ret = MakeCert(cert, buffer, buffSz, key, rng);
  2552. if (ret < 0)
  2553. return ret;
  2554. return SignCert(cert, buffer, buffSz, key, rng);
  2555. }
  2556. /* Set Alt Names from der cert, return 0 on success */
  2557. static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz)
  2558. {
  2559. DecodedCert decoded;
  2560. int ret;
  2561. if (derSz < 0)
  2562. return derSz;
  2563. InitDecodedCert(&decoded, (byte*)der, derSz, 0);
  2564. ret = ParseCertRelative(&decoded, CA_TYPE, NO_VERIFY, 0);
  2565. if (ret < 0)
  2566. return ret;
  2567. if (decoded.extensions) {
  2568. byte b;
  2569. int length;
  2570. word32 maxExtensionsIdx;
  2571. decoded.srcIdx = decoded.extensionsIdx;
  2572. b = decoded.source[decoded.srcIdx++];
  2573. if (b != ASN_EXTENSIONS) {
  2574. FreeDecodedCert(&decoded);
  2575. return ASN_PARSE_E;
  2576. }
  2577. if (GetLength(decoded.source, &decoded.srcIdx, &length,
  2578. decoded.maxIdx) < 0) {
  2579. FreeDecodedCert(&decoded);
  2580. return ASN_PARSE_E;
  2581. }
  2582. if (GetSequence(decoded.source, &decoded.srcIdx, &length,
  2583. decoded.maxIdx) < 0) {
  2584. FreeDecodedCert(&decoded);
  2585. return ASN_PARSE_E;
  2586. }
  2587. maxExtensionsIdx = decoded.srcIdx + length;
  2588. while (decoded.srcIdx < maxExtensionsIdx) {
  2589. word32 oid;
  2590. word32 startIdx = decoded.srcIdx;
  2591. word32 tmpIdx;
  2592. if (GetSequence(decoded.source, &decoded.srcIdx, &length,
  2593. decoded.maxIdx) < 0) {
  2594. FreeDecodedCert(&decoded);
  2595. return ASN_PARSE_E;
  2596. }
  2597. tmpIdx = decoded.srcIdx;
  2598. decoded.srcIdx = startIdx;
  2599. if (GetAlgoId(decoded.source, &decoded.srcIdx, &oid,
  2600. decoded.maxIdx) < 0) {
  2601. FreeDecodedCert(&decoded);
  2602. return ASN_PARSE_E;
  2603. }
  2604. if (oid == ALT_NAMES_OID) {
  2605. cert->altNamesSz = length + (tmpIdx - startIdx);
  2606. if (cert->altNamesSz < (int)sizeof(cert->altNames))
  2607. XMEMCPY(cert->altNames, &decoded.source[startIdx],
  2608. cert->altNamesSz);
  2609. else {
  2610. cert->altNamesSz = 0;
  2611. CYASSL_MSG("AltNames extensions too big");
  2612. }
  2613. }
  2614. decoded.srcIdx = tmpIdx + length;
  2615. }
  2616. }
  2617. FreeDecodedCert(&decoded);
  2618. return 0;
  2619. }
  2620. /* Set cn name from der buffer, return 0 on success */
  2621. static int SetNameFromCert(CertName* cn, const byte* der, int derSz)
  2622. {
  2623. DecodedCert decoded;
  2624. int ret;
  2625. int sz;
  2626. if (derSz < 0)
  2627. return derSz;
  2628. InitDecodedCert(&decoded, (byte*)der, derSz, 0);
  2629. ret = ParseCertRelative(&decoded, CA_TYPE, NO_VERIFY, 0);
  2630. if (ret < 0)
  2631. return ret;
  2632. if (decoded.subjectCN) {
  2633. sz = (decoded.subjectCNLen < CTC_NAME_SIZE) ? decoded.subjectCNLen :
  2634. CTC_NAME_SIZE - 1;
  2635. strncpy(cn->commonName, decoded.subjectCN, CTC_NAME_SIZE);
  2636. cn->commonName[sz] = 0;
  2637. }
  2638. if (decoded.subjectC) {
  2639. sz = (decoded.subjectCLen < CTC_NAME_SIZE) ? decoded.subjectCLen :
  2640. CTC_NAME_SIZE - 1;
  2641. strncpy(cn->country, decoded.subjectC, CTC_NAME_SIZE);
  2642. cn->country[sz] = 0;
  2643. }
  2644. if (decoded.subjectST) {
  2645. sz = (decoded.subjectSTLen < CTC_NAME_SIZE) ? decoded.subjectSTLen :
  2646. CTC_NAME_SIZE - 1;
  2647. strncpy(cn->state, decoded.subjectST, CTC_NAME_SIZE);
  2648. cn->state[sz] = 0;
  2649. }
  2650. if (decoded.subjectL) {
  2651. sz = (decoded.subjectLLen < CTC_NAME_SIZE) ? decoded.subjectLLen :
  2652. CTC_NAME_SIZE - 1;
  2653. strncpy(cn->locality, decoded.subjectL, CTC_NAME_SIZE);
  2654. cn->locality[sz] = 0;
  2655. }
  2656. if (decoded.subjectO) {
  2657. sz = (decoded.subjectOLen < CTC_NAME_SIZE) ? decoded.subjectOLen :
  2658. CTC_NAME_SIZE - 1;
  2659. strncpy(cn->org, decoded.subjectO, CTC_NAME_SIZE);
  2660. cn->org[sz] = 0;
  2661. }
  2662. if (decoded.subjectOU) {
  2663. sz = (decoded.subjectOULen < CTC_NAME_SIZE) ? decoded.subjectOULen :
  2664. CTC_NAME_SIZE - 1;
  2665. strncpy(cn->unit, decoded.subjectOU, CTC_NAME_SIZE);
  2666. cn->unit[sz] = 0;
  2667. }
  2668. if (decoded.subjectSN) {
  2669. sz = (decoded.subjectSNLen < CTC_NAME_SIZE) ? decoded.subjectSNLen :
  2670. CTC_NAME_SIZE - 1;
  2671. strncpy(cn->sur, decoded.subjectSN, CTC_NAME_SIZE);
  2672. cn->sur[sz] = 0;
  2673. }
  2674. if (decoded.subjectEmail) {
  2675. sz = (decoded.subjectEmailLen < CTC_NAME_SIZE) ?
  2676. decoded.subjectEmailLen : CTC_NAME_SIZE - 1;
  2677. strncpy(cn->email, decoded.subjectEmail, CTC_NAME_SIZE);
  2678. cn->email[sz] = 0;
  2679. }
  2680. FreeDecodedCert(&decoded);
  2681. return 0;
  2682. }
  2683. #ifndef NO_FILESYSTEM
  2684. /* forward from CyaSSL */
  2685. int CyaSSL_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz);
  2686. /* Set cert issuer from issuerFile in PEM */
  2687. int SetIssuer(Cert* cert, const char* issuerFile)
  2688. {
  2689. byte der[8192];
  2690. int derSz = CyaSSL_PemCertToDer(issuerFile, der, sizeof(der));
  2691. cert->selfSigned = 0;
  2692. return SetNameFromCert(&cert->issuer, der, derSz);
  2693. }
  2694. /* Set cert subject from subjectFile in PEM */
  2695. int SetSubject(Cert* cert, const char* subjectFile)
  2696. {
  2697. byte der[8192];
  2698. int derSz = CyaSSL_PemCertToDer(subjectFile, der, sizeof(der));
  2699. return SetNameFromCert(&cert->subject, der, derSz);
  2700. }
  2701. /* Set atl names from file in PEM */
  2702. int SetAltNames(Cert* cert, const char* file)
  2703. {
  2704. byte der[8192];
  2705. int derSz = CyaSSL_PemCertToDer(file, der, sizeof(der));
  2706. return SetAltNamesFromCert(cert, der, derSz);
  2707. }
  2708. #endif /* NO_FILESYSTEM */
  2709. /* Set cert issuer from DER buffer */
  2710. int SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
  2711. {
  2712. cert->selfSigned = 0;
  2713. return SetNameFromCert(&cert->issuer, der, derSz);
  2714. }
  2715. /* Set cert subject from DER buffer */
  2716. int SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
  2717. {
  2718. return SetNameFromCert(&cert->subject, der, derSz);
  2719. }
  2720. /* Set cert alt names from DER buffer */
  2721. int SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
  2722. {
  2723. return SetAltNamesFromCert(cert, der, derSz);
  2724. }
  2725. #endif /* CYASSL_CERT_GEN */
  2726. #ifdef HAVE_ECC
  2727. /* Der Encode r & s ints into out, outLen is (in/out) size */
  2728. int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
  2729. {
  2730. word32 idx = 0;
  2731. word32 rSz; /* encoding size */
  2732. word32 sSz;
  2733. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  2734. int rLen = mp_unsigned_bin_size(r); /* big int size */
  2735. int sLen = mp_unsigned_bin_size(s);
  2736. int err;
  2737. if (*outLen < (rLen + sLen + headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
  2738. return BAD_FUNC_ARG;
  2739. idx = SetSequence(rLen + sLen + headerSz, out);
  2740. /* store r */
  2741. out[idx++] = ASN_INTEGER;
  2742. rSz = SetLength(rLen, &out[idx]);
  2743. idx += rSz;
  2744. err = mp_to_unsigned_bin(r, &out[idx]);
  2745. if (err != MP_OKAY) return err;
  2746. idx += rLen;
  2747. /* store s */
  2748. out[idx++] = ASN_INTEGER;
  2749. sSz = SetLength(sLen, &out[idx]);
  2750. idx += sSz;
  2751. err = mp_to_unsigned_bin(s, &out[idx]);
  2752. if (err != MP_OKAY) return err;
  2753. idx += sLen;
  2754. *outLen = idx;
  2755. return 0;
  2756. }
  2757. /* Der Decode ECC-DSA Signautre, r & s stored as big ints */
  2758. int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
  2759. {
  2760. word32 idx = 0;
  2761. int len = 0;
  2762. if (GetSequence(sig, &idx, &len, sigLen) < 0)
  2763. return ASN_ECC_KEY_E;
  2764. if ((word32)len > (sigLen - idx))
  2765. return ASN_ECC_KEY_E;
  2766. if (GetInt(r, sig, &idx, sigLen) < 0)
  2767. return ASN_ECC_KEY_E;
  2768. if (GetInt(s, sig, &idx, sigLen) < 0)
  2769. return ASN_ECC_KEY_E;
  2770. return 0;
  2771. }
  2772. int EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
  2773. word32 inSz)
  2774. {
  2775. word32 oid = 0;
  2776. int version, length;
  2777. int privSz, pubSz;
  2778. byte b;
  2779. byte priv[ECC_MAXSIZE];
  2780. byte pub[ECC_MAXSIZE * 2 + 1]; /* public key has two parts plus header */
  2781. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  2782. return ASN_PARSE_E;
  2783. if (GetMyVersion(input, inOutIdx, &version) < 0)
  2784. return ASN_PARSE_E;
  2785. b = input[*inOutIdx];
  2786. *inOutIdx += 1;
  2787. /* priv type */
  2788. if (b != 4 && b != 6 && b != 7)
  2789. return ASN_PARSE_E;
  2790. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  2791. return ASN_PARSE_E;
  2792. /* priv key */
  2793. privSz = length;
  2794. XMEMCPY(priv, &input[*inOutIdx], privSz);
  2795. *inOutIdx += length;
  2796. /* prefix 0 */
  2797. b = input[*inOutIdx];
  2798. *inOutIdx += 1;
  2799. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  2800. return ASN_PARSE_E;
  2801. /* object id */
  2802. b = input[*inOutIdx];
  2803. *inOutIdx += 1;
  2804. if (b != ASN_OBJECT_ID)
  2805. return ASN_OBJECT_ID_E;
  2806. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  2807. return ASN_PARSE_E;
  2808. while(length--) {
  2809. oid += input[*inOutIdx];
  2810. *inOutIdx += 1;
  2811. }
  2812. if (CheckCurve(oid) < 0)
  2813. return ECC_CURVE_OID_E;
  2814. /* prefix 1 */
  2815. b = input[*inOutIdx];
  2816. *inOutIdx += 1;
  2817. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  2818. return ASN_PARSE_E;
  2819. /* key header */
  2820. b = input[*inOutIdx];
  2821. *inOutIdx += 1;
  2822. if (b != ASN_BIT_STRING)
  2823. return ASN_BITSTR_E;
  2824. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  2825. return ASN_PARSE_E;
  2826. b = input[*inOutIdx];
  2827. *inOutIdx += 1;
  2828. if (b != 0x00)
  2829. return ASN_EXPECT_0_E;
  2830. pubSz = length - 1; /* null prefix */
  2831. XMEMCPY(pub, &input[*inOutIdx], pubSz);
  2832. *inOutIdx += length;
  2833. return ecc_import_private_key(priv, privSz, pub, pubSz, key);
  2834. }
  2835. #endif /* HAVE_ECC */