12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101 |
- /* asn.c
- *
- * Copyright (C) 2006-2023 wolfSSL Inc.
- *
- * This file is part of wolfSSL.
- *
- * wolfSSL is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * wolfSSL is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
- */
- /*
- * DESCRIPTION
- * This library provides the interface to Abstract Syntax Notation One (ASN.1)
- * objects.
- * ASN.1 is a standard interface description language for defining data
- * structures that can be serialized and deserialized in a cross-platform way.
- *
- * Encoding of ASN.1 is either using Basic Encoding Rules (BER) or
- * Distinguished Encoding Rules (DER). DER has only one possible encoding for a
- * ASN.1 description and the data.
- * Encode using DER and decode BER or DER.
- *
- * Provides routines to convert BER into DER. Replaces indefinite length
- * encoded items with explicit lengths.
- */
- #ifdef HAVE_CONFIG_H
- #include <config.h>
- #endif
- #include <wolfssl/wolfcrypt/settings.h>
- /*
- ASN Options:
- * NO_ASN_TIME_CHECK: Disables ASN time checks (avoiding the ASN_BEFORE_DATE_E
- * and ASN_AFTER_DATE_E errors). Safer ways to avoid date errors would be to
- * set the WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY flag when calling the _ex versions of
- * cert loading functions or to define the WOLFSSL_NO_OCSP_DATE_CHECK macro to
- * skip OCSP date errors. Defining NO_ASN_TIME_CHECK will skip ALL date checks
- * and could pose a security risk.
- * NO_ASN_TIME: Disables time parts of the ASN code for systems without an RTC
- or wishing to save space.
- * IGNORE_NAME_CONSTRAINTS: Skip ASN name checks.
- * ASN_DUMP_OID: Allows dump of OID information for debugging.
- * RSA_DECODE_EXTRA: Decodes extra information in RSA public key.
- * WOLFSSL_CERT_GEN: Cert generation. Saves extra certificate info in GetName.
- * WOLFSSL_NO_ASN_STRICT: Disable strict RFC compliance checks to
- restore 3.13.0 behavior.
- * WOLFSSL_NO_OCSP_OPTIONAL_CERTS: Skip optional OCSP certs (responder issuer
- must still be trusted)
- * WOLFSSL_NO_TRUSTED_CERTS_VERIFY: Workaround for situation where entire cert
- chain is not loaded. This only matches on subject and public key and
- does not perform a PKI validation, so it is not a secure solution.
- Only enabled for OCSP.
- * WOLFSSL_NO_OCSP_ISSUER_CHECK: Can be defined for backwards compatibility to
- disable checking of OCSP subject hash with issuer hash.
- * WOLFSSL_SMALL_CERT_VERIFY: Verify the certificate signature without using
- DecodedCert. Doubles up on some code but allows smaller dynamic memory
- usage.
- * WOLFSSL_NO_OCSP_DATE_CHECK: Disable date checks for OCSP responses. This
- may be required when the system's real-time clock is not very accurate.
- It is recommended to enforce the nonce check instead if possible.
- * WOLFSSL_FORCE_OCSP_NONCE_CHECK: Require nonces to be available in OCSP
- responses. The nonces are optional and may not be supported by all
- responders. If it can be ensured that the used responder sends nonces this
- option may improve security.
- * WOLFSSL_ASN_TEMPLATE: Encoding and decoding using a template.
- * WOLFSSL_DEBUG_ASN_TEMPLATE: Enables debugging output when using ASN.1
- templates.
- * WOLFSSL_ASN_TEMPLATE_TYPE_CHECK: Use ASN functions to better test compiler
- type issues for testing
- * CRLDP_VALIDATE_DATA: For ASN template only, validates the reason data
- * WOLFSSL_AKID_NAME: Enable support for full AuthorityKeyIdentifier extension.
- Only supports copying full AKID from an existing certificate.
- * WOLFSSL_CUSTOM_OID: Enable custom OID support for subject and request
- extensions
- * WOLFSSL_HAVE_ISSUER_NAMES: Store pointers to issuer name components and their
- lengths and encodings.
- * WOLFSSL_SUBJ_DIR_ATTR: Enable support for SubjectDirectoryAttributes
- extension.
- * WOLFSSL_SUBJ_INFO_ACC: Enable support for SubjectInfoAccess extension.
- * WOLFSSL_FPKI: Enable support for FPKI (Federal PKI) extensions.
- * WOLFSSL_CERT_NAME_ALL: Adds more certificate name capability at the
- cost of taking up more memory. Adds initials, givenname, dnQualifer for
- example.
- * WC_ASN_HASH_SHA256: Force use of SHA2-256 for the internal hash ID calcs.
- */
- #include <wolfssl/wolfcrypt/error-crypt.h>
- #ifndef NO_RSA
- #include <wolfssl/wolfcrypt/rsa.h>
- #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
- extern int wc_InitRsaHw(RsaKey* key);
- #endif
- #endif
- #ifndef NO_ASN
- #include <wolfssl/wolfcrypt/asn.h>
- #include <wolfssl/wolfcrypt/coding.h>
- #include <wolfssl/wolfcrypt/md2.h>
- #include <wolfssl/wolfcrypt/hmac.h>
- #include <wolfssl/wolfcrypt/pwdbased.h>
- #include <wolfssl/wolfcrypt/des3.h>
- #include <wolfssl/wolfcrypt/aes.h>
- #include <wolfssl/wolfcrypt/rc2.h>
- #include <wolfssl/wolfcrypt/wc_encrypt.h>
- #include <wolfssl/wolfcrypt/logging.h>
- #include <wolfssl/wolfcrypt/random.h>
- #include <wolfssl/wolfcrypt/hash.h>
- #ifdef NO_INLINE
- #include <wolfssl/wolfcrypt/misc.h>
- #else
- #define WOLFSSL_MISC_INCLUDED
- #include <wolfcrypt/src/misc.c>
- #endif
- #ifndef NO_RC4
- #include <wolfssl/wolfcrypt/arc4.h>
- #endif
- #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
- #include <wolfssl/wolfcrypt/sha512.h>
- #endif
- #ifndef NO_SHA256
- #include <wolfssl/wolfcrypt/sha256.h>
- #endif
- #ifdef HAVE_ECC
- #include <wolfssl/wolfcrypt/ecc.h>
- #endif
- #ifdef WOLFSSL_SM2
- #include <wolfssl/wolfcrypt/sm2.h>
- #endif
- #ifdef HAVE_ED25519
- #include <wolfssl/wolfcrypt/ed25519.h>
- #endif
- #ifdef HAVE_CURVE25519
- #include <wolfssl/wolfcrypt/curve25519.h>
- #endif
- #ifdef HAVE_ED448
- #include <wolfssl/wolfcrypt/ed448.h>
- #endif
- #ifdef HAVE_CURVE448
- #include <wolfssl/wolfcrypt/curve448.h>
- #endif
- #ifdef HAVE_PQC
- #if defined(HAVE_FALCON)
- #include <wolfssl/wolfcrypt/falcon.h>
- #endif
- #if defined(HAVE_DILITHIUM)
- #include <wolfssl/wolfcrypt/dilithium.h>
- #endif
- #if defined(HAVE_SPHINCS)
- #include <wolfssl/wolfcrypt/sphincs.h>
- #endif
- #endif
- #ifdef WOLFSSL_QNX_CAAM
- #include <wolfssl/wolfcrypt/port/caam/wolfcaam.h>
- #endif
- #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
- #include <wolfssl/wolfcrypt/port/Renesas/renesas_cmn.h>
- #endif
- #ifndef NO_DSA
- #include <wolfssl/wolfcrypt/dsa.h>
- #else
- typedef void* DsaKey;
- #endif
- #ifdef WOLF_CRYPTO_CB
- #include <wolfssl/wolfcrypt/cryptocb.h>
- #endif
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- #include <wolfssl/internal.h>
- #include <wolfssl/openssl/objects.h>
- #endif
- #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
- !defined(WOLFCRYPT_ONLY)
- #define WOLFSSL_X509_NAME_AVAILABLE
- #endif
- #ifdef _MSC_VER
- /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
- #pragma warning(disable: 4996)
- #endif
- #define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
- #if !defined(NO_SKID) && (!defined(HAVE_FIPS) || !defined(HAVE_FIPS_VERSION))
- #if !defined(HAVE_SELFTEST) || (defined(HAVE_SELFTEST) && \
- (!defined(HAVE_SELFTEST_VERSION) || \
- HAVE_SELFTEST_VERSION < 2))
- #ifndef WOLFSSL_AES_KEY_SIZE_ENUM
- #define WOLFSSL_AES_KEY_SIZE_ENUM
- enum Asn_Misc {
- AES_IV_SIZE = 16,
- AES_128_KEY_SIZE = 16,
- AES_192_KEY_SIZE = 24,
- AES_256_KEY_SIZE = 32
- };
- #endif
- #endif /* HAVE_SELFTEST */
- #endif
- #if defined(WOLFSSL_ASN_PRINT) || defined(WOLFSSL_DEBUG_ASN_TEMPLATE)
- /* String representations of tags. */
- static const char* tagString[4][32] = {
- /* Universal */
- {
- "EOC",
- "BOOLEAN",
- "INTEGER",
- "BIT STRING",
- "OCTET STRING",
- "NULL",
- "OBJECT ID",
- "ObjectDescriptor",
- "INSTANCE OF",
- "REAL",
- "ENUMERATED",
- "EMBEDDED PDV",
- "UT8String",
- "RELATIVE-OID",
- "(0x0e) 14",
- "(0x0f) 15",
- "SEQUENCE",
- "SET",
- "NumericString",
- "PrintableString",
- "T61String",
- "VideotexString",
- "IA5String",
- "UTCTime",
- "GeneralizedTime",
- "GraphicString",
- "ISO646String",
- "GeneralString",
- "UniversalString",
- "CHARACTER STRING",
- "BMPString",
- "(0x1f) 31",
- },
- /* Application */
- {
- "[A 0]", "[A 1]", "[A 2]", "[A 3]",
- "[A 4]", "[A 5]", "[A 6]", "[A 7]",
- "[A 8]", "[A 9]", "[A 10]", "[A 11]",
- "[A 12]", "[A 13]", "[A 14]", "[A 15]",
- "[A 16]", "[A 17]", "[A 18]", "[A 19]",
- "[A 20]", "[A 21]", "[A 22]", "[A 23]",
- "[A 24]", "[A 25]", "[A 26]", "[A 27]",
- "[A 28]", "[A 20]", "[A 30]", "[A 31]"
- },
- /* Context-Specific */
- {
- "[0]", "[1]", "[2]", "[3]", "[4]", "[5]", "[6]", "[7]",
- "[8]", "[9]", "[10]", "[11]", "[12]", "[13]", "[14]", "[15]",
- "[16]", "[17]", "[18]", "[19]", "[20]", "[21]", "[22]", "[23]",
- "[24]", "[25]", "[26]", "[27]", "[28]", "[20]", "[30]", "[31]"
- },
- /* Private */
- {
- "[P 0]", "[P 1]", "[P 2]", "[P 3]",
- "[P 4]", "[P 5]", "[P 6]", "[P 7]",
- "[P 8]", "[P 9]", "[P 10]", "[P 11]",
- "[P 12]", "[P 13]", "[P 14]", "[P 15]",
- "[P 16]", "[P 17]", "[P 18]", "[P 19]",
- "[P 20]", "[P 21]", "[P 22]", "[P 23]",
- "[P 24]", "[P 25]", "[P 26]", "[P 27]",
- "[P 28]", "[P 20]", "[P 30]", "[P 31]"
- }
- };
- /* Converts a tag byte to string.
- *
- * @param [in] tag BER tag value to interpret.
- * @return String corresponding to tag.
- */
- static const char* TagString(byte tag)
- {
- return tagString[tag >> 6][tag & ASN_TYPE_MASK];
- }
- #endif
- /* Calculates the minimum number of bytes required to encode the value.
- *
- * Only support up to 2^24-1.
- *
- * @param [in] value Value to be encoded.
- * @return Number of bytes to encode value.
- */
- static word32 BytePrecision(word32 value)
- {
- word32 i;
- for (i = (word32)sizeof(value) - 1; i; --i)
- if (value >> ((i - 1) * WOLFSSL_BIT_SIZE))
- break;
- return i;
- }
- /* DER encodes the length value in output buffer.
- *
- * 0 -> 2^7-1: <len byte>.
- * 2^7 -> : <0x80 + #bytes> <len big-endian bytes>
- *
- * @param [in] length Value to encode.
- * @param [in, out] output Buffer to encode into.
- * @return Number of bytes used in encoding.
- */
- WOLFSSL_LOCAL word32 SetASNLength(word32 length, byte* output)
- {
- word32 i = 0;
- if (length < ASN_LONG_LENGTH)
- output[i++] = (byte)length;
- else {
- word32 j;
- output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);
- for (j = BytePrecision(length); j; --j) {
- output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
- i++;
- }
- }
- return i;
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* Calculate the size of a DER encoded length value.
- *
- * 0 -> 2^7-1: <length byte>.
- * 2^7 -> : <0x80 + #bytes> <big-endian length bytes>
- *
- * @param [in] length Value to encode.
- * @return Number of bytes required to encode.
- */
- static word32 SizeASNLength(word32 length)
- {
- return 1 + ((length >= ASN_LONG_LENGTH) ? BytePrecision(length) : 0);
- }
- /* Calculate the size of a DER encoded header.
- *
- * Header = Tag | Encoded length
- *
- * @param [in] length Length value to encode.
- * @return Number of bytes required to encode a DER header.
- */
- #define SizeASNHeader(length) \
- (1 + SizeASNLength(length))
- #endif
- #ifdef WOLFSSL_ASN_TEMPLATE
- #ifdef WOLFSSL_SMALL_STACK
- /* Declare the variable that is the dynamic data for decoding BER data.
- *
- * @param [in] name Variable name to declare.
- * @param [in] cnt Number of elements required.
- */
- #define DECL_ASNGETDATA(name, cnt) \
- ASNGetData* name = NULL
- /* Allocates the dynamic BER decoding data.
- *
- * @param [in] name Variable name to declare.
- * @param [in] cnt Number of elements required.
- * @param [in, out] err Error variable.
- * @param [in] heap Dynamic memory allocation hint.
- */
- #define ALLOC_ASNGETDATA(name, cnt, err, heap) \
- do { \
- if ((err) == 0) { \
- (name) = (ASNGetData*)XMALLOC(sizeof(ASNGetData) * (cnt), (heap), \
- DYNAMIC_TYPE_TMP_BUFFER); \
- if ((name) == NULL) { \
- (err) = MEMORY_E; \
- } \
- } \
- } \
- while (0)
- /* Allocates the dynamic BER decoding data and clears the memory.
- *
- * @param [in] name Variable name to declare.
- * @param [in] cnt Number of elements required.
- * @param [in, out] err Error variable.
- * @param [in] heap Dynamic memory allocation hint.
- */
- #define CALLOC_ASNGETDATA(name, cnt, err, heap) \
- do { \
- ALLOC_ASNGETDATA(name, cnt, err, heap); \
- if ((err) == 0) { \
- XMEMSET((name), 0, sizeof(ASNGetData) * (cnt)); \
- } \
- } \
- while (0)
- /* Disposes of the dynamic BER decoding data.
- *
- * @param [in] name Variable name to declare.
- * @param [in] heap Dynamic memory allocation hint.
- */
- #define FREE_ASNGETDATA(name, heap) \
- do { \
- if ((name) != NULL) { \
- XFREE((name), (heap), DYNAMIC_TYPE_TMP_BUFFER); \
- } \
- } \
- while (0)
- /* Declare the variable that is the dynamic data for encoding DER data.
- *
- * @param [in] name Variable name to declare.
- * @param [in] cnt Number of elements required.
- */
- #define DECL_ASNSETDATA(name, cnt) \
- ASNSetData* name = NULL
- /* Allocates the dynamic DER encoding data.
- *
- * @param [in] name Variable name to declare.
- * @param [in] cnt Number of elements required.
- * @param [in, out] err Error variable.
- * @param [in] heap Dynamic memory allocation hint.
- */
- #define ALLOC_ASNSETDATA(name, cnt, err, heap) \
- do { \
- if ((err) == 0) { \
- (name) = (ASNSetData*)XMALLOC(sizeof(ASNGetData) * (cnt), (heap), \
- DYNAMIC_TYPE_TMP_BUFFER); \
- if ((name) == NULL) { \
- (err) = MEMORY_E; \
- } \
- } \
- } \
- while (0)
- /* Allocates the dynamic DER encoding data and clears the memory.
- *
- * @param [in] name Variable name to declare.
- * @param [in] cnt Number of elements required.
- * @param [in, out] err Error variable.
- * @param [in] heap Dynamic memory allocation hint.
- */
- #define CALLOC_ASNSETDATA(name, cnt, err, heap) \
- do { \
- ALLOC_ASNSETDATA(name, cnt, err, heap); \
- if ((err) == 0) { \
- XMEMSET(name, 0, sizeof(ASNSetData) * (cnt)); \
- } \
- } \
- while (0)
- /* Disposes of the dynamic DER encoding data.
- *
- * @param [in] name Variable name to declare.
- * @param [in] heap Dynamic memory allocation hint.
- */
- #define FREE_ASNSETDATA(name, heap) \
- do { \
- if ((name) != NULL) { \
- XFREE(name, heap, DYNAMIC_TYPE_TMP_BUFFER); \
- } \
- } \
- while (0)
- #else
- /* Declare the variable that is the dynamic data for decoding BER data.
- *
- * @param [in] name Variable name to declare.
- * @param [in] cnt Number of elements required.
- */
- #define DECL_ASNGETDATA(name, cnt) \
- ASNGetData name[cnt]
- /* No implementation as declaration is static.
- *
- * @param [in] name Variable name to declare.
- * @param [in] cnt Number of elements required.
- * @param [in, out] err Error variable.
- * @param [in] heap Dynamic memory allocation hint.
- */
- #define ALLOC_ASNGETDATA(name, cnt, err, heap)
- /* Clears the memory of the dynamic BER encoding data.
- *
- * @param [in] name Variable name to declare.
- * @param [in] cnt Number of elements required.
- * @param [in, out] err Error variable.
- * @param [in] heap Dynamic memory allocation hint.
- */
- #define CALLOC_ASNGETDATA(name, cnt, err, heap) \
- XMEMSET(name, 0, sizeof(name))
- /* No implementation as declaration is static.
- *
- * @param [in] name Variable name to declare.
- * @param [in] heap Dynamic memory allocation hint.
- */
- #define FREE_ASNGETDATA(name, heap)
- /* Declare the variable that is the dynamic data for encoding DER data.
- *
- * @param [in] name Variable name to declare.
- * @param [in] cnt Number of elements required.
- */
- #define DECL_ASNSETDATA(name, cnt) \
- ASNSetData name[cnt]
- /* No implementation as declaration is static.
- *
- * @param [in] name Variable name to declare.
- * @param [in] cnt Number of elements required.
- * @param [in, out] err Error variable.
- * @param [in] heap Dynamic memory allocation hint.
- */
- #define ALLOC_ASNSETDATA(name, cnt, err, heap)
- /* Clears the memory of the dynamic BER encoding data.
- *
- * @param [in] name Variable name to declare.
- * @param [in] cnt Number of elements required.
- * @param [in, out] err Error variable.
- * @param [in] heap Dynamic memory allocation hint.
- */
- #define CALLOC_ASNSETDATA(name, cnt, err, heap) \
- XMEMSET(name, 0, sizeof(name))
- /* No implementation as declaration is static.
- *
- * @param [in] name Variable name to declare.
- * @param [in] heap Dynamic memory allocation hint.
- */
- #define FREE_ASNSETDATA(name, heap)
- #endif
- #ifdef DEBUG_WOLFSSL
- /* Enable this when debugging the parsing or creation of ASN.1 data. */
- #if 0
- #define WOLFSSL_DEBUG_ASN_TEMPLATE
- #endif
- #endif
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- #include <stdarg.h>
- /* Log a message that has the printf format string.
- *
- * @param [in] <va_args> printf style arguments.
- */
- #define WOLFSSL_MSG_VSNPRINTF(...) \
- do { \
- char line[81]; \
- snprintf(line, sizeof(line) - 1, __VA_ARGS__); \
- line[sizeof(line) - 1] = '\0'; \
- WOLFSSL_MSG(line); \
- } \
- while (0)
- #endif
- /* Returns whether ASN.1 item is an integer and the Most-Significant Bit is set.
- *
- * @param [in] asn ASN.1 items to encode.
- * @param [in] data_a Data to place in each item. Lengths set were not known.
- * @param [in] i Index of item to check.
- * @return 1 when ASN.1 item is an integer and MSB is 1.
- * @erturn 0 otherwise.
- */
- #define ASNIntMSBSet(asn, data_a, i) \
- (((asn)[i].tag == ASN_INTEGER) && \
- ((data_a)[i].data.buffer.data != NULL && \
- ((data_a)[i].data.buffer.data[0] & 0x80) == 0x80))
- /* Calculate the size of a DER encoded number.
- *
- * @param [in] n Number to be encoded.
- * @param [in] bits Maximum number of bits to encode.
- * @param [in] tag BER tag e.g. INTEGER, BIT_STRING, etc.
- * @return Number of bytes to the ASN.1 item.
- */
- static word32 SizeASN_Num(word32 n, int bits, byte tag)
- {
- int j;
- word32 len;
- len = 1 + 1 + (word32)bits / 8;
- /* Discover actual size by checking for high zeros. */
- for (j = bits - 8; j > 0; j -= 8) {
- if (n >> j)
- break;
- len--;
- }
- if (tag == ASN_BIT_STRING)
- len++;
- else if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80))
- len++;
- return len;
- }
- /* Calculate the size of the data in the constructed item based on the
- * length of the ASN.1 items below.
- *
- * @param [in] asn ASN.1 items to encode.
- * @param [in, out] data Data to place in each item. Lengths set were not
- * known.
- * @param [in] idx Index of item working on.
- */
- static void SizeASN_CalcDataLength(const ASNItem* asn, ASNSetData *data,
- int idx, int max)
- {
- int j;
- data[idx].data.buffer.length = 0;
- /* Sum the item length of all items underneath. */
- for (j = idx + 1; j < max; j++) {
- /* Stop looking if the next ASN.1 is same level or higher. */
- if (asn[j].depth <= asn[idx].depth)
- break;
- /* Only add in length if it is one level below. */
- if (asn[j].depth - 1 == asn[idx].depth) {
- data[idx].data.buffer.length += data[j].length;
- /* The length of a header only item doesn't include the data unless
- * a replacement buffer is supplied.
- */
- if (asn[j].headerOnly && data[j].data.buffer.data == NULL &&
- data[j].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
- data[idx].data.buffer.length += data[j].data.buffer.length;
- }
- }
- }
- }
- /* Calculate the size of the DER encoding.
- *
- * Call SetASN_Items() to write encoding to a buffer.
- *
- * @param [in] asn ASN.1 items to encode.
- * @param [in, out] data Data to place in each item. Lengths set where not
- * known.
- * @param [in] count Count of items to encode.
- * @param [out] encSz Length of the DER encoding.
- * @return 0 on success.
- * @return BAD_STATE_E when the data type is not supported.
- */
- int SizeASN_Items(const ASNItem* asn, ASNSetData *data, int count, int* encSz)
- {
- int i;
- word32 sz = 0;
- word32 len;
- word32 dataLen;
- int length;
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_ENTER("SizeASN_Items");
- #endif
- for (i = count - 1; i >= 0; i--) {
- /* Skip this ASN.1 item when encoding. */
- if (data[i].noOut) {
- /* Set the offset to the current size - used in writing DER. */
- data[i].offset = sz;
- continue;
- }
- len = 0;
- switch (data[i].dataType) {
- /* Calculate the size of the number of different sizes. */
- case ASN_DATA_TYPE_WORD8:
- len = SizeASN_Num(data[i].data.u8, 8, asn[i].tag);
- break;
- case ASN_DATA_TYPE_WORD16:
- len = SizeASN_Num(data[i].data.u16, 16, asn[i].tag);
- break;
- #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
- /* Not used yet! */
- case ASN_DATA_TYPE_WORD32:
- len = SizeASN_Num(data[i].data.u32, 32, asn[i].tag);
- break;
- #endif
- case ASN_DATA_TYPE_MP:
- /* Calculate the size of the MP integer data. */
- length = mp_unsigned_bin_size(data[i].data.mp);
- length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
- len = (word32)SizeASNHeader((word32)length) + (word32)length;
- break;
- case ASN_DATA_TYPE_REPLACE_BUFFER:
- /* Buffer is put in directly - use the length. */
- len = data[i].data.buffer.length;
- break;
- case ASN_DATA_TYPE_NONE:
- /* Calculate the size based on the data to be included.
- * Mostly used for constructed items.
- */
- if (asn[i].headerOnly) {
- if (data[i].data.buffer.data != NULL) {
- /* Force all child nodes to be ignored. Buffer
- * overwrites children. */
- {
- int ii;
- for (ii = i + 1; ii < count; ii++) {
- if (asn[ii].depth <= asn[i].depth)
- break;
- sz -= data[ii].length;
- data[ii].noOut = 1;
- }
- }
- }
- else {
- /* Calculate data length from items below if no buffer
- * supplied. */
- SizeASN_CalcDataLength(asn, data, i, count);
- }
- }
- if (asn[i].tag == ASN_BOOLEAN) {
- dataLen = 1;
- }
- else {
- dataLen = data[i].data.buffer.length;
- }
- /* BIT_STRING and INTEGER have one byte prepended. */
- if ((asn[i].tag == ASN_BIT_STRING) ||
- ASNIntMSBSet(asn, data, i)) {
- dataLen++;
- /* ASN.1 items are below and cannot include extra byte. */
- if (asn[i].headerOnly) {
- len++;
- }
- }
- /* Add in the size of tag and length. */
- len += SizeASNHeader(dataLen);
- /* Include data in length if not header only or if
- * buffer supplied. */
- if (!asn[i].headerOnly || data[i].data.buffer.data != NULL) {
- len += dataLen;
- }
- break;
- #ifdef DEBUG_WOLFSSL
- default:
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("%2d: %d", i, data[i].dataType);
- WOLFSSL_MSG("Bad data type");
- #endif
- return BAD_STATE_E;
- #endif
- }
- /* Set the total length of the item. */
- data[i].length = len;
- /* Add length to total size. */
- sz += len;
- /* Set the offset to the current size - used in writing DER. */
- data[i].offset = sz;
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
- data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
- asn[i].depth, "", TagString(asn[i].tag));
- #endif
- }
- *encSz = (int)sz;
- return 0;
- }
- /* Create the DER encoding of a number.
- *
- * Assumes that the out buffer is large enough for encoding.
- *
- * @param [in] n Number to be encoded.
- * @param [in] bits Maximum number of bits to encode.
- * @param [in] tag DER tag e.g. INTEGER, BIT_STRING, etc.
- */
- static void SetASN_Num(word32 n, int bits, byte* out, byte tag)
- {
- int j;
- word32 idx;
- byte len;
- /* Encoding: Tag (1 byte) | Length (1 byte) | Data (number) */
- /* Data will start at index 2 unless BIT_STRING or INTEGER */
- idx = 2;
- /* Set the length of the number based on maximum bit length. */
- len = (byte)(bits / 8);
- /* Discover actual size by checking for leading zero bytes. */
- for (j = bits - 8; j > 0; j -= 8) {
- if ((n >> j) != 0) {
- break;
- }
- len--;
- }
- /* Keep j, index of first non-zero byte, for writing out. */
- /* A BIT_STRING has the number of unused bits in last byte prepended to
- * data.
- */
- if (tag == ASN_BIT_STRING) {
- byte unusedBits = 0;
- byte lastByte = (byte)(n >> j);
- /* Quick check last bit. */
- if ((lastByte & 0x01) == 0x00) {
- unusedBits++;
- /* Check each bit for first least significant bit set. */
- while (((lastByte >> unusedBits) & 0x01) == 0x00)
- unusedBits++;
- }
- /* Add unused bits byte. */
- len++;
- out[idx++] = unusedBits;
- }
- /* An INTEGER has a prepended byte if MSB of number is 1 - makes encoded
- * value positive. */
- if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80)) {
- len++;
- out[idx++] = 0;
- }
- /* Go back and put in length. */
- out[1] = len;
- /* Place in the required bytes of the number. */
- for (; j >= 0; j -= 8)
- out[idx++] = (byte)(n >> j);
- }
- /* Creates the DER encoding of the ASN.1 items.
- *
- * Assumes the output buffer is large enough to hold encoding.
- * Must call SizeASN_Items() to determine size of encoding and offsets.
- *
- * @param [in] asn ASN.1 items to encode.
- * @param [in] data Data to place in each item.
- * @param [in] count Count of items to encode.
- * @param [in, out] output Buffer to write encoding into.
- * @return Size of the DER encoding in bytes.
- */
- int SetASN_Items(const ASNItem* asn, ASNSetData *data, int count, byte* output)
- {
- int i;
- int length;
- int err;
- word32 sz;
- word32 idx;
- byte* out;
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_ENTER("SetASN_Items");
- #endif
- /* Offset of first item is the total length.
- * SizeASN_Items() calculated this. */
- sz = data[0].offset;
- /* Write out each item. */
- for (i = 0; i < count; i++) {
- /* Skip items not writing out. */
- if (data[i].noOut)
- continue;
- /* Start position to write item based on reverse offsets. */
- out = output + sz - data[i].offset;
- /* Index from start of item out. */
- idx = 0;
- if (data[i].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
- /* Put in the tag - not dumping in DER from buffer. */
- out[idx++] = asn[i].tag |
- (asn[i].constructed ? ASN_CONSTRUCTED : 0);
- }
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
- sz - data[i].offset,
- data[i].length, asn[i].constructed ? '+' : ' ', asn[i].depth,
- "", TagString(asn[i].tag));
- #endif
- switch (data[i].dataType) {
- /* Write out the length and data of a number. */
- case ASN_DATA_TYPE_WORD8:
- SetASN_Num(data[i].data.u8, 8, out, asn[i].tag);
- break;
- case ASN_DATA_TYPE_WORD16:
- SetASN_Num(data[i].data.u16, 16, out, asn[i].tag);
- break;
- #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
- /* Not used yet! */
- case ASN_DATA_TYPE_WORD32:
- SetASN_Num(data[i].data.u32, 32, out, asn[i].tag);
- break;
- #endif
- /* Write out the length and data of a multi-precision number. */
- case ASN_DATA_TYPE_MP:
- /* Get length in bytes. */
- length = mp_unsigned_bin_size(data[i].data.mp);
- /* Add one for leading zero to make encoding a positive num. */
- length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
- /* Write out length. */
- idx += SetASNLength((word32)length, out + idx);
- /* Write out leading zero to make positive. */
- if (mp_leading_bit(data[i].data.mp)) {
- out[idx++] = 0;
- }
- /* Encode number in big-endian byte array. */
- err = mp_to_unsigned_bin(data[i].data.mp, out + idx);
- if (err != MP_OKAY) {
- WOLFSSL_MSG("SetASN_Items: Failed to write mp_int");
- return MP_TO_E;
- }
- break;
- case ASN_DATA_TYPE_REPLACE_BUFFER:
- if (data[i].data.buffer.data == NULL) {
- /* Return pointer for caller to use. */
- data[i].data.buffer.data = out + idx;
- }
- else {
- /* Dump in the DER encoded data. */
- XMEMCPY(out + idx, data[i].data.buffer.data,
- data[i].data.buffer.length);
- }
- break;
- case ASN_DATA_TYPE_NONE:
- if (asn[i].tag == ASN_BOOLEAN) {
- /* Always one byte of data. */
- out[idx++] = 1;
- /* TRUE = 0xff, FALSE = 0x00 */
- out[idx] = data[i].data.u8 ? 0xffU : 0x00U;
- }
- else if (asn[i].tag == ASN_TAG_NULL) {
- /* NULL tag is always a zero length item. */
- out[idx] = 0;
- }
- else {
- word32 dataLen = data[i].data.buffer.length;
- /* Add one to data length for BIT_STRING unused bits and
- * INTEGER leading zero to make positive.
- */
- if ((asn[i].tag == ASN_BIT_STRING) ||
- ASNIntMSBSet(asn, data, i)) {
- dataLen++;
- }
- /* Write out length. */
- idx += SetASNLength(dataLen, out + idx);
- if ((asn[i].tag == ASN_BIT_STRING) ||
- ASNIntMSBSet(asn, data, i)) {
- /* Write out leading byte. BIT_STRING has no unused bits
- * - use number data types if needed. */
- out[idx++] = 0x00;
- }
- /* Record pointer for caller if data not supplied. */
- if (data[i].data.buffer.data == NULL) {
- data[i].data.buffer.data = out + idx;
- }
- /* Copy supplied data if not putting out header only or
- * if buffer supplied. */
- else if (!asn[i].headerOnly ||
- data[i].data.buffer.data != NULL) {
- /* Allow data to come from output buffer. */
- XMEMMOVE(out + idx, data[i].data.buffer.data,
- data[i].data.buffer.length);
- }
- }
- break;
- #ifdef DEBUG_WOLFSSL
- default:
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data[i].dataType);
- #endif
- return BAD_STATE_E;
- #endif
- }
- }
- return (int)sz;
- }
- static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
- word32 oidType, int length);
- /* Maximum supported depth in ASN.1 description. */
- #define GET_ASN_MAX_DEPTH 7
- /* Maximum number of checked numbered choices. Only one of the items with the
- * number is allowed.
- */
- #define GET_ASN_MAX_CHOICES 2
- /* Use existing function to decode BER length encoding. */
- #define GetASN_Length GetLength_ex
- /* Check an INTEGER's first byte - must be a positive number.
- *
- * @param [in] input BER encoded data.
- * @param [in] idx Index of BIT_STRING data.
- * @param [in] length Length of input data.
- * @param [in] positive Indicates number must be positive.
- * @return 0 on success.
- * @return ASN_PARSE_E when 0 is not required but seen.
- * @return ASN_EXPECT_0_E when 0 is required and not seen.
- */
- static int GetASN_Integer(const byte* input, word32 idx, int length,
- int positive)
- {
- #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) || \
- (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
- /* Check contents consist of one or more octets. */
- if (length == 0) {
- WOLFSSL_MSG("Zero length INTEGER not allowed");
- return ASN_PARSE_E;
- }
- #endif
- if (input[idx] == 0) {
- /* Check leading zero byte required. */
- if ((length > 1) && ((input[idx + 1] & 0x80) == 0)) {
- WOLFSSL_MSG("Zero not required on INTEGER");
- #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
- return ASN_PARSE_E;
- #endif
- }
- }
- /* Check whether a leading zero byte was required. */
- else if (positive && (input[idx] & 0x80)) {
- WOLFSSL_MSG("INTEGER is negative");
- #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
- return ASN_EXPECT_0_E;
- #endif /* WOLFSSL_ASN_INT_LEAD_0_ANY */
- }
- return 0;
- }
- /* Check a BIT_STRING's first byte - unused bits.
- *
- * @param [in] input BER encoded data.
- * @param [in] idx Index of BIT_STRING data.
- * @param [in] length Length of input data.
- * @return 0 on success.
- * @return ASN_PARSE_E when unused bits is invalid.
- */
- static int GetASN_BitString(const byte* input, word32 idx, int length)
- {
- #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) || \
- (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
- /* Check contents consist of one or more octets. */
- if (length == 0) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG("Zero length BIT STRING not allowed");
- #endif
- return ASN_PARSE_E;
- }
- #endif
- /* Ensure unused bits value is valid range. */
- if (input[idx] > 7) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits too big: %d > 7",
- input[idx]);
- #endif
- return ASN_PARSE_E;
- }
- /* Ensure unused bits are zero. */
- if ((byte)(input[idx + (word32)length - 1] << (8 - input[idx])) != 0) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits used: %d %02x",
- input[idx], input[idx + length - 1]);
- #endif
- return ASN_PARSE_E;
- }
- return 0;
- }
- /* Get the ASN.1 items from the BER encoding.
- *
- * @param [in] asn ASN.1 item expected.
- * @param [in] data Data array to place found item into.
- * @param [in] input BER encoded data.
- * @param [in] idx Starting index of item data.
- * @param [in] len Length of input buffer upto end of this item's data.
- * @param [in] zeroPadded INTEGER was zero padded to make positive.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data is invalid.
- * @return ASN_EXPECT_0_E when NULL tagged item has a non-zero length.
- * @return MP_INIT_E when the unable to initialize an mp_int.
- * @return ASN_GETINT_E when the unable to convert data to an mp_int.
- * @return BAD_STATE_E when the data type is not supported.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- */
- static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data,
- const byte* input, word32 idx, int len,
- int zeroPadded)
- {
- int i;
- int err;
- /* Parse data based on data type to extract. */
- switch (data->dataType) {
- /* Parse a data into a number of specified bits. */
- case ASN_DATA_TYPE_WORD8:
- /* Check data is small enough to fit. */
- if (len != 1) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("Expecting one byte: %d", len);
- #endif
- return ASN_PARSE_E;
- }
- /* Fill number with all of data. */
- *data->data.u8 = input[idx];
- break;
- case ASN_DATA_TYPE_WORD16:
- /* Check data is small enough to fit. */
- if (len == 0 || len > 2) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", len);
- #endif
- return ASN_PARSE_E;
- }
- /* Fill number with all of data. */
- *data->data.u16 = 0;
- for (i = 0; i < len; i++) {
- *data->data.u16 <<= 8;
- *data->data.u16 |= input[idx + (word32)i] ;
- }
- break;
- case ASN_DATA_TYPE_WORD32:
- /* Check data is small enough to fit. */
- if (len == 0 || len > 4) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("Expecting 1 to 4 bytes: %d", len);
- #endif
- return ASN_PARSE_E;
- }
- /* Fill number with all of data. */
- *data->data.u32 = 0;
- for (i = 0; i < len; i++) {
- *data->data.u32 <<= 8;
- *data->data.u32 |= input[idx + (word32)i] ;
- }
- break;
- case ASN_DATA_TYPE_BUFFER:
- /* Check buffer is big enough to hold data. */
- if (len > (int)*data->data.buffer.length) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("Buffer too small for data: %d %d", len,
- *data->data.buffer.length);
- #endif
- return ASN_PARSE_E;
- }
- /* Copy in data and record actual length seen. */
- XMEMCPY(data->data.buffer.data, input + idx, (size_t)len);
- *data->data.buffer.length = (word32)len;
- break;
- case ASN_DATA_TYPE_EXP_BUFFER:
- /* Check data is same size expected. */
- if (len != (int)data->data.ref.length) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("Data not expected length: %d %d", len,
- data->data.ref.length);
- #endif
- return ASN_PARSE_E;
- }
- /* Check data is same as expected. */
- if (XMEMCMP(data->data.ref.data, input + idx, (size_t)len) != 0) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG("Data not as expected");
- #endif
- return ASN_PARSE_E;
- }
- break;
- case ASN_DATA_TYPE_MP:
- case ASN_DATA_TYPE_MP_POS_NEG:
- /* Initialize mp_int and read in big-endian byte array. */
- if (mp_init(data->data.mp) != MP_OKAY) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("Failed to init mp: %p", data->data.mp);
- #endif
- return MP_INIT_E;
- }
- FALL_THROUGH;
- case ASN_DATA_TYPE_MP_INITED:
- err = mp_read_unsigned_bin(data->data.mp, (byte*)input + idx,
- (word32)len);
- if (err != 0) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("Failed to read mp: %d", err);
- #endif
- mp_clear(data->data.mp);
- return ASN_GETINT_E;
- }
- #ifdef HAVE_WOLF_BIGINT
- err = wc_bigint_from_unsigned_bin(&data->data.mp->raw, input + idx,
- len);
- if (err != 0) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("Failed to create bigint: %d", err);
- #endif
- mp_clear(data->data.mp);
- return ASN_GETINT_E;
- }
- #endif /* HAVE_WOLF_BIGINT */
- #ifdef WOLFSSL_SP_INT_NEGATIVE
- /* Don't always read as positive. */
- if ((data->dataType == ASN_DATA_TYPE_MP_POS_NEG) && (!zeroPadded) &&
- (input[idx] & 0x80)) {
- #ifdef MP_NEG
- data->data.mp->sign = MP_NEG;
- #else
- #ifdef OPENSSL_EXTRA
- /* public API wolfSSL_ASN1_INTEGER_get() depends
- * indirectly on negative bignum handling here.
- */
- #error OPENSSL_EXTRA requires negative bignum support.
- #endif
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("ASN negative integer without bignum support.");
- #endif
- mp_clear(data->data.mp);
- return ASN_GETINT_E;
- #endif
- }
- #else
- (void)zeroPadded;
- #endif
- break;
- case ASN_DATA_TYPE_CHOICE:
- /* Check if tag matched any of the choices specified. */
- for (i = 0; data->data.choice[i] != 0; i++)
- if (data->data.choice[i] == data->tag)
- break;
- if (data->data.choice[i] == 0) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG("Tag didn't match a choice");
- #endif
- return ASN_PARSE_E;
- }
- /* Store data pointer and length for caller. */
- data->data.ref.data = input + idx;
- data->data.ref.length = (word32)len;
- break;
- case ASN_DATA_TYPE_NONE:
- /* Default behaviour based on tag. */
- if (asn->tag == ASN_BOOLEAN) {
- /* BOOLEAN has only one byte of data in BER. */
- if (len != 1) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("BOOLEAN length too long: %d", len);
- #endif
- return ASN_PARSE_E;
- }
- if (data->data.u8 == NULL)
- return BAD_STATE_E;
- /* Store C boolean value. */
- *data->data.u8 = (input[idx] != 0);
- break;
- }
- if (asn->tag == ASN_TAG_NULL) {
- /* NULL has no data in BER. */
- if (len != 0) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("NULL length too long: %d", len);
- #endif
- return ASN_EXPECT_0_E;
- }
- data->data.ref.data = input + idx;
- break;
- }
- if (asn->tag == ASN_OBJECT_ID) {
- word32 oidIdx = 0;
- /* Store OID data pointer and length */
- data->data.oid.data = input + idx;
- data->data.oid.length = (word32)len;
- /* Get the OID sum. */
- err = GetOID(input + idx, &oidIdx, &data->data.oid.sum,
- data->data.oid.type, len);
- if (err < 0) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("OID check failed: %d", err);
- #endif
- return err;
- }
- break;
- }
- /* Otherwise store data pointer and length. */
- data->data.ref.data = input + idx;
- data->data.ref.length = (word32)len;
- break;
- #ifdef DEBUG_WOLFSSL
- default:
- /* Bad ASN data type. */
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data->dataType);
- #endif
- return BAD_STATE_E;
- #endif
- }
- return 0;
- }
- /* Get the ASN.1 items from the BER encoding.
- *
- * @param [in] asn ASN.1 items expected.
- * @param [in] data Data array to place found items into.
- * @param [in] count Count of items to parse.
- * @param [in] complete Whether the whole buffer is to be used up.
- * @param [in] input BER encoded data.
- * @param [in, out] inOutIdx On in, starting index of data.
- * On out, end of parsed data.
- * @param [in] length Length of input buffer.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- * @return MP_INIT_E when the unable to initialize an mp_int.
- * @return ASN_GETINT_E when the unable to convert data to an mp_int.
- * @return BAD_STATE_E when the data type is not supported.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- */
- int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, int complete,
- const byte* input, word32* inOutIdx, word32 length)
- {
- int i;
- int j;
- int err;
- int len;
- /* Current index into buffer. */
- word32 idx = *inOutIdx;
- /* Initialize the end index at each depth to be the length. */
- word32 endIdx[GET_ASN_MAX_DEPTH] = { length, length, length, length, length,
- length, length };
- /* Set choices to -1 to indicate they haven't been seen or found. */
- signed char choiceMet[GET_ASN_MAX_CHOICES] = { -1, -1 };
- /* Not matching a choice right now. */
- int choice = 0;
- /* Current depth of ASN.1 item. */
- int depth;
- /* Minimum depth value seen. */
- int minDepth;
- /* Integer had a zero prepended. */
- int zeroPadded;
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_ENTER("GetASN_Items");
- #endif
- /* Start depth at first items depth. */
- minDepth = depth = asn[0].depth;
- /* Check every ASN.1 item. */
- for (i = 0; i < count; i++) {
- /* Store offset of ASN.1 item. */
- data[i].offset = idx;
- /* Length of data in ASN.1 item starts empty. */
- data[i].length = 0;
- /* Get current item depth. */
- depth = asn[i].depth;
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- if (depth > GET_ASN_MAX_DEPTH) {
- WOLFSSL_MSG("Depth in template too large");
- return ASN_PARSE_E;
- }
- #endif
- /* Keep track of minimum depth. */
- if (depth < minDepth) {
- minDepth = depth;
- }
- /* Reset choice if different from previous. */
- if (choice > 0 && asn[i].optional != choice) {
- choice = 0;
- }
- /* Check if first of numbered choice. */
- if (choice == 0 && asn[i].optional > 1) {
- choice = asn[i].optional;
- if (choiceMet[choice - 2] == -1) {
- /* Choice seen but not found a match yet. */
- choiceMet[choice - 2] = 0;
- }
- }
- /* Check for end of data or not a choice and tag not matching. */
- if (idx == endIdx[depth] || (data[i].dataType != ASN_DATA_TYPE_CHOICE &&
- (input[idx] & ~ASN_CONSTRUCTED) != asn[i].tag)) {
- if (asn[i].optional) {
- /* Skip over ASN.1 items underneath this optional item. */
- for (j = i + 1; j < count; j++) {
- if (asn[i].depth >= asn[j].depth)
- break;
- data[j].offset = idx;
- data[j].length = 0;
- }
- i = j - 1;
- continue;
- }
- /* Check for end of data. */
- if (idx == length) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF(
- "%2d: %4d %4d %c %*s %-16s%*s (index past end)",
- i, data[i].offset, data[i].length,
- asn[i].constructed ? '+' : ' ', asn[i].depth, "",
- TagString(asn[i].tag), 6 - asn[i].depth, "");
- WOLFSSL_MSG_VSNPRINTF("Index past end of data: %d %d", idx,
- length);
- #endif
- return BUFFER_E;
- }
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- /* Show expected versus found. */
- WOLFSSL_MSG_VSNPRINTF(
- "%2d: %4d %4d %c %*s %-16s%*s Tag=0x%02x (%s)",
- i, data[i].offset, data[i].length,
- asn[i].constructed ? '+' : ' ', asn[i].depth, "",
- TagString(asn[i].tag), 6 - asn[i].depth, "",
- input[idx], TagString(input[idx]));
- #endif
- /* Check for end of data at this depth. */
- if (idx == endIdx[depth]) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("Index past outer item: %d %d", idx,
- endIdx[depth]);
- #endif
- return ASN_PARSE_E;
- }
- /* Expecting an OBJECT_ID */
- if (asn[i].tag == ASN_OBJECT_ID) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG("Expecting OBJECT ID");
- #endif
- return ASN_OBJECT_ID_E;
- }
- /* Expecting a BIT_STRING */
- if (asn[i].tag == ASN_BIT_STRING) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG("Expecting BIT STRING");
- #endif
- return ASN_BITSTR_E;
- }
- /* Not the expected tag. */
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG("Bad tag");
- #endif
- return ASN_PARSE_E;
- }
- /* Store found tag in data. */
- data[i].tag = input[idx];
- if (data[i].dataType != ASN_DATA_TYPE_CHOICE) {
- int constructed = (input[idx] & ASN_CONSTRUCTED) == ASN_CONSTRUCTED;
- /* Check constructed match expected for non-choice ASN.1 item. */
- if (asn[i].constructed != constructed) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF(
- "%2d: %4d %4d %c %*s %-16s%*s Tag=0x%02x (%s)",
- i, data[i].offset, data[i].length,
- asn[i].constructed ? '+' : ' ', asn[i].depth, "",
- TagString(asn[i].tag), 6 - asn[i].depth, "",
- input[idx], TagString(input[idx]));
- if (!constructed) {
- WOLFSSL_MSG("Not constructed");
- }
- else {
- WOLFSSL_MSG("Not expected to be constructed");
- }
- #endif
- return ASN_PARSE_E;
- }
- }
- /* Move index to start of length. */
- idx++;
- /* Get the encoded length. */
- if (GetASN_Length(input, &idx, &len, endIdx[depth], 1) < 0) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("%2d: idx=%d len=%d end=%d", i, idx, len,
- endIdx[depth]);
- #endif
- return ASN_PARSE_E;
- }
- /* Store length of data. */
- data[i].length = (word32)len;
- /* Note the max length of items under this one. */
- endIdx[depth + 1] = idx + (word32)len;
- if (choice > 1) {
- /* Note we found a number choice. */
- choiceMet[choice - 2] = 1;
- }
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
- data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
- asn[i].depth, "", TagString(data[i].tag));
- #endif
- /* Assume no zero padding on INTEGER. */
- zeroPadded = 0;
- /* Check data types that prepended a byte. */
- if (asn[i].tag == ASN_INTEGER) {
- /* Check validity of first byte. */
- err = GetASN_Integer(input, idx, len,
- data[i].dataType == ASN_DATA_TYPE_MP ||
- data[i].dataType == ASN_DATA_TYPE_MP_INITED);
- if (err != 0)
- return err;
- if (len > 1 && input[idx] == 0) {
- zeroPadded = 1;
- /* Move over prepended byte. */
- idx++;
- len--;
- }
- }
- else if (asn[i].tag == ASN_BIT_STRING) {
- /* Check prepended byte is correct. */
- err = GetASN_BitString(input, idx, len);
- if (err != 0)
- return err;
- /* Move over prepended byte. */
- idx++;
- len--;
- }
- else if ((asn[i].tag == ASN_OBJECT_ID) && (len < 3)) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("OID length must be 3 or more: %d", len);
- #endif
- return ASN_PARSE_E;
- }
- /* Don't parse data if only header required. */
- if (asn[i].headerOnly) {
- /* Store reference to data and length. */
- data[i].data.ref.data = input + idx;
- data[i].data.ref.length = (word32)len;
- continue;
- }
- /* Store the data at idx in the ASN data item. */
- err = GetASN_StoreData(&asn[i], &data[i], input, idx, len, zeroPadded);
- if (err != 0) {
- return err;
- }
- /* Move index to next item. */
- idx += (word32)len;
- /* When matched numbered choice ... */
- if (asn[i].optional > 1) {
- /* Skip over other ASN.1 items of the same number. */
- for (j = i + 1; j < count; j++) {
- if (asn[j].depth <= asn[i].depth &&
- asn[j].optional != asn[i].optional) {
- break;
- }
- }
- i = j - 1;
- }
- }
- if (complete) {
- /* When expecting ASN.1 items to completely use data, check we did. */
- for (j = depth; j > minDepth; j--) {
- if (idx < endIdx[j]) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF(
- "More data in constructed item at depth: %d", j - 1);
- #endif
- return ASN_PARSE_E;
- }
- }
- }
- /* Check all choices where met - found an item for them. */
- for (j = 0; j < GET_ASN_MAX_CHOICES; j++) {
- if (choiceMet[j] == 0) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("No choice seen: %d", j + 2);
- #endif
- return ASN_PARSE_E;
- }
- }
- /* Return index after ASN.1 data has been parsed. */
- *inOutIdx = idx;
- return 0;
- }
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- /* Calculate the size of the DER encoding.
- *
- * Call SetASN_Items() to write encoding to a buffer.
- *
- * @param [in] asn ASN.1 items to encode.
- * @param [in, out] data Data to place in each item. Lengths set were not
- * known.
- * @param [in] count Count of items to encode.
- * @param [out] len Length of the DER encoding.
- * @return Size of the DER encoding in bytes.
- */
- static int SizeASN_ItemsDebug(const char* name, const ASNItem* asn,
- ASNSetData *data, int count, int* encSz)
- {
- WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
- return SizeASN_Items(asn, data, count, encSz);
- }
- /* Creates the DER encoding of the ASN.1 items.
- *
- * Assumes the output buffer is large enough to hold encoding.
- * Must call SizeASN_Items() to determine size of encoding and offsets.
- *
- * Displays the template name first.
- *
- * @param [in] name Name of ASN.1 template.
- * @param [in] asn ASN.1 items to encode.
- * @param [in] data Data to place in each item.
- * @param [in] count Count of items to encode.
- * @param [in, out] output Buffer to write encoding into.
- * @return Size of the DER encoding in bytes.
- */
- static int SetASN_ItemsDebug(const char* name, const ASNItem* asn,
- ASNSetData *data, int count, byte* output)
- {
- WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
- return SetASN_Items(asn, data, count, output);
- }
- /* Get the ASN.1 items from the BER encoding.
- *
- * Displays the template name first.
- *
- * @param [in] name Name of ASN.1 template.
- * @param [in] asn ASN.1 items expected.
- * @param [in] data Data array to place found items into.
- * @param [in] count Count of items to parse.
- * @param [in] complete Whether the whole buffer is to be used up.
- * @param [in] input BER encoded data.
- * @param [in, out] inOutIdx On in, starting index of data.
- * On out, end of parsed data.
- * @param [in] maxIdx Maximum index of input data.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- * @return MP_INIT_E when the unable to initialize an mp_int.
- * @return ASN_GETINT_E when the unable to convert data to an mp_int.
- * @return BAD_STATE_E when the data type is not supported.
- */
- static int GetASN_ItemsDebug(const char* name, const ASNItem* asn,
- ASNGetData *data, int count, int complete, const byte* input,
- word32* inOutIdx, word32 maxIdx)
- {
- WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
- return GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx);
- }
- /* Calculate the size of the DER encoding.
- *
- * Call SetASN_Items() to write encoding to a buffer.
- *
- * @param [in] asn ASN.1 items to encode.
- * @param [in, out] data Data to place in each item. Lengths set were not
- * known.
- * @param [in] count Count of items to encode.
- * @param [out] len Length of the DER encoding.
- * @return Size of the DER encoding in bytes.
- */
- #define SizeASN_Items(asn, data, count, encSz) \
- SizeASN_ItemsDebug(#asn, asn, data, count, encSz)
- /* Creates the DER encoding of the ASN.1 items.
- *
- * Assumes the output buffer is large enough to hold encoding.
- * Must call SizeASN_Items() to determine size of encoding and offsets.
- *
- * Displays the template name first.
- *
- * @param [in] name Name of ASN.1 template.
- * @param [in] asn ASN.1 items to encode.
- * @param [in] data Data to place in each item.
- * @param [in] count Count of items to encode.
- * @param [in, out] output Buffer to write encoding into.
- * @return Size of the DER encoding in bytes.
- */
- #define SetASN_Items(asn, data, count, output) \
- SetASN_ItemsDebug(#asn, asn, data, count, output)
- /* Get the ASN.1 items from the BER encoding.
- *
- * Displays the template name first.
- *
- * @param [in] name Name of ASN.1 template.
- * @param [in] asn ASN.1 items expected.
- * @param [in] data Data array to place found items into.
- * @param [in] count Count of items to parse.
- * @param [in] complete Whether the whole buffer is to be used up.
- * @param [in] input BER encoded data.
- * @param [in, out] inOutIdx On in, starting index of data.
- * On out, end of parsed data.
- * @param [in] maxIdx Maximum index of input data.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- * @return MP_INIT_E when the unable to initialize an mp_int.
- * @return ASN_GETINT_E when the unable to convert data to an mp_int.
- * @return BAD_STATE_E when the data type is not supported.
- */
- #define GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx) \
- GetASN_ItemsDebug(#asn, asn, data, count, complete, input, inOutIdx, maxIdx)
- #endif /* WOLFSSL_DEBUG_ASN_TEMPLATE */
- /* Decode a BER encoded constructed sequence.
- *
- * @param [in] input Buffer of BER encoded data.
- * @param [in, out] inOutIdx On in, index to start decoding from.
- * On out, index of next encoded byte.
- * @param [out] len Length of data under SEQUENCE.
- * @param [in] maxIdx Maximim index of data. Index of byte after SEQ.
- * @param [in] complete All data used with SEQUENCE and data under.
- * @return 0 on success.
- * @return BUFFER_E when not enough data to complete decode.
- * @return ASN_PARSE when decoding failed.
- */
- static int GetASN_Sequence(const byte* input, word32* inOutIdx, int* len,
- word32 maxIdx, int complete)
- {
- int ret = 0;
- word32 idx = *inOutIdx;
- /* Check buffer big enough for tag. */
- if (idx + 1 > maxIdx) {
- ret = BUFFER_E;
- }
- /* Check it is a constructed SEQUENCE. */
- if ((ret == 0) && (input[idx++] != (ASN_SEQUENCE | ASN_CONSTRUCTED))) {
- ret = ASN_PARSE_E;
- }
- /* Get the length. */
- if ((ret == 0) && (GetASN_Length(input, &idx, len, maxIdx, 1) < 0)) {
- ret = ASN_PARSE_E;
- }
- /* Check all data used if complete set. */
- if ((ret == 0) && complete && (idx + (word32)*len != maxIdx)) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- /* Return index of next byte of encoded data. */
- *inOutIdx = idx;
- }
- return ret;
- }
- #ifdef WOLFSSL_ASN_TEMPLATE_TYPE_CHECK
- /* Setup ASN data item to get an 8-bit number.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] num Pointer to an 8-bit variable.
- */
- void GetASN_Int8Bit(ASNGetData *dataASN, byte* num)
- {
- dataASN->dataType = ASN_DATA_TYPE_WORD8;
- dataASN->data.u8 = num;
- }
- /* Setup ASN data item to get a 16-bit number.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] num Pointer to a 16-bit variable.
- */
- void GetASN_Int16Bit(ASNGetData *dataASN, word16* num)
- {
- dataASN->dataType = ASN_DATA_TYPE_WORD16;
- dataASN->data.u16 = num;
- }
- /* Setup ASN data item to get a 32-bit number.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] num Pointer to a 32-bit variable.
- */
- void GetASN_Int32Bit(ASNGetData *dataASN, word32* num)
- {
- dataASN->dataType = ASN_DATA_TYPE_WORD32;
- dataASN->data.u32 = num;
- }
- /* Setup ASN data item to get data into a buffer of a specific length.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] data Buffer to hold data.
- * @param [in] length Length of buffer in bytes.
- */
- void GetASN_Buffer(ASNGetData *dataASN, byte* data, word32* length)
- {
- dataASN->dataType = ASN_DATA_TYPE_BUFFER;
- dataASN->data.buffer.data = data;
- dataASN->data.buffer.length = length;
- }
- /* Setup ASN data item to check parsed data against expected buffer.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] data Buffer containing expected data.
- * @param [in] length Length of buffer in bytes.
- */
- void GetASN_ExpBuffer(ASNGetData *dataASN, const byte* data, word32 length)
- {
- dataASN->dataType = ASN_DATA_TYPE_EXP_BUFFER;
- dataASN->data.ref.data = data;
- dataASN->data.ref.length = length;
- }
- /* Setup ASN data item to get a number into an mp_int.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] num Multi-precision number object.
- */
- void GetASN_MP(ASNGetData *dataASN, mp_int* num)
- {
- dataASN->dataType = ASN_DATA_TYPE_MP;
- dataASN->data.mp = num;
- }
- /* Setup ASN data item to get a number into an mp_int that is initialized.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] num Multi-precision number object.
- */
- void GetASN_MP_Inited(ASNGetData *dataASN, mp_int* num)
- {
- dataASN->dataType = ASN_DATA_TYPE_MP_INITED;
- dataASN->data.mp = num;
- }
- /* Setup ASN data item to get a positive or negative number into an mp_int.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] num Multi-precision number object.
- */
- void GetASN_MP_PosNeg(ASNGetData *dataASN, mp_int* num)
- {
- dataASN->dataType = ASN_DATA_TYPE_MP_POS_NEG;
- dataASN->data.mp = num;
- }
- /* Setup ASN data item to be a choice of tags.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] options 0 terminated list of tags that are valid.
- */
- void GetASN_Choice(ASNGetData *dataASN, const byte* options)
- {
- dataASN->dataType = ASN_DATA_TYPE_CHOICE;
- dataASN->data.choice = options;
- }
- /* Setup ASN data item to get a boolean value.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] num Pointer to an 8-bit variable.
- */
- void GetASN_Boolean(ASNGetData *dataASN, byte* num)
- {
- dataASN->dataType = ASN_DATA_TYPE_NONE;
- dataASN->data.choice = num;
- }
- /* Setup ASN data item to be a an OID of a specific type.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] oidType Type of OID to expect.
- */
- void GetASN_OID(ASNGetData *dataASN, int oidType)
- {
- dataASN->data.oid.type = oidType;
- }
- /* Get the data and length from an ASN data item.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [out] data Pointer to data of item.
- * @param [out] length Length of buffer in bytes.
- */
- void GetASN_GetConstRef(ASNGetData * dataASN, const byte** data, word32* length)
- {
- *data = dataASN->data.ref.data;
- *length = dataASN->data.ref.length;
- }
- /* Get the data and length from an ASN data item.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [out] data Pointer to data of item.
- * @param [out] length Length of buffer in bytes.
- */
- void GetASN_GetRef(ASNGetData * dataASN, byte** data, word32* length)
- {
- *data = (byte*)dataASN->data.ref.data;
- *length = dataASN->data.ref.length;
- }
- /* Get the data and length from an ASN data item that is an OID.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [out] data Pointer to .
- * @param [out] length Length of buffer in bytes.
- */
- void GetASN_OIDData(ASNGetData * dataASN, byte** data, word32* length)
- {
- *data = (byte*)dataASN->data.oid.data;
- *length = dataASN->data.oid.length;
- }
- /* Setup an ASN data item to set a boolean.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] val Boolean value.
- */
- void SetASN_Boolean(ASNSetData *dataASN, byte val)
- {
- dataASN->dataType = ASN_DATA_TYPE_NONE;
- dataASN->data.u8 = val;
- }
- /* Setup an ASN data item to set an 8-bit number.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] num 8-bit number to set.
- */
- void SetASN_Int8Bit(ASNSetData *dataASN, byte num)
- {
- dataASN->dataType = ASN_DATA_TYPE_WORD8;
- dataASN->data.u8 = num;
- }
- /* Setup an ASN data item to set a 16-bit number.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] num 16-bit number to set.
- */
- void SetASN_Int16Bit(ASNSetData *dataASN, word16 num)
- {
- dataASN->dataType = ASN_DATA_TYPE_WORD16;
- dataASN->data.u16 = num;
- }
- /* Setup an ASN data item to set the data in a buffer.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] data Buffer containing data to set.
- * @param [in] length Length of data in buffer in bytes.
- */
- void SetASN_Buffer(ASNSetData *dataASN, const byte* data, word32 length)
- {
- dataASN->data.buffer.data = data;
- dataASN->data.buffer.length = length;
- }
- /* Setup an ASN data item to set the DER encode data in a buffer.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] data Buffer containing BER encoded data to set.
- * @param [in] length Length of data in buffer in bytes.
- */
- void SetASN_ReplaceBuffer(ASNSetData *dataASN, const byte* data, word32 length)
- {
- dataASN->dataType = ASN_DATA_TYPE_REPLACE_BUFFER;
- dataASN->data.buffer.data = data;
- dataASN->data.buffer.length = length;
- }
- /* Setup an ASN data item to set an multi-precision number.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] num Multi-precision number.
- */
- void SetASN_MP(ASNSetData *dataASN, mp_int* num)
- {
- dataASN->dataType = ASN_DATA_TYPE_MP;
- dataASN->data.mp = num;
- }
- /* Setup an ASN data item to set an OID based on id and type.
- *
- * oid and oidType pair are unique.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [in] oid OID identifier.
- * @param [in] oidType Type of OID.
- */
- void SetASN_OID(ASNSetData *dataASN, int oid, int oidType)
- {
- dataASN->data.buffer.data = OidFromId(oid, oidType,
- &dataASN->data.buffer.length);
- }
- #endif /* WOLFSSL_ASN_TEMPLATE_TYPE_CHECK */
- #ifdef CRLDP_VALIDATE_DATA
- /* Get the data of the BIT_STRING as a 16-bit number.
- *
- * @param [in] dataASN Dynamic ASN data item.
- * @param [out] val ASN.1 item's data as a 16-bit number.
- * @return 0 on success.
- * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
- * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
- */
- static int GetASN_BitString_Int16Bit(ASNGetData* dataASN, word16* val)
- {
- int ret;
- int i;
- const byte* input = dataASN->data.ref.data;
- int length = dataASN->data.ref.length;
- /* Validate the BIT_STRING data. */
- ret = GetASN_BitString(input, 0, length);
- if (ret == 0) {
- /* Skip unused bits byte. */
- input++;
- length--;
- /* Check the data is usable. */
- if (length == 0 || length > 2) {
- #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
- WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", length);
- #endif
- ret = ASN_PARSE_E;
- }
- }
- if (ret == 0) {
- /* Fill 16-bit var with all the data. */
- *val = 0;
- for (i = 0; i < length; i++) {
- *val <<= 8;
- *val |= input[i];
- }
- }
- return ret;
- }
- #endif /* CRLDP_VALIDATE_DATA */
- #endif /* WOLFSSL_ASN_TEMPLATE */
- /* Decode the BER/DER length field.
- *
- * @param [in] input BER encoded data.
- * @param [in, out] inOutIdx On in, starting index of length.
- * On out, end of parsed length.
- * @param [out] len Length value decoded.
- * @param [in] maxIdx Maximum index of input data.
- * @return Length on success.
- * @return ASN_PARSE_E if the encoding is invalid.
- * @return BUFFER_E when not enough data to complete decode.
- */
- int GetLength(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
- {
- return GetLength_ex(input, inOutIdx, len, maxIdx, 1);
- }
- /* Decode the BER/DER length field and check the length is valid on request.
- *
- * BER/DER has Type-Length-Value triplets.
- * When requested will check that the Length decoded, indicating the number
- * of bytes in the Value, is available in the buffer after the Length bytes.
- *
- * Only supporting a length upto INT_MAX.
- *
- * @param [in] input BER encoded data.
- * @param [in, out] inOutIdx On in, starting index of length.
- * On out, end of parsed length.
- * @param [out] len Length value decoded.
- * @param [in] maxIdx Maximum index of input data.
- * @param [in] check Whether to check the buffer has at least the
- * decoded length of bytes remaining.
- * @return Length on success.
- * @return ASN_PARSE_E if the encoding is invalid.
- * @return BUFFER_E when not enough data to complete decode.
- */
- int GetLength_ex(const byte* input, word32* inOutIdx, int* len, word32 maxIdx,
- int check)
- {
- int length = 0;
- word32 idx = (word32)*inOutIdx;
- byte b;
- /* Ensure zero return length on error. */
- *len = 0;
- /* Check there is at least one byte available containing length information.
- */
- if ((idx + 1) > maxIdx) {
- WOLFSSL_MSG("GetLength - bad index on input");
- return BUFFER_E;
- }
- /* Get the first length byte. */
- b = input[idx++];
- /* Check if the first byte indicates the count of bytes. */
- if (b >= ASN_LONG_LENGTH) {
- /* Bottom 7 bits are the number of bytes to calculate length with.
- * Note: 0 indicates indefinite length encoding *not* 0 bytes of length.
- */
- word32 bytes = (word32)b & 0x7FU;
- int minLen;
- /* Calculate minimum length to be encoded with bytes. */
- if (b == ASN_INDEF_LENGTH) {
- /* Indefinite length encoding - no length bytes. */
- minLen = 0;
- }
- else if (bytes == 1) {
- minLen = 0x80;
- }
- /* Only support up to the number of bytes that fit into return var. */
- else if (bytes > sizeof(length)) {
- WOLFSSL_MSG("GetLength - overlong data length spec");
- return ASN_PARSE_E;
- } else {
- minLen = 1 << ((bytes - 1) * 8);
- }
- /* Check the number of bytes required are available. */
- if ((idx + bytes) > maxIdx) {
- WOLFSSL_MSG("GetLength - bad long length");
- return BUFFER_E;
- }
- /* Big-endian encoding of number. */
- while (bytes--) {
- b = input[idx++];
- length = (length << 8) | b;
- }
- /* Negative value indicates we overflowed the signed int. */
- if (length < 0) {
- return ASN_PARSE_E;
- }
- /* Don't allow lengths that are longer than strictly required. */
- if (length < minLen) {
- return ASN_PARSE_E;
- }
- }
- else {
- /* Length in first byte. */
- length = b;
- }
- /* When requested, check the buffer has at least length bytes left. */
- if (check && ((idx + (word32)length) > maxIdx)) {
- WOLFSSL_MSG("GetLength - value exceeds buffer length");
- return BUFFER_E;
- }
- /* Return index after length encoding. */
- *inOutIdx = idx;
- /* Return length if valid. */
- if (length > 0) {
- *len = length;
- }
- /* Return length calculated or error code. */
- return length;
- }
- /* Gets the tag of next BER/DER encoded item.
- *
- * Checks there is enough data in the buffer for the tag byte.
- *
- * @param [in] input BER encoded data.
- * @param [in, out] inOutIdx On in, starting index of tag.
- * On out, end of parsed tag.
- * @param [out] tag Tag value found.
- * @param [in] maxIdx Maximum index of input data.
- *
- * return 0 on success
- * return BAD_FUNC_ARG when tag, inOutIdx or input is NULL.
- * return BUFFER_E when not enough space in buffer for tag.
- */
- int GetASNTag(const byte* input, word32* inOutIdx, byte* tag, word32 maxIdx)
- {
- int ret = 0;
- word32 idx = 0;
- /* Check validity of parameters. */
- if ((tag == NULL) || (inOutIdx == NULL) || (input == NULL)) {
- ret = BAD_FUNC_ARG;
- }
- if (ret == 0) {
- /* Get index and ensure space for tag. */
- idx = *inOutIdx;
- if (idx + ASN_TAG_SZ > maxIdx) {
- WOLFSSL_MSG("Buffer too small for ASN tag");
- ret = BUFFER_E;
- }
- }
- if (ret == 0) {
- /* Return the tag and the index after tag. */
- *tag = input[idx];
- *inOutIdx = idx + ASN_TAG_SZ;
- }
- /* Return error code. */
- return ret;
- }
- /* Decode the DER/BER header (Type-Length) and check the length when requested.
- *
- * BER/DER has Type-Length-Value triplets.
- * Check that the tag/type is the required value.
- * When requested will check that the Length decoded, indicating the number
- * of bytes in the Value, is available in the buffer after the Length bytes.
- *
- * Only supporting a length upto INT_MAX.
- *
- * @param [in] input Buffer holding DER/BER encoded data.
- * @param [in] tag ASN.1 tag value expected in header.
- * @param [in, out] inOutIdx On in, starting index of header.
- * On out, end of parsed header.
- * @param [out] len Number of bytes in the ASN.1 data.
- * @param [in] maxIdx Length of data in buffer.
- * @param [in] check Whether to check the buffer has at least the
- * decoded length of bytes remaining.
- * @return Number of bytes in the ASN.1 data on success.
- * @return BUFFER_E when there is not enough data to parse.
- * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
- */
- static int GetASNHeader_ex(const byte* input, byte tag, word32* inOutIdx,
- int* len, word32 maxIdx, int check)
- {
- int ret = 0;
- word32 idx = *inOutIdx;
- byte tagFound;
- int length = 0;
- /* Get tag/type. */
- if (GetASNTag(input, &idx, &tagFound, maxIdx) != 0) {
- ret = ASN_PARSE_E;
- }
- /* Ensure tag is the expected value. */
- if ((ret == 0) && (tagFound != tag)) {
- ret = ASN_PARSE_E;
- }
- /* Get the encoded length. */
- if ((ret == 0) && (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- /* Return the length of data and index after header. */
- *len = length;
- *inOutIdx = idx;
- ret = length;
- }
- /* Return number of data bytes or error code. */
- return ret;
- }
- /* Decode the DER/BER header (Type-Length) and check the length.
- *
- * BER/DER has Type-Length-Value triplets.
- * Check that the tag/type is the required value.
- * Checks that the Length decoded, indicating the number of bytes in the Value,
- * is available in the buffer after the Length bytes.
- *
- * @param [in] input Buffer holding DER/BER encoded data.
- * @param [in] tag ASN.1 tag value expected in header.
- * @param [in, out] inOutIdx On in, starting index of header.
- * On out, end of parsed header.
- * @param [out] len Number of bytes in the ASN.1 data.
- * @param [in] maxIdx Length of data in buffer.
- * @return Number of bytes in the ASN.1 data on success.
- * @return BUFFER_E when there is not enough data to parse.
- * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
- */
- static int GetASNHeader(const byte* input, byte tag, word32* inOutIdx, int* len,
- word32 maxIdx)
- {
- return GetASNHeader_ex(input, tag, inOutIdx, len, maxIdx, 1);
- }
- #ifndef WOLFSSL_ASN_TEMPLATE
- static int GetHeader(const byte* input, byte* tag, word32* inOutIdx, int* len,
- word32 maxIdx, int check)
- {
- word32 idx = *inOutIdx;
- int length;
- if ((idx + 1) > maxIdx)
- return BUFFER_E;
- *tag = input[idx++];
- if (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)
- return ASN_PARSE_E;
- *len = length;
- *inOutIdx = idx;
- return length;
- }
- #endif
- /* Decode the header of a BER/DER encoded SEQUENCE.
- *
- * @param [in] input Buffer holding DER/BER encoded data.
- * @param [in, out] inOutIdx On in, starting index of header.
- * On out, end of parsed header.
- * @param [out] len Number of bytes in the ASN.1 data.
- * @param [in] maxIdx Length of data in buffer.
- * @return Number of bytes in the ASN.1 data on success.
- * @return BUFFER_E when there is not enough data to parse.
- * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
- */
- int GetSequence(const byte* input, word32* inOutIdx, int* len,
- word32 maxIdx)
- {
- return GetASNHeader(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
- maxIdx);
- }
- /* Decode the header of a BER/DER encoded SEQUENCE.
- *
- * @param [in] input Buffer holding DER/BER encoded data.
- * @param [in, out] inOutIdx On in, starting index of header.
- * On out, end of parsed header.
- * @param [out] len Number of bytes in the ASN.1 data.
- * @param [in] maxIdx Length of data in buffer.
- * @param [in] check Whether to check the buffer has at least the
- * decoded length of bytes remaining.
- * @return Number of bytes in the ASN.1 data on success.
- * @return BUFFER_E when there is not enough data to parse.
- * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
- */
- int GetSequence_ex(const byte* input, word32* inOutIdx, int* len,
- word32 maxIdx, int check)
- {
- return GetASNHeader_ex(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
- maxIdx, check);
- }
- /* Decode the header of a BER/DER encoded SET.
- *
- * @param [in] input Buffer holding DER/BER encoded data.
- * @param [in, out] inOutIdx On in, starting index of header.
- * On out, end of parsed header.
- * @param [out] len Number of bytes in the ASN.1 data.
- * @param [in] maxIdx Length of data in buffer.
- * @return Number of bytes in the ASN.1 data on success.
- * @return BUFFER_E when there is not enough data to parse.
- * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
- */
- int GetSet(const byte* input, word32* inOutIdx, int* len,
- word32 maxIdx)
- {
- return GetASNHeader(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
- maxIdx);
- }
- /* Decode the header of a BER/DER encoded SET.
- *
- * @param [in] input Buffer holding DER/BER encoded data.
- * @param [in, out] inOutIdx On in, starting index of header.
- * On out, end of parsed header.
- * @param [out] len Number of bytes in the ASN.1 data.
- * @param [in] maxIdx Length of data in buffer.
- * @param [in] check Whether to check the buffer has at least the
- * decoded length of bytes remaining.
- * @return Number of bytes in the ASN.1 data on success.
- * @return BUFFER_E when there is not enough data to parse.
- * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
- */
- int GetSet_ex(const byte* input, word32* inOutIdx, int* len,
- word32 maxIdx, int check)
- {
- return GetASNHeader_ex(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
- maxIdx, check);
- }
- #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_OCSP)
- /* Decode the BER/DER encoded NULL.
- *
- * No data in a NULL ASN.1 item.
- * Ensure that the all fields are as expected and move index past the element.
- *
- * @param [in] input Buffer holding DER/BER encoded data.
- * @param [in, out] inOutIdx On in, starting index of NULL item.
- * On out, end of parsed NULL item.
- * @param [in] maxIdx Length of data in buffer.
- * @return 0 on success.
- * @return BUFFER_E when there is not enough data to parse.
- * @return ASN_TAG_NULL_E when the NULL tag is not found.
- * @return ASN_EXPECT_0_E when the length is not zero.
- */
- static int GetASNNull(const byte* input, word32* inOutIdx, word32 maxIdx)
- {
- int ret = 0;
- word32 idx = *inOutIdx;
- /* Check buffer has enough data for a NULL item. */
- if ((idx + 2) > maxIdx) {
- ret = BUFFER_E;
- }
- /* Check the tag is NULL. */
- if ((ret == 0) && (input[idx++] != ASN_TAG_NULL)) {
- ret = ASN_TAG_NULL_E;
- }
- /* Check the length is zero. */
- if ((ret == 0) && (input[idx++] != 0)) {
- ret = ASN_EXPECT_0_E;
- }
- if (ret == 0) {
- /* Return the index after NULL tag. */
- *inOutIdx = idx;
- }
- /* Return error code. */
- return ret;
- }
- #endif
- #ifndef WOLFSSL_ASN_TEMPLATE
- /* Set the DER/BER encoding of the ASN.1 NULL element.
- *
- * output Buffer to write into.
- * returns the number of bytes added to the buffer.
- */
- static int SetASNNull(byte* output)
- {
- output[0] = ASN_TAG_NULL;
- output[1] = 0;
- return 2;
- }
- #endif
- #ifndef NO_CERTS
- #ifndef WOLFSSL_ASN_TEMPLATE
- /* Get the DER/BER encoding of an ASN.1 BOOLEAN.
- *
- * input Buffer holding DER/BER encoded data.
- * inOutIdx Current index into buffer to parse.
- * maxIdx Length of data in buffer.
- * returns BUFFER_E when there is not enough data to parse.
- * ASN_PARSE_E when the BOOLEAN tag is not found or length is not 1.
- * Otherwise, 0 to indicate the value was false and 1 to indicate true.
- */
- static int GetBoolean(const byte* input, word32* inOutIdx, word32 maxIdx)
- {
- word32 idx = *inOutIdx;
- byte b;
- if ((idx + 3) > maxIdx)
- return BUFFER_E;
- b = input[idx++];
- if (b != ASN_BOOLEAN)
- return ASN_PARSE_E;
- if (input[idx++] != 1)
- return ASN_PARSE_E;
- b = input[idx++] != 0;
- *inOutIdx = idx;
- return b;
- }
- #endif
- #endif /* !NO_CERTS*/
- /* Decode the header of a BER/DER encoded OCTET STRING.
- *
- * @param [in] input Buffer holding DER/BER encoded data.
- * @param [in, out] inOutIdx On in, starting index of header.
- * On out, end of parsed header.
- * @param [out] len Number of bytes in the ASN.1 data.
- * @param [in] maxIdx Length of data in buffer.
- * @return Number of bytes in the ASN.1 data on success.
- * @return BUFFER_E when there is not enough data to parse.
- * @return ASN_PARSE_E when the tag is not a OCTET STRING or length is invalid.
- */
- int GetOctetString(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
- {
- return GetASNHeader(input, ASN_OCTET_STRING, inOutIdx, len, maxIdx);
- }
- #ifndef WOLFSSL_ASN_TEMPLATE
- /* Get the DER/BER encoding of an ASN.1 INTEGER header.
- *
- * Removes the leading zero byte when found.
- *
- * input Buffer holding DER/BER encoded data.
- * inOutIdx Current index into buffer to parse.
- * len The number of bytes in the ASN.1 data (excluding any leading zero).
- * maxIdx Length of data in buffer.
- * returns BUFFER_E when there is not enough data to parse.
- * ASN_PARSE_E when the INTEGER tag is not found, length is invalid,
- * or invalid use of or missing leading zero.
- * Otherwise, 0 to indicate success.
- */
- static int GetASNInt(const byte* input, word32* inOutIdx, int* len,
- word32 maxIdx)
- {
- int ret;
- ret = GetASNHeader(input, ASN_INTEGER, inOutIdx, len, maxIdx);
- if (ret < 0)
- return ret;
- if (*len > 0) {
- #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
- /* check for invalid padding on negative integer.
- * c.f. X.690 (ISO/IEC 8825-2:2003 (E)) 10.4.6; RFC 5280 4.1
- */
- if (*len > 1) {
- if ((input[*inOutIdx] == 0xff) && (input[*inOutIdx + 1] & 0x80))
- return ASN_PARSE_E;
- }
- #endif
- /* remove leading zero, unless there is only one 0x00 byte */
- if ((input[*inOutIdx] == 0x00) && (*len > 1)) {
- (*inOutIdx)++;
- (*len)--;
- #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
- if (*len > 0 && (input[*inOutIdx] & 0x80) == 0)
- return ASN_PARSE_E;
- #endif
- }
- }
- return 0;
- }
- #ifndef NO_CERTS
- /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
- * 7 bits.
- *
- * input Buffer holding DER/BER encoded data.
- * inOutIdx Current index into buffer to parse.
- * maxIdx Length of data in buffer.
- * returns BUFFER_E when there is not enough data to parse.
- * ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
- * Otherwise, the 7-bit value.
- */
- static int GetInteger7Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
- {
- word32 idx = *inOutIdx;
- byte b;
- if ((idx + 3) > maxIdx)
- return BUFFER_E;
- if (GetASNTag(input, &idx, &b, maxIdx) != 0)
- return ASN_PARSE_E;
- if (b != ASN_INTEGER)
- return ASN_PARSE_E;
- if (input[idx++] != 1)
- return ASN_PARSE_E;
- b = input[idx++];
- *inOutIdx = idx;
- return b;
- }
- #endif /* !NO_CERTS */
- #if defined(WC_RSA_PSS) && !defined(NO_RSA)
- /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
- * 16 bits.
- *
- * input Buffer holding DER/BER encoded data.
- * inOutIdx Current index into buffer to parse.
- * maxIdx Length of data in buffer.
- * returns BUFFER_E when there is not enough data to parse.
- * ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
- * Otherwise, the 16-bit value.
- */
- static int GetInteger16Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
- {
- word32 idx = *inOutIdx;
- byte tag;
- word16 n;
- if ((idx + 2) > maxIdx)
- return BUFFER_E;
- if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
- return ASN_PARSE_E;
- if (tag != ASN_INTEGER)
- return ASN_PARSE_E;
- if (input[idx] == 1) {
- idx++;
- if ((idx + 1) > maxIdx) {
- return ASN_PARSE_E;
- }
- n = input[idx++];
- }
- else if (input[idx] == 2) {
- idx++;
- if ((idx + 2) > maxIdx) {
- return ASN_PARSE_E;
- }
- n = input[idx++];
- n = (n << 8) | input[idx++];
- }
- else
- return ASN_PARSE_E;
- *inOutIdx = idx;
- return n;
- }
- #endif /* WC_RSA_PSS && !NO_RSA */
- #endif /* !WOLFSSL_ASN_TEMPLATE */
- #if !defined(NO_DSA) && !defined(NO_SHA)
- static const char sigSha1wDsaName[] = "SHAwDSA";
- static const char sigSha256wDsaName[] = "SHA256wDSA";
- #endif /* NO_DSA */
- #ifndef NO_RSA
- #ifdef WOLFSSL_MD2
- static const char sigMd2wRsaName[] = "md2WithRSAEncryption";
- #endif
- #ifndef NO_MD5
- static const char sigMd5wRsaName[] = "md5WithRSAEncryption";
- #endif
- #ifndef NO_SHA
- static const char sigSha1wRsaName[] = "sha1WithRSAEncryption";
- #endif
- #ifdef WOLFSSL_SHA224
- static const char sigSha224wRsaName[] = "sha224WithRSAEncryption";
- #endif
- #ifndef NO_SHA256
- static const char sigSha256wRsaName[] = "sha256WithRSAEncryption";
- #endif
- #ifdef WOLFSSL_SHA384
- static const char sigSha384wRsaName[] = "sha384WithRSAEncryption";
- #endif
- #ifdef WOLFSSL_SHA512
- static const char sigSha512wRsaName[] = "sha512WithRSAEncryption";
- #endif
- #ifdef WOLFSSL_SHA3
- #ifndef WOLFSSL_NOSHA3_224
- static const char sigSha3_224wRsaName[] = "sha3_224WithRSAEncryption";
- #endif
- #ifndef WOLFSSL_NOSHA3_256
- static const char sigSha3_256wRsaName[] = "sha3_256WithRSAEncryption";
- #endif
- #ifndef WOLFSSL_NOSHA3_384
- static const char sigSha3_384wRsaName[] = "sha3_384WithRSAEncryption";
- #endif
- #ifndef WOLFSSL_NOSHA3_512
- static const char sigSha3_512wRsaName[] = "sha3_512WithRSAEncryption";
- #endif
- #endif
- #ifdef WC_RSA_PSS
- static const char sigRsaSsaPssName[] = "rsassaPss";
- #endif
- #endif /* NO_RSA */
- #ifdef HAVE_ECC
- #ifndef NO_SHA
- static const char sigSha1wEcdsaName[] = "SHAwECDSA";
- #endif
- #ifdef WOLFSSL_SHA224
- static const char sigSha224wEcdsaName[] = "SHA224wECDSA";
- #endif
- #ifndef NO_SHA256
- static const char sigSha256wEcdsaName[] = "SHA256wECDSA";
- #endif
- #ifdef WOLFSSL_SHA384
- static const char sigSha384wEcdsaName[] = "SHA384wECDSA";
- #endif
- #ifdef WOLFSSL_SHA512
- static const char sigSha512wEcdsaName[] = "SHA512wECDSA";
- #endif
- #ifdef WOLFSSL_SHA3
- #ifndef WOLFSSL_NOSHA3_224
- static const char sigSha3_224wEcdsaName[] = "SHA3_224wECDSA";
- #endif
- #ifndef WOLFSSL_NOSHA3_256
- static const char sigSha3_256wEcdsaName[] = "SHA3_256wECDSA";
- #endif
- #ifndef WOLFSSL_NOSHA3_384
- static const char sigSha3_384wEcdsaName[] = "SHA3_384wECDSA";
- #endif
- #ifndef WOLFSSL_NOSHA3_512
- static const char sigSha3_512wEcdsaName[] = "SHA3_512wECDSA";
- #endif
- #endif
- #endif /* HAVE_ECC */
- static const char sigUnknownName[] = "Unknown";
- /* Get the human readable string for a signature type
- *
- * oid Oid value for signature
- */
- const char* GetSigName(int oid) {
- switch (oid) {
- #if !defined(NO_DSA) && !defined(NO_SHA)
- case CTC_SHAwDSA:
- return sigSha1wDsaName;
- case CTC_SHA256wDSA:
- return sigSha256wDsaName;
- #endif /* NO_DSA && NO_SHA */
- #ifndef NO_RSA
- #ifdef WOLFSSL_MD2
- case CTC_MD2wRSA:
- return sigMd2wRsaName;
- #endif
- #ifndef NO_MD5
- case CTC_MD5wRSA:
- return sigMd5wRsaName;
- #endif
- #ifndef NO_SHA
- case CTC_SHAwRSA:
- return sigSha1wRsaName;
- #endif
- #ifdef WOLFSSL_SHA224
- case CTC_SHA224wRSA:
- return sigSha224wRsaName;
- #endif
- #ifndef NO_SHA256
- case CTC_SHA256wRSA:
- return sigSha256wRsaName;
- #endif
- #ifdef WOLFSSL_SHA384
- case CTC_SHA384wRSA:
- return sigSha384wRsaName;
- #endif
- #ifdef WOLFSSL_SHA512
- case CTC_SHA512wRSA:
- return sigSha512wRsaName;
- #endif
- #ifdef WOLFSSL_SHA3
- #ifndef WOLFSSL_NOSHA3_224
- case CTC_SHA3_224wRSA:
- return sigSha3_224wRsaName;
- #endif
- #ifndef WOLFSSL_NOSHA3_256
- case CTC_SHA3_256wRSA:
- return sigSha3_256wRsaName;
- #endif
- #ifndef WOLFSSL_NOSHA3_384
- case CTC_SHA3_384wRSA:
- return sigSha3_384wRsaName;
- #endif
- #ifndef WOLFSSL_NOSHA3_512
- case CTC_SHA3_512wRSA:
- return sigSha3_512wRsaName;
- #endif
- #endif
- #ifdef WC_RSA_PSS
- case CTC_RSASSAPSS:
- return sigRsaSsaPssName;
- #endif
- #endif /* NO_RSA */
- #ifdef HAVE_ECC
- #ifndef NO_SHA
- case CTC_SHAwECDSA:
- return sigSha1wEcdsaName;
- #endif
- #ifdef WOLFSSL_SHA224
- case CTC_SHA224wECDSA:
- return sigSha224wEcdsaName;
- #endif
- #ifndef NO_SHA256
- case CTC_SHA256wECDSA:
- return sigSha256wEcdsaName;
- #endif
- #ifdef WOLFSSL_SHA384
- case CTC_SHA384wECDSA:
- return sigSha384wEcdsaName;
- #endif
- #ifdef WOLFSSL_SHA512
- case CTC_SHA512wECDSA:
- return sigSha512wEcdsaName;
- #endif
- #ifdef WOLFSSL_SHA3
- #ifndef WOLFSSL_NOSHA3_224
- case CTC_SHA3_224wECDSA:
- return sigSha3_224wEcdsaName;
- #endif
- #ifndef WOLFSSL_NOSHA3_256
- case CTC_SHA3_256wECDSA:
- return sigSha3_256wEcdsaName;
- #endif
- #ifndef WOLFSSL_NOSHA3_384
- case CTC_SHA3_384wECDSA:
- return sigSha3_384wEcdsaName;
- #endif
- #ifndef WOLFSSL_NOSHA3_512
- case CTC_SHA3_512wECDSA:
- return sigSha3_512wEcdsaName;
- #endif
- #endif
- #endif /* HAVE_ECC */
- default:
- return sigUnknownName;
- }
- }
- #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7) || \
- defined(OPENSSL_EXTRA)
- #if !defined(NO_DSA) || defined(HAVE_ECC) || !defined(NO_CERTS) || \
- (!defined(NO_RSA) && \
- (defined(WOLFSSL_CERT_GEN) || \
- ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA))))
- /* Set the DER/BER encoding of the ASN.1 INTEGER header.
- *
- * When output is NULL, calculate the header length only.
- *
- * @param [in] len Length of INTEGER data in bytes.
- * @param [in] firstByte First byte of data, most significant byte of integer,
- * to encode.
- * @param [out] output Buffer to write into.
- * @return Number of bytes added to the buffer.
- */
- int SetASNInt(int len, byte firstByte, byte* output)
- {
- int idx = 0;
- if (output) {
- /* Write out tag. */
- output[idx] = ASN_INTEGER;
- }
- /* Step over tag. */
- idx += ASN_TAG_SZ;
- /* Check if first byte has top bit set in which case a 0 is needed to
- * maintain positive value. */
- if (firstByte & 0x80) {
- /* Add pre-prepended byte to length of data in INTEGER. */
- len++;
- }
- /* Encode length - passing NULL for output will not encode. */
- idx += (int)SetLength((word32)len, output ? output + idx : NULL);
- /* Put out pre-pended 0 as well. */
- if (firstByte & 0x80) {
- if (output) {
- /* Write out 0 byte. */
- output[idx] = 0x00;
- }
- /* Update index. */
- idx++;
- }
- /* Return index after header. */
- return idx;
- }
- #endif
- #endif
- #ifndef WOLFSSL_ASN_TEMPLATE
- #if !defined(NO_DSA) || defined(HAVE_ECC) || (defined(WOLFSSL_CERT_GEN) && \
- !defined(NO_RSA)) || ((defined(WOLFSSL_KEY_GEN) || \
- (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)) || \
- defined(OPENSSL_EXTRA)) && !defined(NO_RSA) && !defined(HAVE_USER_RSA))
- /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int.
- * The number is assumed to be positive.
- *
- * n Multi-precision integer to encode.
- * maxSz Maximum size of the encoded integer.
- * A negative value indicates no check of length requested.
- * output Buffer to write into.
- * returns BUFFER_E when the data is too long for the buffer.
- * MP_TO_E when encoding the integer fails.
- * Otherwise, the number of bytes added to the buffer.
- */
- static int SetASNIntMP(mp_int* n, int maxSz, byte* output)
- {
- int idx = 0;
- int leadingBit;
- int length;
- leadingBit = mp_leading_bit(n);
- length = mp_unsigned_bin_size(n);
- if (maxSz >= 0 && (1 + length + (leadingBit ? 1 : 0)) > maxSz)
- return BUFFER_E;
- idx = SetASNInt(length, (byte)(leadingBit ? 0x80U : 0x00U), output);
- if (maxSz >= 0 && (idx + length) > maxSz)
- return BUFFER_E;
- if (output) {
- int err = mp_to_unsigned_bin(n, output + idx);
- if (err != MP_OKAY)
- return MP_TO_E;
- }
- idx += length;
- return idx;
- }
- #endif
- #if !defined(NO_RSA) && defined(HAVE_USER_RSA) && \
- (defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA))
- /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int from
- * an RSA key.
- * The number is assumed to be positive.
- *
- * n Multi-precision integer to encode.
- * output Buffer to write into.
- * returns BUFFER_E when the data is too long for the buffer.
- * MP_TO_E when encoding the integer fails.
- * Otherwise, the number of bytes added to the buffer.
- */
- static int SetASNIntRSA(void* n, byte* output)
- {
- int idx = 0;
- int leadingBit;
- int length;
- leadingBit = wc_Rsa_leading_bit(n);
- length = wc_Rsa_unsigned_bin_size(n);
- idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output);
- if ((idx + length) > MAX_RSA_INT_SZ)
- return BUFFER_E;
- if (output) {
- int err = wc_Rsa_to_unsigned_bin(n, output + idx, length);
- if (err != MP_OKAY)
- return MP_TO_E;
- }
- idx += length;
- return idx;
- }
- #endif /* !NO_RSA && HAVE_USER_RSA && WOLFSSL_CERT_GEN */
- #endif /* !WOLFSSL_ASN_TEMPLATE */
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for an INTEGER. */
- static const ASNItem intASN[] = {
- /* INT */ { 0, ASN_INTEGER, 0, 0, 0 }
- };
- enum {
- INTASN_IDX_INT = 0
- };
- /* Number of items in ASN.1 template for an INTEGER. */
- #define intASN_Length (sizeof(intASN) / sizeof(ASNItem))
- #endif /* WOLFSSL_ASN_TEMPLATE */
- /* Windows header clash for WinCE using GetVersion */
- /* Decode Version - one byte INTEGER.
- *
- * @param [in] input Buffer of BER data.
- * @param [in, out] inOutIdx On in, start of encoded Version.
- * On out, start of next encode ASN.1 item.
- * @param [out] version Number encoded in INTEGER.
- * @param [in] maxIdx Maximum index of data in buffer.
- * @return 0 on success.
- * @return ASN_PARSE_E when encoding is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_EXPECT_0_E when the most significant bit is set.
- */
- int GetMyVersion(const byte* input, word32* inOutIdx,
- int* version, word32 maxIdx)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = *inOutIdx;
- byte tag;
- if ((idx + MIN_VERSION_SZ) > maxIdx)
- return ASN_PARSE_E;
- if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
- return ASN_PARSE_E;
- if (tag != ASN_INTEGER)
- return ASN_PARSE_E;
- if (input[idx++] != 0x01)
- return ASN_VERSION_E;
- *version = input[idx++];
- *inOutIdx = idx;
- return *version;
- #else
- ASNGetData dataASN[intASN_Length];
- int ret;
- byte num;
- /* Clear dynamic data and set the version number variable. */
- XMEMSET(dataASN, 0, sizeof(dataASN));
- GetASN_Int8Bit(&dataASN[INTASN_IDX_INT], &num);
- /* Decode the version (INTEGER). */
- ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
- maxIdx);
- if (ret == 0) {
- /* Return version through variable and return value. */
- *version = num;
- ret = num;
- }
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #ifndef NO_PWDBASED
- /* Decode small integer, 32 bits or less.
- *
- * @param [in] input Buffer of BER data.
- * @param [in, out] inOutIdx On in, start of encoded INTEGER.
- * On out, start of next encode ASN.1 item.
- * @param [out] number Number encoded in INTEGER.
- * @param [in] maxIdx Maximum index of data in buffer.
- * @return 0 on success.
- * @return ASN_PARSE_E when encoding is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_EXPECT_0_E when the most significant bit is set.
- */
- int GetShortInt(const byte* input, word32* inOutIdx, int* number, word32 maxIdx)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = *inOutIdx;
- word32 len;
- byte tag;
- *number = 0;
- /* check for type and length bytes */
- if ((idx + 2) > maxIdx)
- return BUFFER_E;
- if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
- return ASN_PARSE_E;
- if (tag != ASN_INTEGER)
- return ASN_PARSE_E;
- len = input[idx++];
- if (len > 4)
- return ASN_PARSE_E;
- if (len + idx > maxIdx)
- return ASN_PARSE_E;
- while (len--) {
- *number = *number << 8 | input[idx++];
- }
- *inOutIdx = idx;
- return *number;
- #else
- ASNGetData dataASN[intASN_Length];
- int ret;
- word32 num;
- /* Clear dynamic data and set the 32-bit number variable. */
- XMEMSET(dataASN, 0, sizeof(dataASN));
- GetASN_Int32Bit(&dataASN[INTASN_IDX_INT], &num);
- /* Decode the short int (INTEGER). */
- ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
- maxIdx);
- if (ret == 0) {
- /* Return number through variable and return value. */
- *number = (int)num;
- ret = (int)num;
- }
- return ret;
- #endif
- }
- #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS8) || \
- defined(HAVE_PKCS12)
- /* Set small integer, 32 bits or less. DER encoding with no leading 0s
- * returns total amount written including ASN tag and length byte on success */
- int SetShortInt(byte* input, word32* inOutIdx, word32 number, word32 maxIdx)
- {
- word32 idx = *inOutIdx;
- int len = 0;
- int i;
- byte ar[MAX_LENGTH_SZ];
- /* check for room for type and length bytes */
- if ((idx + 2) > maxIdx)
- return BUFFER_E;
- input[idx++] = ASN_INTEGER;
- idx++; /* place holder for length byte */
- if (MAX_LENGTH_SZ + idx > maxIdx)
- return ASN_PARSE_E;
- /* find first non zero byte */
- XMEMSET(ar, 0, MAX_LENGTH_SZ);
- c32toa(number, ar);
- for (i = 0; i < MAX_LENGTH_SZ; i++) {
- if (ar[i] != 0) {
- break;
- }
- }
- /* handle case of 0 */
- if (i == MAX_LENGTH_SZ) {
- input[idx++] = 0; len++;
- }
- for (; i < MAX_LENGTH_SZ && idx < maxIdx; i++) {
- input[idx++] = ar[i]; len++;
- }
- /* jump back to beginning of input buffer using unaltered inOutIdx value
- * and set number of bytes for integer, then update the index value */
- input[*inOutIdx + 1] = (byte)len;
- *inOutIdx = idx;
- return len + 2; /* size of integer bytes plus ASN TAG and length byte */
- }
- #endif /* !WOLFSSL_ASN_TEMPLATE || HAVE_PKCS8 || HAVE_PKCS12 */
- #endif /* !NO_PWDBASED */
- #if !defined(WOLFSSL_ASN_TEMPLATE) && !defined(NO_CERTS)
- /* May not have one, not an error */
- static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version,
- word32 maxIdx)
- {
- word32 idx = *inOutIdx;
- byte tag;
- WOLFSSL_ENTER("GetExplicitVersion");
- if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
- return ASN_PARSE_E;
- if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
- int ret;
- *inOutIdx = ++idx; /* skip header */
- ret = GetMyVersion(input, inOutIdx, version, maxIdx);
- if (ret >= 0) {
- /* check if version is expected value rfc 5280 4.1 {0, 1, 2} */
- if (*version > MAX_X509_VERSION || *version < MIN_X509_VERSION) {
- WOLFSSL_MSG("Unexpected certificate version");
- WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
- ret = ASN_VERSION_E;
- }
- }
- return ret;
- }
- /* go back as is */
- *version = 0;
- return 0;
- }
- #endif
- /* Decode small integer, 32 bits or less.
- *
- * mp_int is initialized.
- *
- * @param [out] mpi mp_int to hold number.
- * @param [in] input Buffer of BER data.
- * @param [in, out] inOutIdx On in, start of encoded INTEGER.
- * On out, start of next encode ASN.1 item.
- * @param [in] maxIdx Maximum index of data in buffer.
- * @return 0 on success.
- * @return ASN_PARSE_E when encoding is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_EXPECT_0_E when the most significant bit is set.
- * @return MP_INIT_E when the unable to initialize an mp_int.
- * @return ASN_GETINT_E when the unable to convert data to an mp_int.
- */
- int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, word32 maxIdx)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = *inOutIdx;
- int ret;
- int length;
- ret = GetASNInt(input, &idx, &length, maxIdx);
- if (ret != 0)
- return ret;
- if (mp_init(mpi) != MP_OKAY)
- return MP_INIT_E;
- if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) {
- mp_clear(mpi);
- return ASN_GETINT_E;
- }
- #ifdef HAVE_WOLF_BIGINT
- if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
- mp_clear(mpi);
- return ASN_GETINT_E;
- }
- #endif /* HAVE_WOLF_BIGINT */
- *inOutIdx = idx + (word32)length;
- return 0;
- #else
- ASNGetData dataASN[intASN_Length];
- /* Clear dynamic data and set the mp_int to fill with value. */
- XMEMSET(dataASN, 0, sizeof(dataASN));
- GetASN_MP_PosNeg(&dataASN[INTASN_IDX_INT], mpi);
- /* Decode the big number (INTEGER). */
- return GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
- maxIdx);
- #endif
- }
- #if (defined(HAVE_ECC) || !defined(NO_DSA)) && !defined(WOLFSSL_ASN_TEMPLATE)
- static int GetIntPositive(mp_int* mpi, const byte* input, word32* inOutIdx,
- word32 maxIdx, int initNum)
- {
- word32 idx = *inOutIdx;
- int ret;
- int length;
- ret = GetASNInt(input, &idx, &length, maxIdx);
- if (ret != 0)
- return ret;
- if (((input[idx] & 0x80) == 0x80) && (input[idx - 1] != 0x00))
- return MP_INIT_E;
- if (initNum) {
- if (mp_init(mpi) != MP_OKAY)
- return MP_INIT_E;
- }
- if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) {
- mp_clear(mpi);
- return ASN_GETINT_E;
- }
- #ifdef HAVE_WOLF_BIGINT
- if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
- mp_clear(mpi);
- return ASN_GETINT_E;
- }
- #endif /* HAVE_WOLF_BIGINT */
- *inOutIdx = idx + (word32)length;
- return 0;
- }
- #endif /* (ECC || !NO_DSA) && !WOLFSSL_ASN_TEMPLATE */
- #ifndef WOLFSSL_ASN_TEMPLATE
- #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA)) || !defined(NO_DSA)
- static int SkipInt(const byte* input, word32* inOutIdx, word32 maxIdx)
- {
- word32 idx = *inOutIdx;
- int ret;
- int length;
- ret = GetASNInt(input, &idx, &length, maxIdx);
- if (ret != 0)
- return ret;
- *inOutIdx = idx + (word32)length;
- return 0;
- }
- #endif
- #endif /* !WOLFSSL_ASN_TEMPLATE */
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for a BIT_STRING. */
- static const ASNItem bitStringASN[] = {
- /* BIT_STR */ { 0, ASN_BIT_STRING, 0, 1, 0 }
- };
- enum {
- BITSTRINGASN_IDX_BIT_STR = 0
- };
- /* Number of items in ASN.1 template for a BIT_STRING. */
- #define bitStringASN_Length (sizeof(bitStringASN) / sizeof(ASNItem))
- #endif
- /* Decode and check the BIT_STRING is valid. Return length and unused bits.
- *
- * @param [in] input Buffer holding BER encoding.
- * @param [in, out] inOutIdx On in, start of BIT_STRING.
- * On out, start of ASN.1 item after BIT_STRING.
- * @param [out] len Length of BIT_STRING data.
- * @param [in] maxIdx Maximum index of data in buffer.
- * @param [in] zeroBits Indicates whether zero unused bits is expected.
- * @param [in] unusedBits Number of unused bits in last byte.
- * @return 0 on success.
- * @return ASN_PARSE_E when encoding is invalid.
- * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_EXPECT_0_E when unused bits is not zero when expected.
- */
- int CheckBitString(const byte* input, word32* inOutIdx, int* len,
- word32 maxIdx, int zeroBits, byte* unusedBits)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = *inOutIdx;
- int length;
- byte b;
- if (GetASNTag(input, &idx, &b, maxIdx) != 0) {
- return ASN_BITSTR_E;
- }
- if (b != ASN_BIT_STRING) {
- return ASN_BITSTR_E;
- }
- if (GetLength(input, &idx, &length, maxIdx) < 0)
- return ASN_PARSE_E;
- /* extra sanity check that length is greater than 0 */
- if (length <= 0) {
- WOLFSSL_MSG("Error length was 0 in CheckBitString");
- return BUFFER_E;
- }
- if (idx + 1 > maxIdx) {
- WOLFSSL_MSG("Attempted buffer read larger than input buffer");
- return BUFFER_E;
- }
- b = input[idx];
- if (zeroBits && b != 0x00)
- return ASN_EXPECT_0_E;
- if (b >= 0x08)
- return ASN_PARSE_E;
- if (b != 0) {
- if ((byte)(input[idx + (word32)length - 1] << (8 - b)) != 0)
- return ASN_PARSE_E;
- }
- idx++;
- length--; /* length has been checked for greater than 0 */
- *inOutIdx = idx;
- if (len != NULL)
- *len = length;
- if (unusedBits != NULL)
- *unusedBits = b;
- return 0;
- #else
- ASNGetData dataASN[bitStringASN_Length];
- int ret;
- int bits;
- /* Parse BIT_STRING and check validity of unused bits. */
- XMEMSET(dataASN, 0, sizeof(dataASN));
- /* Decode BIT_STRING. */
- ret = GetASN_Items(bitStringASN, dataASN, bitStringASN_Length, 0, input,
- inOutIdx, maxIdx);
- if (ret == 0) {
- /* Get unused bits from dynamic ASN.1 data. */
- bits = GetASNItem_UnusedBits(dataASN[BITSTRINGASN_IDX_BIT_STR]);
- /* Check unused bits is 0 when expected. */
- if (zeroBits && (bits != 0)) {
- ret = ASN_EXPECT_0_E;
- }
- }
- if (ret == 0) {
- /* Return length of data and unused bits if required. */
- if (len != NULL) {
- *len = (int)dataASN[BITSTRINGASN_IDX_BIT_STR].data.ref.length;
- }
- if (unusedBits != NULL) {
- *unusedBits = (byte)bits;
- }
- }
- return ret;
- #endif
- }
- /* RSA (with CertGen or KeyGen) OR ECC OR ED25519 OR ED448 (with CertGen or
- * KeyGen) */
- #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
- (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
- defined(OPENSSL_EXTRA))) || \
- (defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)) || \
- ((defined(HAVE_ED25519) || defined(HAVE_ED448)) && \
- (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
- defined(OPENSSL_EXTRA))) || \
- (defined(WC_ENABLE_ASYM_KEY_EXPORT) && !defined(NO_CERT)) || \
- (!defined(NO_DSA) && !defined(HAVE_SELFTEST) && defined(WOLFSSL_KEY_GEN)) || \
- (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA))
- /* Set the DER/BER encoding of the ASN.1 BIT STRING header.
- *
- * When output is NULL, calculate the header length only.
- *
- * @param [in] len Length of BIT STRING data.
- * That is, the number of least significant zero bits
- * before a one.
- * The last byte is the most-significant non-zero byte
- * of a number.
- * @param [out] output Buffer to write into.
- * @return Number of bytes added to the buffer.
- */
- word32 SetBitString(word32 len, byte unusedBits, byte* output)
- {
- word32 idx = 0;
- if (output) {
- /* Write out tag. */
- output[idx] = ASN_BIT_STRING;
- }
- /* Step over tag. */
- idx += ASN_TAG_SZ;
- /* Encode length - passing NULL for output will not encode.
- * Add one to length for unused bits. */
- idx += SetLength(len + 1, output ? output + idx : NULL);
- if (output) {
- /* Write out unused bits. */
- output[idx] = unusedBits;
- }
- /* Skip over unused bits. */
- idx++;
- /* Return index after header. */
- return idx;
- }
- #endif /* !NO_RSA || HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
- #ifdef ASN_BER_TO_DER
- /* Convert BER to DER */
- /* Pull informtation from the ASN.1 BER encoded item header */
- static int GetBerHeader(const byte* data, word32* idx, word32 maxIdx,
- byte* pTag, word32* pLen, int* indef)
- {
- int len = 0;
- byte tag;
- word32 i = *idx;
- *indef = 0;
- /* Check there is enough data for a minimal header */
- if (i + 2 > maxIdx) {
- return ASN_PARSE_E;
- }
- /* Retrieve tag */
- tag = data[i++];
- /* Indefinite length handled specially */
- if (data[i] == ASN_INDEF_LENGTH) {
- /* Check valid tag for indefinite */
- if (((tag & 0xc0) == 0) && ((tag & ASN_CONSTRUCTED) == 0x00)) {
- return ASN_PARSE_E;
- }
- i++;
- *indef = 1;
- }
- else if (GetLength(data, &i, &len, maxIdx) < 0) {
- return ASN_PARSE_E;
- }
- /* Return tag, length and index after BER item header */
- *pTag = tag;
- *pLen = (word32)len;
- *idx = i;
- return 0;
- }
- #ifndef INDEF_ITEMS_MAX
- #define INDEF_ITEMS_MAX 20
- #endif
- /* Indef length item data */
- typedef struct Indef {
- word32 start;
- int depth;
- int headerLen;
- word32 len;
- } Indef;
- /* Indef length items */
- typedef struct IndefItems
- {
- Indef len[INDEF_ITEMS_MAX];
- int cnt;
- int idx;
- int depth;
- } IndefItems;
- /* Get header length of current item */
- static int IndefItems_HeaderLen(IndefItems* items)
- {
- return items->len[items->idx].headerLen;
- }
- /* Get data length of current item */
- static word32 IndefItems_Len(IndefItems* items)
- {
- return items->len[items->idx].len;
- }
- /* Add a indefinite length item */
- static int IndefItems_AddItem(IndefItems* items, word32 start)
- {
- int ret = 0;
- int i;
- if (items->cnt == INDEF_ITEMS_MAX) {
- ret = MEMORY_E;
- }
- else {
- i = items->cnt++;
- items->len[i].start = start;
- items->len[i].depth = items->depth++;
- items->len[i].headerLen = 1;
- items->len[i].len = 0;
- items->idx = i;
- }
- return ret;
- }
- /* Increase data length of current item */
- static void IndefItems_AddData(IndefItems* items, word32 length)
- {
- items->len[items->idx].len += length;
- }
- /* Update header length of current item to reflect data length */
- static void IndefItems_UpdateHeaderLen(IndefItems* items)
- {
- items->len[items->idx].headerLen +=
- (int)SetLength(items->len[items->idx].len, NULL);
- }
- /* Go to indefinite parent of current item */
- static void IndefItems_Up(IndefItems* items)
- {
- int i;
- int depth = items->len[items->idx].depth - 1;
- for (i = items->cnt - 1; i >= 0; i--) {
- if (items->len[i].depth == depth) {
- break;
- }
- }
- items->idx = i;
- items->depth = depth + 1;
- }
- /* Calculate final length by adding length of indefinite child items */
- static void IndefItems_CalcLength(IndefItems* items)
- {
- int i;
- int idx = items->idx;
- for (i = idx + 1; i < items->cnt; i++) {
- if (items->len[i].depth == items->depth) {
- items->len[idx].len += (word32)items->len[i].headerLen;
- items->len[idx].len += items->len[i].len;
- }
- }
- items->len[idx].headerLen += (int)SetLength(items->len[idx].len, NULL);
- }
- /* Add more data to indefinite length item */
- static void IndefItems_MoreData(IndefItems* items, word32 length)
- {
- if (items->cnt > 0 && items->idx >= 0) {
- items->len[items->idx].len += length;
- }
- }
- /* Convert a BER encoding with indefinite length items to DER.
- *
- * ber BER encoded data.
- * berSz Length of BER encoded data.
- * der Buffer to hold DER encoded version of data.
- * NULL indicates only the length is required.
- * derSz The size of the buffer to hold the DER encoded data.
- * Will be set if der is NULL, otherwise the value is checked as der is
- * filled.
- * returns ASN_PARSE_E if the BER data is invalid and BAD_FUNC_ARG if ber or
- * derSz are NULL.
- */
- int wc_BerToDer(const byte* ber, word32 berSz, byte* der, word32* derSz)
- {
- int ret = 0;
- word32 i, j;
- #ifdef WOLFSSL_SMALL_STACK
- IndefItems* indefItems = NULL;
- #else
- IndefItems indefItems[1];
- #endif
- byte tag, basic;
- word32 length;
- int indef;
- if (ber == NULL || derSz == NULL)
- return BAD_FUNC_ARG;
- #ifdef WOLFSSL_SMALL_STACK
- indefItems = (IndefItems *)XMALLOC(sizeof(IndefItems), NULL,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (indefItems == NULL) {
- ret = MEMORY_E;
- goto end;
- }
- #endif
- XMEMSET(indefItems, 0, sizeof(*indefItems));
- /* Calculate indefinite item lengths */
- for (i = 0; i < berSz; ) {
- word32 start = i;
- /* Get next BER item */
- ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
- if (ret != 0) {
- goto end;
- }
- if (indef) {
- /* Indefinite item - add to list */
- ret = IndefItems_AddItem(indefItems, i);
- if (ret != 0) {
- goto end;
- }
- if ((tag & 0xC0) == 0 &&
- tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
- tag != (ASN_SET | ASN_CONSTRUCTED)) {
- /* Constructed basic type - get repeating tag */
- basic = (byte)(tag & (~ASN_CONSTRUCTED));
- /* Add up lengths of each item below */
- for (; i < berSz; ) {
- /* Get next BER_item */
- ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
- if (ret != 0) {
- goto end;
- }
- /* End of content closes item */
- if (tag == ASN_EOC) {
- /* Must be zero length */
- if (length != 0) {
- ret = ASN_PARSE_E;
- goto end;
- }
- break;
- }
- /* Must not be indefinite and tag must match parent */
- if (indef || tag != basic) {
- ret = ASN_PARSE_E;
- goto end;
- }
- /* Add to length */
- IndefItems_AddData(indefItems, length);
- /* Skip data */
- i += length;
- }
- /* Ensure we got an EOC and not end of data */
- if (tag != ASN_EOC) {
- ret = ASN_PARSE_E;
- goto end;
- }
- /* Set the header length to include the length field */
- IndefItems_UpdateHeaderLen(indefItems);
- /* Go to indefinite parent item */
- IndefItems_Up(indefItems);
- }
- }
- else if (tag == ASN_EOC) {
- /* End-of-content must be 0 length */
- if (length != 0) {
- ret = ASN_PARSE_E;
- goto end;
- }
- /* Check there is an item to close - missing EOC */
- if (indefItems->depth == 0) {
- ret = ASN_PARSE_E;
- goto end;
- }
- /* Finish calculation of data length for indefinite item */
- IndefItems_CalcLength(indefItems);
- /* Go to indefinite parent item */
- IndefItems_Up(indefItems);
- }
- else {
- /* Known length item to add in - make sure enough data for it */
- if (i + length > berSz) {
- ret = ASN_PARSE_E;
- goto end;
- }
- /* Include all data - can't have indefinite inside definite */
- i += length;
- /* Add entire item to current indefinite item */
- IndefItems_MoreData(indefItems, i - start);
- }
- }
- /* Check we had a EOC for each indefinite item */
- if (indefItems->depth != 0) {
- ret = ASN_PARSE_E;
- goto end;
- }
- /* Write out DER */
- j = 0;
- /* Reset index */
- indefItems->idx = 0;
- for (i = 0; i < berSz; ) {
- word32 start = i;
- /* Get item - checked above */
- (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
- if (indef) {
- if (der != NULL) {
- /* Check enough space for header */
- if (j + (word32)IndefItems_HeaderLen(indefItems) > *derSz) {
- ret = BUFFER_E;
- goto end;
- }
- if ((tag & 0xC0) == 0 &&
- tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
- tag != (ASN_SET | ASN_CONSTRUCTED)) {
- /* Remove constructed tag for basic types */
- tag &= (byte)~ASN_CONSTRUCTED;
- }
- /* Add tag and length */
- der[j] = tag;
- (void)SetLength(IndefItems_Len(indefItems), der + j + 1);
- }
- /* Add header length of indefinite item */
- j += (word32)IndefItems_HeaderLen(indefItems);
- if ((tag & 0xC0) == 0 &&
- tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
- tag != (ASN_SET | ASN_CONSTRUCTED)) {
- /* For basic type - get each child item and add data */
- for (; i < berSz; ) {
- (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
- if (tag == ASN_EOC) {
- break;
- }
- if (der != NULL) {
- if (j + length > *derSz) {
- ret = BUFFER_E;
- goto end;
- }
- XMEMCPY(der + j, ber + i, length);
- }
- j += length;
- i += length;
- }
- }
- /* Move to next indef item in list */
- indefItems->idx++;
- }
- else if (tag == ASN_EOC) {
- /* End-Of-Content is not written out in DER */
- }
- else {
- /* Write out definite length item as is. */
- i += length;
- if (der != NULL) {
- /* Ensure space for item */
- if (j + i - start > *derSz) {
- ret = BUFFER_E;
- goto end;
- }
- /* Copy item as is */
- XMEMCPY(der + j, ber + start, i - start);
- }
- j += i - start;
- }
- }
- /* Return the length of the DER encoded ASN.1 */
- *derSz = j;
- if (der == NULL) {
- ret = LENGTH_ONLY_E;
- }
- end:
- #ifdef WOLFSSL_SMALL_STACK
- if (indefItems != NULL) {
- XFREE(indefItems, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- }
- #endif
- return ret;
- }
- #endif
- #ifndef WOLFSSL_ASN_TEMPLATE
- #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)
- /* Set the DER/BER encoding of the ASN.1 BIT_STRING with a 16-bit value.
- *
- * val 16-bit value to encode.
- * output Buffer to write into.
- * returns the number of bytes added to the buffer.
- */
- static word32 SetBitString16Bit(word16 val, byte* output)
- {
- word32 idx;
- int len;
- byte lastByte;
- byte unusedBits = 0;
- if ((val >> 8) != 0) {
- len = 2;
- lastByte = (byte)(val >> 8);
- }
- else {
- len = 1;
- lastByte = (byte)val;
- }
- while (((lastByte >> unusedBits) & 0x01) == 0x00)
- unusedBits++;
- idx = SetBitString((word32)len, unusedBits, output);
- output[idx++] = (byte)val;
- if (len > 1)
- output[idx++] = (byte)(val >> 8);
- return idx;
- }
- #endif /* WOLFSSL_CERT_EXT || WOLFSSL_CERT_GEN */
- #endif /* !WOLFSSL_ASN_TEMPLATE */
- /* hashType */
- #ifdef WOLFSSL_MD2
- static const byte hashMd2hOid[] = {42, 134, 72, 134, 247, 13, 2, 2};
- #endif
- #ifndef NO_MD5
- static const byte hashMd5hOid[] = {42, 134, 72, 134, 247, 13, 2, 5};
- #endif
- #ifndef NO_SHA
- static const byte hashSha1hOid[] = {43, 14, 3, 2, 26};
- #endif
- #ifdef WOLFSSL_SHA224
- static const byte hashSha224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 4};
- #endif
- #ifndef NO_SHA256
- static const byte hashSha256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 1};
- #endif
- #ifdef WOLFSSL_SHA384
- static const byte hashSha384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 2};
- #endif
- #ifdef WOLFSSL_SHA512
- static const byte hashSha512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 3};
- #ifndef WOLFSSL_NOSHA512_224
- static const byte hashSha512_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 5};
- #endif
- #ifndef WOLFSSL_NOSHA512_256
- static const byte hashSha512_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 6};
- #endif
- #endif
- #ifdef WOLFSSL_SHA3
- #ifndef WOLFSSL_NOSHA3_224
- static const byte hashSha3_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 7};
- #endif /* WOLFSSL_NOSHA3_224 */
- #ifndef WOLFSSL_NOSHA3_256
- static const byte hashSha3_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 8};
- #endif /* WOLFSSL_NOSHA3_256 */
- #ifndef WOLFSSL_NOSHA3_384
- static const byte hashSha3_384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 9};
- #endif /* WOLFSSL_NOSHA3_384 */
- #ifndef WOLFSSL_NOSHA3_512
- static const byte hashSha3_512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 10};
- #endif /* WOLFSSL_NOSHA3_512 */
- #endif /* WOLFSSL_SHA3 */
- /* hmacType */
- #ifndef NO_HMAC
- #ifdef WOLFSSL_SHA224
- static const byte hmacSha224Oid[] = {42, 134, 72, 134, 247, 13, 2, 8};
- #endif
- #ifndef NO_SHA256
- static const byte hmacSha256Oid[] = {42, 134, 72, 134, 247, 13, 2, 9};
- #endif
- #ifdef WOLFSSL_SHA384
- static const byte hmacSha384Oid[] = {42, 134, 72, 134, 247, 13, 2, 10};
- #endif
- #ifdef WOLFSSL_SHA512
- static const byte hmacSha512Oid[] = {42, 134, 72, 134, 247, 13, 2, 11};
- #endif
- #endif
- /* sigType */
- #if !defined(NO_DSA) && !defined(NO_SHA)
- static const byte sigSha1wDsaOid[] = {42, 134, 72, 206, 56, 4, 3};
- static const byte sigSha256wDsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 2};
- #endif /* NO_DSA */
- #ifndef NO_RSA
- #ifdef WOLFSSL_MD2
- static const byte sigMd2wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 2};
- #endif
- #ifndef NO_MD5
- static const byte sigMd5wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 4};
- #endif
- #ifndef NO_SHA
- static const byte sigSha1wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 5};
- #endif
- #ifdef WOLFSSL_SHA224
- static const byte sigSha224wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,14};
- #endif
- #ifndef NO_SHA256
- static const byte sigSha256wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,11};
- #endif
- #ifdef WOLFSSL_SHA384
- static const byte sigSha384wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,12};
- #endif
- #ifdef WOLFSSL_SHA512
- static const byte sigSha512wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,13};
- #endif
- #ifdef WOLFSSL_SHA3
- #ifndef WOLFSSL_NOSHA3_224
- static const byte sigSha3_224wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 13};
- #endif
- #ifndef WOLFSSL_NOSHA3_256
- static const byte sigSha3_256wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 14};
- #endif
- #ifndef WOLFSSL_NOSHA3_384
- static const byte sigSha3_384wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 15};
- #endif
- #ifndef WOLFSSL_NOSHA3_512
- static const byte sigSha3_512wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 16};
- #endif
- #endif
- #ifdef WC_RSA_PSS
- static const byte sigRsaSsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
- #endif
- #endif /* NO_RSA */
- #ifdef HAVE_ECC
- #ifndef NO_SHA
- static const byte sigSha1wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 1};
- #endif
- #ifdef WOLFSSL_SHA224
- static const byte sigSha224wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 1};
- #endif
- #ifndef NO_SHA256
- static const byte sigSha256wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 2};
- #endif
- #ifdef WOLFSSL_SHA384
- static const byte sigSha384wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 3};
- #endif
- #ifdef WOLFSSL_SHA512
- static const byte sigSha512wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 4};
- #endif
- #ifdef WOLFSSL_SHA3
- #ifndef WOLFSSL_NOSHA3_224
- static const byte sigSha3_224wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 9};
- #endif
- #ifndef WOLFSSL_NOSHA3_256
- static const byte sigSha3_256wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 10};
- #endif
- #ifndef WOLFSSL_NOSHA3_384
- static const byte sigSha3_384wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 11};
- #endif
- #ifndef WOLFSSL_NOSHA3_512
- static const byte sigSha3_512wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 12};
- #endif
- #endif
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- /* 0x2A, 0x81, 0x1C, 0xCF, 0x55, 0x01, 0x83, 0x75 */
- static const byte sigSm3wSm2Oid[] = {42, 129, 28, 207, 85, 1, 131, 117};
- #endif
- #endif /* HAVE_ECC */
- #ifdef HAVE_ED25519
- static const byte sigEd25519Oid[] = {43, 101, 112};
- #endif /* HAVE_ED25519 */
- #ifdef HAVE_ED448
- static const byte sigEd448Oid[] = {43, 101, 113};
- #endif /* HAVE_ED448 */
- #ifdef HAVE_PQC
- #ifdef HAVE_FALCON
- /* Falcon Level 1: 1 3 9999 3 1 */
- static const byte sigFalcon_Level1Oid[] = {43, 206, 15, 3, 1};
- /* Falcon Level 5: 1 3 9999 3 4 */
- static const byte sigFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
- #endif /* HAVE_FACON */
- #ifdef HAVE_DILITHIUM
- /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
- static const byte sigDilithium_Level2Oid[] =
- {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};
- /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
- static const byte sigDilithium_Level3Oid[] =
- {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};
- /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
- static const byte sigDilithium_Level5Oid[] =
- {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
- #endif /* HAVE_DILITHIUM */
- #ifdef HAVE_SPHINCS
- /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
- static const byte sigSphincsFast_Level1Oid[] =
- {43, 206, 15, 6, 7, 4};
- /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
- static const byte sigSphincsFast_Level3Oid[] =
- {43, 206, 15, 6, 8, 3};
- /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
- static const byte sigSphincsFast_Level5Oid[] =
- {43, 206, 15, 6, 9, 3};
- /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
- static const byte sigSphincsSmall_Level1Oid[] =
- {43, 206, 15, 6, 7, 10};
- /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
- static const byte sigSphincsSmall_Level3Oid[] =
- {43, 206, 15, 6, 8, 7};
- /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
- static const byte sigSphincsSmall_Level5Oid[] =
- {43, 206, 15, 6, 9, 7};
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- /* keyType */
- #ifndef NO_DSA
- static const byte keyDsaOid[] = {42, 134, 72, 206, 56, 4, 1};
- #endif /* NO_DSA */
- #ifndef NO_RSA
- static const byte keyRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 1};
- #ifdef WC_RSA_PSS
- static const byte keyRsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
- #endif
- #endif /* NO_RSA */
- #ifdef HAVE_ECC
- static const byte keyEcdsaOid[] = {42, 134, 72, 206, 61, 2, 1};
- #endif /* HAVE_ECC */
- #ifdef HAVE_ED25519
- static const byte keyEd25519Oid[] = {43, 101, 112};
- #endif /* HAVE_ED25519 */
- #ifdef HAVE_CURVE25519
- static const byte keyCurve25519Oid[] = {43, 101, 110};
- #endif
- #ifdef HAVE_ED448
- static const byte keyEd448Oid[] = {43, 101, 113};
- #endif /* HAVE_ED448 */
- #ifdef HAVE_CURVE448
- static const byte keyCurve448Oid[] = {43, 101, 111};
- #endif /* HAVE_CURVE448 */
- #ifndef NO_DH
- static const byte keyDhOid[] = {42, 134, 72, 134, 247, 13, 1, 3, 1};
- #endif /* !NO_DH */
- #ifdef HAVE_PQC
- #ifdef HAVE_FALCON
- /* Falcon Level 1: 1 3 9999 3 1 */
- static const byte keyFalcon_Level1Oid[] = {43, 206, 15, 3, 1};
- /* Falcon Level 5: 1 3 9999 3 4 */
- static const byte keyFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
- #endif /* HAVE_FALCON */
- #ifdef HAVE_DILITHIUM
- /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
- static const byte keyDilithium_Level2Oid[] =
- {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};
- /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
- static const byte keyDilithium_Level3Oid[] =
- {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};
- /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
- static const byte keyDilithium_Level5Oid[] =
- {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
- #endif /* HAVE_DILITHIUM */
- #ifdef HAVE_SPHINCS
- /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
- static const byte keySphincsFast_Level1Oid[] =
- {43, 206, 15, 6, 7, 4};
- /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
- static const byte keySphincsFast_Level3Oid[] =
- {43, 206, 15, 6, 8, 3};
- /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
- static const byte keySphincsFast_Level5Oid[] =
- {43, 206, 15, 6, 9, 3};
- /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
- static const byte keySphincsSmall_Level1Oid[] =
- {43, 206, 15, 6, 7, 10};
- /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
- static const byte keySphincsSmall_Level3Oid[] =
- {43, 206, 15, 6, 8, 7};
- /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
- static const byte keySphincsSmall_Level5Oid[] =
- {43, 206, 15, 6, 9, 7};
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- /* curveType */
- #ifdef HAVE_ECC
- /* See "ecc_sets" table in ecc.c */
- #endif /* HAVE_ECC */
- #ifdef HAVE_AES_CBC
- /* blkType */
- #ifdef WOLFSSL_AES_128
- static const byte blkAes128CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 2};
- #endif
- #ifdef WOLFSSL_AES_192
- static const byte blkAes192CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 22};
- #endif
- #ifdef WOLFSSL_AES_256
- static const byte blkAes256CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 42};
- #endif
- #endif /* HAVE_AES_CBC */
- #ifdef HAVE_AESGCM
- #ifdef WOLFSSL_AES_128
- static const byte blkAes128GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 6};
- #endif
- #ifdef WOLFSSL_AES_192
- static const byte blkAes192GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 26};
- #endif
- #ifdef WOLFSSL_AES_256
- static const byte blkAes256GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 46};
- #endif
- #endif /* HAVE_AESGCM */
- #ifdef HAVE_AESCCM
- #ifdef WOLFSSL_AES_128
- static const byte blkAes128CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 7};
- #endif
- #ifdef WOLFSSL_AES_192
- static const byte blkAes192CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 27};
- #endif
- #ifdef WOLFSSL_AES_256
- static const byte blkAes256CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 47};
- #endif
- #endif /* HAVE_AESCCM */
- #ifndef NO_DES3
- static const byte blkDesCbcOid[] = {43, 14, 3, 2, 7};
- static const byte blkDes3CbcOid[] = {42, 134, 72, 134, 247, 13, 3, 7};
- #endif
- /* keyWrapType */
- #ifdef WOLFSSL_AES_128
- static const byte wrapAes128Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 5};
- #endif
- #ifdef WOLFSSL_AES_192
- static const byte wrapAes192Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 25};
- #endif
- #ifdef WOLFSSL_AES_256
- static const byte wrapAes256Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 45};
- #endif
- #ifdef HAVE_PKCS7
- /* From RFC 3211 */
- static const byte wrapPwriKekOid[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3,9};
- #endif
- /* cmsKeyAgreeType */
- #ifndef NO_SHA
- static const byte dhSinglePass_stdDH_sha1kdf_Oid[] =
- {43, 129, 5, 16, 134, 72, 63, 0, 2};
- #endif
- #ifdef WOLFSSL_SHA224
- static const byte dhSinglePass_stdDH_sha224kdf_Oid[] = {43, 129, 4, 1, 11, 0};
- #endif
- #ifndef NO_SHA256
- static const byte dhSinglePass_stdDH_sha256kdf_Oid[] = {43, 129, 4, 1, 11, 1};
- #endif
- #ifdef WOLFSSL_SHA384
- static const byte dhSinglePass_stdDH_sha384kdf_Oid[] = {43, 129, 4, 1, 11, 2};
- #endif
- #ifdef WOLFSSL_SHA512
- static const byte dhSinglePass_stdDH_sha512kdf_Oid[] = {43, 129, 4, 1, 11, 3};
- #endif
- /* ocspType */
- #ifdef HAVE_OCSP
- static const byte ocspBasicOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 1};
- static const byte ocspNonceOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 2};
- static const byte ocspNoCheckOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 5};
- #endif /* HAVE_OCSP */
- /* certExtType */
- static const byte extBasicCaOid[] = {85, 29, 19};
- static const byte extAltNamesOid[] = {85, 29, 17};
- static const byte extCrlDistOid[] = {85, 29, 31};
- static const byte extAuthInfoOid[] = {43, 6, 1, 5, 5, 7, 1, 1};
- static const byte extAuthKeyOid[] = {85, 29, 35};
- static const byte extSubjKeyOid[] = {85, 29, 14};
- static const byte extCertPolicyOid[] = {85, 29, 32};
- static const byte extKeyUsageOid[] = {85, 29, 15};
- static const byte extInhibitAnyOid[] = {85, 29, 54};
- static const byte extExtKeyUsageOid[] = {85, 29, 37};
- #ifndef IGNORE_NAME_CONSTRAINTS
- static const byte extNameConsOid[] = {85, 29, 30};
- #endif
- #ifdef HAVE_CRL
- static const byte extCrlNumberOid[] = {85, 29, 20};
- #endif
- #ifdef WOLFSSL_SUBJ_DIR_ATTR
- static const byte extSubjDirAttrOid[] = {85, 29, 9};
- #endif
- #ifdef WOLFSSL_SUBJ_INFO_ACC
- static const byte extSubjInfoAccessOid[] = {43, 6, 1, 5, 5, 7, 1, 11};
- #endif
- /* certAuthInfoType */
- static const byte extAuthInfoOcspOid[] = {43, 6, 1, 5, 5, 7, 48, 1};
- static const byte extAuthInfoCaIssuerOid[] = {43, 6, 1, 5, 5, 7, 48, 2};
- #ifdef WOLFSSL_SUBJ_INFO_ACC
- static const byte extAuthInfoCaRespOid[] = {43, 6, 1, 5, 5, 7, 48, 5};
- #endif /* WOLFSSL_SUBJ_INFO_ACC */
- /* certPolicyType */
- static const byte extCertPolicyAnyOid[] = {85, 29, 32, 0};
- #ifdef WOLFSSL_FPKI
- #define CERT_POLICY_TYPE_OID_BASE(num) {96, 134, 72, 1, 101, 3, 2, 1, 3, num}
- static const byte extCertPolicyFpkiCommonAuthOid[] =
- CERT_POLICY_TYPE_OID_BASE(13);
- static const byte extCertPolicyFpkiPivAuthOid[] =
- CERT_POLICY_TYPE_OID_BASE(40);
- static const byte extCertPolicyFpkiPivAuthHwOid[] =
- CERT_POLICY_TYPE_OID_BASE(41);
- static const byte extCertPolicyFpkiPiviAuthOid[] =
- CERT_POLICY_TYPE_OID_BASE(45);
- #endif /* WOLFSSL_FPKI */
- /* certAltNameType */
- static const byte extAltNamesHwNameOid[] = {43, 6, 1, 5, 5, 7, 8, 4};
- /* certKeyUseType */
- static const byte extExtKeyUsageAnyOid[] = {85, 29, 37, 0};
- static const byte extExtKeyUsageServerAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 1};
- static const byte extExtKeyUsageClientAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 2};
- static const byte extExtKeyUsageCodeSigningOid[] = {43, 6, 1, 5, 5, 7, 3, 3};
- static const byte extExtKeyUsageEmailProtectOid[] = {43, 6, 1, 5, 5, 7, 3, 4};
- static const byte extExtKeyUsageTimestampOid[] = {43, 6, 1, 5, 5, 7, 3, 8};
- static const byte extExtKeyUsageOcspSignOid[] = {43, 6, 1, 5, 5, 7, 3, 9};
- #ifdef WOLFSSL_WOLFSSH
- #define EXT_KEY_USAGE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 3, num}
- static const byte extExtKeyUsageSshClientAuthOid[] =
- EXT_KEY_USAGE_OID_BASE(21);
- static const byte extExtKeyUsageSshMSCLOid[] =
- {43, 6, 1, 4, 1, 130, 55, 20, 2, 2};
- static const byte extExtKeyUsageSshKpClientAuthOid[] =
- {43, 6, 1, 5, 2, 3, 4};
- #endif /* WOLFSSL_WOLFSSH */
- #ifdef WOLFSSL_SUBJ_DIR_ATTR
- #define SUBJ_DIR_ATTR_TYPE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 9, num}
- static const byte extSubjDirAttrDobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(1);
- static const byte extSubjDirAttrPobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(2);
- static const byte extSubjDirAttrGenderOid[] =
- SUBJ_DIR_ATTR_TYPE_OID_BASE(3);
- static const byte extSubjDirAttrCocOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(4);
- static const byte extSubjDirAttrCorOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(5);
- #endif
- #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
- defined(WOLFSSL_ASN_TEMPLATE) || defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)
- /* csrAttrType */
- #define CSR_ATTR_TYPE_OID_BASE(num) {42, 134, 72, 134, 247, 13, 1, 9, num}
- #if !defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
- defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
- defined(WOLFSSL_ASN_TEMPLATE)
- static const byte attrEmailOid[] = CSR_ATTR_TYPE_OID_BASE(1);
- #endif
- #ifdef WOLFSSL_CERT_REQ
- static const byte attrUnstructuredNameOid[] = CSR_ATTR_TYPE_OID_BASE(2);
- static const byte attrPkcs9ContentTypeOid[] = CSR_ATTR_TYPE_OID_BASE(3);
- static const byte attrChallengePasswordOid[] = CSR_ATTR_TYPE_OID_BASE(7);
- static const byte attrExtensionRequestOid[] = CSR_ATTR_TYPE_OID_BASE(14);
- static const byte attrSerialNumberOid[] = {85, 4, 5};
- static const byte attrDnQualifier[] = {85, 4, 46};
- static const byte attrInitals[] = {85, 4, 43};
- static const byte attrSurname[] = {85, 4, 4};
- static const byte attrGivenName[] = {85, 4, 42};
- #endif
- #endif
- /* kdfType */
- static const byte pbkdf2Oid[] = {42, 134, 72, 134, 247, 13, 1, 5, 12};
- /* PKCS5 */
- #if !defined(NO_DES3) && !defined(NO_MD5)
- static const byte pbeMd5Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 3};
- #endif
- #if !defined(NO_DES3) && !defined(NO_SHA)
- static const byte pbeSha1Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 10};
- #endif
- static const byte pbes2[] = {42, 134, 72, 134, 247, 13, 1, 5, 13};
- /* PKCS12 */
- #if !defined(NO_RC4) && !defined(NO_SHA)
- static const byte pbeSha1RC4128[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 1};
- #endif
- #if !defined(NO_DES3) && !defined(NO_SHA)
- static const byte pbeSha1Des3[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 3};
- #endif
- #if defined(WC_RC2) && !defined(NO_SHA)
- static const byte pbe40Rc2Cbc[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 6};
- #endif
- #ifdef HAVE_LIBZ
- /* zlib compression */
- static const byte zlibCompress[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3, 8};
- #endif
- #ifdef WOLFSSL_APACHE_HTTPD
- /* tlsExtType */
- static const byte tlsFeatureOid[] = {43, 6, 1, 5, 5, 7, 1, 24};
- /* certNameType */
- static const byte dnsSRVOid[] = {43, 6, 1, 5, 5, 7, 8, 7};
- #endif
- #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
- defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
- defined(WOLFSSL_ASN_TEMPLATE)
- /* Pilot attribute types (0.9.2342.19200300.100.1.*) */
- #define PLT_ATTR_TYPE_OID_BASE(num) {9, 146, 38, 137, 147, 242, 44, 100, 1, num}
- static const byte uidOid[] = PLT_ATTR_TYPE_OID_BASE(1); /* user id */
- static const byte fvrtDrk[] = PLT_ATTR_TYPE_OID_BASE(5);/* favourite drink*/
- #endif
- #if defined(WOLFSSL_CERT_GEN) || \
- defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
- defined(WOLFSSL_ASN_TEMPLATE)
- static const byte dcOid[] = {9, 146, 38, 137, 147, 242, 44, 100, 1, 25}; /* domain component */
- #endif
- /* Looks up the ID/type of an OID.
- *
- * When known returns the OID as a byte array and its length.
- * ID-type are unique.
- *
- * Use oidIgnoreType to autofail.
- *
- * @param [in] id OID id.
- * @param [in] type Type of OID (enum Oid_Types).
- * @param [out] oidSz Length of OID byte array returned.
- * @return Array of bytes for the OID.
- * @return NULL when ID/type not recognized.
- */
- const byte* OidFromId(word32 id, word32 type, word32* oidSz)
- {
- const byte* oid = NULL;
- *oidSz = 0;
- switch (type) {
- case oidHashType:
- switch (id) {
- #ifdef WOLFSSL_MD2
- case MD2h:
- oid = hashMd2hOid;
- *oidSz = sizeof(hashMd2hOid);
- break;
- #endif
- #ifndef NO_MD5
- case MD5h:
- oid = hashMd5hOid;
- *oidSz = sizeof(hashMd5hOid);
- break;
- #endif
- #ifndef NO_SHA
- case SHAh:
- oid = hashSha1hOid;
- *oidSz = sizeof(hashSha1hOid);
- break;
- #endif
- #ifdef WOLFSSL_SHA224
- case SHA224h:
- oid = hashSha224hOid;
- *oidSz = sizeof(hashSha224hOid);
- break;
- #endif
- #ifndef NO_SHA256
- case SHA256h:
- oid = hashSha256hOid;
- *oidSz = sizeof(hashSha256hOid);
- break;
- #endif
- #ifdef WOLFSSL_SHA384
- case SHA384h:
- oid = hashSha384hOid;
- *oidSz = sizeof(hashSha384hOid);
- break;
- #endif
- #ifdef WOLFSSL_SHA512
- #ifndef WOLFSSL_NOSHA512_224
- case SHA512_224h:
- oid = hashSha512_224hOid;
- *oidSz = sizeof(hashSha512_224hOid);
- break;
- #endif
- #ifndef WOLFSSL_NOSHA512_256
- case SHA512_256h:
- oid = hashSha512_256hOid;
- *oidSz = sizeof(hashSha512_256hOid);
- break;
- #endif
- case SHA512h:
- oid = hashSha512hOid;
- *oidSz = sizeof(hashSha512hOid);
- break;
- #endif
- #ifdef WOLFSSL_SHA3
- #ifndef WOLFSSL_NOSHA3_224
- case SHA3_224h:
- oid = hashSha3_224hOid;
- *oidSz = sizeof(hashSha3_224hOid);
- break;
- #endif /* WOLFSSL_NOSHA3_224 */
- #ifndef WOLFSSL_NOSHA3_256
- case SHA3_256h:
- oid = hashSha3_256hOid;
- *oidSz = sizeof(hashSha3_256hOid);
- break;
- #endif /* WOLFSSL_NOSHA3_256 */
- #ifndef WOLFSSL_NOSHA3_384
- case SHA3_384h:
- oid = hashSha3_384hOid;
- *oidSz = sizeof(hashSha3_384hOid);
- break;
- #endif /* WOLFSSL_NOSHA3_384 */
- #ifndef WOLFSSL_NOSHA3_512
- case SHA3_512h:
- oid = hashSha3_512hOid;
- *oidSz = sizeof(hashSha3_512hOid);
- break;
- #endif /* WOLFSSL_NOSHA3_512 */
- #endif /* WOLFSSL_SHA3 */
- default:
- break;
- }
- break;
- case oidSigType:
- switch (id) {
- #if !defined(NO_DSA) && !defined(NO_SHA)
- case CTC_SHAwDSA:
- oid = sigSha1wDsaOid;
- *oidSz = sizeof(sigSha1wDsaOid);
- break;
- case CTC_SHA256wDSA:
- oid = sigSha256wDsaOid;
- *oidSz = sizeof(sigSha256wDsaOid);
- break;
- #endif /* NO_DSA */
- #ifndef NO_RSA
- #ifdef WOLFSSL_MD2
- case CTC_MD2wRSA:
- oid = sigMd2wRsaOid;
- *oidSz = sizeof(sigMd2wRsaOid);
- break;
- #endif
- #ifndef NO_MD5
- case CTC_MD5wRSA:
- oid = sigMd5wRsaOid;
- *oidSz = sizeof(sigMd5wRsaOid);
- break;
- #endif
- #ifndef NO_SHA
- case CTC_SHAwRSA:
- oid = sigSha1wRsaOid;
- *oidSz = sizeof(sigSha1wRsaOid);
- break;
- #endif
- #ifdef WOLFSSL_SHA224
- case CTC_SHA224wRSA:
- oid = sigSha224wRsaOid;
- *oidSz = sizeof(sigSha224wRsaOid);
- break;
- #endif
- #ifndef NO_SHA256
- case CTC_SHA256wRSA:
- oid = sigSha256wRsaOid;
- *oidSz = sizeof(sigSha256wRsaOid);
- break;
- #endif
- #ifdef WOLFSSL_SHA384
- case CTC_SHA384wRSA:
- oid = sigSha384wRsaOid;
- *oidSz = sizeof(sigSha384wRsaOid);
- break;
- #endif
- #ifdef WOLFSSL_SHA512
- case CTC_SHA512wRSA:
- oid = sigSha512wRsaOid;
- *oidSz = sizeof(sigSha512wRsaOid);
- break;
- #endif /* WOLFSSL_SHA512 */
- #ifdef WOLFSSL_SHA3
- #ifndef WOLFSSL_NOSHA3_224
- case CTC_SHA3_224wRSA:
- oid = sigSha3_224wRsaOid;
- *oidSz = sizeof(sigSha3_224wRsaOid);
- break;
- #endif
- #ifndef WOLFSSL_NOSHA3_256
- case CTC_SHA3_256wRSA:
- oid = sigSha3_256wRsaOid;
- *oidSz = sizeof(sigSha3_256wRsaOid);
- break;
- #endif
- #ifndef WOLFSSL_NOSHA3_384
- case CTC_SHA3_384wRSA:
- oid = sigSha3_384wRsaOid;
- *oidSz = sizeof(sigSha3_384wRsaOid);
- break;
- #endif
- #ifndef WOLFSSL_NOSHA3_512
- case CTC_SHA3_512wRSA:
- oid = sigSha3_512wRsaOid;
- *oidSz = sizeof(sigSha3_512wRsaOid);
- break;
- #endif
- #endif
- #ifdef WC_RSA_PSS
- case CTC_RSASSAPSS:
- oid = sigRsaSsaPssOid;
- *oidSz = sizeof(sigRsaSsaPssOid);
- break;
- #endif
- #endif /* NO_RSA */
- #ifdef HAVE_ECC
- #ifndef NO_SHA
- case CTC_SHAwECDSA:
- oid = sigSha1wEcdsaOid;
- *oidSz = sizeof(sigSha1wEcdsaOid);
- break;
- #endif
- #ifdef WOLFSSL_SHA224
- case CTC_SHA224wECDSA:
- oid = sigSha224wEcdsaOid;
- *oidSz = sizeof(sigSha224wEcdsaOid);
- break;
- #endif
- #ifndef NO_SHA256
- case CTC_SHA256wECDSA:
- oid = sigSha256wEcdsaOid;
- *oidSz = sizeof(sigSha256wEcdsaOid);
- break;
- #endif
- #ifdef WOLFSSL_SHA384
- case CTC_SHA384wECDSA:
- oid = sigSha384wEcdsaOid;
- *oidSz = sizeof(sigSha384wEcdsaOid);
- break;
- #endif
- #ifdef WOLFSSL_SHA512
- case CTC_SHA512wECDSA:
- oid = sigSha512wEcdsaOid;
- *oidSz = sizeof(sigSha512wEcdsaOid);
- break;
- #endif
- #ifdef WOLFSSL_SHA3
- #ifndef WOLFSSL_NOSHA3_224
- case CTC_SHA3_224wECDSA:
- oid = sigSha3_224wEcdsaOid;
- *oidSz = sizeof(sigSha3_224wEcdsaOid);
- break;
- #endif
- #ifndef WOLFSSL_NOSHA3_256
- case CTC_SHA3_256wECDSA:
- oid = sigSha3_256wEcdsaOid;
- *oidSz = sizeof(sigSha3_256wEcdsaOid);
- break;
- #endif
- #ifndef WOLFSSL_NOSHA3_384
- case CTC_SHA3_384wECDSA:
- oid = sigSha3_384wEcdsaOid;
- *oidSz = sizeof(sigSha3_384wEcdsaOid);
- break;
- #endif
- #ifndef WOLFSSL_NOSHA3_512
- case CTC_SHA3_512wECDSA:
- oid = sigSha3_512wEcdsaOid;
- *oidSz = sizeof(sigSha3_512wEcdsaOid);
- break;
- #endif
- #endif
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- case CTC_SM3wSM2:
- oid = sigSm3wSm2Oid;
- *oidSz = sizeof(sigSm3wSm2Oid);
- break;
- #endif
- #endif /* HAVE_ECC */
- #ifdef HAVE_ED25519
- case CTC_ED25519:
- oid = sigEd25519Oid;
- *oidSz = sizeof(sigEd25519Oid);
- break;
- #endif
- #ifdef HAVE_ED448
- case CTC_ED448:
- oid = sigEd448Oid;
- *oidSz = sizeof(sigEd448Oid);
- break;
- #endif
- #ifdef HAVE_PQC
- #ifdef HAVE_FALCON
- case CTC_FALCON_LEVEL1:
- oid = sigFalcon_Level1Oid;
- *oidSz = sizeof(sigFalcon_Level1Oid);
- break;
- case CTC_FALCON_LEVEL5:
- oid = sigFalcon_Level5Oid;
- *oidSz = sizeof(sigFalcon_Level5Oid);
- break;
- #endif /* HAVE_FALCON */
- #ifdef HAVE_DILITHIUM
- case CTC_DILITHIUM_LEVEL2:
- oid = sigDilithium_Level2Oid;
- *oidSz = sizeof(sigDilithium_Level2Oid);
- break;
- case CTC_DILITHIUM_LEVEL3:
- oid = sigDilithium_Level3Oid;
- *oidSz = sizeof(sigDilithium_Level3Oid);
- break;
- case CTC_DILITHIUM_LEVEL5:
- oid = sigDilithium_Level5Oid;
- *oidSz = sizeof(sigDilithium_Level5Oid);
- break;
- #endif /* HAVE_DILITHIUM */
- #ifdef HAVE_SPHINCS
- case CTC_SPHINCS_FAST_LEVEL1:
- oid = sigSphincsFast_Level1Oid;
- *oidSz = sizeof(sigSphincsFast_Level1Oid);
- break;
- case CTC_SPHINCS_FAST_LEVEL3:
- oid = sigSphincsFast_Level3Oid;
- *oidSz = sizeof(sigSphincsFast_Level3Oid);
- break;
- case CTC_SPHINCS_FAST_LEVEL5:
- oid = sigSphincsFast_Level5Oid;
- *oidSz = sizeof(sigSphincsFast_Level5Oid);
- break;
- case CTC_SPHINCS_SMALL_LEVEL1:
- oid = sigSphincsSmall_Level1Oid;
- *oidSz = sizeof(sigSphincsSmall_Level1Oid);
- break;
- case CTC_SPHINCS_SMALL_LEVEL3:
- oid = sigSphincsSmall_Level3Oid;
- *oidSz = sizeof(sigSphincsSmall_Level3Oid);
- break;
- case CTC_SPHINCS_SMALL_LEVEL5:
- oid = sigSphincsSmall_Level5Oid;
- *oidSz = sizeof(sigSphincsSmall_Level5Oid);
- break;
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- default:
- break;
- }
- break;
- case oidKeyType:
- switch (id) {
- #ifndef NO_DSA
- case DSAk:
- oid = keyDsaOid;
- *oidSz = sizeof(keyDsaOid);
- break;
- #endif /* NO_DSA */
- #ifndef NO_RSA
- case RSAk:
- oid = keyRsaOid;
- *oidSz = sizeof(keyRsaOid);
- break;
- #ifdef WC_RSA_PSS
- case RSAPSSk:
- oid = keyRsaPssOid;
- *oidSz = sizeof(keyRsaPssOid);
- break;
- #endif
- #endif /* NO_RSA */
- #ifdef HAVE_ECC
- case ECDSAk:
- oid = keyEcdsaOid;
- *oidSz = sizeof(keyEcdsaOid);
- break;
- #endif /* HAVE_ECC */
- #ifdef HAVE_ED25519
- case ED25519k:
- oid = keyEd25519Oid;
- *oidSz = sizeof(keyEd25519Oid);
- break;
- #endif /* HAVE_ED25519 */
- #ifdef HAVE_CURVE25519
- case X25519k:
- oid = keyCurve25519Oid;
- *oidSz = sizeof(keyCurve25519Oid);
- break;
- #endif /* HAVE_CURVE25519 */
- #ifdef HAVE_ED448
- case ED448k:
- oid = keyEd448Oid;
- *oidSz = sizeof(keyEd448Oid);
- break;
- #endif /* HAVE_ED448 */
- #ifdef HAVE_CURVE448
- case X448k:
- oid = keyCurve448Oid;
- *oidSz = sizeof(keyCurve448Oid);
- break;
- #endif /* HAVE_CURVE448 */
- #ifndef NO_DH
- case DHk:
- oid = keyDhOid;
- *oidSz = sizeof(keyDhOid);
- break;
- #endif /* !NO_DH */
- #ifdef HAVE_PQC
- #ifdef HAVE_FALCON
- case FALCON_LEVEL1k:
- oid = keyFalcon_Level1Oid;
- *oidSz = sizeof(keyFalcon_Level1Oid);
- break;
- case FALCON_LEVEL5k:
- oid = keyFalcon_Level5Oid;
- *oidSz = sizeof(keyFalcon_Level5Oid);
- break;
- #endif /* HAVE_FALCON */
- #ifdef HAVE_DILITHIUM
- case DILITHIUM_LEVEL2k:
- oid = keyDilithium_Level2Oid;
- *oidSz = sizeof(keyDilithium_Level2Oid);
- break;
- case DILITHIUM_LEVEL3k:
- oid = keyDilithium_Level3Oid;
- *oidSz = sizeof(keyDilithium_Level3Oid);
- break;
- case DILITHIUM_LEVEL5k:
- oid = keyDilithium_Level5Oid;
- *oidSz = sizeof(keyDilithium_Level5Oid);
- break;
- #endif /* HAVE_DILITHIUM */
- #ifdef HAVE_SPHINCS
- case SPHINCS_FAST_LEVEL1k:
- oid = keySphincsFast_Level1Oid;
- *oidSz = sizeof(keySphincsFast_Level1Oid);
- break;
- case SPHINCS_FAST_LEVEL3k:
- oid = keySphincsFast_Level3Oid;
- *oidSz = sizeof(keySphincsFast_Level3Oid);
- break;
- case SPHINCS_FAST_LEVEL5k:
- oid = keySphincsFast_Level5Oid;
- *oidSz = sizeof(keySphincsFast_Level5Oid);
- break;
- case SPHINCS_SMALL_LEVEL1k:
- oid = keySphincsSmall_Level1Oid;
- *oidSz = sizeof(keySphincsSmall_Level1Oid);
- break;
- case SPHINCS_SMALL_LEVEL3k:
- oid = keySphincsSmall_Level3Oid;
- *oidSz = sizeof(keySphincsSmall_Level3Oid);
- break;
- case SPHINCS_SMALL_LEVEL5k:
- oid = keySphincsSmall_Level5Oid;
- *oidSz = sizeof(keySphincsSmall_Level5Oid);
- break;
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- default:
- break;
- }
- break;
- #ifdef HAVE_ECC
- case oidCurveType:
- if (wc_ecc_get_oid(id, &oid, oidSz) < 0) {
- WOLFSSL_MSG("ECC OID not found");
- }
- break;
- #endif /* HAVE_ECC */
- case oidBlkType:
- switch (id) {
- #ifdef HAVE_AES_CBC
- #ifdef WOLFSSL_AES_128
- case AES128CBCb:
- oid = blkAes128CbcOid;
- *oidSz = sizeof(blkAes128CbcOid);
- break;
- #endif
- #ifdef WOLFSSL_AES_192
- case AES192CBCb:
- oid = blkAes192CbcOid;
- *oidSz = sizeof(blkAes192CbcOid);
- break;
- #endif
- #ifdef WOLFSSL_AES_256
- case AES256CBCb:
- oid = blkAes256CbcOid;
- *oidSz = sizeof(blkAes256CbcOid);
- break;
- #endif
- #endif /* HAVE_AES_CBC */
- #ifdef HAVE_AESGCM
- #ifdef WOLFSSL_AES_128
- case AES128GCMb:
- oid = blkAes128GcmOid;
- *oidSz = sizeof(blkAes128GcmOid);
- break;
- #endif
- #ifdef WOLFSSL_AES_192
- case AES192GCMb:
- oid = blkAes192GcmOid;
- *oidSz = sizeof(blkAes192GcmOid);
- break;
- #endif
- #ifdef WOLFSSL_AES_256
- case AES256GCMb:
- oid = blkAes256GcmOid;
- *oidSz = sizeof(blkAes256GcmOid);
- break;
- #endif
- #endif /* HAVE_AESGCM */
- #ifdef HAVE_AESCCM
- #ifdef WOLFSSL_AES_128
- case AES128CCMb:
- oid = blkAes128CcmOid;
- *oidSz = sizeof(blkAes128CcmOid);
- break;
- #endif
- #ifdef WOLFSSL_AES_192
- case AES192CCMb:
- oid = blkAes192CcmOid;
- *oidSz = sizeof(blkAes192CcmOid);
- break;
- #endif
- #ifdef WOLFSSL_AES_256
- case AES256CCMb:
- oid = blkAes256CcmOid;
- *oidSz = sizeof(blkAes256CcmOid);
- break;
- #endif
- #endif /* HAVE_AESCCM */
- #ifndef NO_DES3
- case DESb:
- oid = blkDesCbcOid;
- *oidSz = sizeof(blkDesCbcOid);
- break;
- case DES3b:
- oid = blkDes3CbcOid;
- *oidSz = sizeof(blkDes3CbcOid);
- break;
- #endif /* !NO_DES3 */
- default:
- break;
- }
- break;
- #ifdef HAVE_OCSP
- case oidOcspType:
- switch (id) {
- case OCSP_BASIC_OID:
- oid = ocspBasicOid;
- *oidSz = sizeof(ocspBasicOid);
- break;
- case OCSP_NONCE_OID:
- oid = ocspNonceOid;
- *oidSz = sizeof(ocspNonceOid);
- break;
- default:
- break;
- }
- break;
- #endif /* HAVE_OCSP */
- case oidCertExtType:
- switch (id) {
- case BASIC_CA_OID:
- oid = extBasicCaOid;
- *oidSz = sizeof(extBasicCaOid);
- break;
- case ALT_NAMES_OID:
- oid = extAltNamesOid;
- *oidSz = sizeof(extAltNamesOid);
- break;
- case CRL_DIST_OID:
- oid = extCrlDistOid;
- *oidSz = sizeof(extCrlDistOid);
- break;
- case AUTH_INFO_OID:
- oid = extAuthInfoOid;
- *oidSz = sizeof(extAuthInfoOid);
- break;
- case AUTH_KEY_OID:
- oid = extAuthKeyOid;
- *oidSz = sizeof(extAuthKeyOid);
- break;
- case SUBJ_KEY_OID:
- oid = extSubjKeyOid;
- *oidSz = sizeof(extSubjKeyOid);
- break;
- case CERT_POLICY_OID:
- oid = extCertPolicyOid;
- *oidSz = sizeof(extCertPolicyOid);
- break;
- case KEY_USAGE_OID:
- oid = extKeyUsageOid;
- *oidSz = sizeof(extKeyUsageOid);
- break;
- case INHIBIT_ANY_OID:
- oid = extInhibitAnyOid;
- *oidSz = sizeof(extInhibitAnyOid);
- break;
- case EXT_KEY_USAGE_OID:
- oid = extExtKeyUsageOid;
- *oidSz = sizeof(extExtKeyUsageOid);
- break;
- #ifndef IGNORE_NAME_CONSTRAINTS
- case NAME_CONS_OID:
- oid = extNameConsOid;
- *oidSz = sizeof(extNameConsOid);
- break;
- #endif
- #ifdef HAVE_OCSP
- case OCSP_NOCHECK_OID:
- oid = ocspNoCheckOid;
- *oidSz = sizeof(ocspNoCheckOid);
- break;
- #endif
- #ifdef WOLFSSL_SUBJ_DIR_ATTR
- case SUBJ_DIR_ATTR_OID:
- oid = extSubjDirAttrOid;
- *oidSz = sizeof(extSubjDirAttrOid);
- break;
- #endif
- #ifdef WOLFSSL_SUBJ_INFO_ACC
- case SUBJ_INFO_ACC_OID:
- oid = extSubjInfoAccessOid;
- *oidSz = sizeof(extSubjInfoAccessOid);
- break;
- #endif
- default:
- break;
- }
- break;
- case oidCrlExtType:
- #ifdef HAVE_CRL
- switch (id) {
- case AUTH_KEY_OID:
- oid = extAuthKeyOid;
- *oidSz = sizeof(extAuthKeyOid);
- break;
- case CRL_NUMBER_OID:
- oid = extCrlNumberOid;
- *oidSz = sizeof(extCrlNumberOid);
- break;
- default:
- break;
- }
- #endif
- break;
- case oidCertAuthInfoType:
- switch (id) {
- case AIA_OCSP_OID:
- oid = extAuthInfoOcspOid;
- *oidSz = sizeof(extAuthInfoOcspOid);
- break;
- case AIA_CA_ISSUER_OID:
- oid = extAuthInfoCaIssuerOid;
- *oidSz = sizeof(extAuthInfoCaIssuerOid);
- break;
- #ifdef WOLFSSL_SUBJ_INFO_ACC
- case AIA_CA_REPO_OID:
- oid = extAuthInfoCaRespOid;
- *oidSz = sizeof(extAuthInfoCaRespOid);
- break;
- #endif /* WOLFSSL_SUBJ_INFO_ACC */
- default:
- break;
- }
- break;
- case oidCertPolicyType:
- switch (id) {
- case CP_ANY_OID:
- oid = extCertPolicyAnyOid;
- *oidSz = sizeof(extCertPolicyAnyOid);
- break;
- #if defined(WOLFSSL_FPKI)
- case CP_FPKI_COMMON_AUTH_OID:
- oid = extCertPolicyFpkiCommonAuthOid;
- *oidSz = sizeof(extCertPolicyFpkiCommonAuthOid);
- break;
- case CP_FPKI_PIV_AUTH_OID:
- oid = extCertPolicyFpkiPivAuthOid;
- *oidSz = sizeof(extCertPolicyFpkiPivAuthOid);
- break;
- case CP_FPKI_PIV_AUTH_HW_OID: /* collision with AES256CBCb */
- oid = extCertPolicyFpkiPivAuthHwOid;
- *oidSz = sizeof(extCertPolicyFpkiPivAuthHwOid);
- break;
- case CP_FPKI_PIVI_AUTH_OID:
- oid = extCertPolicyFpkiPiviAuthOid;
- *oidSz = sizeof(extCertPolicyFpkiPiviAuthOid);
- break;
- #endif /* WOLFSSL_FPKI */
- default:
- break;
- }
- break;
- case oidCertAltNameType:
- switch (id) {
- case HW_NAME_OID:
- oid = extAltNamesHwNameOid;
- *oidSz = sizeof(extAltNamesHwNameOid);
- break;
- default:
- break;
- }
- break;
- case oidCertKeyUseType:
- switch (id) {
- case EKU_ANY_OID:
- oid = extExtKeyUsageAnyOid;
- *oidSz = sizeof(extExtKeyUsageAnyOid);
- break;
- case EKU_SERVER_AUTH_OID:
- oid = extExtKeyUsageServerAuthOid;
- *oidSz = sizeof(extExtKeyUsageServerAuthOid);
- break;
- case EKU_CLIENT_AUTH_OID:
- oid = extExtKeyUsageClientAuthOid;
- *oidSz = sizeof(extExtKeyUsageClientAuthOid);
- break;
- case EKU_CODESIGNING_OID:
- oid = extExtKeyUsageCodeSigningOid;
- *oidSz = sizeof(extExtKeyUsageCodeSigningOid);
- break;
- case EKU_EMAILPROTECT_OID:
- oid = extExtKeyUsageEmailProtectOid;
- *oidSz = sizeof(extExtKeyUsageEmailProtectOid);
- break;
- case EKU_TIMESTAMP_OID:
- oid = extExtKeyUsageTimestampOid;
- *oidSz = sizeof(extExtKeyUsageTimestampOid);
- break;
- case EKU_OCSP_SIGN_OID:
- oid = extExtKeyUsageOcspSignOid;
- *oidSz = sizeof(extExtKeyUsageOcspSignOid);
- break;
- #ifdef WOLFSSL_WOLFSSH
- case EKU_SSH_CLIENT_AUTH_OID:
- oid = extExtKeyUsageSshClientAuthOid;
- *oidSz = sizeof(extExtKeyUsageSshClientAuthOid);
- break;
- case EKU_SSH_MSCL_OID:
- oid = extExtKeyUsageSshMSCLOid;
- *oidSz = sizeof(extExtKeyUsageSshMSCLOid);
- break;
- case EKU_SSH_KP_CLIENT_AUTH_OID:
- oid = extExtKeyUsageSshKpClientAuthOid;
- *oidSz = sizeof(extExtKeyUsageSshKpClientAuthOid);
- break;
- #endif /* WOLFSSL_WOLFSSH */
- default:
- break;
- }
- break;
- case oidKdfType:
- switch (id) {
- case PBKDF2_OID:
- oid = pbkdf2Oid;
- *oidSz = sizeof(pbkdf2Oid);
- break;
- default:
- break;
- }
- break;
- case oidPBEType:
- switch (id) {
- #if !defined(NO_SHA) && !defined(NO_RC4)
- case PBE_SHA1_RC4_128_SUM:
- case PBE_SHA1_RC4_128:
- oid = pbeSha1RC4128;
- *oidSz = sizeof(pbeSha1RC4128);
- break;
- #endif
- #if !defined(NO_MD5) && !defined(NO_DES3)
- case PBE_MD5_DES_SUM:
- case PBE_MD5_DES:
- oid = pbeMd5Des;
- *oidSz = sizeof(pbeMd5Des);
- break;
- #endif
- #if !defined(NO_SHA) && !defined(NO_DES3)
- case PBE_SHA1_DES_SUM:
- case PBE_SHA1_DES:
- oid = pbeSha1Des;
- *oidSz = sizeof(pbeSha1Des);
- break;
- #endif
- #if !defined(NO_SHA) && !defined(NO_DES3)
- case PBE_SHA1_DES3_SUM:
- case PBE_SHA1_DES3:
- oid = pbeSha1Des3;
- *oidSz = sizeof(pbeSha1Des3);
- break;
- #endif
- #if !defined(NO_SHA) && defined(WC_RC2)
- case PBE_SHA1_40RC2_CBC_SUM:
- case PBE_SHA1_40RC2_CBC:
- oid = pbe40Rc2Cbc;
- *oidSz = sizeof(pbe40Rc2Cbc);
- break;
- #endif
- case PBES2_SUM:
- case PBES2:
- oid = pbes2;
- *oidSz = sizeof(pbes2);
- break;
- default:
- break;
- }
- break;
- case oidKeyWrapType:
- switch (id) {
- #ifdef WOLFSSL_AES_128
- case AES128_WRAP:
- oid = wrapAes128Oid;
- *oidSz = sizeof(wrapAes128Oid);
- break;
- #endif
- #ifdef WOLFSSL_AES_192
- case AES192_WRAP:
- oid = wrapAes192Oid;
- *oidSz = sizeof(wrapAes192Oid);
- break;
- #endif
- #ifdef WOLFSSL_AES_256
- case AES256_WRAP:
- oid = wrapAes256Oid;
- *oidSz = sizeof(wrapAes256Oid);
- break;
- #endif
- #ifdef HAVE_PKCS7
- case PWRI_KEK_WRAP:
- oid = wrapPwriKekOid;
- *oidSz = sizeof(wrapPwriKekOid);
- break;
- #endif
- default:
- break;
- }
- break;
- case oidCmsKeyAgreeType:
- switch (id) {
- #ifndef NO_SHA
- case dhSinglePass_stdDH_sha1kdf_scheme:
- oid = dhSinglePass_stdDH_sha1kdf_Oid;
- *oidSz = sizeof(dhSinglePass_stdDH_sha1kdf_Oid);
- break;
- #endif
- #ifdef WOLFSSL_SHA224
- case dhSinglePass_stdDH_sha224kdf_scheme:
- oid = dhSinglePass_stdDH_sha224kdf_Oid;
- *oidSz = sizeof(dhSinglePass_stdDH_sha224kdf_Oid);
- break;
- #endif
- #ifndef NO_SHA256
- case dhSinglePass_stdDH_sha256kdf_scheme:
- oid = dhSinglePass_stdDH_sha256kdf_Oid;
- *oidSz = sizeof(dhSinglePass_stdDH_sha256kdf_Oid);
- break;
- #endif
- #ifdef WOLFSSL_SHA384
- case dhSinglePass_stdDH_sha384kdf_scheme:
- oid = dhSinglePass_stdDH_sha384kdf_Oid;
- *oidSz = sizeof(dhSinglePass_stdDH_sha384kdf_Oid);
- break;
- #endif
- #ifdef WOLFSSL_SHA512
- case dhSinglePass_stdDH_sha512kdf_scheme:
- oid = dhSinglePass_stdDH_sha512kdf_Oid;
- *oidSz = sizeof(dhSinglePass_stdDH_sha512kdf_Oid);
- break;
- #endif
- default:
- break;
- }
- break;
- #ifndef NO_HMAC
- case oidHmacType:
- switch (id) {
- #ifdef WOLFSSL_SHA224
- case HMAC_SHA224_OID:
- oid = hmacSha224Oid;
- *oidSz = sizeof(hmacSha224Oid);
- break;
- #endif
- #ifndef NO_SHA256
- case HMAC_SHA256_OID:
- oid = hmacSha256Oid;
- *oidSz = sizeof(hmacSha256Oid);
- break;
- #endif
- #ifdef WOLFSSL_SHA384
- case HMAC_SHA384_OID:
- oid = hmacSha384Oid;
- *oidSz = sizeof(hmacSha384Oid);
- break;
- #endif
- #ifdef WOLFSSL_SHA512
- case HMAC_SHA512_OID:
- oid = hmacSha512Oid;
- *oidSz = sizeof(hmacSha512Oid);
- break;
- #endif
- default:
- break;
- }
- break;
- #endif /* !NO_HMAC */
- #ifdef HAVE_LIBZ
- case oidCompressType:
- switch (id) {
- case ZLIBc:
- oid = zlibCompress;
- *oidSz = sizeof(zlibCompress);
- break;
- default:
- break;
- }
- break;
- #endif /* HAVE_LIBZ */
- #ifdef WOLFSSL_APACHE_HTTPD
- case oidCertNameType:
- switch (id) {
- case NID_id_on_dnsSRV:
- oid = dnsSRVOid;
- *oidSz = sizeof(dnsSRVOid);
- break;
- default:
- break;
- }
- break;
- case oidTlsExtType:
- switch (id) {
- case TLS_FEATURE_OID:
- oid = tlsFeatureOid;
- *oidSz = sizeof(tlsFeatureOid);
- break;
- default:
- break;
- }
- break;
- #endif /* WOLFSSL_APACHE_HTTPD */
- #ifdef WOLFSSL_CERT_REQ
- case oidCsrAttrType:
- switch (id) {
- case GIVEN_NAME_OID:
- oid = attrGivenName;
- *oidSz = sizeof(attrGivenName);
- break;
- case SURNAME_OID:
- oid = attrSurname;
- *oidSz = sizeof(attrSurname);
- break;
- case INITIALS_OID:
- oid = attrInitals;
- *oidSz = sizeof(attrInitals);
- break;
- case DNQUALIFIER_OID:
- oid = attrDnQualifier;
- *oidSz = sizeof(attrDnQualifier);
- break;
- case UNSTRUCTURED_NAME_OID:
- oid = attrUnstructuredNameOid;
- *oidSz = sizeof(attrUnstructuredNameOid);
- break;
- case PKCS9_CONTENT_TYPE_OID:
- oid = attrPkcs9ContentTypeOid;
- *oidSz = sizeof(attrPkcs9ContentTypeOid);
- break;
- case CHALLENGE_PASSWORD_OID:
- oid = attrChallengePasswordOid;
- *oidSz = sizeof(attrChallengePasswordOid);
- break;
- case SERIAL_NUMBER_OID:
- oid = attrSerialNumberOid;
- *oidSz = sizeof(attrSerialNumberOid);
- break;
- case USER_ID_OID:
- oid = uidOid;
- *oidSz = sizeof(uidOid);
- break;
- case EXTENSION_REQUEST_OID:
- oid = attrExtensionRequestOid;
- *oidSz = sizeof(attrExtensionRequestOid);
- break;
- default:
- break;
- }
- break;
- #endif
- #ifdef WOLFSSL_SUBJ_DIR_ATTR
- case oidSubjDirAttrType:
- switch (id) {
- case SDA_DOB_OID:
- oid = extSubjDirAttrDobOid;
- *oidSz = sizeof(extSubjDirAttrDobOid);
- break;
- case SDA_POB_OID:
- oid = extSubjDirAttrPobOid;
- *oidSz = sizeof(extSubjDirAttrPobOid);
- break;
- case SDA_GENDER_OID:
- oid = extSubjDirAttrGenderOid;
- *oidSz = sizeof(extSubjDirAttrGenderOid);
- break;
- case SDA_COC_OID:
- oid = extSubjDirAttrCocOid;
- *oidSz = sizeof(extSubjDirAttrCocOid);
- break;
- case SDA_COR_OID:
- oid = extSubjDirAttrCorOid;
- *oidSz = sizeof(extSubjDirAttrCorOid);
- break;
- default:
- break;
- }
- break;
- #endif /* WOLFSSL_SUBJ_DIR_ATTR */
- case oidIgnoreType:
- default:
- break;
- }
- return oid;
- }
- #ifdef HAVE_ECC
- /* Check the OID id is for a known elliptic curve.
- *
- * @param [in] oid OID id.
- * @return ECC set id on success.
- * @return ECC_CURVE_OID_E when OID id is 0 or not supported.
- */
- static int CheckCurve(word32 oid)
- {
- int ret;
- word32 oidSz;
- /* Lookup OID id. */
- ret = wc_ecc_get_oid(oid, NULL, &oidSz);
- /* Check for error or zero length OID size (can't get OID for encoding). */
- if ((ret < 0) || (oidSz == 0)) {
- WOLFSSL_MSG("CheckCurve not found");
- WOLFSSL_ERROR_VERBOSE(ECC_CURVE_OID_E);
- ret = ECC_CURVE_OID_E;
- }
- /* Return ECC set id or error code. */
- return ret;
- }
- #endif
- #ifdef HAVE_OID_ENCODING
- /* Encode dotted form of OID into byte array version.
- *
- * @param [in] in Dotted form of OID.
- * @param [in] inSz Count of numbers in dotted form.
- * @param [in] out Buffer to hold OID.
- * @param [in, out] outSz On in, size of buffer.
- * On out, number of bytes in buffer.
- * @return 0 on success
- * @return BAD_FUNC_ARG when in or outSz is NULL.
- * @return BUFFER_E when buffer too small.
- */
- int EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz)
- {
- int i, x, len;
- word32 d, t;
- /* check args */
- if (in == NULL || outSz == NULL) {
- return BAD_FUNC_ARG;
- }
- /* compute length of encoded OID */
- d = (in[0] * 40) + in[1];
- len = 0;
- for (i = 1; i < (int)inSz; i++) {
- x = 0;
- t = d;
- while (t) {
- x++;
- t >>= 1;
- }
- len += (x / 7) + ((x % 7) ? 1 : 0) + (d == 0 ? 1 : 0);
- if (i < (int)inSz - 1) {
- d = in[i + 1];
- }
- }
- if (out) {
- /* verify length */
- if ((int)*outSz < len) {
- return BUFFER_E; /* buffer provided is not large enough */
- }
- /* calc first byte */
- d = (in[0] * 40) + in[1];
- /* encode bytes */
- x = 0;
- for (i = 1; i < (int)inSz; i++) {
- if (d) {
- int y = x, z;
- byte mask = 0;
- while (d) {
- out[x++] = (byte)((d & 0x7F) | mask);
- d >>= 7;
- mask |= 0x80; /* upper bit is set on all but the last byte */
- }
- /* now swap bytes y...x-1 */
- z = x - 1;
- while (y < z) {
- mask = out[y];
- out[y] = out[z];
- out[z] = mask;
- ++y;
- --z;
- }
- }
- else {
- out[x++] = 0x00; /* zero value */
- }
- /* next word */
- if (i < (int)inSz - 1) {
- d = in[i + 1];
- }
- }
- }
- /* return length */
- *outSz = len;
- return 0;
- }
- #endif /* HAVE_OID_ENCODING */
- #if defined(HAVE_OID_DECODING) || defined(WOLFSSL_ASN_PRINT)
- /* Encode dotted form of OID into byte array version.
- *
- * @param [in] in Byte array containing OID.
- * @param [in] inSz Size of OID in bytes.
- * @param [in] out Array to hold dotted form of OID.
- * @param [in, out] outSz On in, number of elements in array.
- * On out, count of numbers in dotted form.
- * @return 0 on success
- * @return BAD_FUNC_ARG when in or outSz is NULL.
- * @return BUFFER_E when dotted form buffer too small.
- */
- int DecodeObjectId(const byte* in, word32 inSz, word16* out, word32* outSz)
- {
- int x = 0, y = 0;
- word32 t = 0;
- /* check args */
- if (in == NULL || outSz == NULL) {
- return BAD_FUNC_ARG;
- }
- /* decode bytes */
- while (inSz--) {
- t = (t << 7) | (in[x] & 0x7F);
- if (!(in[x] & 0x80)) {
- if (y >= (int)*outSz) {
- return BUFFER_E;
- }
- if (y == 0) {
- out[0] = (word16)(t / 40);
- out[1] = (word16)(t % 40);
- y = 2;
- }
- else {
- out[y++] = (word16)t;
- }
- t = 0; /* reset tmp */
- }
- x++;
- }
- /* return length */
- *outSz = (word32)y;
- return 0;
- }
- #endif /* HAVE_OID_DECODING */
- /* Decode the header of a BER/DER encoded OBJECT ID.
- *
- * @param [in] input Buffer holding DER/BER encoded data.
- * @param [in, out] inOutIdx On in, starting index of header.
- * On out, end of parsed header.
- * @param [out] len Number of bytes in the ASN.1 data.
- * @param [in] maxIdx Length of data in buffer.
- * @return 0 on success.
- * @return BUFFER_E when there is not enough data to parse.
- * @return ASN_PARSE_E when the tag is not a OBJECT ID or length is invalid.
- */
- int GetASNObjectId(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
- {
- int ret = GetASNHeader(input, ASN_OBJECT_ID, inOutIdx, len, maxIdx);
- if (ret > 0) {
- /* Only return 0 on success. */
- ret = 0;
- }
- return ret;
- }
- /* Set the DER/BER encoding of the ASN.1 OBJECT ID header.
- *
- * When output is NULL, calculate the header length only.
- *
- * @param [in] len Length of OBJECT ID data in bytes.
- * @param [out] output Buffer to write into.
- * @return Number of bytes added to the buffer.
- */
- int SetObjectId(int len, byte* output)
- {
- int idx = 0;
- if (output) {
- /* Write out tag. */
- output[idx] = ASN_OBJECT_ID;
- }
- /* Skip tag. */
- idx += ASN_TAG_SZ;
- /* Encode length - passing NULL for output will not encode. */
- idx += (int)SetLength((word32)len, output ? output + idx : NULL);
- /* Return index after header. */
- return idx;
- }
- #ifdef ASN_DUMP_OID
- /* Dump the OID information.
- *
- * Decode the OID too if function available.
- *
- * @param [in] oidData OID data from buffer.
- * @param [in] oidSz Size of OID data in buffer.
- * @param [in] oid OID id.
- * @param [in] oidType Type of OID.
- * @return 0 on success.
- * @return BUFFER_E when not enough bytes for proper decode.
- * (HAVE_OID_DECODING)
- */
- static int DumpOID(const byte* oidData, word32 oidSz, word32 oid,
- word32 oidType)
- {
- int ret = 0;
- word32 i;
- /* support for dumping OID information */
- printf("OID (Type %d, Sz %d, Sum %d): ", oidType, oidSz, oid);
- /* Dump bytes in decimal. */
- for (i = 0; i < oidSz; i++) {
- printf("%d, ", oidData[i]);
- }
- printf("\n");
- /* Dump bytes in hexadecimal. */
- for (i = 0; i < oidSz; i++) {
- printf("%02x, ", oidData[i]);
- }
- printf("\n");
- #ifdef HAVE_OID_DECODING
- {
- word16 decOid[MAX_OID_SZ];
- word32 decOidSz = sizeof(decOid);
- /* Decode the OID into dotted form. */
- ret = DecodeObjectId(oidData, oidSz, decOid, &decOidSz);
- if (ret == 0) {
- printf(" Decoded (Sz %d): ", decOidSz);
- for (i=0; i<decOidSz; i++) {
- printf("%d.", decOid[i]);
- }
- printf("\n");
- }
- else {
- printf("DecodeObjectId failed: %d\n", ret);
- }
- }
- #endif /* HAVE_OID_DECODING */
- return ret;
- }
- #endif /* ASN_DUMP_OID */
- /* Get the OID data and verify it is of the type specified when compiled in.
- *
- * @param [in] input Buffer holding OID.
- * @param [in, out] inOutIdx On in, starting index of OID.
- * On out, end of parsed OID.
- * @param [out] oid OID id.
- * @param [in] oidType Expected type of OID. Define NO_VERIFY_OID to
- * not compile in check.
- * @param [in] length Length of OID data in buffer.
- * @return 0 on success.
- * @return ASN_UNKNOWN_OID_E when OID is not recognized.
- * @return BUFFER_E when not enough bytes for proper decode. (ASN_DUMP_OID and
- * HAVE_OID_DECODING)
- */
- static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
- word32 oidType, int length)
- {
- int ret = 0;
- word32 idx = *inOutIdx;
- #ifndef NO_VERIFY_OID
- word32 actualOidSz;
- const byte* actualOid;
- const byte* checkOid = NULL;
- word32 checkOidSz;
- #endif /* NO_VERIFY_OID */
- #ifdef HAVE_PQC
- word32 found_collision = 0;
- #endif
- (void)oidType;
- *oid = 0;
- #ifndef NO_VERIFY_OID
- /* Keep references to OID data and length for check. */
- actualOid = &input[idx];
- actualOidSz = (word32)length;
- #endif /* NO_VERIFY_OID */
- #if defined(HAVE_PQC) && defined(HAVE_LIBOQS)
- /* Since we are summing it up, there could be collisions...and indeed there
- * are: SPHINCS_FAST_LEVEL1 and SPHINCS_FAST_LEVEL3.
- *
- * We will look for the special case of SPHINCS_FAST_LEVEL3 and set *oid to
- * 283 instead of 281; 282 is taken.
- *
- * These hacks will hopefully disappear when new standardized OIDs appear.
- */
- if (memcmp(&input[idx], sigSphincsFast_Level3Oid,
- sizeof(sigSphincsFast_Level3Oid)) == 0) {
- found_collision = SPHINCS_FAST_LEVEL3k;
- }
- #endif /* HAVE_PQC */
- /* Sum it up for now. */
- while (length--) {
- /* odd HC08 compiler behavior here when input[idx++] */
- *oid += (word32)input[idx];
- idx++;
- }
- #ifdef HAVE_PQC
- if (found_collision) {
- *oid = found_collision;
- }
- #endif /* HAVE_PQC */
- /* Return the index after the OID data. */
- *inOutIdx = idx;
- #ifndef NO_VERIFY_OID
- /* 'Ignore' type means we don't care which OID it is. */
- if (oidType != oidIgnoreType) {
- /* Get the OID data for the id-type. */
- checkOid = OidFromId(*oid, oidType, &checkOidSz);
- #if defined(WOLFSSL_FPKI)
- /* Handle OID sum collision of
- AES256CBCb (454) 2.16.840.1.101.3.4.1.42
- CP_FPKI_PIV_AUTH_HW_OID (454) 2.16.840.1.101.3.2.1.3.41
- */
- #if defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
- if ((actualOidSz == (word32)sizeof(blkAes256CbcOid)) &&
- (XMEMCMP(actualOid, blkAes256CbcOid,
- sizeof(blkAes256CbcOid)) == 0)) {
- checkOid = blkAes256CbcOid;
- checkOidSz = sizeof(blkAes256CbcOid);
- }
- #endif /* HAVE_AES_CBC */
- #endif /* WOLFSSL_FPKI */
- #ifdef ASN_DUMP_OID
- /* Dump out the data for debug. */
- ret = DumpOID(actualOid, actualOidSz, *oid, oidType);
- #endif
- /* TODO: Want to fail when checkOid is NULL.
- * Can't as too many situations where unknown OID is to be
- * supported. Extra parameter for must not be NULL?
- */
- /* Check that the OID data matches what we found for the OID id. */
- if ((ret == 0) && (checkOid != NULL) && ((checkOidSz != actualOidSz) ||
- (XMEMCMP(actualOid, checkOid, checkOidSz) != 0))) {
- WOLFSSL_MSG("OID Check Failed");
- WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
- ret = ASN_UNKNOWN_OID_E;
- }
- }
- #endif /* NO_VERIFY_OID */
- return ret;
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for an OBJECT_ID. */
- static const ASNItem objectIdASN[] = {
- /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 }
- };
- enum {
- OBJECTIDASN_IDX_OID = 0
- };
- /* Number of items in ASN.1 template for an OBJECT_ID. */
- #define objectIdASN_Length (sizeof(objectIdASN) / sizeof(ASNItem))
- #endif
- /* Get the OID id/sum from the BER encoded OBJECT_ID.
- *
- * @param [in] input Buffer holding BER encoded data.
- * @param [in, out] inOutIdx On in, start of OBJECT_ID.
- * On out, start of ASN.1 item after OBJECT_ID.
- * @param [out] oid Id of OID in OBJECT_ID data.
- * @param [in] oidType Type of OID to expect.
- * @param [in] maxIdx Maximum index of data in buffer.
- * @return 0 on success.
- * @return ASN_PARSE_E when encoding is invalid.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- */
- int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
- word32 oidType, word32 maxIdx)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret, length;
- WOLFSSL_ENTER("GetObjectId");
- ret = GetASNObjectId(input, inOutIdx, &length, maxIdx);
- if (ret != 0)
- return ret;
- return GetOID(input, inOutIdx, oid, oidType, length);
- #else
- ASNGetData dataASN[objectIdASN_Length];
- int ret;
- WOLFSSL_ENTER("GetObjectId");
- /* Clear dynamic data and set OID type expected. */
- XMEMSET(dataASN, 0, sizeof(dataASN));
- GetASN_OID(&dataASN[OBJECTIDASN_IDX_OID], oidType);
- /* Decode OBJECT_ID. */
- ret = GetASN_Items(objectIdASN, dataASN, objectIdASN_Length, 0, input,
- inOutIdx, maxIdx);
- if (ret == 0) {
- /* Return the id/sum. */
- *oid = dataASN[OBJECTIDASN_IDX_OID].data.oid.sum;
- }
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #ifndef WOLFSSL_ASN_TEMPLATE
- static int SkipObjectId(const byte* input, word32* inOutIdx, word32 maxIdx)
- {
- word32 idx = *inOutIdx;
- int length;
- int ret;
- ret = GetASNObjectId(input, &idx, &length, maxIdx);
- if (ret != 0)
- return ret;
- idx += (word32)length;
- *inOutIdx = idx;
- return 0;
- }
- #endif
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for an algorithm identifier. */
- static const ASNItem algoIdASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* NULL */ { 1, ASN_TAG_NULL, 0, 0, 1 },
- };
- enum {
- ALGOIDASN_IDX_SEQ = 0,
- ALGOIDASN_IDX_OID,
- ALGOIDASN_IDX_NULL
- };
- /* Number of items in ASN.1 template for an algorithm identifier. */
- #define algoIdASN_Length (sizeof(algoIdASN) / sizeof(ASNItem))
- #endif
- /* Get the OID id/sum from the BER encoding of an algorithm identifier.
- *
- * NULL tag is skipped if present.
- *
- * @param [in] input Buffer holding BER encoded data.
- * @param [in, out] inOutIdx On in, start of algorithm identifier.
- * On out, start of ASN.1 item after algorithm id.
- * @param [out] oid Id of OID in algorithm identifier data.
- * @param [in] oidType Type of OID to expect.
- * @param [in] maxIdx Maximum index of data in buffer.
- * @return 0 on success.
- * @return ASN_PARSE_E when encoding is invalid.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- */
- int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
- word32 oidType, word32 maxIdx)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int length;
- word32 idx = *inOutIdx;
- int ret;
- *oid = 0;
- WOLFSSL_ENTER("GetAlgoId");
- if (GetSequence(input, &idx, &length, maxIdx) < 0)
- return ASN_PARSE_E;
- if (GetObjectId(input, &idx, oid, oidType, maxIdx) < 0)
- return ASN_OBJECT_ID_E;
- /* could have NULL tag and 0 terminator, but may not */
- if (idx < maxIdx) {
- word32 localIdx = idx; /*use localIdx to not advance when checking tag*/
- byte tag;
- if (GetASNTag(input, &localIdx, &tag, maxIdx) == 0) {
- if (tag == ASN_TAG_NULL) {
- ret = GetASNNull(input, &idx, maxIdx);
- if (ret != 0)
- return ret;
- }
- }
- }
- *inOutIdx = idx;
- return 0;
- #else
- DECL_ASNGETDATA(dataASN, algoIdASN_Length);
- int ret = 0;
- WOLFSSL_ENTER("GetAlgoId");
- CALLOC_ASNGETDATA(dataASN, algoIdASN_Length, ret, NULL);
- if (ret == 0) {
- /* Set OID type expected. */
- GetASN_OID(&dataASN[ALGOIDASN_IDX_OID], oidType);
- /* Decode the algorithm identifier. */
- ret = GetASN_Items(algoIdASN, dataASN, algoIdASN_Length, 0, input,
- inOutIdx, maxIdx);
- }
- if (ret == 0) {
- /* Return the OID id/sum. */
- *oid = dataASN[ALGOIDASN_IDX_OID].data.oid.sum;
- }
- FREE_ASNGETDATA(dataASN, NULL);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #ifndef NO_RSA
- #ifdef WC_RSA_PSS
- /* RFC 8017 - PKCS #1 has RSA PSS parameter ASN definition. */
- /* Convert a hash OID to a hash type.
- *
- * @param [in] oid Hash OID.
- * @param [out] type Hash type.
- * @return 0 on success.
- * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
- */
- static int RsaPssHashOidToType(word32 oid, enum wc_HashType* type)
- {
- int ret = 0;
- switch (oid) {
- /* SHA-1 is missing as it is the default is not allowed to appear. */
- #ifdef WOLFSSL_SHA224
- case SHA224h:
- *type = WC_HASH_TYPE_SHA224;
- break;
- #endif
- #ifndef NO_SHA256
- case SHA256h:
- *type = WC_HASH_TYPE_SHA256;
- break;
- #endif
- #ifdef WOLFSSL_SHA384
- case SHA384h:
- *type = WC_HASH_TYPE_SHA384;
- break;
- #endif
- #ifdef WOLFSSL_SHA512
- case SHA512h:
- *type = WC_HASH_TYPE_SHA512;
- break;
- /* TODO: SHA512_224h */
- /* TODO: SHA512_256h */
- #endif
- default:
- ret = ASN_PARSE_E;
- break;
- }
- return ret;
- }
- /* Convert a hash OID to a MGF1 type.
- *
- * @param [in] oid Hash OID.
- * @param [out] mgf MGF type.
- * @return 0 on success.
- * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
- */
- static int RsaPssHashOidToMgf1(word32 oid, int* mgf)
- {
- int ret = 0;
- switch (oid) {
- /* SHA-1 is missing as it is the default is not allowed to appear. */
- #ifdef WOLFSSL_SHA224
- case SHA224h:
- *mgf = WC_MGF1SHA224;
- break;
- #endif
- #ifndef NO_SHA256
- case SHA256h:
- *mgf = WC_MGF1SHA256;
- break;
- #endif
- #ifdef WOLFSSL_SHA384
- case SHA384h:
- *mgf = WC_MGF1SHA384;
- break;
- #endif
- #ifdef WOLFSSL_SHA512
- case SHA512h:
- *mgf = WC_MGF1SHA512;
- break;
- /* TODO: SHA512_224h */
- /* TODO: SHA512_256h */
- #endif
- default:
- ret = ASN_PARSE_E;
- break;
- }
- return ret;
- }
- #ifndef NO_CERTS
- /* Convert a hash OID to a fake signature OID.
- *
- * @param [in] oid Hash OID.
- * @param [out] sigOid Signature OID to pass wto HashForSignature().
- * @return 0 on success.
- * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
- */
- static int RsaPssHashOidToSigOid(word32 oid, word32* sigOid)
- {
- int ret = 0;
- switch (oid) {
- #ifndef NO_SHA
- case WC_HASH_TYPE_SHA:
- *sigOid = CTC_SHAwRSA;
- break;
- #endif
- #ifdef WOLFSSL_SHA224
- case WC_HASH_TYPE_SHA224:
- *sigOid = CTC_SHA224wRSA;
- break;
- #endif
- #ifndef NO_SHA256
- case WC_HASH_TYPE_SHA256:
- *sigOid = CTC_SHA256wRSA;
- break;
- #endif
- #ifdef WOLFSSL_SHA384
- case WC_HASH_TYPE_SHA384:
- *sigOid = CTC_SHA384wRSA;
- break;
- #endif
- #ifdef WOLFSSL_SHA512
- case WC_HASH_TYPE_SHA512:
- *sigOid = CTC_SHA512wRSA;
- break;
- #endif
- /* TODO: SHA512_224h */
- /* TODO: SHA512_256h */
- /* Not supported by HashForSignature() */
- default:
- ret = ASN_PARSE_E;
- break;
- }
- return ret;
- }
- #endif
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN tag for hashAlgorigthm. */
- #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | 0)
- /* ASN tag for maskGenAlgorithm. */
- #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | 1)
- /* ASN tag for saltLength. */
- #define ASN_TAG_RSA_PSS_SALTLEN (ASN_CONTEXT_SPECIFIC | 2)
- /* ASN tag for trailerField. */
- #define ASN_TAG_RSA_PSS_TRAILER (ASN_CONTEXT_SPECIFIC | 3)
- /* ASN.1 template for RSA PSS parameters. */
- static const ASNItem rsaPssParamsASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* HASH */ { 1, ASN_TAG_RSA_PSS_HASH, 1, 1, 1 },
- /* HASHSEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
- /* HASHOID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
- /* HASHNULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
- /* MGF */ { 1, ASN_TAG_RSA_PSS_MGF, 1, 1, 1 },
- /* MGFSEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
- /* MGFOID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
- /* MGFPARAM */ { 3, ASN_SEQUENCE, 1, 1, 0 },
- /* MGFHOID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
- /* MGFHNULL */ { 4, ASN_TAG_NULL, 0, 0, 1 },
- /* SALTLEN */ { 1, ASN_TAG_RSA_PSS_SALTLEN, 1, 1, 1 },
- /* SALTLENINT */ { 2, ASN_INTEGER, 0, 0, 0 },
- /* TRAILER */ { 1, ASN_TAG_RSA_PSS_TRAILER, 1, 1, 1 },
- /* TRAILERINT */ { 2, ASN_INTEGER, 0, 0, 0 },
- };
- enum {
- RSAPSSPARAMSASN_IDX_SEQ = 0,
- RSAPSSPARAMSASN_IDX_HASH,
- RSAPSSPARAMSASN_IDX_HASHSEQ,
- RSAPSSPARAMSASN_IDX_HASHOID,
- RSAPSSPARAMSASN_IDX_HASHNULL,
- RSAPSSPARAMSASN_IDX_MGF,
- RSAPSSPARAMSASN_IDX_MGFSEQ,
- RSAPSSPARAMSASN_IDX_MGFOID,
- RSAPSSPARAMSASN_IDX_MGFPARAM,
- RSAPSSPARAMSASN_IDX_MGFHOID,
- RSAPSSPARAMSASN_IDX_MGFHNULL,
- RSAPSSPARAMSASN_IDX_SALTLEN,
- RSAPSSPARAMSASN_IDX_SALTLENINT,
- RSAPSSPARAMSASN_IDX_TRAILER,
- RSAPSSPARAMSASN_IDX_TRAILERINT,
- };
- /* Number of items in ASN.1 template for an algorithm identifier. */
- #define rsaPssParamsASN_Length (sizeof(rsaPssParamsASN) / sizeof(ASNItem))
- #else
- /* ASN tag for hashAlgorigthm. */
- #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0)
- /* ASN tag for maskGenAlgorithm. */
- #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)
- /* ASN tag for saltLength. */
- #define ASN_TAG_RSA_PSS_SALTLEN (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)
- /* ASN tag for trailerField. */
- #define ASN_TAG_RSA_PSS_TRAILER (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)
- #endif
- /* Decode the RSA PSS parameters.
- *
- * @param [in] params Buffer holding BER encoded RSA PSS parameters.
- * @param [in] sz Size of data in buffer in bytes.
- * @param [out] hash Hash algorithm to use on message.
- * @param [out] mgf MGF algorithm to use with PSS padding.
- * @param [out] saltLen Length of salt in PSS padding.
- * @return BAD_FUNC_ARG when the params is NULL.
- * @return ASN_PARSE_E when the decoding fails.
- * @return 0 on success.
- */
- static int DecodeRsaPssParams(const byte* params, word32 sz,
- enum wc_HashType* hash, int* mgf, int* saltLen)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret = 0;
- word32 idx = 0;
- int len = 0;
- word32 oid = 0;
- byte tag;
- int length;
- if (params == NULL) {
- ret = BAD_FUNC_ARG;
- }
- if ((ret == 0) && (GetSequence_ex(params, &idx, &len, sz, 1) < 0)) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_HASH)) {
- /* Hash algorithm to use on message. */
- if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- if (GetAlgoId(params, &idx, &oid, oidHashType, sz) < 0) {
- ret = ASN_PARSE_E;
- }
- }
- if (ret == 0) {
- ret = RsaPssHashOidToType(oid, hash);
- }
- }
- else {
- /* Default hash algorithm. */
- *hash = WC_HASH_TYPE_SHA;
- }
- }
- if (ret == 0) {
- if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_MGF)) {
- /* MGF and hash algorithm to use with padding. */
- if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- if (GetAlgoId(params, &idx, &oid, oidIgnoreType, sz) < 0) {
- ret = ASN_PARSE_E;
- }
- }
- if ((ret == 0) && (oid != MGF1_OID)) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- ret = GetAlgoId(params, &idx, &oid, oidHashType, sz);
- if (ret == 0) {
- ret = RsaPssHashOidToMgf1(oid, mgf);
- }
- }
- }
- else {
- /* Default MGF/Hash algorithm. */
- *mgf = WC_MGF1SHA1;
- }
- }
- if (ret == 0) {
- if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_SALTLEN)) {
- /* Salt length to use with padding. */
- if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- ret = GetInteger16Bit(params, &idx, sz);
- if (ret >= 0) {
- *saltLen = ret;
- ret = 0;
- }
- }
- }
- else {
- /* Default salt length. */
- *saltLen = 20;
- }
- }
- if (ret == 0) {
- if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_TRAILER)) {
- /* Unused - trialerField. */
- if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- ret = GetInteger16Bit(params, &idx, sz);
- if (ret > 0) {
- ret = 0;
- }
- }
- }
- }
- if ((ret == 0) && (idx != sz)) {
- ret = ASN_PARSE_E;
- }
- return ret;
- #else
- DECL_ASNGETDATA(dataASN, rsaPssParamsASN_Length);
- int ret = 0;
- word16 sLen = 20;
- if (params == NULL) {
- ret = BAD_FUNC_ARG;
- }
- CALLOC_ASNGETDATA(dataASN, rsaPssParamsASN_Length, ret, NULL);
- if (ret == 0) {
- word32 inOutIdx = 0;
- /* Default values. */
- *hash = WC_HASH_TYPE_SHA;
- *mgf = WC_MGF1SHA1;
- /* Set OID type expected. */
- GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_HASHOID], oidHashType);
- GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_MGFHOID], oidHashType);
- /* Place the salt length into 16-bit var sLen. */
- GetASN_Int16Bit(&dataASN[RSAPSSPARAMSASN_IDX_SALTLENINT], &sLen);
- /* Decode the algorithm identifier. */
- ret = GetASN_Items(rsaPssParamsASN, dataASN, rsaPssParamsASN_Length, 1,
- params, &inOutIdx, sz);
- }
- if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_HASHOID].tag != 0)) {
- word32 oid = dataASN[RSAPSSPARAMSASN_IDX_HASHOID].data.oid.sum;
- ret = RsaPssHashOidToType(oid, hash);
- }
- if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].tag != 0)) {
- word32 oid = dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].data.oid.sum;
- ret = RsaPssHashOidToMgf1(oid, mgf);
- }
- if (ret == 0) {
- *saltLen = sLen;
- }
- FREE_ASNGETDATA(dataASN, NULL);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #endif /* WC_RSA_PSS */
- #ifndef HAVE_USER_RSA
- #if defined(WOLFSSL_ASN_TEMPLATE) || (!defined(NO_CERTS) && \
- (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
- defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)))
- /* Byte offset of numbers in RSA key. */
- size_t rsaIntOffset[] = {
- OFFSETOF(RsaKey, n),
- OFFSETOF(RsaKey, e),
- #ifndef WOLFSSL_RSA_PUBLIC_ONLY
- OFFSETOF(RsaKey, d),
- OFFSETOF(RsaKey, p),
- OFFSETOF(RsaKey, q),
- #if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
- OFFSETOF(RsaKey, dP),
- OFFSETOF(RsaKey, dQ),
- OFFSETOF(RsaKey, u)
- #endif
- #endif
- };
- /* Get a number from the RSA key based on an index.
- *
- * Order: { n, e, d, p, q, dP, dQ, u }
- *
- * Caller must ensure index is not invalid!
- *
- * @param [in] key RSA key object.
- * @param [in] idx Index of number.
- * @return A pointer to an mp_int when valid index.
- * @return NULL when invalid index.
- */
- static mp_int* GetRsaInt(RsaKey* key, int idx)
- {
- /* Cast key to byte array to and use offset to get to mp_int field. */
- return (mp_int*)(((byte*)key) + rsaIntOffset[idx]);
- }
- #endif
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for an RSA private key.
- * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
- */
- static const ASNItem rsaKeyASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* Integers need to be in this specific order
- * as asn code depends on this. */
- /* N */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* E */ { 1, ASN_INTEGER, 0, 0, 0 },
- #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
- /* D */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* DP */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* DQ */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* U */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* otherPrimeInfos OtherPrimeInfos OPTIONAL
- * v2 - multiprime */
- #endif
- };
- enum {
- RSAKEYASN_IDX_SEQ = 0,
- RSAKEYASN_IDX_VER,
- /* Integers need to be in this specific order
- * as asn code depends on this. */
- RSAKEYASN_IDX_N,
- RSAKEYASN_IDX_E,
- #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
- RSAKEYASN_IDX_D,
- RSAKEYASN_IDX_P,
- RSAKEYASN_IDX_Q,
- RSAKEYASN_IDX_DP,
- RSAKEYASN_IDX_DQ,
- RSAKEYASN_IDX_U,
- #endif
- WOLF_ENUM_DUMMY_LAST_ELEMENT(RSAKEYASN_IDX)
- };
- /* Number of items in ASN.1 template for an RSA private key. */
- #define rsaKeyASN_Length (sizeof(rsaKeyASN) / sizeof(ASNItem))
- #endif
- /* Decode RSA private key.
- *
- * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
- *
- * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
- * being extracted.
- *
- * @param [in] input Buffer holding BER encoded data.
- * @param [in, out] inOutIdx On in, start of RSA private key.
- * On out, start of ASN.1 item after RSA private key.
- * @param [in, out] key RSA key object. May be NULL.
- * @param [out] keySz Size of key in bytes. May be NULL.
- * @param [in] inSz Number of bytes in buffer.
- * @return 0 on success.
- * @return BAD_FUNC_ARG when input or inOutIdx is NULL.
- * @return BAD_FUNC_ARG when key and keySz are NULL.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- * @return MP_INIT_E when the unable to initialize an mp_int.
- * @return ASN_GETINT_E when the unable to convert data to an mp_int.
- */
- static int _RsaPrivateKeyDecode(const byte* input, word32* inOutIdx,
- RsaKey* key, int* keySz, word32 inSz)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int version, length;
- word32 algId = 0;
- if (inOutIdx == NULL || input == NULL || (key == NULL && keySz == NULL)) {
- return BAD_FUNC_ARG;
- }
- /* if has pkcs8 header skip it */
- if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
- /* ignore error, did not have pkcs8 header */
- }
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
- return ASN_PARSE_E;
- if (key == NULL) {
- int i;
- /* Modulus */
- if (GetASNInt(input, inOutIdx, keySz, inSz) < 0) {
- return ASN_PARSE_E;
- }
- *inOutIdx += (word32)*keySz;
- for (i = 1; i < RSA_INTS; i++) {
- if (SkipInt(input, inOutIdx, inSz) < 0) {
- return ASN_RSA_KEY_E;
- }
- }
- }
- else {
- key->type = RSA_PRIVATE;
- #ifdef WOLFSSL_CHECK_MEM_ZERO
- mp_memzero_add("Decode RSA key d", &key->d);
- mp_memzero_add("Decode RSA key p", &key->p);
- mp_memzero_add("Decode RSA key q", &key->q);
- #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
- !defined(RSA_LOW_MEM)) && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
- mp_memzero_add("Decode RSA key dP", &key->dP);
- mp_memzero_add("Decode RSA key dQ", &key->dQ);
- mp_memzero_add("Decode RSA key u", &key->u);
- #endif
- #endif
- if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
- GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
- #ifndef WOLFSSL_RSA_PUBLIC_ONLY
- GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
- GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
- GetInt(&key->q, input, inOutIdx, inSz) < 0
- #else
- SkipInt(input, inOutIdx, inSz) < 0 ||
- SkipInt(input, inOutIdx, inSz) < 0 ||
- SkipInt(input, inOutIdx, inSz) < 0
- #endif
- ) {
- return ASN_RSA_KEY_E;
- }
- #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)) \
- && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
- if (GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
- GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
- GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
- #else
- if (SkipInt(input, inOutIdx, inSz) < 0 ||
- SkipInt(input, inOutIdx, inSz) < 0 ||
- SkipInt(input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
- #endif
- #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
- if (wc_InitRsaHw(key) != 0) {
- return BAD_STATE_E;
- }
- #endif
- }
- return 0;
- #else
- DECL_ASNGETDATA(dataASN, rsaKeyASN_Length);
- int ret = 0;
- byte version = (byte)-1;
- #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
- word32 algId = 0;
- #endif
- void* heap = NULL;
- /* Check validity of parameters. */
- if ((inOutIdx == NULL) || (input == NULL) || ((key == NULL) &&
- (keySz == NULL))) {
- ret = BAD_FUNC_ARG;
- }
- if ((ret == 0) && (key != NULL)) {
- heap = key->heap;
- }
- #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
- if (ret == 0) {
- /* if has pkcs8 header skip it */
- if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
- /* ignore error, did not have pkcs8 header */
- }
- }
- #endif
- (void)heap;
- CALLOC_ASNGETDATA(dataASN, rsaKeyASN_Length, ret, heap);
- if (ret == 0) {
- /* Register variable to hold version field. */
- GetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], &version);
- /* Setup data to store INTEGER data in mp_int's in RSA object. */
- #if defined(WOLFSSL_RSA_PUBLIC_ONLY)
- #define RSA_ASN_INTS RSA_PUB_INTS
- /* Not extracting all data from BER encoding. */
- #define RSA_ASN_COMPLETE 0
- #else
- #define RSA_ASN_INTS RSA_INTS
- /* Extracting all data from BER encoding. */
- #define RSA_ASN_COMPLETE 1
- #endif
- if (key != NULL) {
- int i;
- /* Extract all public fields. */
- for (i = 0; i < RSA_ASN_INTS; i++) {
- GetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i],
- GetRsaInt(key, i));
- }
- }
- /* Parse BER encoding for RSA private key. */
- ret = GetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length,
- RSA_ASN_COMPLETE, input, inOutIdx, inSz);
- }
- /* Check version: 0 - two prime, 1 - multi-prime
- * Multi-prime has optional sequence after coefficient for extra primes.
- * If extra primes, parsing will fail as not all the buffer was used.
- */
- if ((ret == 0) && (version > PKCS1v1)) {
- ret = ASN_PARSE_E;
- }
- if ((ret == 0) && (key != NULL)) {
- #if !defined(WOLFSSL_RSA_PUBLIC_ONLY)
- /* RSA key object has all private key values. */
- key->type = RSA_PRIVATE;
- #else
- /* RSA key object has all public key values. */
- key->type = RSA_PUBLIC;
- #endif
- #ifdef WOLFSSL_XILINX_CRYPT
- if (wc_InitRsaHw(key) != 0)
- ret = BAD_STATE_E;
- #endif
- }
- else if (ret == 0) {
- /* Not filling in key but do want key size. */
- *keySz = (int)dataASN[(byte)RSAKEYASN_IDX_N].length;
- /* Check whether first byte of data is 0x00 and drop it. */
- if (input[(int)dataASN[RSAKEYASN_IDX_E].offset - *keySz] == 0) {
- (*keySz)--;
- }
- }
- FREE_ASNGETDATA(dataASN, heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- /* Decode RSA private key.
- *
- * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
- *
- * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
- * being extracted.
- *
- * @param [in] input Buffer holding BER encoded data.
- * @param [in, out] inOutIdx On in, start of RSA private key.
- * On out, start of ASN.1 item after RSA private key.
- * @param [in, out] key RSA key object.
- * @param [in] inSz Number of bytes in buffer.
- * @return 0 on success.
- * @return BAD_FUNC_ARG when input, inOutIdx or key is NULL.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- * @return MP_INIT_E when the unable to initialize an mp_int.
- * @return ASN_GETINT_E when the unable to convert data to an mp_int.
- */
- int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
- word32 inSz)
- {
- if (key == NULL) {
- return BAD_FUNC_ARG;
- }
- return _RsaPrivateKeyDecode(input, inOutIdx, key, NULL, inSz);
- }
- /* Valdidate RSA private key ASN.1 encoding.
- *
- * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
- *
- * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
- * being extracted.
- *
- * @param [in] input Buffer holding BER encoded data.
- * @param [in, out] inOutIdx On in, start of RSA private key.
- * On out, start of ASN.1 item after RSA private key.
- * @param [in] inSz Number of bytes in buffer.
- * @return 0 on success.
- * @return BAD_FUNC_ARG when input, inOutIdx or keySz is NULL.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- * @return MP_INIT_E when the unable to initialize an mp_int.
- * @return ASN_GETINT_E when the unable to convert data to an mp_int.
- */
- int wc_RsaPrivateKeyValidate(const byte* input, word32* inOutIdx, int* keySz,
- word32 inSz)
- {
- return _RsaPrivateKeyDecode(input, inOutIdx, NULL, keySz, inSz);
- }
- #endif /* HAVE_USER_RSA */
- #endif /* NO_RSA */
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for a PKCS #8 key.
- * Ignoring optional attributes and public key.
- * PKCS #8: RFC 5958, 2 - PrivateKeyInfo
- */
- static const ASNItem pkcs8KeyASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* PKEY_ALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* PKEY_ALGO_OID_KEY */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
- /* PKEY_ALGO_OID_CURVE */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
- /* PKEY_ALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
- #ifdef WC_RSA_PSS
- /* PKEY_ALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
- #endif
- /* PKEY_DATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
- /* attributes [0] Attributes OPTIONAL */
- /* [[2: publicKey [1] PublicKey OPTIONAL ]] */
- };
- enum {
- PKCS8KEYASN_IDX_SEQ = 0,
- PKCS8KEYASN_IDX_VER,
- PKCS8KEYASN_IDX_PKEY_ALGO_SEQ,
- PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY,
- PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE,
- PKCS8KEYASN_IDX_PKEY_ALGO_NULL,
- #ifdef WC_RSA_PSS
- PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ,
- #endif
- PKCS8KEYASN_IDX_PKEY_DATA,
- WOLF_ENUM_DUMMY_LAST_ELEMENT(PKCS8KEYASN_IDX)
- };
- /* Number of items in ASN.1 template for a PKCS #8 key. */
- #define pkcs8KeyASN_Length (sizeof(pkcs8KeyASN) / sizeof(ASNItem))
- #endif
- /* Remove PKCS #8 header around an RSA, ECDSA, Ed25519, or Ed448.
- *
- * @param [in] input Buffer holding BER data.
- * @param [in, out] inOutIdx On in, start of PKCS #8 encoding.
- * On out, start of encoded key.
- * @param [in] sz Size of data in buffer.
- * @param [out] algId Key's algorithm id from PKCS #8 header.
- * @return Length of key data on success.
- * @return BAD_FUNC_ARG when input or inOutIdx is NULL.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- */
- int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz,
- word32* algId)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx;
- int version, length;
- int ret;
- byte tag;
- if (input == NULL || inOutIdx == NULL)
- return BAD_FUNC_ARG;
- idx = *inOutIdx;
- if (GetSequence(input, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- if (GetMyVersion(input, &idx, &version, sz) < 0)
- return ASN_PARSE_E;
- if (GetAlgoId(input, &idx, algId, oidKeyType, sz) < 0)
- return ASN_PARSE_E;
- if (GetASNTag(input, &idx, &tag, sz) < 0)
- return ASN_PARSE_E;
- idx = idx - 1; /* reset idx after finding tag */
- #if defined(WC_RSA_PSS) && !defined(NO_RSA)
- if (*algId == RSAPSSk && tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
- word32 seqIdx = idx;
- int seqLen;
- /* Not set when -1. */
- enum wc_HashType hash = WC_HASH_TYPE_NONE;
- int mgf = -1;
- int saltLen = 0;
- if (GetSequence(input, &idx, &seqLen, sz) < 0) {
- return ASN_PARSE_E;
- }
- /* Get the private key parameters. */
- ret = DecodeRsaPssParams(input + seqIdx,
- seqLen + idx - seqIdx, &hash, &mgf, &saltLen);
- if (ret != 0) {
- return ASN_PARSE_E;
- }
- /* TODO: store parameters so that usage can be checked. */
- idx += seqLen;
- }
- #endif /* WC_RSA_PSS && !NO_RSA */
- if (tag == ASN_OBJECT_ID) {
- if (SkipObjectId(input, &idx, sz) < 0)
- return ASN_PARSE_E;
- }
- ret = GetOctetString(input, &idx, &length, sz);
- if (ret < 0) {
- if (ret == BUFFER_E)
- return ASN_PARSE_E;
- /* Some private keys don't expect an octet string */
- WOLFSSL_MSG("Couldn't find Octet string");
- }
- *inOutIdx = idx;
- return length;
- #else
- DECL_ASNGETDATA(dataASN, pkcs8KeyASN_Length);
- int ret = 0;
- word32 oid = 9;
- byte version;
- word32 idx;
- /* Check validity of parameters. */
- if (input == NULL || inOutIdx == NULL) {
- return BAD_FUNC_ARG;
- }
- idx = *inOutIdx;
- CALLOC_ASNGETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
- if (ret == 0) {
- /* Get version, check key type and curve type. */
- GetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], &version);
- GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], oidKeyType);
- GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE], oidCurveType);
- /* Parse data. */
- ret = GetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, 1, input,
- &idx, sz);
- }
- if (ret == 0) {
- /* Key type OID. */
- oid = dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY].data.oid.sum;
- /* Version 1 includes an optional public key.
- * If public key is included then the parsing will fail as it did not
- * use all the data.
- */
- if (version > PKCS8v1) {
- ret = ASN_PARSE_E;
- }
- }
- if (ret == 0) {
- switch (oid) {
- #ifndef NO_RSA
- case RSAk:
- /* Must have NULL item but not OBJECT_ID item. */
- if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag == 0) ||
- (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
- ret = ASN_PARSE_E;
- }
- break;
- #ifdef WC_RSA_PSS
- case RSAPSSk:
- /* Must not have NULL item. */
- if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
- ret = ASN_PARSE_E;
- }
- if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].tag != 0) {
- enum wc_HashType hash;
- int mgf;
- int saltLen;
- const byte* params = GetASNItem_Addr(
- dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
- word32 paramsSz = GetASNItem_Length(
- dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
- /* Validate the private key parameters. */
- ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf,
- &saltLen);
- if (ret != 0) {
- return ASN_PARSE_E;
- }
- /* TODO: store parameters so that usage can be checked. */
- }
- break;
- #endif
- #endif
- #ifdef HAVE_ECC
- case ECDSAk:
- /* Must not have NULL item. */
- if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
- ret = ASN_PARSE_E;
- }
- break;
- #endif
- #ifdef HAVE_ED25519
- case ED25519k:
- /* Neither NULL item nor OBJECT_ID item allowed. */
- if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
- (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
- ret = ASN_PARSE_E;
- }
- break;
- #endif
- #ifdef HAVE_CURVE25519
- case X25519k:
- /* Neither NULL item nor OBJECT_ID item allowed. */
- if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
- (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
- ret = ASN_PARSE_E;
- }
- break;
- #endif
- #ifdef HAVE_ED448
- case ED448k:
- /* Neither NULL item nor OBJECT_ID item allowed. */
- if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
- (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
- ret = ASN_PARSE_E;
- }
- break;
- #endif
- #ifdef HAVE_CURVE448
- case X448k:
- /* Neither NULL item nor OBJECT_ID item allowed. */
- if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
- (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
- ret = ASN_PARSE_E;
- }
- break;
- #endif
- /* DSAk not supported. */
- /* Falcon, Dilithium and Sphincs not supported. */
- /* Ignore OID lookup failures. */
- default:
- break;
- }
- }
- if (ret == 0) {
- /* Return algorithm id of internal key. */
- *algId = oid;
- /* Return index to start of internal key. */
- *inOutIdx = GetASNItem_DataIdx(dataASN[PKCS8KEYASN_IDX_PKEY_DATA], input);
- /* Return value is length of internal key. */
- ret = (int)dataASN[PKCS8KEYASN_IDX_PKEY_DATA].data.ref.length;
- }
- FREE_ASNGETDATA(dataASN, NULL);
- return ret;
- #endif
- }
- /* TODO: test case */
- int ToTraditionalInline(const byte* input, word32* inOutIdx, word32 sz)
- {
- word32 oid;
- return ToTraditionalInline_ex(input, inOutIdx, sz, &oid);
- }
- #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
- /* Remove PKCS8 header, move beginning of traditional to beginning of input */
- int ToTraditional_ex(byte* input, word32 sz, word32* algId)
- {
- word32 inOutIdx = 0;
- int length;
- if (input == NULL)
- return BAD_FUNC_ARG;
- length = ToTraditionalInline_ex(input, &inOutIdx, sz, algId);
- if (length < 0)
- return length;
- if ((word32)length + inOutIdx > sz)
- return BUFFER_E;
- XMEMMOVE(input, input + inOutIdx, (size_t)length);
- return length;
- }
- int ToTraditional(byte* input, word32 sz)
- {
- word32 oid;
- return ToTraditional_ex(input, sz, &oid);
- }
- #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
- #if defined(HAVE_PKCS8)
- int wc_GetPkcs8TraditionalOffset(byte* input, word32* inOutIdx, word32 sz)
- {
- int length;
- word32 algId;
- if (input == NULL || inOutIdx == NULL || (*inOutIdx > sz))
- return BAD_FUNC_ARG;
- length = ToTraditionalInline_ex(input, inOutIdx, sz, &algId);
- return length;
- }
- int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz,
- int algoID, const byte* curveOID, word32 oidSz)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 keyIdx = 0;
- word32 tmpSz = 0;
- word32 sz;
- word32 tmpAlgId = 0;
- /* If out is NULL then return the max size needed
- * + 2 for ASN_OBJECT_ID and ASN_OCTET_STRING tags */
- if (out == NULL && outSz != NULL) {
- *outSz = keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
- + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2;
- if (curveOID != NULL)
- *outSz += oidSz + MAX_LENGTH_SZ + 1;
- WOLFSSL_MSG("Checking size of PKCS8");
- return LENGTH_ONLY_E;
- }
- WOLFSSL_ENTER("wc_CreatePKCS8Key");
- if (key == NULL || out == NULL || outSz == NULL) {
- return BAD_FUNC_ARG;
- }
- /* check the buffer has enough room for largest possible size */
- if (curveOID != NULL) {
- if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
- + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 3 + oidSz + MAX_LENGTH_SZ))
- return BUFFER_E;
- }
- else {
- oidSz = 0; /* with no curveOID oid size must be 0 */
- if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
- + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2))
- return BUFFER_E;
- }
- /* sanity check: make sure the key doesn't already have a PKCS 8 header */
- if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
- (void)tmpAlgId;
- return ASN_PARSE_E;
- }
- /* PrivateKeyInfo ::= SEQUENCE */
- keyIdx = MAX_SEQ_SZ; /* save room for sequence */
- /* version Version
- * no header information just INTEGER */
- sz = (word32)SetMyVersion(PKCS8v0, out + keyIdx, 0);
- tmpSz += sz; keyIdx += sz;
- /* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier */
- sz = 0; /* set sz to 0 and get privateKey oid buffer size needed */
- if (curveOID != NULL && oidSz > 0) {
- byte buf[MAX_LENGTH_SZ];
- sz = SetLength(oidSz, buf);
- sz += 1; /* plus one for ASN object id */
- }
- sz = (word32)SetAlgoID(algoID, out + keyIdx, oidKeyType, (int)(oidSz + sz));
- tmpSz += sz; keyIdx += sz;
- /* privateKey PrivateKey *
- * pkcs8 ecc uses slightly different format. Places curve oid in
- * buffer */
- if (curveOID != NULL && oidSz > 0) {
- sz = (word32)SetObjectId((int)oidSz, out + keyIdx);
- keyIdx += sz; tmpSz += sz;
- XMEMCPY(out + keyIdx, curveOID, oidSz);
- keyIdx += oidSz; tmpSz += oidSz;
- }
- sz = (word32)SetOctetString(keySz, out + keyIdx);
- keyIdx += sz; tmpSz += sz;
- XMEMCPY(out + keyIdx, key, keySz);
- tmpSz += keySz;
- /* attributes optional
- * No attributes currently added */
- /* rewind and add sequence */
- sz = SetSequence(tmpSz, out);
- XMEMMOVE(out + sz, out + MAX_SEQ_SZ, tmpSz);
- *outSz = tmpSz + sz;
- return (int)(tmpSz + sz);
- #else
- DECL_ASNSETDATA(dataASN, pkcs8KeyASN_Length);
- int sz;
- int ret = 0;
- word32 keyIdx = 0;
- word32 tmpAlgId = 0;
- WOLFSSL_ENTER("wc_CreatePKCS8Key");
- /* Check validity of parameters. */
- if (out == NULL && outSz != NULL) {
- }
- else if (key == NULL || out == NULL || outSz == NULL) {
- ret = BAD_FUNC_ARG;
- }
- /* Sanity check: make sure key doesn't have PKCS #8 header. */
- if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
- (void)tmpAlgId;
- ret = ASN_PARSE_E;
- }
- CALLOC_ASNSETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
- if (ret == 0) {
- /* Only support default PKCS #8 format - v0. */
- SetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], PKCS8v0);
- /* Set key OID that corresponds to key data. */
- SetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], (word32)algoID,
- oidKeyType);
- if (curveOID != NULL && oidSz > 0) {
- /* ECC key and curveOID set to write. */
- SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE],
- curveOID, oidSz);
- }
- else {
- /* EC curve OID to encode. */
- dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].noOut = 1;
- }
- /* Only RSA keys have NULL tagged item after OID. */
- dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].noOut = (algoID != RSAk);
- #ifdef WC_RSA_PSS
- dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].noOut = 1;
- #endif
- /* Set key data to encode. */
- SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_DATA], key, keySz);
- /* Get the size of the DER encoding. */
- ret = SizeASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, &sz);
- }
- if (ret == 0) {
- /* Always return the calculated size. */
- *outSz = (word32)sz;
- }
- /* Check for buffer to encoded into. */
- if ((ret == 0) && (out == NULL)) {
- WOLFSSL_MSG("Checking size of PKCS8");
- ret = LENGTH_ONLY_E;
- }
- if (ret == 0) {
- /* Encode PKCS #8 key into buffer. */
- SetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, out);
- ret = sz;
- }
- FREE_ASNSETDATA(dataASN, NULL);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #endif /* HAVE_PKCS8 */
- #if defined(HAVE_PKCS12) || !defined(NO_CHECK_PRIVATE_KEY)
- /* check that the private key is a pair for the public key
- * return 1 (true) on match
- * return 0 or negative value on failure/error
- *
- * privKey : buffer holding DER format private key
- * privKeySz : size of private key buffer
- * pubKey : buffer holding DER format public key
- * pubKeySz : size of public key buffer
- * ks : type of key */
- int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz,
- const byte* pubKey, word32 pubKeySz, enum Key_Sum ks)
- {
- int ret;
- (void)privKeySz;
- (void)pubKeySz;
- (void)ks;
- if (privKey == NULL || pubKey == NULL) {
- return BAD_FUNC_ARG;
- }
- #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
- /* test if RSA key */
- if (ks == RSAk
- #ifdef WC_RSA_PSS
- || ks == RSAPSSk
- #endif
- ) {
- #ifdef WOLFSSL_SMALL_STACK
- RsaKey* a;
- RsaKey* b = NULL;
- #else
- RsaKey a[1], b[1];
- #endif
- word32 keyIdx = 0;
- #ifdef WOLFSSL_SMALL_STACK
- a = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
- if (a == NULL)
- return MEMORY_E;
- b = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
- if (b == NULL) {
- XFREE(a, NULL, DYNAMIC_TYPE_RSA);
- return MEMORY_E;
- }
- #endif
- if ((ret = wc_InitRsaKey(a, NULL)) < 0) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(b, NULL, DYNAMIC_TYPE_RSA);
- XFREE(a, NULL, DYNAMIC_TYPE_RSA);
- #endif
- return ret;
- }
- if ((ret = wc_InitRsaKey(b, NULL)) < 0) {
- wc_FreeRsaKey(a);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(b, NULL, DYNAMIC_TYPE_RSA);
- XFREE(a, NULL, DYNAMIC_TYPE_RSA);
- #endif
- return ret;
- }
- if ((ret = wc_RsaPrivateKeyDecode(privKey, &keyIdx, a, privKeySz)) == 0) {
- WOLFSSL_MSG("Checking RSA key pair");
- keyIdx = 0; /* reset to 0 for parsing public key */
- if ((ret = wc_RsaPublicKeyDecode(pubKey, &keyIdx, b,
- pubKeySz)) == 0) {
- /* limit for user RSA crypto because of RsaKey
- * dereference. */
- #if defined(HAVE_USER_RSA)
- WOLFSSL_MSG("Cannot verify RSA pair with user RSA");
- ret = 1; /* return first RSA cert as match */
- #else
- /* both keys extracted successfully now check n and e
- * values are the same. This is dereferencing RsaKey */
- if (mp_cmp(&(a->n), &(b->n)) != MP_EQ ||
- mp_cmp(&(a->e), &(b->e)) != MP_EQ) {
- ret = MP_CMP_E;
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- else
- ret = 1;
- #endif
- }
- else {
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- }
- wc_FreeRsaKey(b);
- wc_FreeRsaKey(a);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(b, NULL, DYNAMIC_TYPE_RSA);
- XFREE(a, NULL, DYNAMIC_TYPE_RSA);
- #endif
- }
- else
- #endif /* !NO_RSA && !NO_ASN_CRYPT */
- #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
- if (ks == ECDSAk) {
- #ifdef WOLFSSL_SMALL_STACK
- ecc_key* key_pair;
- byte* privDer;
- #else
- ecc_key key_pair[1];
- byte privDer[MAX_ECC_BYTES];
- #endif
- word32 privSz = MAX_ECC_BYTES;
- word32 keyIdx = 0;
- #ifdef WOLFSSL_SMALL_STACK
- key_pair = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL, DYNAMIC_TYPE_ECC);
- if (key_pair == NULL)
- return MEMORY_E;
- privDer = (byte*)XMALLOC(MAX_ECC_BYTES, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- if (privDer == NULL) {
- XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
- return MEMORY_E;
- }
- #endif
- if ((ret = wc_ecc_init(key_pair)) < 0) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
- #endif
- return ret;
- }
- if ((ret = wc_EccPrivateKeyDecode(privKey, &keyIdx, key_pair,
- privKeySz)) == 0) {
- WOLFSSL_MSG("Checking ECC key pair");
- if ((ret = wc_ecc_export_private_only(key_pair, privDer, &privSz))
- == 0) {
- #ifdef WOLFSSL_CHECK_MEM_ZERO
- wc_MemZero_Add("wc_CheckPrivateKey privDer", privDer, privSz);
- #endif
- wc_ecc_free(key_pair);
- ret = wc_ecc_init(key_pair);
- if (ret == 0) {
- ret = wc_ecc_import_private_key(privDer,
- privSz, pubKey,
- pubKeySz, key_pair);
- }
- /* public and private extracted successfully now check if is
- * a pair and also do sanity checks on key. wc_ecc_check_key
- * checks that private * base generator equals pubkey */
- if (ret == 0) {
- if ((ret = wc_ecc_check_key(key_pair)) == 0) {
- ret = 1;
- }
- else {
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- }
- ForceZero(privDer, privSz);
- }
- }
- else {
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- wc_ecc_free(key_pair);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
- #elif defined(WOLFSSL_CHECK_MEM_ZERO)
- wc_MemZero_Check(privDer, MAX_ECC_BYTES);
- #endif
- }
- else
- #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
- #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
- if (ks == ED25519k) {
- #ifdef WOLFSSL_SMALL_STACK
- ed25519_key* key_pair;
- #else
- ed25519_key key_pair[1];
- #endif
- word32 keyIdx = 0;
- #ifdef WOLFSSL_SMALL_STACK
- key_pair = (ed25519_key*)XMALLOC(sizeof(ed25519_key), NULL,
- DYNAMIC_TYPE_ED25519);
- if (key_pair == NULL)
- return MEMORY_E;
- #endif
- if ((ret = wc_ed25519_init(key_pair)) < 0) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
- #endif
- return ret;
- }
- if ((ret = wc_Ed25519PrivateKeyDecode(privKey, &keyIdx, key_pair,
- privKeySz)) == 0) {
- WOLFSSL_MSG("Checking ED25519 key pair");
- keyIdx = 0;
- if ((ret = wc_ed25519_import_public(pubKey, pubKeySz,
- key_pair)) == 0) {
- /* public and private extracted successfully no check if is
- * a pair and also do sanity checks on key. wc_ecc_check_key
- * checks that private * base generator equals pubkey */
- if ((ret = wc_ed25519_check_key(key_pair)) == 0) {
- ret = 1;
- }
- else {
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- }
- }
- else {
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- wc_ed25519_free(key_pair);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
- #endif
- }
- else
- #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
- #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
- if (ks == ED448k) {
- #ifdef WOLFSSL_SMALL_STACK
- ed448_key* key_pair = NULL;
- #else
- ed448_key key_pair[1];
- #endif
- word32 keyIdx = 0;
- #ifdef WOLFSSL_SMALL_STACK
- key_pair = (ed448_key*)XMALLOC(sizeof(ed448_key), NULL,
- DYNAMIC_TYPE_ED448);
- if (key_pair == NULL)
- return MEMORY_E;
- #endif
- if ((ret = wc_ed448_init(key_pair)) < 0) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
- #endif
- return ret;
- }
- if ((ret = wc_Ed448PrivateKeyDecode(privKey, &keyIdx, key_pair,
- privKeySz)) == 0) {
- WOLFSSL_MSG("Checking ED448 key pair");
- keyIdx = 0;
- if ((ret = wc_ed448_import_public(pubKey, pubKeySz,
- key_pair)) == 0) {
- /* public and private extracted successfully no check if is
- * a pair and also do sanity checks on key. wc_ecc_check_key
- * checks that private * base generator equals pubkey */
- if ((ret = wc_ed448_check_key(key_pair)) == 0) {
- ret = 1;
- }
- else {
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- }
- }
- else {
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- wc_ed448_free(key_pair);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
- #endif
- }
- else
- #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
- #if defined(HAVE_PQC)
- #if defined(HAVE_FALCON)
- if ((ks == FALCON_LEVEL1k) || (ks == FALCON_LEVEL5k)) {
- #ifdef WOLFSSL_SMALL_STACK
- falcon_key* key_pair = NULL;
- #else
- falcon_key key_pair[1];
- #endif
- word32 keyIdx = 0;
- #ifdef WOLFSSL_SMALL_STACK
- key_pair = (falcon_key*)XMALLOC(sizeof(falcon_key), NULL,
- DYNAMIC_TYPE_FALCON);
- if (key_pair == NULL)
- return MEMORY_E;
- #endif
- ret = wc_falcon_init(key_pair);
- if (ret < 0) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
- #endif
- return ret;
- }
- if (ks == FALCON_LEVEL1k) {
- ret = wc_falcon_set_level(key_pair, 1);
- }
- else if (ks == FALCON_LEVEL5k) {
- ret = wc_falcon_set_level(key_pair, 5);
- }
- if (ret < 0) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
- #endif
- return ret;
- }
- if ((ret = wc_Falcon_PrivateKeyDecode(privKey, &keyIdx, key_pair,
- privKeySz)) == 0) {
- WOLFSSL_MSG("Checking Falcon key pair");
- keyIdx = 0;
- if ((ret = wc_falcon_import_public(pubKey, pubKeySz,
- key_pair)) == 0) {
- /* Public and private extracted successfully. Sanity check. */
- if ((ret = wc_falcon_check_key(key_pair)) == 0) {
- ret = 1;
- }
- else {
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- }
- }
- else {
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- wc_falcon_free(key_pair);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
- #endif
- }
- else
- #endif /* HAVE_FALCON */
- #if defined(HAVE_DILITHIUM)
- if ((ks == DILITHIUM_LEVEL2k) ||
- (ks == DILITHIUM_LEVEL3k) ||
- (ks == DILITHIUM_LEVEL5k)) {
- #ifdef WOLFSSL_SMALL_STACK
- dilithium_key* key_pair = NULL;
- #else
- dilithium_key key_pair[1];
- #endif
- word32 keyIdx = 0;
- #ifdef WOLFSSL_SMALL_STACK
- key_pair = (dilithium_key*)XMALLOC(sizeof(dilithium_key), NULL,
- DYNAMIC_TYPE_DILITHIUM);
- if (key_pair == NULL)
- return MEMORY_E;
- #endif
- ret = wc_dilithium_init(key_pair);
- if (ret < 0) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
- #endif
- return ret;
- }
- if (ks == DILITHIUM_LEVEL2k) {
- ret = wc_dilithium_set_level(key_pair, 2);
- }
- else if (ks == DILITHIUM_LEVEL3k) {
- ret = wc_dilithium_set_level(key_pair, 3);
- }
- else if (ks == DILITHIUM_LEVEL5k) {
- ret = wc_dilithium_set_level(key_pair, 5);
- }
- if (ret < 0) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
- #endif
- return ret;
- }
- if ((ret = wc_Dilithium_PrivateKeyDecode(privKey, &keyIdx, key_pair,
- privKeySz)) == 0) {
- WOLFSSL_MSG("Checking Dilithium key pair");
- keyIdx = 0;
- if ((ret = wc_dilithium_import_public(pubKey, pubKeySz,
- key_pair)) == 0) {
- /* Public and private extracted successfully. Sanity check. */
- if ((ret = wc_dilithium_check_key(key_pair)) == 0)
- ret = 1;
- }
- }
- wc_dilithium_free(key_pair);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
- #endif
- }
- else
- #endif /* HAVE_DILITHIUM */
- #if defined(HAVE_SPHINCS)
- if ((ks == SPHINCS_FAST_LEVEL1k) ||
- (ks == SPHINCS_FAST_LEVEL3k) ||
- (ks == SPHINCS_FAST_LEVEL5k) ||
- (ks == SPHINCS_SMALL_LEVEL1k) ||
- (ks == SPHINCS_SMALL_LEVEL3k) ||
- (ks == SPHINCS_SMALL_LEVEL5k)) {
- #ifdef WOLFSSL_SMALL_STACK
- sphincs_key* key_pair = NULL;
- #else
- sphincs_key key_pair[1];
- #endif
- word32 keyIdx = 0;
- #ifdef WOLFSSL_SMALL_STACK
- key_pair = (sphincs_key*)XMALLOC(sizeof(sphincs_key), NULL,
- DYNAMIC_TYPE_SPHINCS);
- if (key_pair == NULL)
- return MEMORY_E;
- #endif
- ret = wc_sphincs_init(key_pair);
- if (ret < 0) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
- #endif
- return ret;
- }
- if (ks == SPHINCS_FAST_LEVEL1k) {
- ret = wc_sphincs_set_level_and_optim(key_pair, 1, FAST_VARIANT);
- }
- else if (ks == SPHINCS_FAST_LEVEL3k) {
- ret = wc_sphincs_set_level_and_optim(key_pair, 3, FAST_VARIANT);
- }
- else if (ks == SPHINCS_FAST_LEVEL5k) {
- ret = wc_sphincs_set_level_and_optim(key_pair, 5, FAST_VARIANT);
- }
- else if (ks == SPHINCS_SMALL_LEVEL1k) {
- ret = wc_sphincs_set_level_and_optim(key_pair, 1, SMALL_VARIANT);
- }
- else if (ks == SPHINCS_SMALL_LEVEL3k) {
- ret = wc_sphincs_set_level_and_optim(key_pair, 3, SMALL_VARIANT);
- }
- else if (ks == SPHINCS_SMALL_LEVEL5k) {
- ret = wc_sphincs_set_level_and_optim(key_pair, 5, SMALL_VARIANT);
- }
- if (ret < 0) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
- #endif
- return ret;
- }
- if ((ret = wc_Sphincs_PrivateKeyDecode(privKey, &keyIdx, key_pair,
- privKeySz)) == 0) {
- WOLFSSL_MSG("Checking Sphincs key pair");
- keyIdx = 0;
- if ((ret = wc_sphincs_import_public(pubKey, pubKeySz,
- key_pair)) == 0) {
- /* Public and private extracted successfully. Sanity check. */
- if ((ret = wc_sphincs_check_key(key_pair)) == 0)
- ret = 1;
- }
- }
- wc_sphincs_free(key_pair);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
- #endif
- }
- else
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- {
- ret = 0;
- }
- (void)ks;
- return ret;
- }
- /* check that the private key is a pair for the public key in certificate
- * return 1 (true) on match
- * return 0 or negative value on failure/error
- *
- * key : buffer holding DER format key
- * keySz : size of key buffer
- * der : a initialized and parsed DecodedCert holding a certificate */
- int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der)
- {
- if (key == NULL || der == NULL) {
- return BAD_FUNC_ARG;
- }
- return wc_CheckPrivateKey(key, keySz, der->publicKey,
- der->pubKeySize, (enum Key_Sum) der->keyOID);
- }
- #endif /* HAVE_PKCS12 || !NO_CHECK_PRIVATE_KEY */
- #ifndef NO_PWDBASED
- #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
- /* Check the PBE algorithm is supported and return wolfSSL id, version and block
- * size of encryption algorithm.
- *
- * When PBES2, version is PKCS5v2, CheckAlgoV2() must be called to get id and
- * blockSz based on encryption algorithm.
- *
- * @param [in] first First byte of OID to use in check.
- * @param [in] second Second byte of OID to use in check.
- * @param [out] id wolfSSL id for PBE algorithm.
- * @param [out] version Version of PBE OID:
- * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
- * @param [out] blockSz Block size of encryption algorithm.
- * @return 0 on success.
- * @return ALGO_ID_E when OID not supported.
- * @return ASN_INPUT_E when first byte is invalid.
- */
- static int CheckAlgo(int first, int second, int* id, int* version, int* blockSz)
- {
- int ret = 0;
- (void)id;
- (void)blockSz;
- *version = -1;
- /* pkcs-12 1 = pkcs-12PbeIds */
- if (first == 1) {
- /* PKCS #12: Appendix C */
- switch (second) {
- #if !defined(NO_SHA)
- #ifndef NO_RC4
- case PBE_SHA1_RC4_128:
- *id = PBE_SHA1_RC4_128;
- *version = PKCS12v1;
- if (blockSz != NULL) {
- *blockSz = 1;
- }
- break;
- #endif
- #ifndef NO_DES3
- case PBE_SHA1_DES3:
- *id = PBE_SHA1_DES3;
- *version = PKCS12v1;
- if (blockSz != NULL) {
- *blockSz = DES_BLOCK_SIZE;
- }
- break;
- #endif
- #ifdef WC_RC2
- case PBE_SHA1_40RC2_CBC:
- *id = PBE_SHA1_40RC2_CBC;
- *version = PKCS12v1;
- if (blockSz != NULL) {
- *blockSz = RC2_BLOCK_SIZE;
- }
- break;
- #endif
- #endif /* !NO_SHA */
- default:
- ret = ALGO_ID_E;
- break;
- }
- }
- else if (first != PKCS5) {
- /* Bad OID. */
- ret = ASN_INPUT_E;
- }
- /* PKCS #5 PBES2: Appendix A.4
- * pkcs-5 13 = id-PBES2 */
- else if (second == PBES2) {
- *version = PKCS5v2;
- /* Id and block size come from CheckAlgoV2() */
- }
- else {
- /* PKCS #5 PBES1: Appendix A.3 */
- /* see RFC 2898 for ids */
- switch (second) {
- #ifndef NO_DES3
- #ifndef NO_MD5
- case PBES1_MD5_DES:
- *id = PBE_MD5_DES;
- *version = PKCS5;
- if (blockSz != NULL) {
- *blockSz = DES_BLOCK_SIZE;
- }
- break;
- #endif
- #ifndef NO_SHA
- case PBES1_SHA1_DES:
- *id = PBE_SHA1_DES;
- *version = PKCS5;
- if (blockSz != NULL) {
- *blockSz = DES_BLOCK_SIZE;
- }
- break;
- #endif
- #endif /* !NO_DES3 */
- default:
- ret = ALGO_ID_E;
- break;
- }
- }
- /* Return error code. */
- return ret;
- }
- #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
- #ifdef HAVE_PKCS8
- /* Check the encryption algorithm with PBES2 is supported and return block size
- * and wolfSSL id for the PBE.
- *
- * @param [in] oid Encryption algorithm OID id.
- * @param [out] id wolfSSL id for PBE algorithm.
- * @param [out] version Version of PBE OID:
- * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
- * @return 0 on success.
- * @return ALGO_ID_E when encryption algorithm is not supported with PBES2.
- */
- static int CheckAlgoV2(int oid, int* id, int* blockSz)
- {
- int ret = 0;
- (void)id;
- (void)blockSz;
- switch (oid) {
- #if !defined(NO_DES3) && !defined(NO_SHA)
- case DESb:
- *id = PBE_SHA1_DES;
- if (blockSz != NULL) {
- *blockSz = DES_BLOCK_SIZE;
- }
- break;
- case DES3b:
- *id = PBE_SHA1_DES3;
- if (blockSz != NULL) {
- *blockSz = DES_BLOCK_SIZE;
- }
- break;
- #endif
- #ifdef WOLFSSL_AES_256
- case AES256CBCb:
- *id = PBE_AES256_CBC;
- if (blockSz != NULL) {
- *blockSz = AES_BLOCK_SIZE;
- }
- break;
- #endif
- #ifdef WOLFSSL_AES_128
- case AES128CBCb:
- *id = PBE_AES128_CBC;
- if (blockSz != NULL) {
- *blockSz = AES_BLOCK_SIZE;
- }
- break;
- #endif
- default:
- WOLFSSL_MSG("No PKCS v2 algo found");
- ret = ALGO_ID_E;
- break;
- }
- /* Return error code. */
- return ret;
- }
- #endif /* HAVE_PKCS8 */
- #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
- int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz,
- int* algoID, void* heap)
- {
- word32 tmpIdx = 0;
- if (key == NULL || algoID == NULL)
- return BAD_FUNC_ARG;
- *algoID = 0;
- #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
- {
- RsaKey *rsa = (RsaKey *)XMALLOC(sizeof *rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (rsa == NULL)
- return MEMORY_E;
- wc_InitRsaKey(rsa, heap);
- if (wc_RsaPrivateKeyDecode(key, &tmpIdx, rsa, keySz) == 0) {
- *algoID = RSAk;
- }
- else {
- WOLFSSL_MSG("Not RSA DER key");
- }
- wc_FreeRsaKey(rsa);
- XFREE(rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
- }
- #endif /* !NO_RSA && !NO_ASN_CRYPT */
- #if defined(HAVE_ECC) && !defined(NO_ASN_CRYPT)
- if (*algoID == 0) {
- ecc_key *ecc = (ecc_key *)XMALLOC(sizeof *ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (ecc == NULL)
- return MEMORY_E;
- tmpIdx = 0;
- wc_ecc_init_ex(ecc, heap, INVALID_DEVID);
- if (wc_EccPrivateKeyDecode(key, &tmpIdx, ecc, keySz) == 0) {
- *algoID = ECDSAk;
- /* now find oid */
- if (wc_ecc_get_oid(ecc->dp->oidSum, curveOID, oidSz) < 0) {
- WOLFSSL_MSG("Error getting ECC curve OID");
- wc_ecc_free(ecc);
- XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
- return BAD_FUNC_ARG;
- }
- }
- else {
- WOLFSSL_MSG("Not ECC DER key either");
- }
- wc_ecc_free(ecc);
- XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
- }
- #endif /* HAVE_ECC && !NO_ASN_CRYPT */
- #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
- if (*algoID == 0) {
- ed25519_key *ed25519 = (ed25519_key *)XMALLOC(sizeof *ed25519, heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (ed25519 == NULL)
- return MEMORY_E;
- tmpIdx = 0;
- if (wc_ed25519_init_ex(ed25519, heap, INVALID_DEVID) == 0) {
- if (wc_Ed25519PrivateKeyDecode(key, &tmpIdx, ed25519, keySz) == 0) {
- *algoID = ED25519k;
- }
- else {
- WOLFSSL_MSG("Not ED25519 DER key");
- }
- wc_ed25519_free(ed25519);
- }
- else {
- WOLFSSL_MSG("GetKeyOID wc_ed25519_init failed");
- }
- XFREE(ed25519, heap, DYNAMIC_TYPE_TMP_BUFFER);
- }
- #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
- #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
- if (*algoID == 0) {
- ed448_key *ed448 = (ed448_key *)XMALLOC(sizeof *ed448, heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (ed448 == NULL)
- return MEMORY_E;
- tmpIdx = 0;
- if (wc_ed448_init(ed448) == 0) {
- if (wc_Ed448PrivateKeyDecode(key, &tmpIdx, ed448, keySz) == 0) {
- *algoID = ED448k;
- }
- else {
- WOLFSSL_MSG("Not ED448 DER key");
- }
- wc_ed448_free(ed448);
- }
- else {
- WOLFSSL_MSG("GetKeyOID wc_ed448_init failed");
- }
- XFREE(ed448, heap, DYNAMIC_TYPE_TMP_BUFFER);
- }
- #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
- #if defined(HAVE_PQC)
- #if defined(HAVE_FALCON)
- if (*algoID == 0) {
- falcon_key *falcon = (falcon_key *)XMALLOC(sizeof(*falcon), heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (falcon == NULL)
- return MEMORY_E;
- if (wc_falcon_init(falcon) != 0) {
- tmpIdx = 0;
- if (wc_falcon_set_level(falcon, 1) == 0) {
- if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
- == 0) {
- *algoID = FALCON_LEVEL1k;
- }
- else {
- WOLFSSL_MSG("Not Falcon Level 1 DER key");
- }
- }
- else if (wc_falcon_set_level(falcon, 5) == 0) {
- if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
- == 0) {
- *algoID = FALCON_LEVEL5k;
- }
- else {
- WOLFSSL_MSG("Not Falcon Level 5 DER key");
- }
- }
- else {
- WOLFSSL_MSG("GetKeyOID falcon initialization failed");
- }
- wc_falcon_free(falcon);
- }
- XFREE(falcon, heap, DYNAMIC_TYPE_TMP_BUFFER);
- }
- #endif /* HAVE_FALCON */
- #if defined(HAVE_DILITHIUM)
- if (*algoID == 0) {
- dilithium_key *dilithium = (dilithium_key *)XMALLOC(sizeof(*dilithium),
- heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (dilithium == NULL)
- return MEMORY_E;
- if (wc_dilithium_init(dilithium) != 0) {
- tmpIdx = 0;
- if (wc_dilithium_set_level(dilithium, 2)
- == 0) {
- if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
- keySz) == 0) {
- *algoID = DILITHIUM_LEVEL2k;
- }
- else {
- WOLFSSL_MSG("Not Dilithium Level 2 DER key");
- }
- }
- else if (wc_dilithium_set_level(dilithium, 3)
- == 0) {
- if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
- keySz) == 0) {
- *algoID = DILITHIUM_LEVEL3k;
- }
- else {
- WOLFSSL_MSG("Not Dilithium Level 3 DER key");
- }
- }
- else if (wc_dilithium_set_level(dilithium, 5)
- == 0) {
- if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
- keySz) == 0) {
- *algoID = DILITHIUM_LEVEL5k;
- }
- else {
- WOLFSSL_MSG("Not Dilithium Level 5 DER key");
- }
- }
- else {
- WOLFSSL_MSG("GetKeyOID dilithium initialization failed");
- }
- wc_dilithium_free(dilithium);
- }
- XFREE(dilithium, heap, DYNAMIC_TYPE_TMP_BUFFER);
- }
- #endif /* HAVE_DILITHIUM */
- #if defined(HAVE_SPHINCS)
- if (*algoID == 0) {
- sphincs_key *sphincs = (sphincs_key *)XMALLOC(sizeof(*sphincs),
- heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (sphincs == NULL)
- return MEMORY_E;
- if (wc_sphincs_init(sphincs) != 0) {
- tmpIdx = 0;
- if (wc_sphincs_set_level_and_optim(sphincs, 1, FAST_VARIANT)
- == 0) {
- if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
- keySz) == 0) {
- *algoID = SPHINCS_FAST_LEVEL1k;
- }
- else {
- WOLFSSL_MSG("Not Sphincs-fast Level 1 DER key");
- }
- }
- else if (wc_sphincs_set_level_and_optim(sphincs, 3, FAST_VARIANT)
- == 0) {
- if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
- keySz) == 0) {
- *algoID = SPHINCS_FAST_LEVEL3k;
- }
- else {
- WOLFSSL_MSG("Not Sphincs-fast Level 3 DER key");
- }
- }
- else if (wc_sphincs_set_level_and_optim(sphincs, 5, FAST_VARIANT)
- == 0) {
- if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
- keySz) == 0) {
- *algoID = SPHINCS_FAST_LEVEL5k;
- }
- else {
- WOLFSSL_MSG("Not Sphincs-fast Level 5 DER key");
- }
- }
- else if (wc_sphincs_set_level_and_optim(sphincs, 1, SMALL_VARIANT)
- == 0) {
- if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
- keySz) == 0) {
- *algoID = SPHINCS_SMALL_LEVEL1k;
- }
- else {
- WOLFSSL_MSG("Not Sphincs-small Level 1 DER key");
- }
- }
- else if (wc_sphincs_set_level_and_optim(sphincs, 3, SMALL_VARIANT)
- == 0) {
- if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
- keySz) == 0) {
- *algoID = SPHINCS_SMALL_LEVEL3k;
- }
- else {
- WOLFSSL_MSG("Not Sphincs-small Level 3 DER key");
- }
- }
- else if (wc_sphincs_set_level_and_optim(sphincs, 5, SMALL_VARIANT)
- == 0) {
- if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
- keySz) == 0) {
- *algoID = SPHINCS_SMALL_LEVEL5k;
- }
- else {
- WOLFSSL_MSG("Not Sphincs-small Level 5 DER key");
- }
- }
- else {
- WOLFSSL_MSG("GetKeyOID sphincs initialization failed");
- }
- wc_sphincs_free(sphincs);
- }
- XFREE(sphincs, heap, DYNAMIC_TYPE_TMP_BUFFER);
- }
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- /* if flag is not set then this is not a key that we understand. */
- if (*algoID == 0) {
- WOLFSSL_MSG("Bad key DER or compile options");
- return BAD_FUNC_ARG;
- }
- (void)tmpIdx;
- (void)curveOID;
- (void)oidSz;
- (void)keySz;
- (void)heap;
- return 1;
- }
- #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
- #ifdef WOLFSSL_ASN_TEMPLATE
- #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
- /* ASN.1 template for PBES2 parameters.
- * PKCS #5: RFC 8018, A.4 - PBES2-params without outer SEQUENCE
- * A.2 - PBKDF2-params
- * B.2 - Encryption schemes
- * C - AlgorithmIdentifier
- */
- static const ASNItem pbes2ParamsASN[] = {
- /* KDF_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* PBKDF2 */
- /* KDF_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* PBKDF2_PARAMS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* Salt */
- /* PBKDF2_PARAMS_SALT */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
- /* Iteration count */
- /* PBKDF2_PARAMS_ITER */ { 2, ASN_INTEGER, 0, 0, 0 },
- /* Key length */
- /* PBKDF2_PARAMS_KEYLEN */ { 2, ASN_INTEGER, 0, 0, 1 },
- /* PRF - default is HMAC-SHA1 */
- /* PBKDF2_PARAMS_PRF */ { 2, ASN_SEQUENCE, 1, 1, 1 },
- /* PBKDF2_PARAMS_PRF_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
- /* PBKDF2_PARAMS_PRF_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
- /* ENCS_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* Encryption algorithm */
- /* ENCS_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* IV for CBC */
- /* ENCS_PARAMS */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
- };
- enum {
- PBES2PARAMSASN_IDX_KDF_SEQ = 0,
- PBES2PARAMSASN_IDX_KDF_OID,
- PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SEQ,
- PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT,
- PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER,
- PBES2PARAMSASN_IDX_PBKDF2_PARAMS_KEYLEN,
- PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF,
- PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID,
- PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_NULL,
- PBES2PARAMSASN_IDX_ENCS_SEQ,
- PBES2PARAMSASN_IDX_ENCS_OID,
- PBES2PARAMSASN_IDX_ENCS_PARAMS
- };
- /* Number of items in ASN.1 template for PBES2 parameters. */
- #define pbes2ParamsASN_Length (sizeof(pbes2ParamsASN) / sizeof(ASNItem))
- /* ASN.1 template for PBES1 parameters.
- * PKCS #5: RFC 8018, A.3. - PBEParameter without outer SEQUENCE
- */
- static const ASNItem pbes1ParamsASN[] = {
- /* Salt */
- /* SALT */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
- /* Iteration count */
- /* ITER */ { 0, ASN_INTEGER, 0, 0, 0 },
- };
- enum {
- PBES1PARAMSASN_IDX_SALT = 0,
- PBES1PARAMSASN_IDX_ITER
- };
- /* Number of items in ASN.1 template for PBES1 parameters. */
- #define pbes1ParamsASN_Length (sizeof(pbes1ParamsASN) / sizeof(ASNItem))
- #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
- #endif /* WOLFSSL_ASN_TEMPLATE */
- #ifdef HAVE_PKCS8
- /*
- * Equivalent to calling TraditionalEnc with the same parameters but with
- * encAlgId set to 0. This function must be kept alive because it's sometimes
- * part of the API (WOLFSSL_ASN_API).
- */
- int UnTraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
- const char* password, int passwordSz, int vPKCS, int vAlgo,
- byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
- {
- return TraditionalEnc(key, keySz, out, outSz, password, passwordSz,
- vPKCS, vAlgo, 0, salt, saltSz, itt, rng, heap);
- }
- static int GetAlgoV2(int encAlgId, const byte** oid, int *len, int* id,
- int *blkSz)
- {
- int ret = 0;
- switch (encAlgId) {
- #if !defined(NO_DES3) && !defined(NO_SHA)
- case DESb:
- *len = sizeof(blkDesCbcOid);
- *oid = blkDesCbcOid;
- *id = PBE_SHA1_DES;
- *blkSz = 8;
- break;
- case DES3b:
- *len = sizeof(blkDes3CbcOid);
- *oid = blkDes3CbcOid;
- *id = PBE_SHA1_DES3;
- *blkSz = 8;
- break;
- #endif
- #if defined(WOLFSSL_AES_128) && defined(HAVE_AES_CBC)
- case AES128CBCb:
- *len = sizeof(blkAes128CbcOid);
- *oid = blkAes128CbcOid;
- *id = PBE_AES128_CBC;
- *blkSz = 16;
- break;
- #endif
- #if defined(WOLFSSL_AES_256) && defined(HAVE_AES_CBC)
- case AES256CBCb:
- *len = sizeof(blkAes256CbcOid);
- *oid = blkAes256CbcOid;
- *id = PBE_AES256_CBC;
- *blkSz = 16;
- break;
- #endif
- default:
- (void)len;
- (void)oid;
- (void)id;
- (void)blkSz;
- ret = ALGO_ID_E;
- }
- return ret;
- }
- int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz,
- const char* password, int passwordSz, int vPKCS, int pbeOid,
- int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
- void* heap)
- {
- #ifdef WOLFSSL_SMALL_STACK
- byte* saltTmp = NULL;
- #else
- byte saltTmp[MAX_SALT_SIZE];
- #endif
- int genSalt = 0;
- int ret = 0;
- int version = 0;
- int pbeId = 0;
- int blockSz = 0;
- const byte* encOid = NULL;
- int encOidSz = 0;
- word32 padSz = 0;
- word32 innerLen = 0;
- const byte* pbeOidBuf = NULL;
- word32 pbeOidBufSz = 0;
- word32 pbeLen = 0;
- word32 kdfLen = 0;
- word32 encLen = 0;
- byte cbcIv[MAX_IV_SIZE];
- word32 idx = 0;
- word32 encIdx = 0;
- (void)heap;
- WOLFSSL_ENTER("wc_EncryptPKCS8Key");
- if (key == NULL || outSz == NULL || password == NULL) {
- ret = BAD_FUNC_ARG;
- }
- if (ret == 0) {
- ret = CheckAlgo(vPKCS, pbeOid, &pbeId, &version, &blockSz);
- }
- if (ret == 0 && (salt == NULL || saltSz == 0)) {
- genSalt = 1;
- saltSz = 8;
- }
- if (ret == 0 && version == PKCS5v2) {
- ret = GetAlgoV2(encAlgId, &encOid, &encOidSz, &pbeId, &blockSz);
- }
- if (ret == 0) {
- padSz = (word32)((blockSz - ((int)keySz & (blockSz - 1))) &
- (blockSz - 1));
- /* inner = OCT salt INT itt */
- innerLen = 2 + saltSz + 2 + ((itt < 256) ? 1 : ((itt < 65536) ? 2 : 3));
- if (version != PKCS5v2) {
- pbeOidBuf = OidFromId((word32)pbeId, oidPBEType, &pbeOidBufSz);
- /* pbe = OBJ pbse1 SEQ [ inner ] */
- pbeLen = 2 + pbeOidBufSz + 2 + innerLen;
- }
- else {
- pbeOidBuf = pbes2;
- pbeOidBufSz = sizeof(pbes2);
- /* kdf = OBJ pbkdf2 [ SEQ innerLen ] */
- kdfLen = 2 + sizeof(pbkdf2Oid) + 2 + innerLen;
- /* enc = OBJ enc_alg OCT iv */
- encLen = 2 + (word32)encOidSz + 2 + (word32)blockSz;
- /* pbe = OBJ pbse2 SEQ [ SEQ [ kdf ] SEQ [ enc ] ] */
- pbeLen = (word32)(2 + sizeof(pbes2) + 2 + 2 + (size_t)kdfLen + 2 +
- (size_t)encLen);
- ret = wc_RNG_GenerateBlock(rng, cbcIv, (word32)blockSz);
- }
- }
- if (ret == 0) {
- /* outerLen = length of PBE encoding + octet string data */
- /* Plus 2 for tag and length for pbe */
- word32 outerLen = 2 + pbeLen;
- /* Octet string tag, length */
- outerLen += 1 + SetLength(keySz + padSz, NULL);
- /* Octet string bytes */
- outerLen += keySz + padSz;
- if (out == NULL) {
- /* Sequence tag, length */
- *outSz = 1 + SetLength(outerLen, NULL) + outerLen;
- return LENGTH_ONLY_E;
- }
- SetOctetString(keySz + padSz, out);
- idx += SetSequence(outerLen, out + idx);
- encIdx = idx + outerLen - keySz - padSz;
- /* Put Encrypted content in place. */
- XMEMCPY(out + encIdx, key, keySz);
- if (padSz > 0) {
- XMEMSET(out + encIdx + keySz, (int)padSz, padSz);
- keySz += padSz;
- }
- if (genSalt == 1) {
- #ifdef WOLFSSL_SMALL_STACK
- saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (saltTmp == NULL) {
- ret = MEMORY_E;
- }
- else
- #endif
- {
- salt = saltTmp;
- if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
- WOLFSSL_MSG("Error generating random salt");
- }
- }
- }
- }
- if (ret == 0) {
- ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, pbeId,
- out + encIdx, (int)keySz, version, cbcIv, 1, 0);
- }
- if (ret == 0) {
- if (version != PKCS5v2) {
- /* PBE algorithm */
- idx += SetSequence(pbeLen, out + idx);
- idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
- XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
- idx += pbeOidBufSz;
- }
- else {
- /* PBES2 algorithm identifier */
- idx += SetSequence(pbeLen, out + idx);
- idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
- XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
- idx += pbeOidBufSz;
- /* PBES2 Parameters: SEQ [ kdf ] SEQ [ enc ] */
- idx += SetSequence(2 + kdfLen + 2 + encLen, out + idx);
- /* KDF Algorithm Identifier */
- idx += SetSequence(kdfLen, out + idx);
- idx += (word32)SetObjectId((int)sizeof(pbkdf2Oid), out + idx);
- XMEMCPY(out + idx, pbkdf2Oid, sizeof(pbkdf2Oid));
- idx += sizeof(pbkdf2Oid);
- }
- idx += SetSequence(innerLen, out + idx);
- idx += SetOctetString(saltSz, out + idx);
- XMEMCPY(out + idx, salt, saltSz); idx += saltSz;
- ret = SetShortInt(out, &idx, (word32)itt, *outSz);
- if (ret > 0)
- ret = 0;
- }
- if (ret == 0) {
- if (version == PKCS5v2) {
- /* Encryption Algorithm Identifier */
- idx += SetSequence(encLen, out + idx);
- idx += (word32)SetObjectId(encOidSz, out + idx);
- XMEMCPY(out + idx, encOid, (size_t)encOidSz);
- idx += (word32)encOidSz;
- /* Encryption Algorithm Parameter: CBC IV */
- idx += SetOctetString((word32)blockSz, out + idx);
- XMEMCPY(out + idx, cbcIv, (size_t)blockSz);
- idx += (word32)blockSz;
- }
- idx += SetOctetString(keySz, out + idx);
- /* Default PRF - no need to write out OID */
- idx += keySz;
- ret = (int)idx;
- }
- #ifdef WOLFSSL_SMALL_STACK
- if (saltTmp != NULL) {
- XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
- }
- #endif
- WOLFSSL_LEAVE("wc_EncryptPKCS8Key", ret);
- return ret;
- }
- int wc_DecryptPKCS8Key(byte* input, word32 sz, const char* password,
- int passwordSz)
- {
- int ret;
- int length;
- word32 inOutIdx = 0;
- if (input == NULL || password == NULL) {
- return BAD_FUNC_ARG;
- }
- if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
- ret = ASN_PARSE_E;
- }
- else {
- ret = DecryptContent(input + inOutIdx, sz - inOutIdx, password,
- passwordSz);
- if (ret > 0) {
- XMEMMOVE(input, input + inOutIdx, (size_t)ret);
- }
- }
- if (ret > 0) {
- /* DecryptContent will decrypt the data, but it will leave any padding
- * bytes intact. This code calculates the length without the padding
- * and we return that to the user. */
- inOutIdx = 0;
- if (GetSequence(input, &inOutIdx, &length, (word32)ret) < 0) {
- ret = ASN_PARSE_E;
- }
- else {
- ret = (int)inOutIdx + length;
- }
- }
- return ret;
- }
- /* Takes an unencrypted, traditional DER-encoded key and converts it to a PKCS#8
- * encrypted key. If out is not NULL, it will hold the encrypted key. If it's
- * NULL, LENGTH_ONLY_E will be returned and outSz will have the required out
- * buffer size. */
- int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
- const char* password, int passwordSz, int vPKCS, int vAlgo,
- int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
- void* heap)
- {
- int ret = 0;
- byte *pkcs8Key = NULL;
- word32 pkcs8KeySz = 0;
- int algId = 0;
- const byte* curveOid = NULL;
- word32 curveOidSz = 0;
- if (ret == 0) {
- /* check key type and get OID if ECC */
- ret = wc_GetKeyOID(key, keySz, &curveOid, &curveOidSz, &algId, heap);
- if (ret == 1)
- ret = 0;
- }
- if (ret == 0) {
- ret = wc_CreatePKCS8Key(NULL, &pkcs8KeySz, key, keySz, algId, curveOid,
- curveOidSz);
- if (ret == LENGTH_ONLY_E)
- ret = 0;
- }
- if (ret == 0) {
- pkcs8Key = (byte*)XMALLOC(pkcs8KeySz, heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (pkcs8Key == NULL)
- ret = MEMORY_E;
- }
- if (ret == 0) {
- ret = wc_CreatePKCS8Key(pkcs8Key, &pkcs8KeySz, key, keySz, algId,
- curveOid, curveOidSz);
- if (ret >= 0) {
- pkcs8KeySz = (word32)ret;
- ret = 0;
- }
- }
- #ifdef WOLFSSL_CHECK_MEM_ZERO
- if (ret == 0) {
- wc_MemZero_Add("TraditionalEnc pkcs8Key", pkcs8Key, pkcs8KeySz);
- }
- #endif
- if (ret == 0) {
- ret = wc_EncryptPKCS8Key(pkcs8Key, pkcs8KeySz, out, outSz, password,
- passwordSz, vPKCS, vAlgo, encAlgId, salt, saltSz, itt, rng, heap);
- }
- if (pkcs8Key != NULL) {
- ForceZero(pkcs8Key, pkcs8KeySz);
- XFREE(pkcs8Key, heap, DYNAMIC_TYPE_TMP_BUFFER);
- }
- (void)rng;
- return ret;
- }
- /* Same as TraditionalEnc, but in the public API. */
- int wc_CreateEncryptedPKCS8Key(byte* key, word32 keySz, byte* out,
- word32* outSz, const char* password, int passwordSz, int vPKCS,
- int pbeOid, int encAlgId, byte* salt, word32 saltSz, int itt,
- WC_RNG* rng, void* heap)
- {
- return TraditionalEnc(key, keySz, out, outSz, password, passwordSz, vPKCS,
- pbeOid, encAlgId, salt, saltSz, itt, rng, heap);
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for PKCS #8/#7 encrypted key for decrypting
- * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
- * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
- */
- static const ASNItem pkcs8DecASN[] = {
- /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
- /* ENCALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 0 },
- /* PKCS #7 */
- /* ENCCONTENT */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ENC_CONTENT,
- 0, 0, 2 },
- /* PKCS #8 */
- /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
- };
- enum {
- PKCS8DECASN_IDX_ENCALGO_SEQ = 0,
- PKCS8DECASN_IDX_ENCALGO_OID,
- PKCS8DECASN_IDX_ENCALGO_PARAMS,
- PKCS8DECASN_IDX_ENCCONTENT,
- PKCS8DECASN_IDX_ENCDATA
- };
- /* Number of items in ASN.1 template for PKCS #8/#7 encrypted key. */
- #define pkcs8DecASN_Length (sizeof(pkcs8DecASN) / sizeof(ASNItem))
- #endif
- /* Decrypt data using PBE algorithm.
- *
- * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
- * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
- *
- * Note: input buffer is overwritten with decrypted data!
- *
- * Salt is in KDF parameters and IV is PBE parameters when needed.
- *
- * @param [in] input Data to decrypt and unwrap.
- * @param [in] sz Size of encrypted data.
- * @param [in] password Password to derive encryption key with.
- * @param [in] passwordSz Size of password in bytes.
- * @return Length of decrypted data on success.
- * @return MEMORY_E when dynamic memory allocation fails.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return Other when decryption fails.
- */
- int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 inOutIdx = 0, seqEnd, oid, shaOid = 0;
- int ret = 0, first, second, length = 0, version, saltSz, id = 0;
- int iterations = 0, keySz = 0;
- #ifdef WOLFSSL_SMALL_STACK
- byte* salt = NULL;
- byte* cbcIv = NULL;
- #else
- byte salt[MAX_SALT_SIZE];
- byte cbcIv[MAX_IV_SIZE];
- #endif
- byte tag;
- if (passwordSz < 0) {
- WOLFSSL_MSG("Bad password size");
- return BAD_FUNC_ARG;
- }
- if (GetAlgoId(input, &inOutIdx, &oid, oidIgnoreType, sz) < 0) {
- ERROR_OUT(ASN_PARSE_E, exit_dc);
- }
- first = input[inOutIdx - 2]; /* PKCS version always 2nd to last byte */
- second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
- if (CheckAlgo(first, second, &id, &version, NULL) < 0) {
- ERROR_OUT(ASN_INPUT_E, exit_dc); /* Algo ID error */
- }
- if (version == PKCS5v2) {
- if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
- ERROR_OUT(ASN_PARSE_E, exit_dc);
- }
- if (GetAlgoId(input, &inOutIdx, &oid, oidKdfType, sz) < 0) {
- ERROR_OUT(ASN_PARSE_E, exit_dc);
- }
- if (oid != PBKDF2_OID) {
- ERROR_OUT(ASN_PARSE_E, exit_dc);
- }
- }
- if (GetSequence(input, &inOutIdx, &length, sz) <= 0) {
- ERROR_OUT(ASN_PARSE_E, exit_dc);
- }
- /* Find the end of this SEQUENCE so we can check for the OPTIONAL and
- * DEFAULT items. */
- seqEnd = inOutIdx + (word32)length;
- ret = GetOctetString(input, &inOutIdx, &saltSz, sz);
- if (ret < 0)
- goto exit_dc;
- if (saltSz > MAX_SALT_SIZE) {
- ERROR_OUT(ASN_PARSE_E, exit_dc);
- }
- #ifdef WOLFSSL_SMALL_STACK
- salt = (byte*)XMALLOC(MAX_SALT_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- if (salt == NULL) {
- ERROR_OUT(MEMORY_E, exit_dc);
- }
- #endif
- XMEMCPY(salt, &input[inOutIdx], (size_t)saltSz);
- inOutIdx += (word32)saltSz;
- if (GetShortInt(input, &inOutIdx, &iterations, sz) < 0) {
- ERROR_OUT(ASN_PARSE_E, exit_dc);
- }
- /* OPTIONAL key length */
- if (seqEnd > inOutIdx) {
- word32 localIdx = inOutIdx;
- if (GetASNTag(input, &localIdx, &tag, sz) < 0) {
- ERROR_OUT(ASN_PARSE_E, exit_dc);
- }
- if (tag == ASN_INTEGER &&
- GetShortInt(input, &inOutIdx, &keySz, sz) < 0) {
- ERROR_OUT(ASN_PARSE_E, exit_dc);
- }
- }
- /* DEFAULT HMAC is SHA-1 */
- if (seqEnd > inOutIdx) {
- if (GetAlgoId(input, &inOutIdx, &oid, oidHmacType, sz) < 0) {
- ERROR_OUT(ASN_PARSE_E, exit_dc);
- }
- shaOid = oid;
- }
- #ifdef WOLFSSL_SMALL_STACK
- cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- if (cbcIv == NULL) {
- ERROR_OUT(MEMORY_E, exit_dc);
- }
- #endif
- if (version == PKCS5v2) {
- /* get encryption algo */
- if (GetAlgoId(input, &inOutIdx, &oid, oidBlkType, sz) < 0) {
- ERROR_OUT(ASN_PARSE_E, exit_dc);
- }
- if (CheckAlgoV2((int)oid, &id, NULL) < 0) {
- ERROR_OUT(ASN_PARSE_E, exit_dc); /* PKCS v2 algo id error */
- }
- if (shaOid == 0)
- shaOid = oid;
- ret = GetOctetString(input, &inOutIdx, &length, sz);
- if (ret < 0)
- goto exit_dc;
- if (length > MAX_IV_SIZE) {
- ERROR_OUT(ASN_PARSE_E, exit_dc);
- }
- XMEMCPY(cbcIv, &input[inOutIdx], (size_t)length);
- inOutIdx += (word32)length;
- }
- if (GetASNTag(input, &inOutIdx, &tag, sz) < 0) {
- ERROR_OUT(ASN_PARSE_E, exit_dc);
- }
- if (tag != (ASN_CONTEXT_SPECIFIC | 0) && tag != ASN_OCTET_STRING) {
- ERROR_OUT(ASN_PARSE_E, exit_dc);
- }
- if (GetLength(input, &inOutIdx, &length, sz) < 0) {
- ERROR_OUT(ASN_PARSE_E, exit_dc);
- }
- ret = wc_CryptKey(password, passwordSz, salt, saltSz, iterations, id,
- input + inOutIdx, length, version, cbcIv, 0, (int)shaOid);
- exit_dc:
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- if (ret == 0) {
- XMEMMOVE(input, input + inOutIdx, (size_t)length);
- ret = length;
- }
- return ret;
- #else
- /* pbes2ParamsASN longer than pkcs8DecASN_Length/pbes1ParamsASN_Length. */
- DECL_ASNGETDATA(dataASN, pbes2ParamsASN_Length);
- int ret = 0;
- int id = 0;
- int version;
- word32 idx = 0;
- word32 pIdx = 0;
- word32 iterations;
- word32 keySz = 0;
- word32 saltSz = 0;
- word32 shaOid = 0;
- byte* salt = NULL;
- byte* key = NULL;
- byte cbcIv[MAX_IV_SIZE];
- byte* params = NULL;
- WOLFSSL_ENTER("DecryptContent");
- CALLOC_ASNGETDATA(dataASN, pbes2ParamsASN_Length, ret, NULL);
- if (ret == 0) {
- /* Check OID is a PBE Type */
- GetASN_OID(&dataASN[PKCS8DECASN_IDX_ENCALGO_OID], oidPBEType);
- ret = GetASN_Items(pkcs8DecASN, dataASN, pkcs8DecASN_Length, 0, input,
- &idx, sz);
- }
- if (ret == 0) {
- /* Check the PBE algorithm and get the version and id. */
- idx = dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.length;
- /* Second last byte: 1 (PKCS #12 PBE Id) or 5 (PKCS #5)
- * Last byte: Alg or PBES2 */
- ret = CheckAlgo(dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 2],
- dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 1],
- &id, &version, NULL);
- }
- if (ret == 0) {
- /* Get the parameters data. */
- GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCALGO_PARAMS], ¶ms, &sz);
- /* Having a numbered choice means none or both will have errored out. */
- if (dataASN[PKCS8DECASN_IDX_ENCCONTENT].tag != 0)
- GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCCONTENT], &key, &keySz);
- else if (dataASN[PKCS8DECASN_IDX_ENCDATA].tag != 0)
- GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCDATA], &key, &keySz);
- else
- ret = ASN_RSA_KEY_E;
- }
- if (ret == 0) {
- if (version != PKCS5v2) {
- /* Initialize for PBES1 parameters and put iterations in var. */
- XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes1ParamsASN_Length);
- GetASN_Int32Bit(&dataASN[PBES1PARAMSASN_IDX_ITER], &iterations);
- /* Parse the PBES1 parameters. */
- ret = GetASN_Items(pbes1ParamsASN, dataASN, pbes1ParamsASN_Length,
- 0, params, &pIdx, sz);
- if (ret == 0) {
- /* Get the salt data. */
- GetASN_GetRef(&dataASN[PBES1PARAMSASN_IDX_SALT], &salt, &saltSz);
- }
- }
- else {
- word32 ivSz = MAX_IV_SIZE;
- /* Initialize for PBES2 parameters. Put iterations in var; match
- * KDF, HMAC and cipher, and copy CBC into buffer. */
- XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes2ParamsASN_Length);
- GetASN_ExpBuffer(&dataASN[PBES2PARAMSASN_IDX_KDF_OID], pbkdf2Oid, sizeof(pbkdf2Oid));
- GetASN_Int32Bit(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER], &iterations);
- GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID], oidHmacType);
- GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_ENCS_OID], oidBlkType);
- GetASN_Buffer(&dataASN[PBES2PARAMSASN_IDX_ENCS_PARAMS], cbcIv, &ivSz);
- /* Parse the PBES2 parameters */
- ret = GetASN_Items(pbes2ParamsASN, dataASN, pbes2ParamsASN_Length,
- 0, params, &pIdx, sz);
- if (ret == 0) {
- /* Get the salt data. */
- GetASN_GetRef(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT], &salt, &saltSz);
- /* Get the digest and encryption algorithm id. */
- shaOid = dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID].data.oid.sum; /* Default HMAC-SHA1 */
- id = (int)dataASN[PBES2PARAMSASN_IDX_ENCS_OID].data.oid.sum;
- /* Convert encryption algorithm to a PBE algorithm if needed. */
- CheckAlgoV2(id, &id, NULL);
- }
- }
- }
- if (ret == 0) {
- /* Decrypt the key. */
- ret = wc_CryptKey(
- password, passwordSz, salt, (int)saltSz, (int)iterations, id, key,
- (int)keySz, version, cbcIv, 0, (int)shaOid);
- }
- if (ret == 0) {
- /* Copy the decrypted key into the input (inline). */
- XMEMMOVE(input, key, keySz);
- ret = (int)keySz;
- }
- FREE_ASNGETDATA(dataASN, NULL);
- return ret;
- #endif
- }
- /* Decrypt data using PBE algorithm and get key from PKCS#8 wrapping.
- *
- * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
- * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo
- *
- * Note: input buffer is overwritten with decrypted key!
- *
- * Salt is in KDF parameters and IV is PBE parameters when needed.
- *
- * @param [in] input Data to decrypt and unwrap.
- * @param [in] sz Size of encrypted data.
- * @param [in] password Password to derive encryption key with.
- * @param [in] passwordSz Size of password in bytes.
- * @param [out] algId Key algorithm from PKCS#8 wrapper.
- * @return Length of decrypted data on success.
- * @return MEMORY_E when dynamic memory allocation fails.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return Other when decryption fails.
- */
- int ToTraditionalEnc(byte* input, word32 sz, const char* password,
- int passwordSz, word32* algId)
- {
- int ret;
- ret = wc_DecryptPKCS8Key(input, sz, password, passwordSz);
- if (ret > 0) {
- ret = ToTraditional_ex(input, (word32)ret, algId);
- }
- return ret;
- }
- #endif /* HAVE_PKCS8 */
- #ifdef HAVE_PKCS12
- #define PKCS8_MIN_BLOCK_SIZE 8
- static int Pkcs8Pad(byte* buf, int sz, int blockSz)
- {
- int padSz;
- /* calculate pad size */
- padSz = blockSz - (sz & (blockSz - 1));
- /* pad with padSz value */
- if (buf) {
- int i;
- for (i = 0; i < padSz; i++) {
- buf[sz+i] = (byte)(padSz & 0xFF);
- }
- }
- /* return adjusted length */
- return sz + padSz;
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for PKCS #8 encrypted key with PBES1 parameters.
- * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
- * PKCS #5: RFC 8018, A.3 - PBEParameter
- */
- static const ASNItem p8EncPbes1ASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* PBE algorithm */
- /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
- /* ENCALGO_PBEPARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
- /* Salt */
- /* ENCALGO_PBEPARAM_SALT */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
- /* Iteration Count */
- /* ENCALGO_PBEPARAM_ITER */ { 3, ASN_INTEGER, 0, 0, 0 },
- /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
- };
- enum {
- P8ENCPBES1ASN_IDX_SEQ = 0,
- P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
- P8ENCPBES1ASN_IDX_ENCALGO_OID,
- P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SEQ,
- P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT,
- P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER,
- P8ENCPBES1ASN_IDX_ENCDATA
- };
- #define p8EncPbes1ASN_Length (sizeof(p8EncPbes1ASN) / sizeof(ASNItem))
- #endif
- /* Wrap a private key in PKCS#8 and encrypt.
- *
- * Used for PKCS#12 and PKCS#7.
- * vPKCS is the version of PKCS to use.
- * vAlgo is the algorithm version to use.
- *
- * When salt is NULL, a random number is generated.
- *
- * data returned is :
- * [ seq - obj [ seq -salt,itt]] , construct with encrypted data
- *
- * @param [in] input Data to encrypt.
- * @param [in] inputSz Length of data in bytes.
- * @param [out] out Buffer to write wrapped encrypted data into.
- * @param [out] outSz Length of encrypted data in bytes.
- * @param [in] password Password used to create encryption key.
- * @param [in] passwordSz Length of password in bytes.
- * @param [in] vPKCS First byte used to determine PBE algorithm.
- * @param [in] vAlgo Second byte used to determine PBE algorithm.
- * @param [in] salt Salt to use with KDF.
- * @param [in] saltSz Length of salt in bytes.
- * @param [in] itt Number of iterations to use in KDF.
- * @param [in] rng Random number generator to use to generate salt.
- * @param [in] heap Dynamic memory allocator hint.
- * @return The size of encrypted data on success
- * @return LENGTH_ONLY_E when out is NULL and able to encode.
- * @return ASN_PARSE_E when the salt size is too large.
- * @return ASN_VERSION_E when attempting to use a PBES2 algorithm (use
- * TraditionalEnc).
- * @return MEMORY_E when dynamic memory allocation fails.
- * @return Other when encryption or random number generation fails.
- */
- int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz,
- const char* password, int passwordSz, int vPKCS, int vAlgo,
- byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 sz;
- word32 inOutIdx = 0;
- word32 tmpIdx = 0;
- word32 totalSz = 0;
- word32 seqSz;
- word32 innerSz;
- int ret;
- int version, id, blockSz = 0;
- #ifdef WOLFSSL_SMALL_STACK
- byte* saltTmp = NULL;
- byte* cbcIv = NULL;
- #else
- byte saltTmp[MAX_SALT_SIZE];
- byte cbcIv[MAX_IV_SIZE];
- #endif
- byte seq[MAX_SEQ_SZ];
- byte shr[MAX_SHORT_SZ];
- word32 maxShr = MAX_SHORT_SZ;
- word32 algoSz;
- const byte* algoName;
- (void)heap;
- WOLFSSL_ENTER("EncryptContent");
- if (CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0)
- return ASN_INPUT_E; /* Algo ID error */
- if (version == PKCS5v2) {
- WOLFSSL_MSG("PKCS#5 version 2 not supported yet");
- return BAD_FUNC_ARG;
- }
- if (saltSz > MAX_SALT_SIZE)
- return ASN_PARSE_E;
- if (outSz == NULL) {
- return BAD_FUNC_ARG;
- }
- /* calculate size */
- /* size of constructed string at end */
- sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
- totalSz = ASN_TAG_SZ;
- totalSz += SetLength(sz, seq);
- totalSz += sz;
- /* size of sequence holding object id and sub sequence of salt and itt */
- algoName = OidFromId((word32)id, oidPBEType, &algoSz);
- if (algoName == NULL) {
- WOLFSSL_MSG("Unknown Algorithm");
- return 0;
- }
- innerSz = (word32)SetObjectId((int)algoSz, seq);
- innerSz += algoSz;
- /* get subsequence of salt and itt */
- if (salt == NULL || saltSz == 0) {
- sz = 8;
- }
- else {
- sz = saltSz;
- }
- seqSz = SetOctetString(sz, seq);
- seqSz += sz;
- tmpIdx = 0;
- ret = SetShortInt(shr, &tmpIdx, (word32)itt, maxShr);
- if (ret >= 0) {
- seqSz += (word32)ret;
- }
- else {
- return ret;
- }
- innerSz += seqSz + SetSequence(seqSz, seq);
- totalSz += innerSz + SetSequence(innerSz, seq);
- if (out == NULL) {
- *outSz = totalSz;
- return LENGTH_ONLY_E;
- }
- inOutIdx = 0;
- if (totalSz > *outSz)
- return BUFFER_E;
- inOutIdx += SetSequence(innerSz, out + inOutIdx);
- inOutIdx += (word32)SetObjectId((int)algoSz, out + inOutIdx);
- XMEMCPY(out + inOutIdx, algoName, algoSz);
- inOutIdx += algoSz;
- inOutIdx += SetSequence(seqSz, out + inOutIdx);
- /* create random salt if one not provided */
- if (salt == NULL || saltSz == 0) {
- saltSz = 8;
- #ifdef WOLFSSL_SMALL_STACK
- saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (saltTmp == NULL)
- return MEMORY_E;
- #endif
- salt = saltTmp;
- if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
- WOLFSSL_MSG("Error generating random salt");
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return ret;
- }
- }
- inOutIdx += SetOctetString(saltSz, out + inOutIdx);
- if (saltSz + inOutIdx > *outSz) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return BUFFER_E;
- }
- XMEMCPY(out + inOutIdx, salt, saltSz);
- inOutIdx += saltSz;
- /* place iteration setting in buffer */
- ret = SetShortInt(out, &inOutIdx, (word32)itt, *outSz);
- if (ret < 0) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return ret;
- }
- if (inOutIdx + 1 > *outSz) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return BUFFER_E;
- }
- out[inOutIdx++] = ASN_CONTEXT_SPECIFIC | 0;
- /* get pad size and verify buffer room */
- sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
- if (sz + inOutIdx > *outSz) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return BUFFER_E;
- }
- inOutIdx += SetLength(sz, out + inOutIdx);
- /* copy input to output buffer and pad end */
- XMEMCPY(out + inOutIdx, input, inputSz);
- sz = (word32)Pkcs8Pad(out + inOutIdx, (int)inputSz, blockSz);
- #ifdef WOLFSSL_SMALL_STACK
- cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (cbcIv == NULL) {
- XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
- return MEMORY_E;
- }
- #endif
- /* encrypt */
- if ((ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
- out + inOutIdx, (int)sz, version, cbcIv, 1, 0)) < 0) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return ret; /* encrypt failure */
- }
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- (void)rng;
- return (int)(inOutIdx + sz);
- #else
- DECL_ASNSETDATA(dataASN, p8EncPbes1ASN_Length);
- int ret = 0;
- int sz = 0;
- int version = 0;
- int id = -1;
- int blockSz = 0;
- word32 pkcs8Sz = 0;
- (void)heap;
- WOLFSSL_ENTER("EncryptContent");
- /* Must have a output size to return or check. */
- if (outSz == NULL) {
- ret = BAD_FUNC_ARG;
- }
- /* Check salt size is valid. */
- if ((ret == 0) && (saltSz > MAX_SALT_SIZE)) {
- ret = ASN_PARSE_E;
- }
- /* Get algorithm parameters for algorithm identifier. */
- if ((ret == 0) && CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0) {
- ret = ASN_INPUT_E;
- }
- /* Check PKCS #5 version - only PBSE1 parameters supported. */
- if ((ret == 0) && (version == PKCS5v2)) {
- ret = BAD_FUNC_ARG;
- }
- CALLOC_ASNSETDATA(dataASN, p8EncPbes1ASN_Length, ret, heap);
- if (ret == 0) {
- /* Setup data to go into encoding including PBE algorithm, salt,
- * iteration count, and padded key length. */
- SetASN_OID(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_OID], (word32)id,
- oidPBEType);
- if (salt == NULL || saltSz == 0) {
- salt = NULL;
- saltSz = PKCS5_SALT_SZ;
- /* Salt generated into encoding below. */
- }
- SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT],
- salt, saltSz);
- SetASN_Int16Bit(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER],
- (word16)itt);
- pkcs8Sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
- SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCDATA], NULL, pkcs8Sz);
- /* Calculate size of encoding. */
- ret = SizeASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
- dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
- (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
- &sz);
- }
- /* Return size when no output buffer. */
- if ((ret == 0) && (out == NULL)) {
- *outSz = (word32)sz;
- ret = LENGTH_ONLY_E;
- }
- /* Check output buffer is big enough for encoded data. */
- if ((ret == 0) && (sz > (int)*outSz)) {
- ret = BAD_FUNC_ARG;
- }
- if (ret == 0) {
- /* Encode PKCS#8 key. */
- SetASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
- dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
- (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
- out);
- if (salt == NULL) {
- /* Generate salt into encoding. */
- salt = (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT].
- data.buffer.data;
- ret = wc_RNG_GenerateBlock(rng, salt, saltSz);
- }
- }
- if (ret == 0) {
- byte cbcIv[MAX_IV_SIZE];
- /* Store PKCS#8 key in output buffer. */
- byte* pkcs8 =
- (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCDATA].data.buffer.data;
- XMEMCPY(pkcs8, input, inputSz);
- Pkcs8Pad(pkcs8, (int)inputSz, blockSz);
- /* Encrypt PKCS#8 key inline. */
- ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
- pkcs8, (int)pkcs8Sz, version, cbcIv, 1, 0);
- }
- if (ret == 0) {
- /* Returning size on success. */
- ret = sz;
- }
- FREE_ASNSETDATA(dataASN, heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #endif /* HAVE_PKCS12 */
- #endif /* NO_PWDBASED */
- #ifndef NO_RSA
- #ifndef HAVE_USER_RSA
- #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
- /* This function is to retrieve key position information in a cert.*
- * The information will be used to call TSIP TLS-linked API for *
- * certificate verification. */
- static int RsaPublicKeyDecodeRawIndex(const byte* input, word32* inOutIdx,
- word32 inSz, word32* key_n,
- word32* key_n_len, word32* key_e,
- word32* key_e_len)
- {
- int ret = 0;
- int length = 0;
- #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
- byte b;
- #endif
- if (input == NULL || inOutIdx == NULL)
- return BAD_FUNC_ARG;
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
- if ((*inOutIdx + 1) > inSz)
- return BUFFER_E;
- b = input[*inOutIdx];
- if (b != ASN_INTEGER) {
- /* not from decoded cert, will have algo id, skip past */
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- if (SkipObjectId(input, inOutIdx, inSz) < 0)
- return ASN_PARSE_E;
- /* Option NULL ASN.1 tag */
- if (*inOutIdx >= inSz) {
- return BUFFER_E;
- }
- if (input[*inOutIdx] == ASN_TAG_NULL) {
- ret = GetASNNull(input, inOutIdx, inSz);
- if (ret != 0)
- return ret;
- }
- /* TODO: support RSA PSS */
- /* should have bit tag length and seq next */
- ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
- if (ret != 0)
- return ret;
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- }
- #endif /* OPENSSL_EXTRA */
- /* Get modulus */
- ret = GetASNInt(input, inOutIdx, &length, inSz);
- *key_n += *inOutIdx;
- if (ret < 0) {
- return ASN_RSA_KEY_E;
- }
- if (key_n_len)
- *key_n_len = length;
- *inOutIdx += length;
- /* Get exponent */
- ret = GetASNInt(input, inOutIdx, &length, inSz);
- *key_e += *inOutIdx;
- if (ret < 0) {
- return ASN_RSA_KEY_E;
- }
- if (key_e_len)
- *key_e_len = length;
- return ret;
- }
- #endif /* WOLFSSL_RENESAS_TSIP */
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for an RSA public key.
- * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
- * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
- */
- static const ASNItem rsaPublicKeyASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
- /* ALGOID_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
- #ifdef WC_RSA_PSS
- /* ALGOID_P_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
- #endif
- /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 1, 0 },
- /* RSAPublicKey */
- /* PUBKEY_RSA_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
- /* PUBKEY_RSA_N */ { 3, ASN_INTEGER, 0, 0, 0 },
- /* PUBKEY_RSA_E */ { 3, ASN_INTEGER, 0, 0, 0 },
- };
- enum {
- RSAPUBLICKEYASN_IDX_SEQ = 0,
- RSAPUBLICKEYASN_IDX_ALGOID_SEQ,
- RSAPUBLICKEYASN_IDX_ALGOID_OID,
- RSAPUBLICKEYASN_IDX_ALGOID_NULL,
- #ifdef WC_RSA_PSS
- RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ,
- #endif
- RSAPUBLICKEYASN_IDX_PUBKEY,
- RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ,
- RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N,
- RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E
- };
- /* Number of items in ASN.1 template for an RSA public key. */
- #define rsaPublicKeyASN_Length (sizeof(rsaPublicKeyASN) / sizeof(ASNItem))
- #endif
- /* Decode RSA public key.
- *
- * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
- * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
- *
- * @param [in] input Buffer holding BER encoded data.
- * @param [in, out] inOutIdx On in, start of RSA public key.
- * On out, start of ASN.1 item after RSA public key.
- * @param [in] inSz Number of bytes in buffer.
- * @param [out] n Pointer to modulus in buffer.
- * @param [out] nSz Size of modulus in bytes.
- * @param [out] e Pointer to exponent in buffer.
- * @param [out] eSz Size of exponent in bytes.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- */
- int wc_RsaPublicKeyDecode_ex(const byte* input, word32* inOutIdx, word32 inSz,
- const byte** n, word32* nSz, const byte** e, word32* eSz)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret = 0;
- int length = 0;
- #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
- word32 localIdx;
- byte tag;
- #endif
- if (input == NULL || inOutIdx == NULL)
- return BAD_FUNC_ARG;
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
- localIdx = *inOutIdx;
- if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
- return BUFFER_E;
- if (tag != ASN_INTEGER) {
- /* not from decoded cert, will have algo id, skip past */
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- if (SkipObjectId(input, inOutIdx, inSz) < 0)
- return ASN_PARSE_E;
- /* Option NULL ASN.1 tag */
- if (*inOutIdx >= inSz) {
- return BUFFER_E;
- }
- localIdx = *inOutIdx;
- if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
- return ASN_PARSE_E;
- if (tag == ASN_TAG_NULL) {
- ret = GetASNNull(input, inOutIdx, inSz);
- if (ret != 0)
- return ret;
- }
- #ifdef WC_RSA_PSS
- /* Skip RSA PSS parameters. */
- else if (tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- *inOutIdx += length;
- }
- #endif
- /* should have bit tag length and seq next */
- ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
- if (ret != 0)
- return ret;
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- }
- #endif /* OPENSSL_EXTRA */
- /* Get modulus */
- ret = GetASNInt(input, inOutIdx, &length, inSz);
- if (ret < 0) {
- return ASN_RSA_KEY_E;
- }
- if (nSz)
- *nSz = (word32)length;
- if (n)
- *n = &input[*inOutIdx];
- *inOutIdx += (word32)length;
- /* Get exponent */
- ret = GetASNInt(input, inOutIdx, &length, inSz);
- if (ret < 0) {
- return ASN_RSA_KEY_E;
- }
- if (eSz)
- *eSz = (word32)length;
- if (e)
- *e = &input[*inOutIdx];
- *inOutIdx += (word32)length;
- return ret;
- #else
- DECL_ASNGETDATA(dataASN, rsaPublicKeyASN_Length);
- int ret = 0;
- #ifdef WC_RSA_PSS
- word32 oid = RSAk;
- #endif
- /* Check validity of parameters. */
- if (input == NULL || inOutIdx == NULL) {
- ret = BAD_FUNC_ARG;
- }
- CALLOC_ASNGETDATA(dataASN, rsaPublicKeyASN_Length, ret, NULL);
- if (ret == 0) {
- /* Try decoding PKCS #1 public key by ignoring rest of ASN.1. */
- ret = GetASN_Items(&rsaPublicKeyASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
- &dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
- (int)(rsaPublicKeyASN_Length - RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ),
- 0, input, inOutIdx, inSz);
- if (ret != 0) {
- /* Didn't work - try whole SubjectKeyInfo instead. */
- #ifdef WC_RSA_PSS
- /* Could be RSA or RSA PSS key. */
- GetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], oidKeyType);
- #else
- /* Set the OID to expect. */
- GetASN_ExpBuffer(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID],
- keyRsaOid, sizeof(keyRsaOid));
- #endif
- /* Decode SubjectKeyInfo. */
- ret = GetASN_Items(rsaPublicKeyASN, dataASN,
- rsaPublicKeyASN_Length, 1, input, inOutIdx,
- inSz);
- }
- }
- #ifdef WC_RSA_PSS
- if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].tag != 0)) {
- /* Two possible OIDs supported - RSA and RSA PSS. */
- oid = dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].data.oid.sum;
- if ((oid != RSAk) && (oid != RSAPSSk)) {
- ret = ASN_PARSE_E;
- }
- }
- if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].tag != 0)) {
- /* Can't have NULL and SEQ. */
- if (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_NULL].tag != 0) {
- ret = ASN_PARSE_E;
- }
- /* SEQ present only with RSA PSS. */
- if ((ret == 0) && (oid != RSAPSSk)) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- enum wc_HashType hash;
- int mgf;
- int saltLen;
- const byte* params = GetASNItem_Addr(
- dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
- word32 paramsSz = GetASNItem_Length(
- dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
- /* Validate the private key parameters. */
- ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf, &saltLen);
- /* TODO: store parameters so that usage can be checked. */
- }
- }
- #endif
- if (ret == 0) {
- /* Return the buffers and lengths asked for. */
- if (n != NULL) {
- *n = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.data;
- }
- if (nSz != NULL) {
- *nSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.length;
- }
- if (e != NULL) {
- *e = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.data;
- }
- if (eSz != NULL) {
- *eSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.length;
- }
- }
- FREE_ASNGETDATA(dataASN, NULL);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- /* Decode RSA public key.
- *
- * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
- * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
- *
- * @param [in] input Buffer holding BER encoded data.
- * @param [in, out] inOutIdx On in, start of RSA public key.
- * On out, start of ASN.1 item after RSA public key.
- * @param [in, out] key RSA key object.
- * @param [in] inSz Number of bytes in buffer.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- */
- int wc_RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
- word32 inSz)
- {
- int ret;
- const byte *n = NULL, *e = NULL;
- word32 nSz = 0, eSz = 0;
- if (key == NULL)
- return BAD_FUNC_ARG;
- ret = wc_RsaPublicKeyDecode_ex(input, inOutIdx, inSz, &n, &nSz, &e, &eSz);
- if (ret == 0) {
- ret = wc_RsaPublicKeyDecodeRaw(n, nSz, e, eSz, key);
- }
- return ret;
- }
- #endif /* HAVE_USER_RSA */
- #endif /* !NO_RSA */
- #ifndef NO_DH
- #if defined(WOLFSSL_DH_EXTRA)
- /*
- * Decodes DH public key to fill specified DhKey.
- *
- * return 0 on success, negative on failure
- */
- int wc_DhPublicKeyDecode(const byte* input, word32* inOutIdx,
- DhKey* key, word32 inSz)
- {
- int ret = 0;
- int length;
- word32 oid = 0;
- if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
- return BAD_FUNC_ARG;
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
- if (oid != DHk || ret < 0)
- return ASN_DH_KEY_E;
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- if (GetInt(&key->p, input, inOutIdx, inSz) < 0)
- return ASN_DH_KEY_E;
- if (GetInt(&key->g, input, inOutIdx, inSz) < 0) {
- mp_clear(&key->p);
- return ASN_DH_KEY_E;
- }
- ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
- if (ret > 0) {
- /* Found Bit String WOLFSSL_DH_EXTRA is required to access DhKey.pub */
- if (GetInt(&key->pub, input, inOutIdx, inSz) < 0) {
- mp_clear(&key->p);
- mp_clear(&key->g);
- return ASN_DH_KEY_E;
- }
- }
- else {
- mp_clear(&key->p);
- mp_clear(&key->g);
- return ASN_DH_KEY_E;
- }
- return 0;
- }
- #endif /* WOLFSSL_DH_EXTRA */
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for DH key.
- * PKCS #3, 9 - DHParameter.
- * (Also in: RFC 2786, 3)
- */
- static const ASNItem dhParamASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* prime */
- /* PRIME */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* base */
- /* BASE */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* privateValueLength */
- /* PRIVLEN */ { 1, ASN_INTEGER, 0, 0, 1 },
- };
- enum {
- DHPARAMASN_IDX_SEQ = 0,
- DHPARAMASN_IDX_PRIME,
- DHPARAMASN_IDX_BASE,
- DHPARAMASN_IDX_PRIVLEN
- };
- /* Number of items in ASN.1 template for DH key. */
- #define dhParamASN_Length (sizeof(dhParamASN) / sizeof(ASNItem))
- #ifdef WOLFSSL_DH_EXTRA
- /* ASN.1 template for DH key wrapped in PKCS #8 or SubjectPublicKeyInfo.
- * PKCS #8: RFC 5208, 5 - PrivateKeyInfo
- * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
- * RFC 3279, 2.3.3 - DH in SubjectPublicKeyInfo
- */
- static const ASNItem dhKeyPkcs8ASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* VER */ { 1, ASN_INTEGER, 0, 0, 1 },
- /* PKEYALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* PKEYALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
- /* DHParameter */
- /* PKEYALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
- /* p */
- /* PKEYALGO_PARAM_P */ { 3, ASN_INTEGER, 0, 0, 0 },
- /* g */
- /* PKEYALGO_PARAM_G */ { 3, ASN_INTEGER, 0, 0, 0 },
- /* q - factor of p-1 */
- /* PKEYALGO_PARAM_Q */ { 3, ASN_INTEGER, 0, 0, 1 },
- /* j - subgroup factor */
- /* PKEYALGO_PARAM_J */ { 3, ASN_INTEGER, 0, 0, 1 },
- /* ValidationParms */
- /* PKEYALGO_PARAM_VALID */ { 3, ASN_SEQUENCE, 0, 0, 1 },
- /* PrivateKey - PKCS #8 */
- /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 2 },
- /* PKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
- /* PublicKey - SubjectPublicKeyInfo. */
- /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 2 },
- /* PUBKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
- };
- enum {
- DHKEYPKCS8ASN_IDX_SEQ = 0,
- DHKEYPKCS8ASN_IDX_VER,
- DHKEYPKCS8ASN_IDX_PKEYALGO_SEQ,
- DHKEYPKCS8ASN_IDX_PKEYALGO_OID,
- DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_SEQ,
- DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P,
- DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G,
- DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q,
- DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J,
- DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID,
- DHKEYPKCS8ASN_IDX_PKEY_STR,
- DHKEYPKCS8ASN_IDX_PKEY_INT,
- DHKEYPKCS8ASN_IDX_PUBKEY_STR,
- DHKEYPKCS8ASN_IDX_PUBKEY_INT
- };
- #define dhKeyPkcs8ASN_Length (sizeof(dhKeyPkcs8ASN) / sizeof(ASNItem))
- #endif
- #endif
- /* Decodes either PKCS#3 DH parameters or PKCS#8 DH key file (WOLFSSL_DH_EXTRA).
- *
- * See also wc_DhParamsLoad(). Loads directly into buffers rather than key
- * object.
- *
- * @param [in] input BER/DER encoded data.
- * @param [in, out] inOutIdx On in, start of DH key data.
- * On out, end of DH key data.
- * @param [in, out] key DH key object.
- * @param [in] inSz Size of data in bytes.
- * @return 0 on success.
- * @return BAD_FUNC_ARG when input, inOutIDx or key is NULL.
- * @return MEMORY_E when dynamic memory allocation fails.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- * @return MP_INIT_E when the unable to initialize an mp_int.
- * @return ASN_GETINT_E when the unable to convert data to an mp_int.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- */
- int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret = 0;
- int length;
- #ifdef WOLFSSL_DH_EXTRA
- #if !defined(HAVE_FIPS) || \
- (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
- word32 oid = 0, temp = 0;
- #endif
- #endif
- WOLFSSL_ENTER("wc_DhKeyDecode");
- if (inOutIdx == NULL)
- return BAD_FUNC_ARG;
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- #ifdef WOLFSSL_DH_EXTRA
- #if !defined(HAVE_FIPS) || \
- (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
- temp = *inOutIdx;
- #endif
- #endif
- /* Assume input started after 1.2.840.113549.1.3.1 dhKeyAgreement */
- if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
- ret = ASN_DH_KEY_E;
- }
- if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
- mp_clear(&key->p);
- ret = ASN_DH_KEY_E;
- }
- #ifdef WOLFSSL_DH_EXTRA
- #if !defined(HAVE_FIPS) || \
- (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
- /* If ASN_DH_KEY_E: Check if input started at beginning of key */
- if (ret == ASN_DH_KEY_E) {
- *inOutIdx = temp;
- /* the version (0) - private only (for public skip) */
- if (GetASNInt(input, inOutIdx, &length, inSz) == 0) {
- *inOutIdx += (word32)length;
- }
- /* Size of dhKeyAgreement section */
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- /* Check for dhKeyAgreement */
- ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
- if (oid != DHk || ret < 0)
- return ASN_DH_KEY_E;
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
- return ASN_DH_KEY_E;
- }
- if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
- mp_clear(&key->p);
- return ASN_DH_KEY_E;
- }
- }
- temp = *inOutIdx;
- ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
- if (ret > 0) {
- /* Found Bit String */
- if (GetInt(&key->pub, input, inOutIdx, inSz) == 0) {
- WOLFSSL_MSG("Found Public Key");
- ret = 0;
- }
- } else {
- *inOutIdx = temp;
- ret = (GetOctetString(input, inOutIdx, &length, inSz) >= 0);
- if (ret > 0) {
- /* Found Octet String */
- if (GetInt(&key->priv, input, inOutIdx, inSz) == 0) {
- WOLFSSL_MSG("Found Private Key");
- /* Compute public */
- ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
- }
- } else {
- /* Don't use length from failed CheckBitString/GetOctetString */
- *inOutIdx = temp;
- ret = 0;
- }
- }
- #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
- #endif /* WOLFSSL_DH_EXTRA */
- WOLFSSL_LEAVE("wc_DhKeyDecode", ret);
- return ret;
- #else
- #ifdef WOLFSSL_DH_EXTRA
- DECL_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length);
- #else
- DECL_ASNGETDATA(dataASN, dhParamASN_Length);
- #endif
- int ret = 0;
- /* Check input parameters are valid. */
- if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
- ret = BAD_FUNC_ARG;
- }
- #ifdef WOLFSSL_DH_EXTRA
- ALLOC_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length, ret, key->heap);
- #else
- ALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, key->heap);
- #endif
- if (ret == 0) {
- /* Initialize data and set mp_ints to hold p and g. */
- XMEMSET(dataASN, 0, sizeof(*dataASN) * dhParamASN_Length);
- GetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
- GetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
- /* Try simple PKCS #3 template. */
- ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
- inOutIdx, inSz);
- #ifdef WOLFSSL_DH_EXTRA
- if (ret != 0) {
- mp_free(&key->p);
- mp_free(&key->g);
- /* Initialize data and set mp_ints to hold p, g, q, priv and pub. */
- XMEMSET(dataASN, 0, sizeof(*dataASN) * dhKeyPkcs8ASN_Length);
- GetASN_ExpBuffer(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID],
- keyDhOid, sizeof(keyDhOid));
- GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
- GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
- GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q], &key->q);
- GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
- GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
- /* Try PKCS #8 wrapped template. */
- ret = GetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, 1,
- input, inOutIdx, inSz);
- if (ret == 0) {
- /* VERSION only present in PKCS #8 private key structure */
- if ((dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].length != 0) &&
- (dataASN[DHKEYPKCS8ASN_IDX_VER].length == 0)) {
- ret = ASN_PARSE_E;
- }
- else if ((dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].length != 0) &&
- (dataASN[DHKEYPKCS8ASN_IDX_VER].length != 0)) {
- ret = ASN_PARSE_E;
- }
- }
- if ((ret == 0) && mp_iszero(&key->pub)) {
- ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
- }
- }
- #endif
- }
- FREE_ASNGETDATA(dataASN, key->heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #ifdef WOLFSSL_DH_EXTRA
- /* Export DH Key (private or public) */
- int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret, privSz = 0, pubSz = 0;
- word32 keySz, idx, len, total;
- if (key == NULL || outSz == NULL) {
- return BAD_FUNC_ARG;
- }
- /* determine size */
- if (exportPriv) {
- /* octect string: priv */
- privSz = SetASNIntMP(&key->priv, -1, NULL);
- if (privSz < 0)
- return privSz;
- idx = 1 + SetLength((word32)privSz, NULL) +
- (word32)privSz; /* +1 for ASN_OCTET_STRING */
- }
- else {
- /* bit string: public */
- pubSz = SetASNIntMP(&key->pub, -1, NULL);
- if (pubSz < 0)
- return pubSz;
- idx = SetBitString((word32)pubSz, 0, NULL) + (word32)pubSz;
- }
- keySz = idx;
- /* DH Parameters sequence with P and G */
- total = 0;
- ret = wc_DhParamsToDer(key, NULL, &total);
- if (ret != LENGTH_ONLY_E)
- return ret;
- idx += total;
- /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
- idx += (word32)SetObjectId(sizeof(keyDhOid), NULL);
- idx += (word32)sizeof(keyDhOid);
- len = idx - keySz;
- /* sequence - all but pub/priv */
- idx += SetSequence(len, NULL);
- if (exportPriv) {
- /* version: 0 (ASN_INTEGER, 0x01, 0x00) */
- idx += 3;
- }
- /* sequence */
- total = idx + SetSequence(idx, NULL);
- /* if no output, then just getting size */
- if (output == NULL) {
- *outSz = total;
- return LENGTH_ONLY_E;
- }
- /* make sure output fits in buffer */
- if (total > *outSz) {
- return BUFFER_E;
- }
- total = idx;
- /* sequence */
- idx = SetSequence(total, output);
- if (exportPriv) {
- /* version: 0 */
- idx += (word32)SetMyVersion(0, output + idx, 0);
- }
- /* sequence - all but pub/priv */
- idx += SetSequence(len, output + idx);
- /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
- idx += (word32)SetObjectId(sizeof(keyDhOid), output + idx);
- XMEMCPY(output + idx, keyDhOid, sizeof(keyDhOid));
- idx += sizeof(keyDhOid);
- /* DH Parameters sequence with P and G */
- total = *outSz - idx;
- ret = wc_DhParamsToDer(key, output + idx, &total);
- if (ret < 0)
- return ret;
- idx += total;
- /* octect string: priv */
- if (exportPriv) {
- idx += (word32)SetOctetString((word32)privSz, output + idx);
- idx += (word32)SetASNIntMP(&key->priv, -1, output + idx);
- }
- else {
- /* bit string: public */
- idx += (word32)SetBitString((word32)pubSz, 0, output + idx);
- idx += (word32)SetASNIntMP(&key->pub, -1, output + idx);
- }
- *outSz = idx;
- return (int)idx;
- #else
- ASNSetData dataASN[dhKeyPkcs8ASN_Length];
- int ret = 0;
- int sz;
- WOLFSSL_ENTER("wc_DhKeyToDer");
- XMEMSET(dataASN, 0, sizeof(dataASN));
- SetASN_Int8Bit(&dataASN[DHKEYPKCS8ASN_IDX_VER], 0);
- SetASN_OID(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID], DHk, oidKeyType);
- /* Set mp_int containing p and g. */
- SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
- SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
- dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q].noOut = 1;
- dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J].noOut = 1;
- dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID].noOut = 1;
- if (exportPriv) {
- SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
- dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_STR].noOut = 1;
- dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].noOut = 1;
- }
- else {
- dataASN[DHKEYPKCS8ASN_IDX_VER].noOut = 1;
- dataASN[DHKEYPKCS8ASN_IDX_PKEY_STR].noOut = 1;
- dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].noOut = 1;
- SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
- }
- /* Calculate the size of the DH parameters. */
- ret = SizeASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, &sz);
- if (output == NULL) {
- *outSz = (word32)sz;
- ret = LENGTH_ONLY_E;
- }
- /* Check buffer is big enough for encoding. */
- if ((ret == 0) && ((int)*outSz < sz)) {
- ret = BUFFER_E;
- }
- if (ret == 0) {
- /* Encode the DH parameters into buffer. */
- SetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, output);
- /* Set the actual encoding size. */
- *outSz = (word32)sz;
- /* Return the actual encoding size. */
- ret = sz;
- }
- return ret;
- #endif
- }
- int wc_DhPubKeyToDer(DhKey* key, byte* out, word32* outSz)
- {
- return wc_DhKeyToDer(key, out, outSz, 0);
- }
- int wc_DhPrivKeyToDer(DhKey* key, byte* out, word32* outSz)
- {
- return wc_DhKeyToDer(key, out, outSz, 1);
- }
- /* Convert DH key parameters to DER format, write to output (outSz)
- * If output is NULL then max expected size is set to outSz and LENGTH_ONLY_E is
- * returned.
- *
- * Note : static function due to redefinition complications with DhKey and FIPS
- * version 2 build.
- *
- * return bytes written on success */
- int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret;
- word32 idx, total;
- if (key == NULL || outSz == NULL) {
- return BAD_FUNC_ARG;
- }
- /* determine size */
- /* integer - g */
- ret = SetASNIntMP(&key->g, -1, NULL);
- if (ret < 0)
- return ret;
- idx = (word32)ret;
- /* integer - p */
- ret = SetASNIntMP(&key->p, -1, NULL);
- if (ret < 0)
- return ret;
- idx += (word32)ret;
- total = idx;
- /* sequence */
- idx += SetSequence(idx, NULL);
- if (output == NULL) {
- *outSz = idx;
- return LENGTH_ONLY_E;
- }
- /* make sure output fits in buffer */
- if (idx > *outSz) {
- return BUFFER_E;
- }
- /* write DH parameters */
- /* sequence - for P and G only */
- idx = SetSequence(total, output);
- /* integer - p */
- ret = SetASNIntMP(&key->p, -1, output + idx);
- if (ret < 0)
- return ret;
- idx += (word32)ret;
- /* integer - g */
- ret = SetASNIntMP(&key->g, -1, output + idx);
- if (ret < 0)
- return ret;
- idx += (word32)ret;
- *outSz = idx;
- return (int)idx;
- #else
- ASNSetData dataASN[dhParamASN_Length];
- int ret = 0;
- int sz = 0;
- WOLFSSL_ENTER("wc_DhParamsToDer");
- if (key == NULL || outSz == NULL) {
- ret = BAD_FUNC_ARG;
- }
- if (ret == 0) {
- XMEMSET(dataASN, 0, sizeof(dataASN));
- /* Set mp_int containing p and g. */
- SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
- SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
- /* privateValueLength not encoded. */
- dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
- /* Calculate the size of the DH parameters. */
- ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
- }
- if ((ret == 0) && (output == NULL)) {
- *outSz = (word32)sz;
- ret = LENGTH_ONLY_E;
- }
- /* Check buffer is big enough for encoding. */
- if ((ret == 0) && (*outSz < (word32)sz)) {
- ret = BUFFER_E;
- }
- if (ret == 0) {
- /* Encode the DH parameters into buffer. */
- SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, output);
- /* Set the actual encoding size. */
- *outSz = (word32)sz;
- /* Return count of bytes written. */
- ret = sz;
- }
- return ret;
- #endif
- }
- #endif /* WOLFSSL_DH_EXTRA */
- /* Decode DH parameters.
- *
- * PKCS #3, 9 - DHParameter.
- * (Also in: RFC 2786, 3)
- *
- * @param [in] input Buffer holding BER encoded data.
- * @param [in, out] inOutIdx On in, start of RSA public key.
- * On out, start of ASN.1 item after RSA public key.
- * @param [in] inSz Number of bytes in buffer.
- * @param [in, out] p Buffer to hold prime.
- * @param [out] pInOutSz On in, size of buffer to hold prime in bytes.
- * On out, size of prime in bytes.
- * @param [in, out] g Buffer to hold base.
- * @param [out] gInOutSz On in, size of buffer to hold base in bytes.
- * On out, size of base in bytes.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
- */
- int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
- byte* g, word32* gInOutSz)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0;
- int ret;
- int length;
- if (GetSequence(input, &idx, &length, inSz) <= 0)
- return ASN_PARSE_E;
- ret = GetASNInt(input, &idx, &length, inSz);
- if (ret != 0)
- return ret;
- if (length <= (int)*pInOutSz) {
- XMEMCPY(p, &input[idx], (size_t)length);
- *pInOutSz = (word32)length;
- }
- else {
- return BUFFER_E;
- }
- idx += (word32)length;
- ret = GetASNInt(input, &idx, &length, inSz);
- if (ret != 0)
- return ret;
- if (length <= (int)*gInOutSz) {
- XMEMCPY(g, &input[idx], (size_t)length);
- *gInOutSz = (word32)length;
- }
- else {
- return BUFFER_E;
- }
- return 0;
- #else
- DECL_ASNGETDATA(dataASN, dhParamASN_Length);
- word32 idx = 0;
- int ret = 0;
- /* Make sure pointers are valid before use. */
- if ((input == NULL) || (p == NULL) || (pInOutSz == NULL) || (g == NULL) ||
- (gInOutSz == NULL)) {
- ret = BAD_FUNC_ARG;
- }
- CALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, NULL);
- if (ret == 0) {
- /* Set the buffers to copy p and g into. */
- GetASN_Buffer(&dataASN[DHPARAMASN_IDX_PRIME], p, pInOutSz);
- GetASN_Buffer(&dataASN[DHPARAMASN_IDX_BASE], g, gInOutSz);
- /* Decode the DH Parameters. */
- ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
- &idx, inSz);
- }
- FREE_ASNGETDATA(dataASN, NULL);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #endif /* !NO_DH */
- #ifndef NO_DSA
- static mp_int* GetDsaInt(DsaKey* key, int idx)
- {
- if (idx == 0)
- return &key->p;
- if (idx == 1)
- return &key->q;
- if (idx == 2)
- return &key->g;
- if (idx == 3)
- return &key->y;
- if (idx == 4)
- return &key->x;
- return NULL;
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for DSA public and private keys.
- * Public key: seq, p, q, g, y
- * Private key: seq, version, p, q, g, y, x
- * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
- */
- static const ASNItem dsaKeyASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* Y */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* X */ { 1, ASN_INTEGER, 0, 0, 0 },
- };
- enum {
- DSAKEYASN_IDX_SEQ = 0,
- DSAKEYASN_IDX_VER,
- DSAKEYASN_IDX_P,
- DSAKEYASN_IDX_Q,
- DSAKEYASN_IDX_G,
- DSAKEYASN_IDX_Y,
- DSAKEYASN_IDX_X
- };
- /* Number of items in ASN.1 template for DSA private key. */
- #define dsaKeyASN_Length (sizeof(dsaKeyASN) / sizeof(ASNItem))
- /* Number of items in ASN.1 template for DSA public key. */
- #define dsaPublicKeyASN_Length ((sizeof(dsaKeyASN) / sizeof(ASNItem)) - 2)
- /* ASN.1 template for PublicKeyInfo with DSA.
- * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
- * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
- */
- static const ASNItem dsaPubKeyASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
- /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 1, 0 },
- /* p */
- /* ALGOID_PARAMS_P */ { 3, ASN_INTEGER, 0, 0, 0 },
- /* q */
- /* ALGOID_PARAMS_Q */ { 3, ASN_INTEGER, 0, 0, 0 },
- /* g */
- /* ALGOID_PARAMS_G */ { 3, ASN_INTEGER, 0, 0, 0 },
- /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 1 },
- /* y */
- /* PUBKEY_Y */ { 2, ASN_INTEGER, 0, 0, 0 },
- };
- enum {
- DSAPUBKEYASN_IDX_SEQ = 0,
- DSAPUBKEYASN_IDX_ALGOID_SEQ,
- DSAPUBKEYASN_IDX_ALGOID_OID,
- DSAPUBKEYASN_IDX_ALGOID_PARAMS,
- DSAPUBKEYASN_IDX_ALGOID_PARAMS_P,
- DSAPUBKEYASN_IDX_ALGOID_PARAMS_Q,
- DSAPUBKEYASN_IDX_ALGOID_PARAMS_G,
- DSAPUBKEYASN_IDX_PUBKEY_STR,
- DSAPUBKEYASN_IDX_PUBKEY_Y
- };
- /* Number of items in ASN.1 template for PublicKeyInfo with DSA. */
- #define dsaPubKeyASN_Length (sizeof(dsaPubKeyASN) / sizeof(ASNItem))
- #endif /* WOLFSSL_ASN_TEMPLATE */
- /* Decode DSA public key.
- *
- * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
- * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
- *
- * @param [in] input Buffer holding BER encoded data.
- * @param [in, out] inOutIdx On in, start of DSA public key.
- * On out, start of ASN.1 item after DSA public key.
- * @param [in, out] key DSA key object.
- * @param [in] inSz Number of bytes in buffer.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- */
- int wc_DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
- word32 inSz)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int length;
- int ret = 0;
- word32 oid;
- word32 maxIdx;
- if (input == NULL || inOutIdx == NULL || key == NULL)
- return BAD_FUNC_ARG;
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- maxIdx = (word32)(*inOutIdx + (word32)length);
- if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
- GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
- GetInt(&key->g, input, inOutIdx, maxIdx) < 0 ||
- GetInt(&key->y, input, inOutIdx, maxIdx) < 0 )
- ret = ASN_DH_KEY_E;
- if (ret != 0) {
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- ret = GetObjectId(input, inOutIdx, &oid, oidIgnoreType, inSz);
- if (ret != 0)
- return ret;
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
- GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
- GetInt(&key->g, input, inOutIdx, inSz) < 0)
- return ASN_DH_KEY_E;
- if (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) < 0)
- return ASN_PARSE_E;
- if (GetInt(&key->y, input, inOutIdx, inSz) < 0 )
- return ASN_DH_KEY_E;
- ret = 0;
- }
- key->type = DSA_PUBLIC;
- return ret;
- #else
- /* dsaPubKeyASN is longer than dsaPublicKeyASN. */
- DECL_ASNGETDATA(dataASN, dsaPubKeyASN_Length);
- int ret = 0;
- /* Validated parameters. */
- if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
- ret = BAD_FUNC_ARG;
- }
- ALLOC_ASNGETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
- if (ret == 0) {
- int i;
- /* Clear dynamic data items. */
- XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPublicKeyASN_Length);
- /* seq
- * p, q, g, y
- * Start DSA ints from DSAKEYASN_IDX_VER instead of DSAKEYASN_IDX_P */
- for (i = 0; i < DSA_INTS - 1; i++)
- GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i], GetDsaInt(key, i));
- /* Parse as simple form. */
- ret = GetASN_Items(dsaKeyASN, dataASN, dsaPublicKeyASN_Length, 0, input,
- inOutIdx, inSz);
- if (ret != 0) {
- /* Clear dynamic data items. */
- XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPubKeyASN_Length);
- /* Set DSA OID to expect. */
- GetASN_ExpBuffer(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID],
- keyDsaOid, sizeof(keyDsaOid));
- /* p, q, g */
- for (i = 0; i < DSA_INTS - 2; i++)
- GetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
- GetDsaInt(key, i));
- /* y */
- GetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
- /* Parse as SubjectPublicKeyInfo. */
- ret = GetASN_Items(dsaPubKeyASN, dataASN, dsaPubKeyASN_Length, 1,
- input, inOutIdx, inSz);
- }
- }
- if (ret == 0) {
- /* Data parsed - set type of key parsed. */
- key->type = DSA_PUBLIC;
- }
- FREE_ASNGETDATA(dataASN, key->heap);
- return ret;
- #endif
- }
- int wc_DsaParamsDecode(const byte* input, word32* inOutIdx, DsaKey* key,
- word32 inSz)
- {
- int length;
- word32 maxIdx;
- if (input == NULL || inOutIdx == NULL || key == NULL)
- return BAD_FUNC_ARG;
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- maxIdx = (word32)(*inOutIdx + (word32)length);
- if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
- GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
- GetInt(&key->g, input, inOutIdx, maxIdx) < 0)
- return ASN_DH_KEY_E;
- return 0;
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for a DSA key holding private key in an OCTET_STRING. */
- static const ASNItem dsaKeyOctASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* p */
- /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* q */
- /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* g */
- /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* Private key */
- /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
- /* x */
- /* X */ { 2, ASN_INTEGER, 0, 0, 0 },
- };
- enum {
- DSAKEYOCTASN_IDX_SEQ = 0,
- DSAKEYOCTASN_IDX_P,
- DSAKEYOCTASN_IDX_Q,
- DSAKEYOCTASN_IDX_G,
- DSAKEYOCTASN_IDX_PKEY_STR,
- DSAKEYOCTASN_IDX_X
- };
- /* Number of items in ASN.1 template for a DSA key (OCTET_STRING version). */
- #define dsaKeyOctASN_Length (sizeof(dsaKeyOctASN) / sizeof(ASNItem))
- #endif
- /* Decode DSA private key.
- *
- * @param [in] input Buffer holding BER encoded data.
- * @param [in, out] inOutIdx On in, start of DSA public key.
- * On out, start of ASN.1 item after DSA public key.
- * @param [in, out] key DSA key object.
- * @param [in] inSz Number of bytes in buffer.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- */
- int wc_DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
- word32 inSz)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int length, version, ret = 0, temp = 0;
- word32 algId = 0;
- /* Sanity checks on input */
- if (input == NULL || inOutIdx == NULL || key == NULL) {
- return BAD_FUNC_ARG;
- }
- /* if has pkcs8 header skip it */
- if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
- /* ignore error, did not have pkcs8 header */
- }
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- temp = (int)*inOutIdx;
- /* Default case expects a certificate with OctetString but no version ID */
- ret = GetInt(&key->p, input, inOutIdx, inSz);
- if (ret < 0) {
- mp_clear(&key->p);
- ret = ASN_PARSE_E;
- }
- else {
- ret = GetInt(&key->q, input, inOutIdx, inSz);
- if (ret < 0) {
- mp_clear(&key->p);
- mp_clear(&key->q);
- ret = ASN_PARSE_E;
- }
- else {
- ret = GetInt(&key->g, input, inOutIdx, inSz);
- if (ret < 0) {
- mp_clear(&key->p);
- mp_clear(&key->q);
- mp_clear(&key->g);
- ret = ASN_PARSE_E;
- }
- else {
- ret = GetOctetString(input, inOutIdx, &length, inSz);
- if (ret < 0) {
- mp_clear(&key->p);
- mp_clear(&key->q);
- mp_clear(&key->g);
- ret = ASN_PARSE_E;
- }
- else {
- ret = GetInt(&key->y, input, inOutIdx, inSz);
- if (ret < 0) {
- mp_clear(&key->p);
- mp_clear(&key->q);
- mp_clear(&key->g);
- mp_clear(&key->y);
- ret = ASN_PARSE_E;
- }
- }
- }
- }
- }
- /* An alternate pass if default certificate fails parsing */
- if (ret == ASN_PARSE_E) {
- *inOutIdx = (word32)temp;
- if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
- return ASN_PARSE_E;
- if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
- GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
- GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
- GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
- GetInt(&key->x, input, inOutIdx, inSz) < 0 )
- return ASN_DH_KEY_E;
- }
- key->type = DSA_PRIVATE;
- return 0;
- #else
- /* dsaKeyASN is longer than dsaKeyOctASN. */
- DECL_ASNGETDATA(dataASN, dsaKeyASN_Length);
- int ret = 0;
- byte version = 0;
- /* Sanity checks on input */
- if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
- ret = BAD_FUNC_ARG;
- }
- CALLOC_ASNGETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
- if (ret == 0) {
- int i;
- /* Try dsaKeyOctASN */
- /* Initialize key data and set mp_ints for params */
- for (i = 0; i < DSA_INTS - 2; i++) {
- GetASN_MP(&dataASN[(int)DSAKEYOCTASN_IDX_P + i], GetDsaInt(key, i));
- }
- /* and priv */
- GetASN_MP(&dataASN[DSAKEYOCTASN_IDX_X], GetDsaInt(key, i));
- /* Try simple form. */
- ret = GetASN_Items(dsaKeyOctASN, dataASN, dsaKeyOctASN_Length, 1, input,
- inOutIdx, inSz);
- if (ret != 0) {
- /* Try dsaKeyASN */
- XMEMSET(dataASN, 0, sizeof(*dataASN) * dsaKeyASN_Length);
- GetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], &version);
- for (i = 0; i < DSA_INTS; i++) {
- mp_int* n = GetDsaInt(key, i);
- mp_clear(n);
- GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], n);
- }
- /* Try simple OCTET_STRING form. */
- ret = GetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, 1, input,
- inOutIdx, inSz);
- }
- }
- if (ret == 0) {
- /* Set the contents to be a private key. */
- key->type = DSA_PRIVATE;
- }
- FREE_ASNGETDATA(dataASN, key->heap);
- return ret;
- #endif
- }
- #ifndef WOLFSSL_ASN_TEMPLATE
- /* Release Tmp DSA resources */
- static WC_INLINE void FreeTmpDsas(byte** tmps, void* heap, int ints)
- {
- int i;
- for (i = 0; i < ints; i++)
- XFREE(tmps[i], heap, DYNAMIC_TYPE_DSA);
- (void)heap;
- }
- #endif /* !WOLFSSL_ASN_TEMPLATE */
- #if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \
- defined(WOLFSSL_CERT_GEN))
- /* Encode a DSA public key into buffer.
- *
- * @param [out] output Buffer to hold encoded data.
- * @param [in] key DSA key object.
- * @param [out] outLen Length of buffer.
- * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
- * @return Size of encoded data in bytes on success.
- * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
- * than a minimal size (5 bytes), or buffer size is smaller than
- * encoding size.
- * @return MEMORY_E when dynamic memory allocation fails.
- */
- int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- /* p, g, q = DSA params, y = public exponent */
- #ifdef WOLFSSL_SMALL_STACK
- byte* p = NULL;
- byte* g = NULL;
- byte* q = NULL;
- byte* y = NULL;
- #else
- byte p[MAX_DSA_INT_SZ];
- byte g[MAX_DSA_INT_SZ];
- byte q[MAX_DSA_INT_SZ];
- byte y[MAX_DSA_INT_SZ];
- #endif
- byte innerSeq[MAX_SEQ_SZ];
- byte outerSeq[MAX_SEQ_SZ];
- byte bitString[1 + MAX_LENGTH_SZ + 1];
- int pSz, gSz, qSz, ySz;
- word32 idx, innerSeqSz, outerSeqSz, bitStringSz = 0;
- WOLFSSL_ENTER("wc_SetDsaPublicKey");
- if (output == NULL || key == NULL || outLen < MAX_SEQ_SZ) {
- return BAD_FUNC_ARG;
- }
- /* p */
- #ifdef WOLFSSL_SMALL_STACK
- p = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (p == NULL)
- return MEMORY_E;
- #endif
- if ((pSz = SetASNIntMP(&key->p, MAX_DSA_INT_SZ, p)) < 0) {
- WOLFSSL_MSG("SetASNIntMP Error with p");
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return pSz;
- }
- /* q */
- #ifdef WOLFSSL_SMALL_STACK
- q = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (q == NULL)
- return MEMORY_E;
- #endif
- if ((qSz = SetASNIntMP(&key->q, MAX_DSA_INT_SZ, q)) < 0) {
- WOLFSSL_MSG("SetASNIntMP Error with q");
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return qSz;
- }
- /* g */
- #ifdef WOLFSSL_SMALL_STACK
- g = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (g == NULL)
- return MEMORY_E;
- #endif
- if ((gSz = SetASNIntMP(&key->g, MAX_DSA_INT_SZ, g)) < 0) {
- WOLFSSL_MSG("SetASNIntMP Error with g");
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return gSz;
- }
- /* y */
- #ifdef WOLFSSL_SMALL_STACK
- y = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (y == NULL)
- return MEMORY_E;
- #endif
- if ((ySz = SetASNIntMP(&key->y, MAX_DSA_INT_SZ, y)) < 0) {
- WOLFSSL_MSG("SetASNIntMP Error with y");
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return ySz;
- }
- if (with_header) {
- word32 algoSz;
- #ifdef WOLFSSL_SMALL_STACK
- byte* algo = NULL;
- algo = (byte*)XMALLOC(MAX_ALGO_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (algo == NULL) {
- XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- return MEMORY_E;
- }
- #else
- byte algo[MAX_ALGO_SZ];
- #endif
- innerSeqSz = SetSequence((word32)(pSz + qSz + gSz), innerSeq);
- algoSz = SetAlgoID(DSAk, algo, oidKeyType, 0);
- bitStringSz = SetBitString((word32)ySz, 0, bitString);
- outerSeqSz = SetSequence(algoSz + innerSeqSz +
- (word32)(pSz + qSz + gSz), outerSeq);
- idx = SetSequence(algoSz + innerSeqSz + (word32)(pSz + qSz + gSz) +
- bitStringSz + (word32)ySz + outerSeqSz, output);
- /* check output size */
- if ((idx + algoSz + bitStringSz + innerSeqSz +
- (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen)
- {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- WOLFSSL_MSG("Error, output size smaller than outlen");
- return BUFFER_E;
- }
- /* outerSeq */
- XMEMCPY(output + idx, outerSeq, outerSeqSz);
- idx += outerSeqSz;
- /* algo */
- XMEMCPY(output + idx, algo, algoSz);
- idx += algoSz;
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- } else {
- innerSeqSz = SetSequence((word32)(pSz + qSz + gSz + ySz), innerSeq);
- /* check output size */
- if ((innerSeqSz + (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- WOLFSSL_MSG("Error, output size smaller than outlen");
- return BUFFER_E;
- }
- idx = 0;
- }
- /* innerSeq */
- XMEMCPY(output + idx, innerSeq, innerSeqSz);
- idx += innerSeqSz;
- /* p */
- XMEMCPY(output + idx, p, (size_t)pSz);
- idx += (word32)pSz;
- /* q */
- XMEMCPY(output + idx, q, (size_t)qSz);
- idx += (word32)qSz;
- /* g */
- XMEMCPY(output + idx, g, (size_t)gSz);
- idx += (word32)gSz;
- /* bit string */
- if (bitStringSz > 0) {
- XMEMCPY(output + idx, bitString, bitStringSz);
- idx += bitStringSz;
- }
- /* y */
- XMEMCPY(output + idx, y, (size_t)ySz);
- idx += (word32)ySz;
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return (int)idx;
- #else
- DECL_ASNSETDATA(dataASN, dsaPubKeyASN_Length);
- int ret = 0;
- int i;
- int sz = 0;
- const ASNItem *data = NULL;
- int count = 0;
- WOLFSSL_ENTER("wc_SetDsaPublicKey");
- if ((output == NULL) || (key == NULL) || (outLen < MAX_SEQ_SZ)) {
- ret = BAD_FUNC_ARG;
- }
- CALLOC_ASNSETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
- if (ret == 0) {
- if (with_header) {
- /* Using dsaPubKeyASN */
- data = dsaPubKeyASN;
- count = dsaPubKeyASN_Length;
- /* Set the algorithm OID to write out. */
- SetASN_OID(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID], DSAk, oidKeyType);
- /* Set the mp_ints to encode - parameters and public value. */
- for (i = 0; i < DSA_INTS - 2; i++) {
- SetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
- GetDsaInt(key, i));
- }
- SetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
- }
- else {
- /* Using dsaKeyASN */
- data = dsaKeyASN;
- count = dsaPublicKeyASN_Length;
- /* Set the mp_ints to encode - parameters and public value. */
- for (i = 0; i < DSA_INTS - 1; i++) {
- /* Move all DSA ints up one slot (ignore VERSION so now
- * it means P) */
- SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i],
- GetDsaInt(key, i));
- }
- }
- ret = SizeASN_Items(data, dataASN, count, &sz);
- }
- /* Check buffer is big enough for encoding. */
- if ((ret == 0) && (sz > (int)outLen)) {
- ret = BAD_FUNC_ARG;
- }
- /* Encode the DSA public key into output buffer. */
- if (ret == 0) {
- ret = SetASN_Items(data, dataASN, count, output);
- }
- FREE_ASNSETDATA(dataASN, key->heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- /* Encode a DSA public key into buffer.
- *
- * @param [out] output Buffer to hold encoded data.
- * @param [in] key DSA key object.
- * @param [out] outLen Length of buffer.
- * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
- * @return Size of encoded data in bytes on success.
- * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
- * than a minimal size (5 bytes), or buffer size is smaller than
- * encoding size.
- * @return MEMORY_E when dynamic memory allocation fails.
- */
- int wc_DsaKeyToPublicDer(DsaKey* key, byte* output, word32 inLen)
- {
- return wc_SetDsaPublicKey(output, key, (int)inLen, 1);
- }
- #endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */
- static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen,
- int ints, int includeVersion)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen, j;
- word32 sizes[DSA_INTS];
- int i, ret = 0;
- byte seq[MAX_SEQ_SZ];
- byte ver[MAX_VERSION_SZ];
- byte* tmps[DSA_INTS];
- if (ints > DSA_INTS || inLen == NULL)
- return BAD_FUNC_ARG;
- XMEMSET(sizes, 0, sizeof(sizes));
- for (i = 0; i < ints; i++)
- tmps[i] = NULL;
- /* write all big ints from key to DER tmps */
- for (i = 0; i < ints; i++) {
- int mpSz;
- mp_int* keyInt = GetDsaInt(key, i);
- word32 rawLen = (word32)mp_unsigned_bin_size(keyInt) + 1;
- tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
- DYNAMIC_TYPE_DSA);
- if (tmps[i] == NULL) {
- ret = MEMORY_E;
- break;
- }
- mpSz = SetASNIntMP(keyInt, -1, tmps[i]);
- if (mpSz < 0) {
- ret = mpSz;
- break;
- }
- sizes[i] = (word32)mpSz;
- intTotalLen += (word32)mpSz;
- }
- if (ret != 0) {
- FreeTmpDsas(tmps, key->heap, ints);
- return ret;
- }
- /* make headers */
- if (includeVersion)
- verSz = (word32)SetMyVersion(0, ver, FALSE);
- seqSz = SetSequence(verSz + intTotalLen, seq);
- outLen = seqSz + verSz + intTotalLen;
- *inLen = outLen;
- if (output == NULL) {
- FreeTmpDsas(tmps, key->heap, ints);
- return LENGTH_ONLY_E;
- }
- if (outLen > *inLen) {
- FreeTmpDsas(tmps, key->heap, ints);
- return BAD_FUNC_ARG;
- }
- /* write to output */
- XMEMCPY(output, seq, seqSz);
- j = seqSz;
- if (includeVersion) {
- XMEMCPY(output + j, ver, verSz);
- j += verSz;
- }
- for (i = 0; i < ints; i++) {
- XMEMCPY(output + j, tmps[i], sizes[i]);
- j += sizes[i];
- }
- FreeTmpDsas(tmps, key->heap, ints);
- return (int)outLen;
- #else
- DECL_ASNSETDATA(dataASN, dsaKeyASN_Length);
- int ret = 0;
- int sz = 0;
- (void)ints;
- if ((key == NULL) || (inLen == NULL)) {
- ret = BAD_FUNC_ARG;
- }
- if ((ret == 0) && (ints > DSA_INTS)) {
- ret = BAD_FUNC_ARG;
- }
- CALLOC_ASNSETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
- if (ret == 0) {
- int i;
- if (includeVersion) {
- /* Set the version. */
- SetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], 0);
- }
- else {
- dataASN[DSAKEYASN_IDX_VER].noOut = 1;
- }
- dataASN[DSAKEYASN_IDX_Y].noOut = mp_iszero(&key->y);
- dataASN[DSAKEYASN_IDX_X].noOut = mp_iszero(&key->x);
- /* Set the mp_ints to encode - params, public and private value. */
- for (i = 0; i < DSA_INTS; i++) {
- if (i < ints)
- SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], GetDsaInt(key, i));
- else
- dataASN[(int)DSAKEYASN_IDX_P + i].noOut = 1;
- }
- /* Calculate size of the encoding. */
- ret = SizeASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, &sz);
- }
- if ((ret == 0) && (output == NULL)) {
- *inLen = (word32)sz;
- ret = LENGTH_ONLY_E;
- }
- /* Check buffer is big enough for encoding. */
- if ((ret == 0) && (sz > (int)*inLen)) {
- ret = BAD_FUNC_ARG;
- }
- if (ret == 0) {
- /* Encode the DSA private key into output buffer. */
- SetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, output);
- /* Return the size of the encoding. */
- ret = sz;
- }
- FREE_ASNSETDATA(dataASN, key->heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- /* Encode a DSA private key into buffer.
- *
- * @param [in] key DSA key object.
- * @param [out] output Buffer to hold encoded data.
- * @param [out] inLen Length of buffer.
- * @return Size of encoded data in bytes on success.
- * @return BAD_FUNC_ARG when key or output is NULL, or key is not a private key
- * or, buffer size is smaller than encoding size.
- * @return MEMORY_E when dynamic memory allocation fails.
- */
- int wc_DsaKeyToDer(DsaKey* key, byte* output, word32 inLen)
- {
- if (!key || !output)
- return BAD_FUNC_ARG;
- if (key->type != DSA_PRIVATE)
- return BAD_FUNC_ARG;
- return DsaKeyIntsToDer(key, output, &inLen, DSA_INTS, 1);
- }
- /* Convert DsaKey parameters to DER format, write to output (inLen),
- return bytes written. Version is excluded to be compatible with
- OpenSSL d2i_DSAparams */
- int wc_DsaKeyToParamsDer(DsaKey* key, byte* output, word32 inLen)
- {
- if (!key || !output)
- return BAD_FUNC_ARG;
- return DsaKeyIntsToDer(key, output, &inLen, DSA_PARAM_INTS, 0);
- }
- /* This version of the function allows output to be NULL. In that case, the
- DsaKeyIntsToDer will return LENGTH_ONLY_E and the required output buffer
- size will be pointed to by inLen. */
- int wc_DsaKeyToParamsDer_ex(DsaKey* key, byte* output, word32* inLen)
- {
- if (!key || !inLen)
- return BAD_FUNC_ARG;
- return DsaKeyIntsToDer(key, output, inLen, DSA_PARAM_INTS, 0);
- }
- #endif /* NO_DSA */
- #ifndef NO_CERTS
- /* Initialize decoded certificate object with buffer of DER encoding.
- *
- * @param [in, out] cert Decoded certificate object.
- * @param [in] source Buffer containing DER encoded certificate.
- * @param [in] inSz Size of DER data in buffer in bytes.
- * @param [in] heap Dynamic memory hint.
- */
- void InitDecodedCert(DecodedCert* cert,
- const byte* source, word32 inSz, void* heap)
- {
- InitDecodedCert_ex(cert, source, inSz, heap, INVALID_DEVID);
- }
- /* Initialize decoded certificate object with buffer of DER encoding.
- *
- * @param [in, out] cert Decoded certificate object.
- * @param [in] source Buffer containing DER encoded certificate.
- * @param [in] inSz Size of DER data in buffer in bytes.
- * @param [in] heap Dynamic memory hint.
- * @param [in] devId Crypto callback ID to use.
- */
- void InitDecodedCert_ex(DecodedCert* cert,
- const byte* source, word32 inSz, void* heap, int devId)
- {
- if (cert != NULL) {
- XMEMSET(cert, 0, sizeof(DecodedCert));
- cert->subjectCNEnc = CTC_UTF8;
- cert->issuer[0] = '\0';
- cert->subject[0] = '\0';
- cert->source = source; /* don't own */
- cert->maxIdx = inSz; /* can't go over this index */
- cert->heap = heap;
- cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- #ifdef WOLFSSL_CERT_NAME_ALL
- cert->subjectNEnc = CTC_UTF8;
- cert->subjectIEnc = CTC_UTF8;
- cert->subjectDNQEnc = CTC_UTF8;
- cert->subjectGNEnc = CTC_UTF8;
- #endif
- cert->subjectSNEnc = CTC_UTF8;
- cert->subjectCEnc = CTC_PRINTABLE;
- cert->subjectLEnc = CTC_UTF8;
- cert->subjectSTEnc = CTC_UTF8;
- cert->subjectOEnc = CTC_UTF8;
- cert->subjectOUEnc = CTC_UTF8;
- #ifdef WOLFSSL_HAVE_ISSUER_NAMES
- cert->issuerSNEnc = CTC_UTF8;
- cert->issuerCEnc = CTC_PRINTABLE;
- cert->issuerLEnc = CTC_UTF8;
- cert->issuerSTEnc = CTC_UTF8;
- cert->issuerOEnc = CTC_UTF8;
- cert->issuerOUEnc = CTC_UTF8;
- #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
- InitSignatureCtx(&cert->sigCtx, heap, devId);
- }
- }
- void wc_InitDecodedCert(DecodedCert* cert, const byte* source, word32 inSz,
- void* heap)
- {
- InitDecodedCert(cert, source, inSz, heap);
- }
- /* Free the alternative names object.
- *
- * Frees each linked list items and its name.
- *
- * @param [in, out] altNames Alternative names.
- * @param [in] heap Dynamic memory hint.
- */
- void FreeAltNames(DNS_entry* altNames, void* heap)
- {
- (void)heap;
- while (altNames) {
- DNS_entry* tmp = altNames->next;
- XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
- XFREE(altNames->ipString, heap, DYNAMIC_TYPE_ALTNAME);
- #endif
- XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME);
- altNames = tmp;
- }
- }
- /* malloc and initialize a new alt name structure */
- DNS_entry* AltNameNew(void* heap)
- {
- DNS_entry* ret;
- ret = (DNS_entry*)XMALLOC(sizeof(DNS_entry), heap, DYNAMIC_TYPE_ALTNAME);
- if (ret != NULL) {
- XMEMSET(ret, 0, sizeof(DNS_entry));
- }
- (void)heap;
- return ret;
- }
- #ifndef IGNORE_NAME_CONSTRAINTS
- /* Free the subtree names object.
- *
- * Frees each linked list items and its name.
- *
- * @param [in, out] names Subtree names.
- * @param [in] heap Dynamic memory hint.
- */
- void FreeNameSubtrees(Base_entry* names, void* heap)
- {
- (void)heap;
- while (names) {
- Base_entry* tmp = names->next;
- XFREE(names->name, heap, DYNAMIC_TYPE_ALTNAME);
- XFREE(names, heap, DYNAMIC_TYPE_ALTNAME);
- names = tmp;
- }
- }
- #endif /* IGNORE_NAME_CONSTRAINTS */
- /* Free the decoded cert object's dynamic data.
- *
- * @param [in, out] cert Decoded certificate object.
- */
- void FreeDecodedCert(DecodedCert* cert)
- {
- if (cert == NULL)
- return;
- if (cert->subjectCNStored == 1) {
- XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
- }
- if (cert->pubKeyStored == 1) {
- XFREE((void*)cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- }
- if (cert->weOwnAltNames && cert->altNames)
- FreeAltNames(cert->altNames, cert->heap);
- #ifndef IGNORE_NAME_CONSTRAINTS
- if (cert->altEmailNames)
- FreeAltNames(cert->altEmailNames, cert->heap);
- if (cert->altDirNames)
- FreeAltNames(cert->altDirNames, cert->heap);
- if (cert->permittedNames)
- FreeNameSubtrees(cert->permittedNames, cert->heap);
- if (cert->excludedNames)
- FreeNameSubtrees(cert->excludedNames, cert->heap);
- #endif /* IGNORE_NAME_CONSTRAINTS */
- #ifdef WOLFSSL_SEP
- XFREE(cert->deviceType, cert->heap, DYNAMIC_TYPE_X509_EXT);
- XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
- XFREE(cert->hwSerialNum, cert->heap, DYNAMIC_TYPE_X509_EXT);
- #endif /* WOLFSSL_SEP */
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- if (cert->issuerName != NULL)
- wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->issuerName);
- if (cert->subjectName != NULL)
- wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->subjectName);
- #endif /* WOLFSSL_X509_NAME_AVAILABLE */
- #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
- if (cert->sce_tsip_encRsaKeyIdx != NULL)
- XFREE(cert->sce_tsip_encRsaKeyIdx, cert->heap, DYNAMIC_TYPE_RSA);
- #endif
- FreeSignatureCtx(&cert->sigCtx);
- }
- void wc_FreeDecodedCert(DecodedCert* cert)
- {
- FreeDecodedCert(cert);
- }
- #ifndef WOLFSSL_ASN_TEMPLATE
- static int GetCertHeader(DecodedCert* cert)
- {
- int ret = 0, len;
- if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
- return ASN_PARSE_E;
- /* Reset the max index for the size indicated in the outer wrapper. */
- cert->maxIdx = (word32)len + cert->srcIdx;
- cert->certBegin = cert->srcIdx;
- if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
- return ASN_PARSE_E;
- cert->sigIndex = (word32)len + cert->srcIdx;
- if (cert->sigIndex > cert->maxIdx)
- return ASN_PARSE_E;
- if (GetExplicitVersion(cert->source, &cert->srcIdx, &cert->version,
- cert->sigIndex) < 0)
- return ASN_PARSE_E;
- if (wc_GetSerialNumber(cert->source, &cert->srcIdx, cert->serial,
- &cert->serialSz, cert->sigIndex) < 0)
- return ASN_PARSE_E;
- return ret;
- }
- #endif
- #if defined(HAVE_ED25519) || defined(HAVE_ED448) || (defined(HAVE_PQC) && \
- defined(HAVE_LIBOQS))
- /* Store the key data under the BIT_STRING in dynamicly allocated data.
- *
- * @param [in, out] cert Certificate object.
- * @param [in] source Buffer containing encoded key.
- * @param [in, out] srcIdx On in, start of key data.
- * On out, start of element after key data.
- * @param [in] maxIdx Maximum index of certificate data.
- */
- static int StoreKey(DecodedCert* cert, const byte* source, word32* srcIdx,
- word32 maxIdx)
- {
- int ret;
- int length;
- byte* publicKey;
- ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
- if (ret == 0) {
- #ifdef HAVE_OCSP
- ret = CalcHashId_ex(source + *srcIdx, (word32)length,
- cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
- }
- if (ret == 0) {
- #endif
- publicKey = (byte*)XMALLOC((size_t)length, cert->heap,
- DYNAMIC_TYPE_PUBLIC_KEY);
- if (publicKey == NULL) {
- ret = MEMORY_E;
- }
- else {
- XMEMCPY(publicKey, &source[*srcIdx], (size_t)length);
- cert->publicKey = publicKey;
- cert->pubKeyStored = 1;
- cert->pubKeySize = (word32)length;
- *srcIdx += (word32)length;
- }
- }
- return ret;
- }
- #endif /* HAVE_ED25519 || HAVE_ED448 */
- #endif
- #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
- static int SetCurve(ecc_key* key, byte* output, size_t outSz)
- {
- #ifdef HAVE_OID_ENCODING
- int ret;
- #endif
- int idx;
- word32 oidSz = 0;
- /* validate key */
- if (key == NULL || key->dp == NULL) {
- return BAD_FUNC_ARG;
- }
- #ifdef HAVE_OID_ENCODING
- ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, NULL, &oidSz);
- if (ret != 0) {
- return ret;
- }
- #else
- oidSz = key->dp->oidSz;
- #endif
- idx = SetObjectId((int)oidSz, output);
- /* length only */
- if (output == NULL) {
- return idx + (int)oidSz;
- }
- /* verify output buffer has room */
- if (oidSz > outSz)
- return BUFFER_E;
- #ifdef HAVE_OID_ENCODING
- ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, output+idx, &oidSz);
- if (ret != 0) {
- return ret;
- }
- #else
- XMEMCPY(output+idx, key->dp->oid, oidSz);
- #endif
- idx += (int)oidSz;
- return idx;
- }
- #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
- #ifdef HAVE_ECC
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for ECC public key (SubjectPublicKeyInfo).
- * RFC 5480, 2 - Subject Public Key Information Fields
- * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
- * X9.62 ECC point format.
- * See ASN.1 template 'eccSpecifiedASN' for specifiedCurve.
- */
- static const ASNItem eccPublicKeyASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* AlgorithmIdentifier */
- /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* algorithm */
- /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
- /* namedCurve */
- /* ALGOID_CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
- /* specifiedCurve - explicit parameters */
- /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
- /* Public Key */
- /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
- };
- enum {
- ECCPUBLICKEYASN_IDX_SEQ = 0,
- ECCPUBLICKEYASN_IDX_ALGOID_SEQ,
- ECCPUBLICKEYASN_IDX_ALGOID_OID,
- ECCPUBLICKEYASN_IDX_ALGOID_CURVEID,
- ECCPUBLICKEYASN_IDX_ALGOID_PARAMS,
- ECCPUBLICKEYASN_IDX_PUBKEY
- };
- /* Number of items in ASN.1 template for ECC public key. */
- #define eccPublicKeyASN_Length (sizeof(eccPublicKeyASN) / sizeof(ASNItem))
- #endif /* WOLFSSL_ASN_TEMPLATE */
- #endif /* HAVE_ECC */
- #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
- /* Encode public ECC key in DER format.
- *
- * RFC 5480, 2 - Subject Public Key Information Fields
- * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
- * X9.62 ECC point format.
- * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
- *
- * @param [out] output Buffer to put encoded data in.
- * @param [in] key ECC key object.
- * @param [in] outLen Size of buffer in bytes.
- * @param [in] with_header Whether to use SubjectPublicKeyInfo format.
- * @return Size of encoded data in bytes on success.
- * @return BAD_FUNC_ARG when key or key's parameters is NULL.
- * @return MEMORY_E when dynamic memory allocation failed.
- */
- static int SetEccPublicKey(byte* output, ecc_key* key, int outLen,
- int with_header, int comp)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret;
- word32 idx = 0, curveSz, algoSz, pubSz, bitStringSz;
- byte bitString[1 + MAX_LENGTH_SZ + 1]; /* 6 */
- byte algo[MAX_ALGO_SZ]; /* 20 */
- /* public size */
- pubSz = key->dp ? (word32)key->dp->size : MAX_ECC_BYTES;
- if (comp)
- pubSz = 1 + pubSz;
- else
- pubSz = 1 + 2 * pubSz;
- /* check for buffer overflow */
- if (output != NULL && pubSz > (word32)outLen) {
- return BUFFER_E;
- }
- /* headers */
- if (with_header) {
- ret = SetCurve(key, NULL, 0);
- if (ret <= 0) {
- return ret;
- }
- curveSz = (word32)ret;
- ret = 0;
- /* calculate size */
- algoSz = SetAlgoID(ECDSAk, algo, oidKeyType, (int)curveSz);
- bitStringSz = SetBitString(pubSz, 0, bitString);
- idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz, NULL);
- /* check for buffer overflow */
- if (output != NULL &&
- curveSz + algoSz + bitStringSz + idx + pubSz > (word32)outLen) {
- return BUFFER_E;
- }
- idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz,
- output);
- /* algo */
- if (output)
- XMEMCPY(output + idx, algo, algoSz);
- idx += algoSz;
- /* curve */
- if (output)
- (void)SetCurve(key, output + idx, curveSz);
- idx += curveSz;
- /* bit string */
- if (output)
- XMEMCPY(output + idx, bitString, bitStringSz);
- idx += bitStringSz;
- }
- /* pub */
- if (output) {
- PRIVATE_KEY_UNLOCK();
- ret = wc_ecc_export_x963_ex(key, output + idx, &pubSz, comp);
- PRIVATE_KEY_LOCK();
- if (ret != 0) {
- return ret;
- }
- }
- idx += pubSz;
- return (int)idx;
- #else
- word32 pubSz = 0;
- int sz = 0;
- int ret = 0;
- int curveIdSz = 0;
- byte* curveOid = NULL;
- /* Check key validity. */
- if ((key == NULL) || (key->dp == NULL)) {
- ret = BAD_FUNC_ARG;
- }
- if (ret == 0) {
- /* Calculate the size of the encoded public point. */
- PRIVATE_KEY_UNLOCK();
- #if defined(HAVE_COMP_KEY) && defined(HAVE_FIPS) && \
- defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
- /* in earlier versions of FIPS the get length functionality is not
- * available with compressed keys */
- pubSz = key->dp ? key->dp->size : MAX_ECC_BYTES;
- if (comp)
- pubSz = 1 + pubSz;
- else
- pubSz = 1 + 2 * pubSz;
- ret = LENGTH_ONLY_E;
- #else
- ret = wc_ecc_export_x963_ex(key, NULL, &pubSz, comp);
- #endif
- PRIVATE_KEY_LOCK();
- /* LENGTH_ONLY_E on success. */
- if (ret == LENGTH_ONLY_E) {
- ret = 0;
- }
- }
- if ((ret == 0) && with_header) {
- /* Including SubjectPublicKeyInfo header. */
- DECL_ASNSETDATA(dataASN, eccPublicKeyASN_Length);
- CALLOC_ASNSETDATA(dataASN, eccPublicKeyASN_Length, ret, key->heap);
- /* Get the length of the named curve OID to put into the encoding. */
- curveIdSz = SetCurve(key, NULL, 0);
- if (curveIdSz < 0) {
- ret = curveIdSz;
- }
- if (ret == 0) {
- /* Set the key type OID. */
- SetASN_OID(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], ECDSAk,
- oidKeyType);
- /* Set the curve OID. */
- SetASN_ReplaceBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID],
- NULL, (word32)curveIdSz);
- /* Don't try to write out explicit parameters. */
- dataASN[ECCPUBLICKEYASN_IDX_ALGOID_PARAMS].noOut = 1;
- /* Set size of public point to ensure space is made for it. */
- SetASN_Buffer(&dataASN[ECCPUBLICKEYASN_IDX_PUBKEY], NULL, pubSz);
- /* Calculate size of ECC public key. */
- ret = SizeASN_Items(eccPublicKeyASN, dataASN,
- eccPublicKeyASN_Length, &sz);
- }
- /* Check buffer, if passed in, is big enough for encoded data. */
- if ((ret == 0) && (output != NULL) && (sz > outLen)) {
- ret = BUFFER_E;
- }
- if ((ret == 0) && (output != NULL)) {
- /* Encode ECC public key. */
- SetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length,
- output);
- /* Skip to where public point is to be encoded. */
- output += sz - (int)pubSz;
- /* Cache the location to place the name curve OID. */
- curveOid = (byte*)
- dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID].data.buffer.data;
- }
- FREE_ASNSETDATA(dataASN, key->heap);
- }
- else if ((ret == 0) && (output != NULL) && (pubSz > (word32)outLen)) {
- ret = BUFFER_E;
- }
- else {
- /* Total size is the public point size. */
- sz = (int)pubSz;
- }
- if ((ret == 0) && (output != NULL)) {
- /* Put named curve OID data into encoding. */
- curveIdSz = SetCurve(key, curveOid, (size_t)curveIdSz);
- if (curveIdSz < 0) {
- ret = curveIdSz;
- }
- }
- if ((ret == 0) && (output != NULL)) {
- /* Encode public point. */
- PRIVATE_KEY_UNLOCK();
- ret = wc_ecc_export_x963_ex(key, output, &pubSz, comp);
- PRIVATE_KEY_LOCK();
- }
- if (ret == 0) {
- /* Return the size of the encoding. */
- ret = sz;
- }
- return ret;
- #endif
- }
- /* Encode the public part of an ECC key in a DER.
- *
- * Pass NULL for output to get the size of the encoding.
- *
- * @param [in] key ECC key object.
- * @param [out] output Buffer to hold DER encoding.
- * @param [in] inLen Size of buffer in bytes.
- * @param [in] with_AlgCurve Whether to use SubjectPublicKeyInfo format.
- * @return Size of encoded data in bytes on success.
- * @return BAD_FUNC_ARG when key or key's parameters is NULL.
- * @return MEMORY_E when dynamic memory allocation failed.
- */
- WOLFSSL_ABI
- int wc_EccPublicKeyToDer(ecc_key* key, byte* output, word32 inLen,
- int with_AlgCurve)
- {
- return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, 0);
- }
- int wc_EccPublicKeyToDer_ex(ecc_key* key, byte* output, word32 inLen,
- int with_AlgCurve, int comp)
- {
- return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, comp);
- }
- int wc_EccPublicKeyDerSize(ecc_key* key, int with_AlgCurve)
- {
- return SetEccPublicKey(NULL, key, 0, with_AlgCurve, 0);
- }
- #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
- #ifdef WOLFSSL_ASN_TEMPLATE
- #if defined(WC_ENABLE_ASYM_KEY_EXPORT) || defined(WC_ENABLE_ASYM_KEY_IMPORT)
- /* ASN.1 template for Ed25519 and Ed448 public key (SubkectPublicKeyInfo).
- * RFC 8410, 4 - Subject Public Key Fields
- */
- static const ASNItem edPubKeyASN[] = {
- /* SubjectPublicKeyInfo */
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* AlgorithmIdentifier */
- /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* Ed25519/Ed448 OID */
- /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
- /* Public key stream */
- /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
- };
- enum {
- EDPUBKEYASN_IDX_SEQ = 0,
- EDPUBKEYASN_IDX_ALGOID_SEQ,
- EDPUBKEYASN_IDX_ALGOID_OID,
- EDPUBKEYASN_IDX_PUBKEY
- };
- /* Number of items in ASN.1 template for Ed25519 and Ed448 public key. */
- #define edPubKeyASN_Length (sizeof(edPubKeyASN) / sizeof(ASNItem))
- #endif /* WC_ENABLE_ASYM_KEY_EXPORT || WC_ENABLE_ASYM_KEY_IMPORT */
- #endif /* WOLFSSL_ASN_TEMPLATE */
- #ifdef WC_ENABLE_ASYM_KEY_EXPORT
- /* Build ASN.1 formatted public key based on RFC 8410
- *
- * Pass NULL for output to get the size of the encoding.
- *
- * @param [in] pubKey public key buffer
- * @param [in] pubKeyLen public ket buffer length
- * @param [out] output Buffer to put encoded data in (optional)
- * @param [in] outLen Size of buffer in bytes
- * @param [in] keyType is "enum Key_Sum" like ED25519k
- * @param [in] withHeader Whether to include SubjectPublicKeyInfo around key.
- * @return Size of encoded data in bytes on success
- * @return BAD_FUNC_ARG when key is NULL.
- * @return MEMORY_E when dynamic memory allocation failed.
- */
- int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen,
- byte* output, word32 outLen, int keyType, int withHeader)
- {
- int ret = 0;
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0;
- word32 seqDataSz = 0;
- word32 sz;
- #else
- int sz = 0;
- DECL_ASNSETDATA(dataASN, edPubKeyASN_Length);
- #endif
- if (pubKey == NULL) {
- return BAD_FUNC_ARG;
- }
- #ifndef WOLFSSL_ASN_TEMPLATE
- /* calculate size */
- if (withHeader) {
- word32 algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
- word32 bitStringSz = SetBitString(pubKeyLen, 0, NULL);
- seqDataSz = algoSz + bitStringSz + pubKeyLen;
- sz = SetSequence(seqDataSz, NULL) + seqDataSz;
- }
- else {
- sz = pubKeyLen;
- }
- /* checkout output size */
- if (output != NULL && sz > outLen) {
- ret = BUFFER_E;
- }
- /* headers */
- if (ret == 0 && output != NULL && withHeader) {
- /* sequence */
- idx = SetSequence(seqDataSz, output);
- /* algo */
- idx += SetAlgoID(keyType, output + idx, oidKeyType, 0);
- /* bit string */
- idx += SetBitString(pubKeyLen, 0, output + idx);
- }
- if (ret == 0 && output != NULL) {
- /* pub */
- XMEMCPY(output + idx, pubKey, pubKeyLen);
- idx += pubKeyLen;
- sz = idx;
- }
- if (ret == 0) {
- ret = (int)sz;
- }
- #else
- if (withHeader) {
- CALLOC_ASNSETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
- if (ret == 0) {
- /* Set the OID. */
- SetASN_OID(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], (word32)keyType,
- oidKeyType);
- /* Leave space for public point. */
- SetASN_Buffer(&dataASN[EDPUBKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
- /* Calculate size of public key encoding. */
- ret = SizeASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, &sz);
- }
- if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
- ret = BUFFER_E;
- }
- if ((ret == 0) && (output != NULL)) {
- /* Encode public key. */
- SetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, output);
- /* Set location to encode public point. */
- output = (byte*)dataASN[EDPUBKEYASN_IDX_PUBKEY].data.buffer.data;
- }
- FREE_ASNSETDATA(dataASN, NULL);
- }
- else if ((output != NULL) && (pubKeyLen > outLen)) {
- ret = BUFFER_E;
- }
- else if (ret == 0) {
- sz = (int)pubKeyLen;
- }
- if ((ret == 0) && (output != NULL)) {
- /* Put public key into space provided. */
- XMEMCPY(output, pubKey, pubKeyLen);
- }
- if (ret == 0) {
- ret = sz;
- }
- #endif /* WOLFSSL_ASN_TEMPLATE */
- return ret;
- }
- #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
- #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
- /* Encode the public part of an Ed25519 key in DER.
- *
- * Pass NULL for output to get the size of the encoding.
- *
- * @param [in] key Ed25519 key object.
- * @param [out] output Buffer to put encoded data in.
- * @param [in] outLen Size of buffer in bytes.
- * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
- * @return Size of encoded data in bytes on success.
- * @return BAD_FUNC_ARG when key is NULL.
- * @return MEMORY_E when dynamic memory allocation failed.
- */
- int wc_Ed25519PublicKeyToDer(ed25519_key* key, byte* output, word32 inLen,
- int withAlg)
- {
- int ret;
- byte pubKey[ED25519_PUB_KEY_SIZE];
- word32 pubKeyLen = (word32)sizeof(pubKey);
- if (key == NULL) {
- return BAD_FUNC_ARG;
- }
- ret = wc_ed25519_export_public(key, pubKey, &pubKeyLen);
- if (ret == 0) {
- ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
- ED25519k, withAlg);
- }
- return ret;
- }
- #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
- #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
- /* Encode the public part of an Ed448 key in DER.
- *
- * Pass NULL for output to get the size of the encoding.
- *
- * @param [in] key Ed448 key object.
- * @param [out] output Buffer to put encoded data in.
- * @param [in] outLen Size of buffer in bytes.
- * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
- * @return Size of encoded data in bytes on success.
- * @return BAD_FUNC_ARG when key is NULL.
- * @return MEMORY_E when dynamic memory allocation failed.
- */
- int wc_Ed448PublicKeyToDer(ed448_key* key, byte* output, word32 inLen,
- int withAlg)
- {
- int ret;
- byte pubKey[ED448_PUB_KEY_SIZE];
- word32 pubKeyLen = (word32)sizeof(pubKey);
- if (key == NULL) {
- return BAD_FUNC_ARG;
- }
- ret = wc_ed448_export_public(key, pubKey, &pubKeyLen);
- if (ret == 0) {
- ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
- ED448k, withAlg);
- }
- return ret;
- }
- #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
- #if !defined(NO_RSA) && !defined(NO_CERTS)
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for header before RSA key in certificate. */
- static const ASNItem rsaCertKeyASN[] = {
- /* STR */ { 0, ASN_BIT_STRING, 0, 1, 0 },
- /* SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
- };
- enum {
- RSACERTKEYASN_IDX_STR = 0,
- RSACERTKEYASN_IDX_SEQ
- };
- /* Number of items in ASN.1 template for header before RSA key in cert. */
- #define rsaCertKeyASN_Length (sizeof(rsaCertKeyASN) / sizeof(ASNItem))
- #endif
- /* Store RSA key pointer and length in certificate object.
- *
- * @param [in, out] cert Certificate object.
- * @param [in] source Buffer containing encoded key.
- * @param [in, out] srcIdx On in, start of RSA key data.
- * On out, start of element after RSA key data.
- * @param [in] maxIdx Maximum index of key data.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- */
- static int StoreRsaKey(DecodedCert* cert, const byte* source, word32* srcIdx,
- word32 maxIdx)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int length;
- int pubLen;
- word32 pubIdx;
- if (CheckBitString(source, srcIdx, &pubLen, maxIdx, 1, NULL) != 0)
- return ASN_PARSE_E;
- pubIdx = *srcIdx;
- if (GetSequence(source, srcIdx, &length, pubIdx + (word32)pubLen) < 0)
- return ASN_PARSE_E;
- #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
- cert->sigCtx.CertAtt.pubkey_n_start =
- cert->sigCtx.CertAtt.pubkey_e_start = pubIdx;
- #endif
- cert->pubKeySize = (word32)pubLen;
- cert->publicKey = source + pubIdx;
- #ifdef WOLFSSL_MAXQ10XX_TLS
- cert->publicKeyIndex = pubIdx;
- #endif
- *srcIdx += (word32)length;
- #ifdef HAVE_OCSP
- return CalcHashId_ex(cert->publicKey, cert->pubKeySize,
- cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
- #else
- return 0;
- #endif
- #else
- ASNGetData dataASN[rsaCertKeyASN_Length];
- int ret;
- /* No dynamic data. */
- XMEMSET(dataASN, 0, sizeof(dataASN));
- /* Decode the header before the key data. */
- ret = GetASN_Items(rsaCertKeyASN, dataASN, rsaCertKeyASN_Length, 1, source,
- srcIdx, maxIdx);
- if (ret == 0) {
- /* Store the pointer and length in certificate object starting at
- * SEQUENCE. */
- GetASN_GetConstRef(&dataASN[RSACERTKEYASN_IDX_STR],
- &cert->publicKey, &cert->pubKeySize);
- #ifdef WOLFSSL_MAXQ10XX_TLS
- cert->publicKeyIndex = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
- #endif
- #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
- /* Start of SEQUENCE. */
- cert->sigCtx.CertAtt.pubkey_n_start =
- cert->sigCtx.CertAtt.pubkey_e_start = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
- #endif
- #ifdef HAVE_OCSP
- /* Calculate the hash of the public key for OCSP. */
- ret = CalcHashId_ex(cert->publicKey, cert->pubKeySize,
- cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
- #endif
- }
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #endif /* !NO_RSA && !NO_CERTS */
- #if defined(HAVE_ECC) && !defined(NO_CERTS)
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for header before ECC key in certificate. */
- static const ASNItem eccCertKeyASN[] = {
- /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 2 },
- /* Algo parameters */
- /* PARAMS */ { 1, ASN_SEQUENCE, 1, 0, 2 },
- /* Subject public key */
- /* SUBJPUBKEY */ { 0, ASN_BIT_STRING, 0, 0, 0 },
- };
- enum {
- ECCCERTKEYASN_IDX_OID = 0,
- ECCCERTKEYASN_IDX_PARAMS,
- ECCCERTKEYASN_IDX_SUBJPUBKEY
- };
- /* Number of items in ASN.1 template for header before ECC key in cert. */
- #define eccCertKeyASN_Length (sizeof(eccCertKeyASN) / sizeof(ASNItem))
- #endif /* WOLFSSL_ASN_TEMPLATE */
- /* Store public ECC key in certificate object.
- *
- * Parse parameters and store public key data.
- *
- * @param [in, out] cert Certificate object.
- * @param [in] source Buffer containing encoded key.
- * @param [in, out] srcIdx On in, start of ECC key data.
- * On out, start of element after ECC key data.
- * @param [in] maxIdx Maximum index of key data.
- * @param [in] pubKey Buffer holding encoded public key.
- * @param [in] pubKeyLen Length of encoded public key in bytes.
- * @return 0 on success.
- * @return BAD_FUNC_ARG when pubKey is NULL.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- */
- static int StoreEccKey(DecodedCert* cert, const byte* source, word32* srcIdx,
- word32 maxIdx, const byte* pubKey, word32 pubKeyLen)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret;
- word32 localIdx;
- byte* publicKey;
- byte tag;
- int length;
- if (pubKey == NULL) {
- return BAD_FUNC_ARG;
- }
- localIdx = *srcIdx;
- if (GetASNTag(source, &localIdx, &tag, maxIdx) < 0)
- return ASN_PARSE_E;
- if (tag != (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
- if (GetObjectId(source, srcIdx, &cert->pkCurveOID, oidCurveType,
- maxIdx) < 0)
- return ASN_PARSE_E;
- if ((ret = CheckCurve(cert->pkCurveOID)) < 0)
- return ECC_CURVE_OID_E;
- #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
- cert->sigCtx.CertAtt.curve_id = ret;
- #else
- (void)ret;
- #endif
- /* key header */
- ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
- if (ret != 0)
- return ret;
- #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
- cert->sigCtx.CertAtt.pubkey_n_start =
- cert->sigCtx.CertAtt.pubkey_e_start = (*srcIdx + 1);
- cert->sigCtx.CertAtt.pubkey_n_len = ((length - 1) >> 1);
- cert->sigCtx.CertAtt.pubkey_e_start +=
- cert->sigCtx.CertAtt.pubkey_n_len;
- cert->sigCtx.CertAtt.pubkey_e_len =
- cert->sigCtx.CertAtt.pubkey_n_len;
- #endif
- #ifdef WOLFSSL_MAXQ10XX_TLS
- cert->publicKeyIndex = *srcIdx + 1;
- #endif
- #ifdef HAVE_OCSP
- ret = CalcHashId_ex(source + *srcIdx, (word32)length,
- cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
- if (ret != 0)
- return ret;
- #endif
- *srcIdx += (word32)length;
- }
- publicKey = (byte*)XMALLOC(pubKeyLen, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
- if (publicKey == NULL)
- return MEMORY_E;
- XMEMCPY(publicKey, pubKey, pubKeyLen);
- cert->publicKey = publicKey;
- cert->pubKeyStored = 1;
- cert->pubKeySize = pubKeyLen;
- return 0;
- #else
- int ret = 0;
- DECL_ASNGETDATA(dataASN, eccCertKeyASN_Length);
- byte* publicKey;
- /* Validate parameters. */
- if (pubKey == NULL) {
- ret = BAD_FUNC_ARG;
- }
- /* Clear dynamic data and check OID is a curve. */
- CALLOC_ASNGETDATA(dataASN, eccCertKeyASN_Length, ret, cert->heap);
- if (ret == 0) {
- GetASN_OID(&dataASN[ECCCERTKEYASN_IDX_OID], oidCurveType);
- /* Parse ECC public key header. */
- ret = GetASN_Items(eccCertKeyASN, dataASN, eccCertKeyASN_Length, 1,
- source, srcIdx, maxIdx);
- }
- if (ret == 0) {
- if (dataASN[ECCCERTKEYASN_IDX_OID].tag != 0) {
- /* Store curve OID. */
- cert->pkCurveOID = dataASN[ECCCERTKEYASN_IDX_OID].data.oid.sum;
- }
- /* Ignore explicit parameters. */
- #ifdef WOLFSSL_MAXQ10XX_TLS
- cert->publicKeyIndex =
- GetASNItem_DataIdx(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY], source)
- + 1;
- #endif
- #ifdef HAVE_OCSP
- /* Calculate the hash of the subject public key for OCSP. */
- ret = CalcHashId_ex(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.data,
- dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.length,
- cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
- }
- if (ret == 0) {
- #endif
- /* Store public key data length. */
- cert->pubKeySize = pubKeyLen;
- /* Must allocated space for key.
- * Don't memcpy into constant pointer so use temp. */
- publicKey = (byte*)XMALLOC(cert->pubKeySize, cert->heap,
- DYNAMIC_TYPE_PUBLIC_KEY);
- if (publicKey == NULL) {
- ret = MEMORY_E;
- }
- else {
- /* Copy in whole public key and store pointer. */
- XMEMCPY(publicKey, pubKey, cert->pubKeySize);
- cert->publicKey = publicKey;
- /* Indicate publicKey needs to be freed. */
- cert->pubKeyStored = 1;
- }
- }
- FREE_ASNGETDATA(dataASN, cert->heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #endif /* HAVE_ECC && !NO_CERTS */
- #ifndef NO_CERTS
- #if !defined(NO_DSA)
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for DSA key in certificate.
- * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
- * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
- */
- static const ASNItem dsaCertKeyASN[] = {
- /* 0 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* 1 */ { 2, ASN_INTEGER, 0, 0, 0 },
- /* 2 */ { 2, ASN_INTEGER, 0, 0, 0 },
- /* 3 */ { 2, ASN_INTEGER, 0, 0, 0 },
- /* 4 */ { 0, ASN_BIT_STRING, 0, 1, 0 },
- /* 5 */ { 1, ASN_INTEGER, 0, 0, 0 },
- };
- /* Number of items in ASN.1 template for DSA key in certificate. */
- #define dsaCertKeyASN_Length (sizeof(dsaCertKeyASN) / sizeof(ASNItem))
- #endif /* WOLFSSL_ASN_TEMPLATE */
- /* Parse DSA parameters to ensure valid.
- *
- * @param [in] source Buffer containing encoded key.
- * @param [in, out] srcIdx On in, start of DSA key data.
- * On out, start of element after DSA key data.
- * @param [in] maxIdx Maximum index of key data.
- * @param [in] heap Dynamic memory hint.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- */
- static int ParseDsaKey(const byte* source, word32* srcIdx, word32 maxIdx,
- void* heap)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret;
- int length;
- (void)heap;
- ret = GetSequence(source, srcIdx, &length, maxIdx);
- if (ret < 0)
- return ret;
- ret = SkipInt(source, srcIdx, maxIdx);
- if (ret != 0)
- return ret;
- ret = SkipInt(source, srcIdx, maxIdx);
- if (ret != 0)
- return ret;
- ret = SkipInt(source, srcIdx, maxIdx);
- if (ret != 0)
- return ret;
- ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
- if (ret != 0)
- return ret;
- ret = GetASNInt(source, srcIdx, &length, maxIdx);
- if (ret != 0)
- return ASN_PARSE_E;
- *srcIdx += (word32)length;
- return 0;
- #else
- DECL_ASNGETDATA(dataASN, dsaCertKeyASN_Length);
- int ret = 0;
- (void)heap;
- CALLOC_ASNGETDATA(dataASN, dsaCertKeyASN_Length, ret, heap);
- if (ret == 0) {
- /* Parse the DSA key data to ensure valid. */
- ret = GetASN_Items(dsaCertKeyASN, dataASN, dsaCertKeyASN_Length, 1,
- source, srcIdx, maxIdx);
- }
- FREE_ASNGETDATA(dataASN, heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #endif /* !NO_DSA */
- /* Decode the SubjectPublicKeyInfo block in a certificate.
- *
- * Stores the public key in fields of the certificate object.
- * Validates the BER/DER items and does not store in a key object.
- *
- * @param [in, out] cert Decoded certificate oject.
- * @param [in] source BER/DER encoded SubjectPublicKeyInfo block.
- * @param [in, out] inOutIdx On in, start of public key.
- * On out, start of ASN.1 item after public key.
- * @param [in] maxIdx Maximum index of key data.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- */
- static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx,
- word32 maxIdx)
- {
- word32 srcIdx = *inOutIdx;
- #if defined(HAVE_ECC) || !defined(NO_DSA)
- int pubLen;
- #endif
- #if defined(HAVE_ECC) || !defined(NO_DSA)
- int pubIdx = (int)srcIdx;
- #endif
- int ret = 0;
- int length;
- /* Validate paramaters. */
- if (source == NULL) {
- return ASN_PARSE_E;
- }
- #ifndef WOLFSSL_ASN_TEMPLATE
- if (GetSequence(source, &srcIdx, &length, maxIdx) < 0)
- #else
- /* Get SEQUENCE and expect all data to be accounted for. */
- if (GetASN_Sequence(source, &srcIdx, &length, maxIdx, 1) != 0)
- #endif
- {
- return ASN_PARSE_E;
- }
- #if defined(HAVE_ECC) || !defined(NO_DSA)
- pubLen = (int)srcIdx - pubIdx + length;
- #endif
- maxIdx = srcIdx + (word32)length;
- /* Decode the algorithm identifier for the key. */
- if (GetAlgoId(source, &srcIdx, &cert->keyOID, oidKeyType, maxIdx) < 0) {
- return ASN_PARSE_E;
- }
- (void)length;
- /* Parse each type of public key. */
- switch (cert->keyOID) {
- #ifndef NO_RSA
- #ifdef WC_RSA_PSS
- case RSAPSSk:
- if (srcIdx != maxIdx &&
- source[srcIdx] == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
- word32 seqIdx = srcIdx;
- int seqLen;
- /* Not set when -1. */
- enum wc_HashType hash = WC_HASH_TYPE_NONE;
- int mgf = -1;
- int saltLen = 0;
- /* Defaults for sig algorithm parameters. */
- enum wc_HashType sigHash = WC_HASH_TYPE_SHA;
- int sigMgf = WC_MGF1SHA1;
- int sigSaltLen = 20;
- if (GetSequence(source, &srcIdx, &seqLen, maxIdx) < 0) {
- return ASN_PARSE_E;
- }
- /* Get the pubic key parameters. */
- ret = DecodeRsaPssParams(source + seqIdx,
- (word32)seqLen + srcIdx - seqIdx, &hash, &mgf, &saltLen);
- if (ret != 0) {
- return ASN_PARSE_E;
- }
- /* Get the signature parameters. */
- ret = DecodeRsaPssParams(source + cert->sigParamsIndex,
- cert->sigParamsLength, &sigHash, &sigMgf, &sigSaltLen);
- if (ret != 0) {
- return ASN_PARSE_E;
- }
- /* Validated signature params match public key params. */
- if (hash != WC_HASH_TYPE_NONE && hash != sigHash) {
- WOLFSSL_MSG("RSA PSS: hash not matching signature hash");
- return ASN_PARSE_E;
- }
- if (mgf != -1 && mgf != sigMgf) {
- WOLFSSL_MSG("RSA PSS: MGF not matching signature MGF");
- return ASN_PARSE_E;
- }
- if (saltLen > sigSaltLen) {
- WOLFSSL_MSG("RSA PSS: sig salt length too small");
- return ASN_PARSE_E;
- }
- srcIdx += (word32)seqLen;
- }
- FALL_THROUGH;
- #endif /* WC_RSA_PSS */
- case RSAk:
- ret = StoreRsaKey(cert, source, &srcIdx, maxIdx);
- break;
- #endif /* NO_RSA */
- #ifdef HAVE_ECC
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- case SM2k:
- #endif
- case ECDSAk:
- ret = StoreEccKey(cert, source, &srcIdx, maxIdx, source + pubIdx,
- (word32)pubLen);
- break;
- #endif /* HAVE_ECC */
- #ifdef HAVE_ED25519
- case ED25519k:
- cert->pkCurveOID = ED25519k;
- ret = StoreKey(cert, source, &srcIdx, maxIdx);
- break;
- #endif /* HAVE_ED25519 */
- #ifdef HAVE_ED448
- case ED448k:
- cert->pkCurveOID = ED448k;
- ret = StoreKey(cert, source, &srcIdx, maxIdx);
- break;
- #endif /* HAVE_ED448 */
- #if defined(HAVE_PQC) && defined(HAVE_LIBOQS)
- #ifdef HAVE_FALCON
- case FALCON_LEVEL1k:
- cert->pkCurveOID = FALCON_LEVEL1k;
- ret = StoreKey(cert, source, &srcIdx, maxIdx);
- break;
- case FALCON_LEVEL5k:
- cert->pkCurveOID = FALCON_LEVEL5k;
- ret = StoreKey(cert, source, &srcIdx, maxIdx);
- break;
- #endif /* HAVE_FALCON */
- #ifdef HAVE_DILITHIUM
- case DILITHIUM_LEVEL2k:
- cert->pkCurveOID = DILITHIUM_LEVEL2k;
- ret = StoreKey(cert, source, &srcIdx, maxIdx);
- break;
- case DILITHIUM_LEVEL3k:
- cert->pkCurveOID = DILITHIUM_LEVEL3k;
- ret = StoreKey(cert, source, &srcIdx, maxIdx);
- break;
- case DILITHIUM_LEVEL5k:
- cert->pkCurveOID = DILITHIUM_LEVEL5k;
- ret = StoreKey(cert, source, &srcIdx, maxIdx);
- break;
- #endif /* HAVE_DILITHIUM */
- #ifdef HAVE_SPHINCS
- case SPHINCS_FAST_LEVEL1k:
- cert->pkCurveOID = SPHINCS_FAST_LEVEL1k;
- ret = StoreKey(cert, source, &srcIdx, maxIdx);
- break;
- case SPHINCS_FAST_LEVEL3k:
- cert->pkCurveOID = SPHINCS_FAST_LEVEL3k;
- ret = StoreKey(cert, source, &srcIdx, maxIdx);
- break;
- case SPHINCS_FAST_LEVEL5k:
- cert->pkCurveOID = SPHINCS_FAST_LEVEL5k;
- ret = StoreKey(cert, source, &srcIdx, maxIdx);
- break;
- case SPHINCS_SMALL_LEVEL1k:
- cert->pkCurveOID = SPHINCS_SMALL_LEVEL1k;
- ret = StoreKey(cert, source, &srcIdx, maxIdx);
- break;
- case SPHINCS_SMALL_LEVEL3k:
- cert->pkCurveOID = SPHINCS_SMALL_LEVEL3k;
- ret = StoreKey(cert, source, &srcIdx, maxIdx);
- break;
- case SPHINCS_SMALL_LEVEL5k:
- cert->pkCurveOID = SPHINCS_SMALL_LEVEL5k;
- ret = StoreKey(cert, source, &srcIdx, maxIdx);
- break;
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- #ifndef NO_DSA
- case DSAk:
- cert->publicKey = source + pubIdx;
- cert->pubKeySize = (word32)pubLen;
- ret = ParseDsaKey(source, &srcIdx, maxIdx, cert->heap);
- break;
- #endif /* NO_DSA */
- default:
- WOLFSSL_MSG("Unknown or not compiled in key OID");
- WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
- ret = ASN_UNKNOWN_OID_E;
- }
- /* Return index after public key. */
- *inOutIdx = srcIdx;
- /* Return error code. */
- return ret;
- }
- #endif
- /* Return the hash algorithm to use with the signature algorithm.
- *
- * @param [in] oidSum Signature id.
- * @return Hash algorithm id.
- */
- int HashIdAlg(int oidSum)
- {
- (void)oidSum;
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- if (oidSum == CTC_SM3wSM2) {
- return WC_SM3;
- }
- if (oidSum == SM2k) {
- return WC_SM3;
- }
- #endif
- #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
- return WC_SHA256;
- #else
- return WC_SHA;
- #endif
- }
- /* Calculate hash of the id using the SHA-1 or SHA-256.
- *
- * @param [in] data Data to hash.
- * @param [in] len Length of data to hash.
- * @param [out] hash Buffer to hold hash.
- * @return 0 on success.
- * @return MEMORY_E when dynamic memory allocation fails.
- */
- int CalcHashId(const byte* data, word32 len, byte* hash)
- {
- /* Use default hash algorithm. */
- return CalcHashId_ex(data, len, hash,
- #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
- WC_SHA256
- #else
- WC_SHA
- #endif
- );
- }
- /* Calculate hash of the id using the SHA-1 or SHA-256.
- *
- * @param [in] data Data to hash.
- * @param [in] len Length of data to hash.
- * @param [out] hash Buffer to hold hash.
- * @return 0 on success.
- * @return MEMORY_E when dynamic memory allocation fails.
- */
- int CalcHashId_ex(const byte* data, word32 len, byte* hash, int hashAlg)
- {
- int ret;
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- if (hashAlg == WC_SM3) {
- ret = wc_Sm3Hash(data, len, hash);
- }
- else
- #endif
- #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
- if (hashAlg == WC_SHA256) {
- ret = wc_Sha256Hash(data, len, hash);
- }
- else
- #elif !defined(NO_SHA)
- if (hashAlg == WC_SHA) {
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- XMEMSET(hash + WC_SHA_DIGEST_SIZE, 0, KEYID_SIZE - WC_SHA_DIGEST_SIZE);
- #endif
- ret = wc_ShaHash(data, len, hash);
- }
- else
- #else
- (void)data;
- (void)len;
- (void)hash;
- #endif
- {
- ret = NOT_COMPILED_IN;
- }
- return ret;
- }
- #ifndef NO_CERTS
- /* Get the hash of the id using the SHA-1 or SHA-256.
- *
- * If the id is not the length of the hash, then hash it.
- *
- * @param [in] id Id to get hash for.
- * @param [in] len Length of id in bytes.
- * @param [out] hash Buffer to hold hash.
- * @return 0 on success.
- * @return MEMORY_E when dynamic memory allocation fails.
- */
- static int GetHashId(const byte* id, int length, byte* hash, int hashAlg)
- {
- int ret;
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- if (length == wc_HashGetDigestSize(wc_HashTypeConvert(hashAlg)))
- #else
- if (length == KEYID_SIZE)
- #endif
- {
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- XMEMSET(hash + length, 0, KEYID_SIZE - length);
- #endif
- XMEMCPY(hash, id, (size_t)length);
- ret = 0;
- }
- else {
- ret = CalcHashId_ex(id, (word32)length, hash, hashAlg);
- }
- return ret;
- }
- #endif /* !NO_CERTS */
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* Id for email address. */
- #define ASN_EMAIL 0x100
- /* Id for domain component. */
- #define ASN_DC 0x102
- /* Id for jurisdiction country. */
- #define ASN_JURIS_C 0x203
- /* Id for jurisdiction state. */
- #define ASN_JURIS_ST 0x202
- /* Set the string for a name component into the subject name. */
- #define SetCertNameSubject(cert, id, val) \
- *((char**)(((byte *)(cert)) + certNameSubject[(id) - 3].data)) = (val)
- /* Set the string length for a name component into the subject name. */
- #define SetCertNameSubjectLen(cert, id, val) \
- *((int*)(((byte *)(cert)) + certNameSubject[(id) - 3].len)) = (int)(val)
- /* Set the encoding for a name component into the subject name. */
- #define SetCertNameSubjectEnc(cert, id, val) \
- *((byte*)(((byte *)(cert)) + certNameSubject[(id) - 3].enc)) = (val)
- /* Get the string of a name component from the subject name. */
- #define GetCertNameSubjectStr(id) \
- (certNameSubject[(id) - 3].str)
- /* Get the string length of a name component from the subject name. */
- #define GetCertNameSubjectStrLen(id) \
- (certNameSubject[(id) - 3].strLen)
- /* Get the NID of a name component from the subject name. */
- #define GetCertNameSubjectNID(id) \
- (certNameSubject[(id) - 3].nid)
- #define ValidCertNameSubject(id) \
- (((id) - 3) >= 0 && ((id) - 3) < certNameSubjectSz && \
- (certNameSubject[(id) - 3].strLen > 0))
- /* Mapping of certificate name component to useful information. */
- typedef struct CertNameData {
- /* Type string of name component. */
- const char* str;
- /* Length of type string of name component. */
- byte strLen;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- /* Offset of data in subject name component. */
- size_t data;
- /* Offset of length in subject name component. */
- size_t len;
- /* Offset of encoding in subject name component. */
- size_t enc;
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- /* NID of type for subject name component. */
- int nid;
- #endif
- } CertNameData;
- /* List of data for common name components. */
- static const CertNameData certNameSubject[] = {
- /* Common Name */
- {
- "/CN=", 4,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- OFFSETOF(DecodedCert, subjectCN),
- OFFSETOF(DecodedCert, subjectCNLen),
- OFFSETOF(DecodedCert, subjectCNEnc),
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- NID_commonName
- #endif
- },
- /* Surname */
- {
- "/SN=", 4,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- OFFSETOF(DecodedCert, subjectSN),
- OFFSETOF(DecodedCert, subjectSNLen),
- OFFSETOF(DecodedCert, subjectSNEnc),
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- NID_surname
- #endif
- },
- /* Serial Number */
- {
- "/serialNumber=", 14,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- OFFSETOF(DecodedCert, subjectSND),
- OFFSETOF(DecodedCert, subjectSNDLen),
- OFFSETOF(DecodedCert, subjectSNDEnc),
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- NID_serialNumber
- #endif
- },
- /* Country Name */
- {
- "/C=", 3,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- OFFSETOF(DecodedCert, subjectC),
- OFFSETOF(DecodedCert, subjectCLen),
- OFFSETOF(DecodedCert, subjectCEnc),
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- NID_countryName
- #endif
- },
- /* Locality Name */
- {
- "/L=", 3,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- OFFSETOF(DecodedCert, subjectL),
- OFFSETOF(DecodedCert, subjectLLen),
- OFFSETOF(DecodedCert, subjectLEnc),
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- NID_localityName
- #endif
- },
- /* State Name */
- {
- "/ST=", 4,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- OFFSETOF(DecodedCert, subjectST),
- OFFSETOF(DecodedCert, subjectSTLen),
- OFFSETOF(DecodedCert, subjectSTEnc),
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- NID_stateOrProvinceName
- #endif
- },
- /* Street Address */
- {
- "/street=", 8,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- OFFSETOF(DecodedCert, subjectStreet),
- OFFSETOF(DecodedCert, subjectStreetLen),
- OFFSETOF(DecodedCert, subjectStreetEnc),
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- NID_streetAddress
- #endif
- },
- /* Organization Name */
- {
- "/O=", 3,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- OFFSETOF(DecodedCert, subjectO),
- OFFSETOF(DecodedCert, subjectOLen),
- OFFSETOF(DecodedCert, subjectOEnc),
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- NID_organizationName
- #endif
- },
- /* Organization Unit Name */
- {
- "/OU=", 4,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- OFFSETOF(DecodedCert, subjectOU),
- OFFSETOF(DecodedCert, subjectOULen),
- OFFSETOF(DecodedCert, subjectOUEnc),
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- NID_organizationalUnitName
- #endif
- },
- /* Title */
- {
- NULL, 0,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- 0,
- 0,
- 0,
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- 0,
- #endif
- },
- /* Undefined */
- {
- NULL, 0,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- 0,
- 0,
- 0,
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- 0,
- #endif
- },
- /* Undefined */
- {
- NULL, 0,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- 0,
- 0,
- 0,
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- 0,
- #endif
- },
- /* Business Category */
- {
- "/businessCategory=", 18,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- OFFSETOF(DecodedCert, subjectBC),
- OFFSETOF(DecodedCert, subjectBCLen),
- OFFSETOF(DecodedCert, subjectBCEnc),
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- NID_businessCategory
- #endif
- },
- /* Undefined */
- {
- NULL, 0,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- 0,
- 0,
- 0,
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- 0,
- #endif
- },
- /* Postal Code */
- {
- "/postalCode=", 12,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- OFFSETOF(DecodedCert, subjectPC),
- OFFSETOF(DecodedCert, subjectPCLen),
- OFFSETOF(DecodedCert, subjectPCEnc),
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- NID_postalCode
- #endif
- },
- /* User Id */
- {
- "/userid=", 8,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- OFFSETOF(DecodedCert, subjectUID),
- OFFSETOF(DecodedCert, subjectUIDLen),
- OFFSETOF(DecodedCert, subjectUIDEnc),
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- NID_userId
- #endif
- },
- #ifdef WOLFSSL_CERT_NAME_ALL
- /* Name, id 41 */
- {
- "/N=", 3,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- OFFSETOF(DecodedCert, subjectN),
- OFFSETOF(DecodedCert, subjectNLen),
- OFFSETOF(DecodedCert, subjectNEnc),
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- NID_name
- #endif
- },
- /* Given Name, id 42 */
- {
- "/GN=", 4,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- OFFSETOF(DecodedCert, subjectGN),
- OFFSETOF(DecodedCert, subjectGNLen),
- OFFSETOF(DecodedCert, subjectGNEnc),
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- NID_givenName
- #endif
- },
- /* initials, id 43 */
- {
- "/initials=", 10,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- OFFSETOF(DecodedCert, subjectI),
- OFFSETOF(DecodedCert, subjectILen),
- OFFSETOF(DecodedCert, subjectIEnc),
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- NID_initials
- #endif
- },
- /* DN Qualifier Name, id 46 */
- {
- "/dnQualifier=", 13,
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- OFFSETOF(DecodedCert, subjectDNQ),
- OFFSETOF(DecodedCert, subjectDNQLen),
- OFFSETOF(DecodedCert, subjectDNQEnc),
- #endif
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- NID_dnQualifier
- #endif
- },
- #endif /* WOLFSSL_CERT_NAME_ALL */
- };
- static const int certNameSubjectSz =
- (int) (sizeof(certNameSubject) / sizeof(CertNameData));
- /* ASN.1 template for an RDN.
- * X.509: RFC 5280, 4.1.2.4 - RelativeDistinguishedName
- */
- static const ASNItem rdnASN[] = {
- /* SET */ { 1, ASN_SET, 1, 1, 0 },
- /* AttributeTypeAndValue */
- /* ATTR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
- /* AttributeType */
- /* ATTR_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
- /* AttributeValue: Choice of tags - rdnChoice. */
- /* ATTR_VAL */ { 3, 0, 0, 0, 0 },
- };
- enum {
- RDNASN_IDX_SET = 0,
- RDNASN_IDX_ATTR_SEQ,
- RDNASN_IDX_ATTR_TYPE,
- RDNASN_IDX_ATTR_VAL
- };
- /* Number of items in ASN.1 template for an RDN. */
- #define rdnASN_Length (sizeof(rdnASN) / sizeof(ASNItem))
- /* Supported types of encodings (tags) for RDN strings.
- * X.509: RFC 5280, 4.1.2.4 - DirectoryString
- * (IA5 String not listed in RFC but required for alternative types)
- */
- static const byte rdnChoice[] = {
- ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, ASN_T61STRING,
- ASN_UNIVERSALSTRING, ASN_BMPSTRING, 0
- };
- #endif
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
- /* used to set the human readable string for the IP address with a ASN_IP_TYPE
- * DNS entry
- * return 0 on success
- */
- static int GenerateDNSEntryIPString(DNS_entry* entry, void* heap)
- {
- int ret = 0;
- int nameSz;
- char tmpName[WOLFSSL_MAX_IPSTR] = {0};
- char* ip;
- if (entry == NULL || entry->type != ASN_IP_TYPE) {
- return BAD_FUNC_ARG;
- }
- if (entry->len != WOLFSSL_IP4_ADDR_LEN &&
- entry->len != WOLFSSL_IP6_ADDR_LEN) {
- WOLFSSL_MSG("Unexpected IP size");
- return BAD_FUNC_ARG;
- }
- ip = entry->name;
- /* store IP addresses as a string */
- if (entry->len == WOLFSSL_IP4_ADDR_LEN) {
- if (XSNPRINTF(tmpName, sizeof(tmpName), "%u.%u.%u.%u", 0xFFU & ip[0],
- 0xFFU & ip[1], 0xFFU & ip[2], 0xFFU & ip[3])
- >= (int)sizeof(tmpName))
- {
- WOLFSSL_MSG("IP buffer overrun");
- return BUFFER_E;
- }
- }
- if (entry->len == WOLFSSL_IP6_ADDR_LEN) {
- int i;
- for (i = 0; i < 8; i++) {
- if (XSNPRINTF(tmpName + i * 5, sizeof(tmpName) - i * 5,
- "%02X%02X%s", 0xFF & ip[2 * i], 0xFF & ip[2 * i + 1],
- (i < 7) ? ":" : "")
- >= (int)sizeof(tmpName))
- {
- WOLFSSL_MSG("IPv6 buffer overrun");
- return BUFFER_E;
- }
- }
- }
- nameSz = (int)XSTRLEN(tmpName);
- entry->ipString = (char*)XMALLOC(nameSz + 1, heap, DYNAMIC_TYPE_ALTNAME);
- if (entry->ipString == NULL) {
- ret = MEMORY_E;
- }
- if (ret == 0) {
- XMEMCPY(entry->ipString, tmpName, nameSz);
- entry->ipString[nameSz] = '\0';
- }
- (void)heap;
- return ret;
- }
- #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
- #ifdef WOLFSSL_ASN_TEMPLATE
- #if defined(WOLFSSL_CERT_GEN) || !defined(NO_CERTS)
- /* Adds a DNS entry to a list of DNS entries
- *
- * @param [in, out] lst Linked list of DNS name entries.
- * @param [in] entry Entry to add to the list
- * @return 0 on success.
- */
- static int AddDNSEntryToList(DNS_entry** lst, DNS_entry* entry)
- {
- #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
- entry->next = NULL;
- if (*lst == NULL) {
- /* First on list */
- *lst = entry;
- }
- else {
- DNS_entry* temp = *lst;
- /* Find end */
- for (; (temp->next != NULL); temp = temp->next);
- /* Add to end */
- temp->next = entry;
- }
- #else
- /* Prepend entry to linked list. */
- entry->next = *lst;
- *lst = entry;
- #endif
- return 0;
- }
- /* Allocate a DNS entry and set the fields.
- *
- * @param [in] cert Certificate object.
- * @param [in] str DNS name string.
- * @param [in] strLen Length of DNS name string.
- * @param [in] type Type of DNS name string.
- * @param [in, out] entries Linked list of DNS name entries.
- * @return 0 on success.
- * @return MEMORY_E when dynamic memory allocation fails.
- */
- static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen,
- int type, DNS_entry** entries)
- {
- DNS_entry* dnsEntry;
- int ret = 0;
- /* Only used for heap. */
- (void)cert;
- /* TODO: consider one malloc. */
- /* Allocate DNS Entry object. */
- dnsEntry = AltNameNew(cert->heap);
- if (dnsEntry == NULL) {
- ret = MEMORY_E;
- }
- if (ret == 0) {
- /* Allocate DNS Entry name - length of string plus 1 for NUL. */
- dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
- DYNAMIC_TYPE_ALTNAME);
- if (dnsEntry->name == NULL) {
- XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
- ret = MEMORY_E;
- }
- }
- if (ret == 0) {
- /* Set tag type, name length, name and NUL terminate name. */
- dnsEntry->type = type;
- dnsEntry->len = strLen;
- XMEMCPY(dnsEntry->name, str, (size_t)strLen);
- dnsEntry->name[strLen] = '\0';
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
- /* store IP addresses as a string */
- if (type == ASN_IP_TYPE) {
- if ((ret = GenerateDNSEntryIPString(dnsEntry, cert->heap)) != 0) {
- XFREE(dnsEntry->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
- XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
- }
- }
- }
- if (ret == 0) {
- #endif
- ret = AddDNSEntryToList(entries, dnsEntry);
- }
- return ret;
- }
- #endif
- /* Set the details of a subject name component into a certificate.
- *
- * @param [in, out] cert Certificate object.
- * @param [in] id Id of component.
- * @param [in] str String for component.
- * @param [in] strLen Length of string.
- * @param [in] tag BER tag representing encoding of string.
- * @return 0 on success, negative values on failure.
- */
- static int SetSubject(DecodedCert* cert, int id, byte* str, int strLen,
- byte tag)
- {
- int ret = 0;
- /* Put string and encoding into certificate. */
- if (id == ASN_COMMON_NAME) {
- cert->subjectCN = (char *)str;
- cert->subjectCNLen = (int)strLen;
- cert->subjectCNEnc = (char)tag;
- }
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- else if (id > ASN_COMMON_NAME && id <= ASN_USER_ID) {
- /* Use table and offsets to put data into appropriate fields. */
- SetCertNameSubject(cert, id, (char*)str);
- SetCertNameSubjectLen(cert, id, strLen);
- SetCertNameSubjectEnc(cert, id, tag);
- }
- #endif
- #if !defined(IGNORE_NAME_CONSTRAINTS) || \
- defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- else if (id == ASN_EMAIL) {
- cert->subjectEmail = (char*)str;
- cert->subjectEmailLen = strLen;
- }
- #endif
- #ifdef WOLFSSL_CERT_EXT
- /* TODO: consider mapping id to an index and using SetCertNameSubect*(). */
- else if (id == ASN_JURIS_C) {
- cert->subjectJC = (char*)str;
- cert->subjectJCLen = strLen;
- cert->subjectJCEnc = (char)tag;
- }
- else if (id == ASN_JURIS_ST) {
- cert->subjectJS = (char*)str;
- cert->subjectJSLen = strLen;
- cert->subjectJSEnc = (char)tag;
- }
- #endif
- return ret;
- }
- /* Get a RelativeDistinguishedName from the encoding and put in certificate.
- *
- * @param [in, out] cert Certificate object.
- * @param [in, out] full Full name string. ([/<type>=<value>]*)
- * @param [in, out] idx Index int full name to place next component.
- * @param [in, out] nid NID of component type.
- * @param [in] isSubject Whether this data is for a subject name.
- * @param [in] dataASN Decoded data of RDN. Expected rdnASN type.
- * @return 0 on success.
- * @return MEMORY_E when dynamic memory allocation fails.
- * @return ASN_PARSE_E when type not supported.
- */
- static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid,
- int isSubject, ASNGetData* dataASN)
- {
- int ret = 0;
- const char* typeStr = NULL;
- byte typeStrLen = 0;
- byte* oid;
- word32 oidSz;
- int id = 0;
- (void)nid;
- /* Get name type OID from data items. */
- GetASN_OIDData(&dataASN[RDNASN_IDX_ATTR_TYPE], &oid, &oidSz);
- /* v1 name types */
- if ((oidSz == 3) && (oid[0] == 0x55) && (oid[1] == 0x04)) {
- id = oid[2];
- /* Check range of supported ids in table. */
- if (ValidCertNameSubject(id)) {
- /* Get the type string, length and NID from table. */
- typeStr = GetCertNameSubjectStr(id);
- typeStrLen = GetCertNameSubjectStrLen(id);
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- *nid = GetCertNameSubjectNID(id);
- #endif
- }
- }
- else if (oidSz == sizeof(attrEmailOid) && XMEMCMP(oid, attrEmailOid, oidSz) == 0) {
- /* Set the email id, type string, length and NID. */
- id = ASN_EMAIL;
- typeStr = WOLFSSL_EMAIL_ADDR;
- typeStrLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- *nid = NID_emailAddress;
- #endif
- }
- else if (oidSz == sizeof(uidOid) && XMEMCMP(oid, uidOid, oidSz) == 0) {
- /* Set the user id, type string, length and NID. */
- id = ASN_USER_ID;
- typeStr = WOLFSSL_USER_ID;
- typeStrLen = sizeof(WOLFSSL_USER_ID) - 1;
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- *nid = NID_userId;
- #endif
- }
- else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz) == 0) {
- /* Set the domain component, type string, length and NID. */
- id = ASN_DC;
- typeStr = WOLFSSL_DOMAIN_COMPONENT;
- typeStrLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- *nid = NID_domainComponent;
- #endif
- }
- else if (oidSz == sizeof(fvrtDrk) && XMEMCMP(oid, fvrtDrk, oidSz) == 0) {
- /* Set the favourite drink, type string, length and NID. */
- id = ASN_FAVOURITE_DRINK;
- typeStr = WOLFSSL_FAVOURITE_DRINK;
- typeStrLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- *nid = NID_favouriteDrink;
- #endif
- }
- /* Other OIDs that start with the same values. */
- else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz-1) == 0) {
- WOLFSSL_MSG("Unknown pilot attribute type");
- WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
- ret = ASN_PARSE_E;
- }
- else if (oidSz == ASN_JOI_PREFIX_SZ + 1 &&
- XMEMCMP(oid, ASN_JOI_PREFIX, ASN_JOI_PREFIX_SZ) == 0) {
- /* Set the jurisdiction id. */
- id = 0x200 + oid[ASN_JOI_PREFIX_SZ];
- /* Set the jurisdiction type string, length and NID if known. */
- if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_C) {
- typeStr = WOLFSSL_JOI_C;
- typeStrLen = sizeof(WOLFSSL_JOI_C) - 1;
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- *nid = NID_jurisdictionCountryName;
- #endif /* WOLFSSL_X509_NAME_AVAILABLE */
- }
- else if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_ST) {
- typeStr = WOLFSSL_JOI_ST;
- typeStrLen = sizeof(WOLFSSL_JOI_ST) - 1;
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- *nid = NID_jurisdictionStateOrProvinceName;
- #endif /* WOLFSSL_X509_NAME_AVAILABLE */
- }
- else {
- WOLFSSL_MSG("Unknown Jurisdiction, skipping");
- }
- }
- if ((ret == 0) && (typeStr != NULL)) {
- /* OID type to store for subject name and add to full string. */
- byte* str;
- word32 strLen;
- byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
- /* Get the string reference and length. */
- GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
- if (isSubject) {
- /* Store subject field components. */
- ret = SetSubject(cert, id, str, (int)strLen, tag);
- }
- if (ret == 0) {
- /* Check there is space for this in the full name string and
- * terminating NUL character. */
- if ((typeStrLen + strLen) < (word32)(WC_ASN_NAME_MAX - *idx))
- {
- /* Add RDN to full string. */
- XMEMCPY(&full[*idx], typeStr, typeStrLen);
- *idx += typeStrLen;
- XMEMCPY(&full[*idx], str, strLen);
- *idx += strLen;
- }
- else {
- WOLFSSL_MSG("ASN Name too big, skipping");
- }
- }
- }
- return ret;
- }
- #endif /* WOLFSSL_ASN_TEMPLATE */
- /* Get a certificate name into the certificate object.
- *
- * @param [in, out] cert Decoded certificate object.
- * @param [out] full Buffer to hold full name as a string.
- * @param [out] hash Buffer to hold hash of name.
- * @param [in] nameType ISSUER or SUBJECT.
- * @param [in] input Buffer holding certificate name.
- * @param [in, out] inOutIdx On in, start of certificate name.
- * On out, start of ASN.1 item after cert name.
- * @param [in] maxIdx Index of next item after certificate name.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- * @return MEMORY_E when dynamic memory allocation fails.
- */
- static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType,
- const byte* input, word32* inOutIdx, word32 maxIdx)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int length; /* length of all distinguished names */
- int dummy;
- int ret;
- word32 idx;
- word32 srcIdx = *inOutIdx;
- #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
- !defined(WOLFCRYPT_ONLY)
- WOLFSSL_X509_NAME* dName = NULL;
- #endif
- WOLFSSL_MSG("Getting Cert Name");
- /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
- * calculated over the entire DER encoding of the Name field, including
- * the tag and length. */
- if (CalcHashId_ex(input + *inOutIdx, maxIdx - *inOutIdx, hash,
- HashIdAlg(cert->signatureOID)) != 0) {
- return ASN_PARSE_E;
- }
- #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
- !defined(WOLFCRYPT_ONLY)
- dName = wolfSSL_X509_NAME_new_ex(cert->heap);
- if (dName == NULL) {
- return MEMORY_E;
- }
- #endif /* OPENSSL_EXTRA */
- if (GetSequence(input, &srcIdx, &length, maxIdx) < 0) {
- #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
- !defined(WOLFCRYPT_ONLY)
- wolfSSL_X509_NAME_free(dName);
- #endif /* OPENSSL_EXTRA */
- return ASN_PARSE_E;
- }
- #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
- /* store pointer to raw issuer */
- if (nameType == ISSUER) {
- cert->issuerRaw = &input[srcIdx];
- cert->issuerRawLen = length;
- }
- #endif
- #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectRaw = &input[srcIdx];
- cert->subjectRawLen = length;
- }
- #endif
- length += (int)srcIdx;
- idx = 0;
- while (srcIdx < (word32)length) {
- byte b = 0;
- byte joint[3];
- byte tooBig = FALSE;
- int oidSz;
- const char* copy = NULL;
- int copyLen = 0;
- int strLen = 0;
- byte id = 0;
- #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- int nid = NID_undef;
- int enc;
- #endif /* OPENSSL_EXTRA */
- if (GetSet(input, &srcIdx, &dummy, maxIdx) < 0) {
- WOLFSSL_MSG("Cert name lacks set header, trying sequence");
- }
- if (GetSequence(input, &srcIdx, &dummy, maxIdx) <= 0) {
- #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
- !defined(WOLFCRYPT_ONLY)
- wolfSSL_X509_NAME_free(dName);
- #endif /* OPENSSL_EXTRA */
- return ASN_PARSE_E;
- }
- ret = GetASNObjectId(input, &srcIdx, &oidSz, maxIdx);
- if (ret != 0) {
- #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
- !defined(WOLFCRYPT_ONLY)
- wolfSSL_X509_NAME_free(dName);
- #endif /* OPENSSL_EXTRA */
- return ret;
- }
- /* make sure there is room for joint */
- if ((srcIdx + sizeof(joint)) > (word32)maxIdx) {
- #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
- !defined(WOLFCRYPT_ONLY)
- wolfSSL_X509_NAME_free(dName);
- #endif /* OPENSSL_EXTRA */
- return ASN_PARSE_E;
- }
- XMEMCPY(joint, &input[srcIdx], sizeof(joint));
- /* v1 name types */
- if (joint[0] == 0x55 && joint[1] == 0x04) {
- srcIdx += 3;
- id = joint[2];
- if (GetHeader(input, &b, &srcIdx, &strLen, maxIdx, 1) < 0) {
- #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
- !defined(WOLFCRYPT_ONLY)
- wolfSSL_X509_NAME_free(dName);
- #endif /* OPENSSL_EXTRA */
- return ASN_PARSE_E;
- }
- if (id == ASN_COMMON_NAME) {
- if (nameType == SUBJECT) {
- cert->subjectCN = (char *)&input[srcIdx];
- cert->subjectCNLen = strLen;
- cert->subjectCNEnc = (char)b;
- }
- #if (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)) && \
- defined(WOLFSSL_HAVE_ISSUER_NAMES)
- else if (nameType == ISSUER) {
- cert->issuerCN = (char*)&input[srcIdx];
- cert->issuerCNLen = strLen;
- cert->issuerCNEnc = (char)b;
- }
- #endif
- copy = WOLFSSL_COMMON_NAME;
- copyLen = sizeof(WOLFSSL_COMMON_NAME) - 1;
- #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_commonName;
- #endif /* OPENSSL_EXTRA */
- }
- #ifdef WOLFSSL_CERT_NAME_ALL
- else if (id == ASN_NAME) {
- copy = WOLFSSL_NAME;
- copyLen = sizeof(WOLFSSL_NAME) - 1;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectN = (char*)&input[srcIdx];
- cert->subjectNLen = strLen;
- cert->subjectNEnc = b;
- }
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_name;
- #endif /* OPENSSL_EXTRA */
- }
- else if (id == ASN_INITIALS) {
- copy = WOLFSSL_INITIALS;
- copyLen = sizeof(WOLFSSL_INITIALS) - 1;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectI = (char*)&input[srcIdx];
- cert->subjectILen = strLen;
- cert->subjectIEnc = b;
- }
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_initials;
- #endif /* OPENSSL_EXTRA */
- }
- else if (id == ASN_GIVEN_NAME) {
- copy = WOLFSSL_GIVEN_NAME;
- copyLen = sizeof(WOLFSSL_GIVEN_NAME) - 1;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectGN = (char*)&input[srcIdx];
- cert->subjectGNLen = strLen;
- cert->subjectGNEnc = b;
- }
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_givenName;
- #endif /* OPENSSL_EXTRA */
- }
- else if (id == ASN_DNQUALIFIER) {
- copy = WOLFSSL_DNQUALIFIER;
- copyLen = sizeof(WOLFSSL_DNQUALIFIER) - 1;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectDNQ = (char*)&input[srcIdx];
- cert->subjectDNQLen = strLen;
- cert->subjectDNQEnc = b;
- }
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_dnQualifier;
- #endif /* OPENSSL_EXTRA */
- }
- #endif /* WOLFSSL_CERT_NAME_ALL */
- else if (id == ASN_SUR_NAME) {
- copy = WOLFSSL_SUR_NAME;
- copyLen = sizeof(WOLFSSL_SUR_NAME) - 1;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectSN = (char*)&input[srcIdx];
- cert->subjectSNLen = strLen;
- cert->subjectSNEnc = (char)b;
- }
- #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
- else if (nameType == ISSUER) {
- cert->issuerSN = (char*)&input[srcIdx];
- cert->issuerSNLen = strLen;
- cert->issuerSNEnc = (char)b;
- }
- #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_surname;
- #endif /* OPENSSL_EXTRA */
- }
- else if (id == ASN_COUNTRY_NAME) {
- copy = WOLFSSL_COUNTRY_NAME;
- copyLen = sizeof(WOLFSSL_COUNTRY_NAME) - 1;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectC = (char*)&input[srcIdx];
- cert->subjectCLen = strLen;
- cert->subjectCEnc = (char)b;
- }
- #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
- else if (nameType == ISSUER) {
- cert->issuerC = (char*)&input[srcIdx];
- cert->issuerCLen = strLen;
- cert->issuerCEnc = (char)b;
- }
- #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_countryName;
- #endif /* OPENSSL_EXTRA */
- }
- else if (id == ASN_LOCALITY_NAME) {
- copy = WOLFSSL_LOCALITY_NAME;
- copyLen = sizeof(WOLFSSL_LOCALITY_NAME) - 1;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectL = (char*)&input[srcIdx];
- cert->subjectLLen = strLen;
- cert->subjectLEnc = (char)b;
- }
- #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
- else if (nameType == ISSUER) {
- cert->issuerL = (char*)&input[srcIdx];
- cert->issuerLLen = strLen;
- cert->issuerLEnc = (char)b;
- }
- #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_localityName;
- #endif /* OPENSSL_EXTRA */
- }
- else if (id == ASN_STATE_NAME) {
- copy = WOLFSSL_STATE_NAME;
- copyLen = sizeof(WOLFSSL_STATE_NAME) - 1;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectST = (char*)&input[srcIdx];
- cert->subjectSTLen = strLen;
- cert->subjectSTEnc = (char)b;
- }
- #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
- else if (nameType == ISSUER) {
- cert->issuerST = (char*)&input[srcIdx];
- cert->issuerSTLen = strLen;
- cert->issuerSTEnc = (char)b;
- }
- #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_stateOrProvinceName;
- #endif /* OPENSSL_EXTRA */
- }
- else if (id == ASN_ORG_NAME) {
- copy = WOLFSSL_ORG_NAME;
- copyLen = sizeof(WOLFSSL_ORG_NAME) - 1;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectO = (char*)&input[srcIdx];
- cert->subjectOLen = strLen;
- cert->subjectOEnc = (char)b;
- }
- #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
- else if (nameType == ISSUER) {
- cert->issuerO = (char*)&input[srcIdx];
- cert->issuerOLen = strLen;
- cert->issuerOEnc = (char)b;
- }
- #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_organizationName;
- #endif /* OPENSSL_EXTRA */
- }
- else if (id == ASN_ORGUNIT_NAME) {
- copy = WOLFSSL_ORGUNIT_NAME;
- copyLen = sizeof(WOLFSSL_ORGUNIT_NAME) - 1;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectOU = (char*)&input[srcIdx];
- cert->subjectOULen = strLen;
- cert->subjectOUEnc = (char)b;
- }
- #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
- else if (nameType == ISSUER) {
- cert->issuerOU = (char*)&input[srcIdx];
- cert->issuerOULen = strLen;
- cert->issuerOUEnc = (char)b;
- }
- #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_organizationalUnitName;
- #endif /* OPENSSL_EXTRA */
- }
- else if (id == ASN_SERIAL_NUMBER) {
- copy = WOLFSSL_SERIAL_NUMBER;
- copyLen = sizeof(WOLFSSL_SERIAL_NUMBER) - 1;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectSND = (char*)&input[srcIdx];
- cert->subjectSNDLen = strLen;
- cert->subjectSNDEnc = (char)b;
- }
- #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
- else if (nameType == ISSUER) {
- cert->issuerSND = (char*)&input[srcIdx];
- cert->issuerSNDLen = strLen;
- cert->issuerSNDEnc = (char)b;
- }
- #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_serialNumber;
- #endif /* OPENSSL_EXTRA */
- }
- else if (id == ASN_USER_ID) {
- copy = WOLFSSL_USER_ID;
- copyLen = sizeof(WOLFSSL_USER_ID) - 1;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectUID = (char*)&input[srcIdx];
- cert->subjectUIDLen = strLen;
- cert->subjectUIDEnc = (char)b;
- }
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_userId;
- #endif /* OPENSSL_EXTRA */
- }
- #ifdef WOLFSSL_CERT_EXT
- else if (id == ASN_STREET_ADDR) {
- copy = WOLFSSL_STREET_ADDR_NAME;
- copyLen = sizeof(WOLFSSL_STREET_ADDR_NAME) - 1;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectStreet = (char*)&input[srcIdx];
- cert->subjectStreetLen = strLen;
- cert->subjectStreetEnc = (char)b;
- }
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_streetAddress;
- #endif /* OPENSSL_EXTRA */
- }
- else if (id == ASN_BUS_CAT) {
- copy = WOLFSSL_BUS_CAT;
- copyLen = sizeof(WOLFSSL_BUS_CAT) - 1;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectBC = (char*)&input[srcIdx];
- cert->subjectBCLen = strLen;
- cert->subjectBCEnc = (char)b;
- }
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
- #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_businessCategory;
- #endif /* OPENSSL_EXTRA */
- }
- else if (id == ASN_POSTAL_CODE) {
- copy = WOLFSSL_POSTAL_NAME;
- copyLen = sizeof(WOLFSSL_POSTAL_NAME) - 1;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectPC = (char*)&input[srcIdx];
- cert->subjectPCLen = strLen;
- cert->subjectPCEnc = (char)b;
- }
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_postalCode;
- #endif /* OPENSSL_EXTRA */
- }
- #endif /* WOLFSSL_CERT_EXT */
- }
- #ifdef WOLFSSL_CERT_EXT
- else if ((srcIdx + ASN_JOI_PREFIX_SZ + 2 <= (word32)maxIdx) &&
- (0 == XMEMCMP(&input[srcIdx], ASN_JOI_PREFIX,
- ASN_JOI_PREFIX_SZ)) &&
- ((input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_C) ||
- (input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_ST)))
- {
- srcIdx += ASN_JOI_PREFIX_SZ;
- id = input[srcIdx++];
- b = input[srcIdx++]; /* encoding */
- if (GetLength(input, &srcIdx, &strLen,
- maxIdx) < 0) {
- #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
- !defined(WOLFCRYPT_ONLY)
- wolfSSL_X509_NAME_free(dName);
- #endif /* OPENSSL_EXTRA */
- return ASN_PARSE_E;
- }
- /* Check for jurisdiction of incorporation country name */
- if (id == ASN_JOI_C) {
- copy = WOLFSSL_JOI_C;
- copyLen = sizeof(WOLFSSL_JOI_C) - 1;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectJC = (char*)&input[srcIdx];
- cert->subjectJCLen = strLen;
- cert->subjectJCEnc = (char)b;
- }
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_jurisdictionCountryName;
- #endif /* OPENSSL_EXTRA */
- }
- /* Check for jurisdiction of incorporation state name */
- else if (id == ASN_JOI_ST) {
- copy = WOLFSSL_JOI_ST;
- copyLen = sizeof(WOLFSSL_JOI_ST) - 1;
- #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectJS = (char*)&input[srcIdx];
- cert->subjectJSLen = strLen;
- cert->subjectJSEnc = (char)b;
- }
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_jurisdictionStateOrProvinceName;
- #endif /* OPENSSL_EXTRA */
- }
- if ((strLen + copyLen) > (int)(WC_ASN_NAME_MAX - idx)) {
- WOLFSSL_MSG("ASN Name too big, skipping");
- tooBig = TRUE;
- }
- }
- #endif /* WOLFSSL_CERT_EXT */
- else {
- /* skip */
- byte email = FALSE;
- byte pilot = FALSE;
- if (joint[0] == 0x2a && joint[1] == 0x86) { /* email id hdr 42.134.* */
- id = ASN_EMAIL_NAME;
- email = TRUE;
- }
- if (joint[0] == 0x9 && joint[1] == 0x92) { /* uid id hdr 9.146.* */
- /* last value of OID is the type of pilot attribute */
- id = input[srcIdx + (word32)oidSz - 1];
- if (id == 0x01)
- id = ASN_USER_ID;
- pilot = TRUE;
- }
- srcIdx += (word32)oidSz + 1;
- if (GetLength(input, &srcIdx, &strLen, maxIdx) < 0) {
- #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
- !defined(WOLFCRYPT_ONLY)
- wolfSSL_X509_NAME_free(dName);
- #endif /* OPENSSL_EXTRA */
- return ASN_PARSE_E;
- }
- if (strLen > (int)(WC_ASN_NAME_MAX - idx)) {
- WOLFSSL_MSG("ASN name too big, skipping");
- tooBig = TRUE;
- }
- if (email) {
- copyLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
- if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx)) {
- WOLFSSL_MSG("ASN name too big, skipping");
- tooBig = TRUE;
- }
- else {
- copy = WOLFSSL_EMAIL_ADDR;
- }
- #if !defined(IGNORE_NAME_CONSTRAINTS) || \
- defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
- if (nameType == SUBJECT) {
- cert->subjectEmail = (char*)&input[srcIdx];
- cert->subjectEmailLen = strLen;
- }
- #if defined(WOLFSSL_HAVE_ISSUER_NAMES) && \
- (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
- else if (nameType == ISSUER) {
- cert->issuerEmail = (char*)&input[srcIdx];
- cert->issuerEmailLen = strLen;
- }
- #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
- #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_emailAddress;
- #endif /* OPENSSL_EXTRA */
- }
- if (pilot) {
- switch (id) {
- case ASN_USER_ID:
- copy = WOLFSSL_USER_ID;
- copyLen = sizeof(WOLFSSL_USER_ID) - 1;
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_userId;
- #endif /* OPENSSL_EXTRA */
- break;
- case ASN_DOMAIN_COMPONENT:
- copy = WOLFSSL_DOMAIN_COMPONENT;
- copyLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_domainComponent;
- #endif /* OPENSSL_EXTRA */
- break;
- case ASN_FAVOURITE_DRINK:
- copy = WOLFSSL_FAVOURITE_DRINK;
- copyLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) \
- && !defined(WOLFCRYPT_ONLY)
- nid = NID_favouriteDrink;
- #endif /* OPENSSL_EXTRA */
- break;
- default:
- WOLFSSL_MSG("Unknown pilot attribute type");
- #if (defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)) && \
- !defined(WOLFCRYPT_ONLY)
- wolfSSL_X509_NAME_free(dName);
- #endif /* OPENSSL_EXTRA */
- return ASN_PARSE_E;
- }
- }
- }
- if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx))
- {
- WOLFSSL_MSG("ASN Name too big, skipping");
- tooBig = TRUE;
- }
- if ((copy != NULL) && !tooBig) {
- XMEMCPY(&full[idx], copy, (size_t)copyLen);
- idx += (word32)copyLen;
- XMEMCPY(&full[idx], &input[srcIdx], (size_t)strLen);
- idx += (word32)strLen;
- }
- #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
- !defined(WOLFCRYPT_ONLY)
- switch (b) {
- case CTC_UTF8:
- enc = MBSTRING_UTF8;
- break;
- case CTC_PRINTABLE:
- enc = V_ASN1_PRINTABLESTRING;
- break;
- default:
- WOLFSSL_MSG("Unknown encoding type, using UTF8 by default");
- enc = MBSTRING_UTF8;
- }
- if (nid != NID_undef) {
- if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc,
- &input[srcIdx], strLen, -1, -1) !=
- WOLFSSL_SUCCESS) {
- wolfSSL_X509_NAME_free(dName);
- return ASN_PARSE_E;
- }
- }
- #endif /* OPENSSL_EXTRA */
- srcIdx += (word32)strLen;
- }
- full[idx++] = 0;
- #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
- !defined(WOLFCRYPT_ONLY)
- if (nameType == ISSUER) {
- #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)) && \
- (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
- dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX);
- XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
- #endif
- cert->issuerName = dName;
- }
- else {
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
- dName->rawLen = min(cert->subjectRawLen, WC_ASN_NAME_MAX);
- XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
- #endif
- cert->subjectName = dName;
- }
- #endif
- *inOutIdx = srcIdx;
- return 0;
- #else
- DECL_ASNGETDATA(dataASN, rdnASN_Length);
- int ret = 0;
- word32 idx = 0;
- int len;
- word32 srcIdx = *inOutIdx;
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- WOLFSSL_X509_NAME* dName = NULL;
- #endif /* WOLFSSL_X509_NAME_AVAILABLE */
- WOLFSSL_MSG("Getting Cert Name");
- /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
- * calculated over the entire DER encoding of the Name field, including
- * the tag and length. */
- if (CalcHashId_ex(input + srcIdx, maxIdx - srcIdx, hash,
- HashIdAlg(cert->signatureOID)) != 0) {
- ret = ASN_PARSE_E;
- }
- CALLOC_ASNGETDATA(dataASN, rdnASN_Length, ret, cert->heap);
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- if (ret == 0) {
- /* Create an X509_NAME to hold data for OpenSSL compatability APIs. */
- dName = wolfSSL_X509_NAME_new_ex(cert->heap);
- if (dName == NULL) {
- ret = MEMORY_E;
- }
- }
- #endif /* WOLFSSL_X509_NAME_AVAILABLE */
- if (ret == 0) {
- /* Expecting a SEQUENCE using up all data. */
- ret = GetASN_Sequence(input, &srcIdx, &len, maxIdx, 1);
- }
- if (ret == 0) {
- #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
- /* Store pointer and length to raw issuer. */
- if (nameType == ISSUER) {
- cert->issuerRaw = &input[srcIdx];
- cert->issuerRawLen = len;
- }
- #endif
- #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
- /* Store pointer and length to raw subject. */
- if (nameType == SUBJECT) {
- cert->subjectRaw = &input[srcIdx];
- cert->subjectRawLen = len;
- }
- #endif
- /* Process all RDNs in name. */
- while ((ret == 0) && (srcIdx < maxIdx)) {
- int nid = 0;
- /* Initialize for data and setup RDN choice. */
- GetASN_Choice(&dataASN[RDNASN_IDX_ATTR_VAL], rdnChoice);
- /* Ignore type OID as too many to store in table. */
- GetASN_OID(&dataASN[RDNASN_IDX_ATTR_TYPE], oidIgnoreType);
- /* Parse RDN. */
- ret = GetASN_Items(rdnASN, dataASN, rdnASN_Length, 1, input,
- &srcIdx, maxIdx);
- if (ret == 0) {
- /* Put RDN data into certificate. */
- ret = GetRDN(cert, full, &idx, &nid, nameType == SUBJECT,
- dataASN);
- }
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- /* TODO: push this back up to ssl.c
- * (do parsing for WOLFSSL_X509_NAME on demand) */
- if (ret == 0) {
- int enc;
- byte* str;
- word32 strLen;
- byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
- /* Get string reference. */
- GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
- /* Convert BER tag to a OpenSSL type. */
- switch (tag) {
- case CTC_UTF8:
- enc = MBSTRING_UTF8;
- break;
- case CTC_PRINTABLE:
- enc = V_ASN1_PRINTABLESTRING;
- break;
- default:
- WOLFSSL_MSG("Unknown encoding type, default UTF8");
- enc = MBSTRING_UTF8;
- }
- if (nid != 0) {
- /* Add an entry to the X509_NAME. */
- if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc, str,
- strLen, -1, -1) != WOLFSSL_SUCCESS) {
- ret = ASN_PARSE_E;
- }
- }
- }
- #endif
- }
- }
- if (ret == 0) {
- /* Terminate string. */
- full[idx] = 0;
- /* Return index into encoding after name. */
- *inOutIdx = srcIdx;
- #ifdef WOLFSSL_X509_NAME_AVAILABLE
- /* Store X509_NAME in certificate. */
- if (nameType == ISSUER) {
- #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
- defined(HAVE_LIGHTY)) && \
- (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
- dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX);
- XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
- #endif
- cert->issuerName = dName;
- }
- else {
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
- dName->rawLen = min(cert->subjectRawLen, WC_ASN_NAME_MAX);
- XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
- #endif
- cert->subjectName = dName;
- }
- }
- else {
- /* Dispose of unused X509_NAME. */
- wolfSSL_X509_NAME_free(dName);
- #endif
- }
- FREE_ASNGETDATA(dataASN, cert->heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for certificate name. */
- static const ASNItem certNameASN[] = {
- /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
- /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
- };
- enum {
- CERTNAMEASN_IDX_OID = 0,
- CERTNAMEASN_IDX_NAME
- };
- /* Number of items in ASN.1 template for certificate name. */
- #define certNameASN_Length (sizeof(certNameASN) / sizeof(ASNItem))
- #endif
- /* Get a certificate name into the certificate object.
- *
- * Either the issuer or subject name.
- *
- * @param [in, out] cert Decoded certificate object.
- * @param [in] nameType Type of name being decoded: ISSUER or SUBJECT.
- * @param [in] maxIdx Index of next item after certificate name.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- * @return MEMORY_E when dynamic memory allocation fails.
- */
- int GetName(DecodedCert* cert, int nameType, int maxIdx)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- char* full;
- byte* hash;
- int length;
- word32 localIdx;
- byte tag;
- WOLFSSL_MSG("Getting Name");
- if (nameType == ISSUER) {
- full = cert->issuer;
- hash = cert->issuerHash;
- }
- else {
- full = cert->subject;
- hash = cert->subjectHash;
- }
- if (cert->srcIdx >= (word32)maxIdx) {
- return BUFFER_E;
- }
- localIdx = cert->srcIdx;
- if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
- return ASN_PARSE_E;
- }
- if (tag == ASN_OBJECT_ID) {
- WOLFSSL_MSG("Trying optional prefix...");
- if (SkipObjectId(cert->source, &cert->srcIdx, (word32)maxIdx) < 0)
- return ASN_PARSE_E;
- WOLFSSL_MSG("Got optional prefix");
- }
- localIdx = cert->srcIdx;
- if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
- return ASN_PARSE_E;
- }
- localIdx = cert->srcIdx + 1;
- if (GetLength(cert->source, &localIdx, &length, (word32)maxIdx) < 0) {
- return ASN_PARSE_E;
- }
- length += (int)(localIdx - cert->srcIdx);
- return GetCertName(cert, full, hash, nameType, cert->source, &cert->srcIdx,
- cert->srcIdx + (word32)length);
- #else
- ASNGetData dataASN[certNameASN_Length];
- word32 idx = cert->srcIdx;
- int ret = 0;
- WOLFSSL_MSG("Getting Name");
- XMEMSET(dataASN, 0, sizeof(dataASN));
- /* Initialize for data and don't check optional prefix OID. */
- GetASN_OID(&dataASN[CERTNAMEASN_IDX_OID], oidIgnoreType);
- ret = GetASN_Items(certNameASN, dataASN, certNameASN_Length, 0,
- cert->source, &idx, (word32)maxIdx);
- if (ret == 0) {
- char* full;
- byte* hash;
- /* Store offset of SEQUENCE that is start of name. */
- cert->srcIdx = dataASN[CERTNAMEASN_IDX_NAME].offset;
- /* Get fields to fill in based on name type. */
- if (nameType == ISSUER) {
- full = cert->issuer;
- hash = cert->issuerHash;
- }
- else {
- full = cert->subject;
- hash = cert->subjectHash;
- }
- /* Parse certificate name. */
- ret = GetCertName(cert, full, hash, nameType, cert->source,
- &cert->srcIdx, idx);
- }
- return ret;
- #endif
- }
- #ifndef NO_ASN_TIME
- /* two byte date/time, add to value */
- static WC_INLINE int GetTime(int* value, const byte* date, int* idx)
- {
- int i = *idx;
- if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
- date[i+1] > 0x39) {
- return ASN_PARSE_E;
- }
- *value += (int)btoi(date[i++]) * 10;
- *value += (int)btoi(date[i++]);
- *idx = i;
- return 0;
- }
- #ifdef WOLFSSL_LINUXKM
- static WC_INLINE int GetTime_Long(long* value, const byte* date, int* idx)
- {
- int i = *idx;
- if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
- date[i+1] > 0x39) {
- return ASN_PARSE_E;
- }
- *value += (long)btoi(date[i++]) * 10;
- *value += (long)btoi(date[i++]);
- *idx = i;
- return 0;
- }
- #endif
- int ExtractDate(const unsigned char* date, unsigned char format,
- struct tm* certTime, int* idx)
- {
- XMEMSET(certTime, 0, sizeof(struct tm));
- if (format == ASN_UTC_TIME) {
- if (btoi(date[*idx]) >= 5)
- certTime->tm_year = 1900;
- else
- certTime->tm_year = 2000;
- }
- else { /* format == GENERALIZED_TIME */
- #ifdef WOLFSSL_LINUXKM
- if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
- #else
- if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
- #endif
- certTime->tm_year *= 100;
- }
- #ifdef AVR
- /* Extract the time from the struct tm and adjust tm_year, tm_mon */
- /* AVR libc stores these as uint8_t instead of int */
- /* AVR time_t also offsets from midnight 1 Jan 2000 */
- int tm_year = certTime->tm_year - 2000;
- int tm_mon = certTime->tm_mon - 1;
- int tm_mday = certTime->tm_mday;
- int tm_hour = certTime->tm_hour;
- int tm_min = certTime->tm_min;
- int tm_sec = certTime->tm_sec;
- #ifdef WOLFSSL_LINUXKM
- if (GetTime_Long(&tm_year, date, idx) != 0) return 0;
- #else
- if (GetTime(&tm_year, date, idx) != 0) return 0;
- #endif
- if (GetTime(&tm_mon , date, idx) != 0) return 0;
- if (GetTime(&tm_mday, date, idx) != 0) return 0;
- if (GetTime(&tm_hour, date, idx) != 0) return 0;
- if (GetTime(&tm_min , date, idx) != 0) return 0;
- if (GetTime(&tm_sec , date, idx) != 0) return 0;
- /* Re-populate certTime with computed values */
- certTime->tm_year = tm_year;
- certTime->tm_mon = tm_mon;
- certTime->tm_mday = tm_mday;
- certTime->tm_hour = tm_hour;
- certTime->tm_min = tm_min;
- certTime->tm_sec = tm_sec;
- #else
- /* adjust tm_year, tm_mon */
- #ifdef WOLFSSL_LINUXKM
- if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
- #else
- if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
- #endif
- certTime->tm_year -= 1900;
- if (GetTime(&certTime->tm_mon , date, idx) != 0) return 0;
- certTime->tm_mon -= 1;
- if (GetTime(&certTime->tm_mday, date, idx) != 0) return 0;
- if (GetTime(&certTime->tm_hour, date, idx) != 0) return 0;
- if (GetTime(&certTime->tm_min , date, idx) != 0) return 0;
- if (GetTime(&certTime->tm_sec , date, idx) != 0) return 0;
- #endif
- return 1;
- }
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
- defined(OPENSSL_EXTRA) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
- int GetTimeString(byte* date, int format, char* buf, int len)
- {
- struct tm t;
- int idx = 0;
- if (!ExtractDate(date, (unsigned char)format, &t, &idx)) {
- return 0;
- }
- if (date[idx] != 'Z') {
- WOLFSSL_MSG("UTCtime, not Zulu") ;
- return 0;
- }
- /* place month in buffer */
- buf[0] = '\0';
- switch(t.tm_mon) {
- case 0: XSTRNCAT(buf, "Jan ", 5); break;
- case 1: XSTRNCAT(buf, "Feb ", 5); break;
- case 2: XSTRNCAT(buf, "Mar ", 5); break;
- case 3: XSTRNCAT(buf, "Apr ", 5); break;
- case 4: XSTRNCAT(buf, "May ", 5); break;
- case 5: XSTRNCAT(buf, "Jun ", 5); break;
- case 6: XSTRNCAT(buf, "Jul ", 5); break;
- case 7: XSTRNCAT(buf, "Aug ", 5); break;
- case 8: XSTRNCAT(buf, "Sep ", 5); break;
- case 9: XSTRNCAT(buf, "Oct ", 5); break;
- case 10: XSTRNCAT(buf, "Nov ", 5); break;
- case 11: XSTRNCAT(buf, "Dec ", 5); break;
- default:
- return 0;
- }
- idx = 4; /* use idx now for char buffer */
- if (XSNPRINTF(buf + idx, len - idx, "%2d %02d:%02d:%02d %d GMT",
- t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, (int)t.tm_year + 1900)
- >= len - idx)
- {
- WOLFSSL_MSG("buffer overrun in GetTimeString");
- return 0;
- }
- return 1;
- }
- #endif /* OPENSSL_ALL || WOLFSSL_MYSQL_COMPATIBLE || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
- #if !defined(NO_ASN_TIME) && !defined(USER_TIME) && \
- !defined(TIME_OVERRIDES) && (defined(OPENSSL_EXTRA) || defined(HAVE_PKCS7))
- /* Set current time string, either UTC or GeneralizedTime.
- * (void*) tm should be a pointer to time_t, output is placed in buf.
- *
- * Return time string length placed in buf on success, negative on error */
- int GetAsnTimeString(void* currTime, byte* buf, word32 len)
- {
- byte* data_ptr = buf;
- byte uf_time[ASN_GENERALIZED_TIME_SIZE];
- int data_len = 0;
- WOLFSSL_ENTER("GetAsnTimeString");
- if (buf == NULL || len == 0)
- return BAD_FUNC_ARG;
- XMEMSET(uf_time, 0, sizeof(uf_time));
- /* GetFormattedTime returns length with null terminator */
- data_len = GetFormattedTime(currTime, uf_time, (word32)sizeof(uf_time));
- if (data_len <= 0) {
- return ASN_TIME_E;
- }
- /* ensure room to add 2 bytes (ASN type and length) before proceeding */
- else if (len < (word32)data_len + 2) {
- return BUFFER_E;
- }
- if (data_len == ASN_UTC_TIME_SIZE-1) {
- /* increment data_len for ASN length byte after adding the data_ptr */
- *data_ptr = (byte)ASN_UTC_TIME; data_ptr++; data_len++;
- /* -1 below excludes null terminator */
- *data_ptr = (byte)ASN_UTC_TIME_SIZE - 1; data_ptr++; data_len++;
- XMEMCPY(data_ptr, (byte *)uf_time, ASN_UTC_TIME_SIZE - 1);
- data_ptr += ASN_UTC_TIME_SIZE - 1;
- }
- else if (data_len == ASN_GENERALIZED_TIME_SIZE-1) {
- /* increment data_len for ASN length byte after adding the data_ptr */
- *data_ptr = (byte)ASN_GENERALIZED_TIME; data_ptr++; data_len++;
- /* -1 below excludes null terminator */
- *data_ptr = (byte)ASN_GENERALIZED_TIME_SIZE - 1; data_ptr++; data_len++;
- XMEMCPY(data_ptr, (byte*)uf_time, ASN_GENERALIZED_TIME_SIZE - 1);
- data_ptr += ASN_GENERALIZED_TIME_SIZE - 1;
- }
- else {
- WOLFSSL_MSG("Invalid time size returned");
- return ASN_TIME_E;
- }
- /* append null terminator */
- *data_ptr = 0;
- /* return length without null terminator */
- return data_len;
- }
- /* return just the time string as either UTC or Generalized Time*/
- int GetFormattedTime(void* currTime, byte* buf, word32 len)
- {
- struct tm* ts = NULL;
- struct tm* tmpTime = NULL;
- int year, mon, day, hour, mini, sec;
- int ret;
- #if defined(NEED_TMP_TIME)
- struct tm tmpTimeStorage;
- tmpTime = &tmpTimeStorage;
- #endif
- /* Needed in case XGMTIME does not use the tmpTime argument. */
- (void)tmpTime;
- WOLFSSL_ENTER("GetFormattedTime");
- if (buf == NULL || len == 0)
- return BAD_FUNC_ARG;
- ts = (struct tm *)XGMTIME((time_t*)currTime, tmpTime);
- if (ts == NULL) {
- WOLFSSL_MSG("failed to get time data.");
- return ASN_TIME_E;
- }
- /* Note ASN_UTC_TIME_SIZE and ASN_GENERALIZED_TIME_SIZE include space for
- * the null terminator. ASN encoded values leave off the terminator. */
- if (ts->tm_year >= 50 && ts->tm_year < 150) {
- /* UTC Time */
- if (ts->tm_year >= 50 && ts->tm_year < 100) {
- year = ts->tm_year;
- }
- else {
- year = ts->tm_year - 100;
- }
- mon = ts->tm_mon + 1;
- day = ts->tm_mday;
- hour = ts->tm_hour;
- mini = ts->tm_min;
- sec = ts->tm_sec;
- #if defined(WOLF_C89)
- if (len < ASN_UTC_TIME_SIZE) {
- WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
- return BUFFER_E;
- }
- ret = XSPRINTF((char*)buf,
- "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
- hour, mini, sec);
- #else
- ret = XSNPRINTF((char*)buf, len,
- "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
- hour, mini, sec);
- #endif
- }
- else {
- /* GeneralizedTime */
- year = ts->tm_year + 1900;
- mon = ts->tm_mon + 1;
- day = ts->tm_mday;
- hour = ts->tm_hour;
- mini = ts->tm_min;
- sec = ts->tm_sec;
- #if defined(WOLF_C89)
- if (len < ASN_GENERALIZED_TIME_SIZE) {
- WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
- return BUFFER_E;
- }
- ret = XSPRINTF((char*)buf,
- "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
- hour, mini, sec);
- #else
- ret = XSNPRINTF((char*)buf, len,
- "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
- hour, mini, sec);
- #endif
- }
- return ret;
- }
- #endif /* !NO_ASN_TIME && !USER_TIME && !TIME_OVERRIDES &&
- * (OPENSSL_EXTRA || HAVE_PKCS7) */
- #if defined(USE_WOLF_VALIDDATE)
- /* to the second */
- int DateGreaterThan(const struct tm* a, const struct tm* b)
- {
- if (a->tm_year > b->tm_year)
- return 1;
- if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
- return 1;
- if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
- a->tm_mday > b->tm_mday)
- return 1;
- if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
- a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
- return 1;
- if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
- a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
- a->tm_min > b->tm_min)
- return 1;
- if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
- a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
- a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
- return 1;
- return 0; /* false */
- }
- static WC_INLINE int DateLessThan(const struct tm* a, const struct tm* b)
- {
- return DateGreaterThan(b,a);
- }
- /* like atoi but only use first byte */
- /* Make sure before and after dates are valid */
- int wc_ValidateDate(const byte* date, byte format, int dateType)
- {
- time_t ltime;
- struct tm certTime;
- struct tm* localTime;
- struct tm* tmpTime;
- int i = 0;
- int timeDiff = 0;
- int diffHH = 0, diffMM = 0;
- #if defined(NEED_TMP_TIME)
- struct tm tmpTimeStorage;
- tmpTime = &tmpTimeStorage;
- #else
- tmpTime = NULL;
- #endif
- (void)tmpTime;
- ltime = wc_Time(0);
- if (sizeof(ltime) == sizeof(word32) && (int)ltime < 0){
- /* A negative response here could be due to a 32-bit time_t
- * where the year is 2038 or later. */
- WOLFSSL_MSG("wc_Time failed to return a valid value");
- return 0;
- }
- #ifdef WOLFSSL_BEFORE_DATE_CLOCK_SKEW
- if (dateType == BEFORE) {
- WOLFSSL_MSG("Skewing local time for before date check");
- ltime += WOLFSSL_BEFORE_DATE_CLOCK_SKEW;
- }
- #endif
- #ifdef WOLFSSL_AFTER_DATE_CLOCK_SKEW
- if (dateType == AFTER) {
- WOLFSSL_MSG("Skewing local time for after date check");
- ltime -= WOLFSSL_AFTER_DATE_CLOCK_SKEW;
- }
- #endif
- if (!ExtractDate(date, format, &certTime, &i)) {
- WOLFSSL_MSG("Error extracting the date");
- return 0;
- }
- if ((date[i] == '+') || (date[i] == '-')) {
- int diffSign;
- WOLFSSL_MSG("Using time differential, not Zulu") ;
- diffSign = date[i++] == '+' ? 1 : -1 ;
- if (GetTime(&diffHH, date, &i) != 0)
- return 0;
- if (GetTime(&diffMM, date, &i) != 0)
- return 0;
- timeDiff = diffSign * (diffHH*60 + diffMM) * 60 ;
- } else if (date[i] != 'Z') {
- WOLFSSL_MSG("UTCtime, neither Zulu or time differential") ;
- return 0;
- }
- ltime -= (time_t)timeDiff;
- localTime = XGMTIME(<ime, tmpTime);
- if (localTime == NULL) {
- WOLFSSL_MSG("XGMTIME failed");
- return 0;
- }
- if (dateType == BEFORE) {
- if (DateLessThan(localTime, &certTime)) {
- WOLFSSL_MSG("Date BEFORE check failed");
- return 0;
- }
- }
- else { /* dateType == AFTER */
- if (DateGreaterThan(localTime, &certTime)) {
- WOLFSSL_MSG("Date AFTER check failed");
- return 0;
- }
- }
- return 1;
- }
- #endif /* USE_WOLF_VALIDDATE */
- int wc_GetTime(void* timePtr, word32 timeSize)
- {
- time_t* ltime = (time_t*)timePtr;
- if (timePtr == NULL) {
- return BAD_FUNC_ARG;
- }
- if ((word32)sizeof(time_t) > timeSize) {
- return BUFFER_E;
- }
- *ltime = wc_Time(0);
- return 0;
- }
- #ifdef TIME_OVERRIDES
- #ifndef HAVE_TIME_T_TYPE
- typedef long time_t;
- #endif
- extern time_t XTIME(time_t* t);
- #endif
- static wc_time_cb timeFunc = NULL;
- int wc_SetTimeCb(wc_time_cb f)
- {
- timeFunc = f;
- return 0;
- }
- time_t wc_Time(time_t* t)
- {
- if (timeFunc != NULL) {
- return timeFunc(t);
- }
- return XTIME(t);
- }
- #endif /* !NO_ASN_TIME */
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* TODO: use a CHOICE instead of two items? */
- /* ASN.1 template for a date - either UTC or Generalized Time. */
- static const ASNItem dateASN[] = {
- /* UTC */ { 0, ASN_UTC_TIME, 0, 0, 2 },
- /* GT */ { 0, ASN_GENERALIZED_TIME, 0, 0, 2 },
- };
- enum {
- DATEASN_IDX_UTC = 0,
- DATEASN_IDX_GT
- };
- /* Number of items in ASN.1 template for a date. */
- #define dateASN_Length (sizeof(dateASN) / sizeof(ASNItem))
- #endif /* WOLFSSL_ASN_TEMPLATE */
- /* Get date buffer, format and length. Returns 0=success or error */
- /* Decode a DateInfo - choice of UTC TIME or GENERALIZED TIME.
- *
- * @param [in] source Buffer containing encoded date.
- * @param [in, out] idx On in, the index of the date.
- * On out, index after date.
- * @param [out] pDate Pointer into buffer of data bytes.
- * @param [out] pFormat Format of date - BER/DER tag.
- * @param [out] pLength Length of date bytes.
- * @param [in] maxIdx Index of next item after date.
- * @return 0 on success.
- * @return BAD_FUNC_ARG when source or idx is NULL.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- */
- static int GetDateInfo(const byte* source, word32* idx, const byte** pDate,
- byte* pFormat, int* pLength, word32 maxIdx)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int length;
- byte format;
- if (source == NULL || idx == NULL)
- return BAD_FUNC_ARG;
- /* get ASN format header */
- if (*idx+1 > maxIdx)
- return BUFFER_E;
- format = source[*idx];
- *idx += 1;
- if (format != ASN_UTC_TIME && format != ASN_GENERALIZED_TIME) {
- WOLFSSL_ERROR_VERBOSE(ASN_TIME_E);
- return ASN_TIME_E;
- }
- /* get length */
- if (GetLength(source, idx, &length, maxIdx) < 0)
- return ASN_PARSE_E;
- if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
- return ASN_DATE_SZ_E;
- /* return format, date and length */
- if (pFormat)
- *pFormat = format;
- if (pDate)
- *pDate = &source[*idx];
- if (pLength)
- *pLength = length;
- *idx += (word32)length;
- return 0;
- #else
- ASNGetData dataASN[dateASN_Length];
- int ret = 0;
- if ((source == NULL) || (idx == NULL)) {
- ret = BAD_FUNC_ARG;
- }
- if (ret == 0) {
- /* Initialize data. */
- XMEMSET(dataASN, 0, sizeof(dataASN));
- /* Parse date. */
- ret = GetASN_Items(dateASN, dataASN, dateASN_Length, 0, source, idx,
- maxIdx);
- }
- if (ret == 0) {
- /* Determine which tag was seen. */
- int i = (dataASN[DATEASN_IDX_UTC].tag != 0) ? DATEASN_IDX_UTC
- : DATEASN_IDX_GT;
- /* Return data from seen item. */
- if (pFormat != NULL) {
- *pFormat = dataASN[i].tag;
- }
- if (pDate != NULL) {
- *pDate = dataASN[i].data.ref.data;
- }
- if (pLength != NULL) {
- *pLength = (int)dataASN[i].data.ref.length;
- }
- }
- return ret;
- #endif
- }
- #if !defined(NO_CERTS) && !defined(WOLFSSL_ASN_TEMPLATE)
- static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx)
- {
- int ret, length;
- const byte *datePtr = NULL;
- byte date[MAX_DATE_SIZE];
- byte format;
- word32 startIdx = 0;
- if (dateType == BEFORE)
- cert->beforeDate = &cert->source[cert->srcIdx];
- else
- cert->afterDate = &cert->source[cert->srcIdx];
- startIdx = cert->srcIdx;
- ret = GetDateInfo(cert->source, &cert->srcIdx, &datePtr, &format,
- &length, (word32)maxIdx);
- if (ret < 0)
- return ret;
- XMEMSET(date, 0, MAX_DATE_SIZE);
- XMEMCPY(date, datePtr, (size_t)length);
- if (dateType == BEFORE)
- cert->beforeDateLen = (int)(cert->srcIdx - startIdx);
- else
- cert->afterDateLen = (int)(cert->srcIdx - startIdx);
- #ifndef NO_ASN_TIME_CHECK
- if (verify != NO_VERIFY && verify != VERIFY_SKIP_DATE &&
- !XVALIDATE_DATE(date, format, dateType)) {
- if (dateType == BEFORE) {
- WOLFSSL_ERROR_VERBOSE(ASN_BEFORE_DATE_E);
- return ASN_BEFORE_DATE_E;
- }
- else {
- WOLFSSL_ERROR_VERBOSE(ASN_AFTER_DATE_E);
- return ASN_AFTER_DATE_E;
- }
- }
- #else
- (void)verify;
- #endif
- return 0;
- }
- static int GetValidity(DecodedCert* cert, int verify, int maxIdx)
- {
- int length;
- int badDate = 0;
- if (GetSequence(cert->source, &cert->srcIdx, &length, (word32)maxIdx) < 0)
- return ASN_PARSE_E;
- maxIdx = (int)cert->srcIdx + length;
- if (GetDate(cert, BEFORE, verify, maxIdx) < 0)
- badDate = ASN_BEFORE_DATE_E; /* continue parsing */
- if (GetDate(cert, AFTER, verify, maxIdx) < 0)
- return ASN_AFTER_DATE_E;
- if (badDate != 0)
- return badDate;
- return 0;
- }
- #endif /* !NO_CERTS && !WOLFSSL_ASN_TEMPLATE */
- int wc_GetDateInfo(const byte* certDate, int certDateSz, const byte** date,
- byte* format, int* length)
- {
- int ret;
- word32 idx = 0;
- ret = GetDateInfo(certDate, &idx, date, format, length, (word32)certDateSz);
- return ret;
- }
- #ifndef NO_ASN_TIME
- int wc_GetDateAsCalendarTime(const byte* date, int length, byte format,
- struct tm* timearg)
- {
- int idx = 0;
- (void)length;
- if (!ExtractDate(date, format, timearg, &idx))
- return ASN_TIME_E;
- return 0;
- }
- #if defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_ALT_NAMES)
- int wc_GetCertDates(Cert* cert, struct tm* before, struct tm* after)
- {
- int ret = 0;
- const byte* date;
- byte format;
- int length;
- if (cert == NULL)
- return BAD_FUNC_ARG;
- if (before && cert->beforeDateSz > 0) {
- ret = wc_GetDateInfo(cert->beforeDate, cert->beforeDateSz, &date,
- &format, &length);
- if (ret == 0)
- ret = wc_GetDateAsCalendarTime(date, length, format, before);
- }
- if (after && cert->afterDateSz > 0) {
- ret = wc_GetDateInfo(cert->afterDate, cert->afterDateSz, &date,
- &format, &length);
- if (ret == 0)
- ret = wc_GetDateAsCalendarTime(date, length, format, after);
- }
- return ret;
- }
- #endif /* WOLFSSL_CERT_GEN && WOLFSSL_ALT_NAMES */
- #endif /* !NO_ASN_TIME */
- #if !defined(WOLFSSL_ASN_TEMPLATE) && !defined(NO_CERTS)
- static int GetSigAlg(DecodedCert* cert, word32* sigOid, word32 maxIdx)
- {
- int length;
- word32 endSeqIdx;
- if (GetSequence(cert->source, &cert->srcIdx, &length, maxIdx) < 0)
- return ASN_PARSE_E;
- endSeqIdx = cert->srcIdx + (word32)length;
- if (GetObjectId(cert->source, &cert->srcIdx, sigOid, oidSigType,
- maxIdx) < 0) {
- return ASN_OBJECT_ID_E;
- }
- if (cert->srcIdx != endSeqIdx) {
- #ifdef WC_RSA_PSS
- if (*sigOid == CTC_RSASSAPSS) {
- cert->sigParamsIndex = cert->srcIdx;
- cert->sigParamsLength = endSeqIdx - cert->srcIdx;
- }
- else
- #endif
- /* Only allowed a ASN NULL header with zero length. */
- if (endSeqIdx - cert->srcIdx != 2)
- return ASN_PARSE_E;
- else {
- byte tag;
- if (GetASNTag(cert->source, &cert->srcIdx, &tag, endSeqIdx) != 0)
- return ASN_PARSE_E;
- if (tag != ASN_TAG_NULL)
- return ASN_PARSE_E;
- }
- }
- cert->srcIdx = endSeqIdx;
- return 0;
- }
- #endif
- #ifndef NO_CERTS
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* TODO: move code around to not require this. */
- static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
- int* badDateRet, int stopAtPubKey,
- int stopAfterPubKey);
- #endif
- /* Parse the certificate up to the X.509 public key.
- *
- * If cert data is invalid then badDate get set to error value.
- *
- * @param [in, out] cert Decoded certificate object.
- * @param [in] verify Whether to verify dates.
- * @param [out] badDate Error code when verify dates.
- * @return 0 on success.
- * @return BAD_FUNC_ARG when cert or badDate is NULL.
- * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
- * @return ASN_DATE_SZ_E when time data is not supported.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
- */
- int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret;
- if (cert == NULL || badDate == NULL)
- return BAD_FUNC_ARG;
- *badDate = 0;
- if ( (ret = GetCertHeader(cert)) < 0)
- return ret;
- WOLFSSL_MSG("Got Cert Header");
- #ifdef WOLFSSL_CERT_REQ
- if (!cert->isCSR) {
- #endif
- /* Using the sigIndex as the upper bound because that's where the
- * actual certificate data ends. */
- if ((ret = GetSigAlg(cert, &cert->signatureOID, cert->sigIndex)) < 0)
- return ret;
- WOLFSSL_MSG("Got Algo ID");
- if ( (ret = GetName(cert, ISSUER, (int)cert->sigIndex)) < 0)
- return ret;
- if ( (ret = GetValidity(cert, verify, (int)cert->sigIndex)) < 0)
- *badDate = ret;
- #ifdef WOLFSSL_CERT_REQ
- }
- #endif
- if ( (ret = GetName(cert, SUBJECT, (int)cert->sigIndex)) < 0)
- return ret;
- WOLFSSL_MSG("Got Subject Name");
- return ret;
- #else
- /* Use common decode routine and stop at public key. */
- int ret;
- *badDate = 0;
- ret = DecodeCertInternal(cert, verify, NULL, badDate, 1, 0);
- if (ret >= 0) {
- /* Store current index: public key. */
- cert->srcIdx = (word32)ret;
- }
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- /* Parse the certificate up to and including X.509 public key.
- *
- * @param [in, out] cert Decoded certificate object.
- * @param [in] verify Whether to verify dates.
- * @return 0 on success.
- * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
- * @return ASN_DATE_SZ_E when time data is not supported.
- * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
- * @return ASN_AFTER_DATE_E when AFTER date is invalid.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
- */
- int DecodeToKey(DecodedCert* cert, int verify)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int badDate = 0;
- int ret;
- if ( (ret = wc_GetPubX509(cert, verify, &badDate)) < 0)
- return ret;
- /* Determine if self signed */
- #ifdef WOLFSSL_CERT_REQ
- if (cert->isCSR)
- cert->selfSigned = 1;
- else
- #endif
- {
- cert->selfSigned = XMEMCMP(cert->issuerHash, cert->subjectHash,
- KEYID_SIZE) == 0 ? 1 : 0;
- }
- ret = GetCertKey(cert, cert->source, &cert->srcIdx, cert->maxIdx);
- if (ret != 0)
- return ret;
- WOLFSSL_MSG("Got Key");
- if (badDate != 0)
- return badDate;
- return ret;
- #else
- int ret;
- int badDate = 0;
- /* Call internal version and stop after public key. */
- ret = DecodeCertInternal(cert, verify, NULL, &badDate, 0, 1);
- /* Always return date errors. */
- if (ret == 0) {
- ret = badDate;
- }
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #if !defined(WOLFSSL_ASN_TEMPLATE)
- static int GetSignature(DecodedCert* cert)
- {
- int length;
- int ret;
- ret = CheckBitString(cert->source, &cert->srcIdx, &length, cert->maxIdx, 1,
- NULL);
- if (ret != 0)
- return ret;
- cert->sigLength = (word32)length;
- cert->signature = &cert->source[cert->srcIdx];
- cert->srcIdx += cert->sigLength;
- if (cert->srcIdx != cert->maxIdx)
- return ASN_PARSE_E;
- return 0;
- }
- #endif /* !WOLFSSL_ASN_TEMPLATE */
- #endif /* !NO_CERTS */
- #ifndef WOLFSSL_ASN_TEMPLATE
- static word32 SetOctetString8Bit(word32 len, byte* output)
- {
- output[0] = ASN_OCTET_STRING;
- output[1] = (byte)len;
- return 2;
- }
- static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
- {
- word32 idx = SetOctetString8Bit(digSz, output);
- XMEMCPY(&output[idx], digest, digSz);
- return idx + digSz;
- }
- #endif
- /* Encode a length for DER.
- *
- * @param [in] length Value to encode.
- * @param [out] output Buffer to encode into.
- * @return Number of bytes encoded.
- */
- word32 SetLength(word32 length, byte* output)
- {
- /* Start encoding at start of buffer. */
- word32 i = 0;
- if (length < ASN_LONG_LENGTH) {
- /* Only one byte needed to encode. */
- if (output) {
- /* Write out length value. */
- output[i] = (byte)length;
- }
- /* Skip over length. */
- i++;
- }
- else {
- /* Calculate the number of bytes required to encode value. */
- byte j = (byte)BytePrecision(length);
- if (output) {
- /* Encode count byte. */
- output[i] = (byte)(j | ASN_LONG_LENGTH);
- }
- /* Skip over count byte. */
- i++;
- /* Encode value as a big-endian byte array. */
- for (; j > 0; --j) {
- if (output) {
- /* Encode next most-significant byte. */
- output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
- }
- /* Skip over byte. */
- i++;
- }
- }
- /* Return number of bytes in encoded length. */
- return i;
- }
- /* Encode a DER header - type/tag and length.
- *
- * @param [in] tag DER tag of ASN.1 item.
- * @param [in] len Length of data in ASN.1 item.
- * @param [out] output Buffer to encode into.
- * @return Number of bytes encoded.
- */
- static word32 SetHeader(byte tag, word32 len, byte* output)
- {
- if (output) {
- /* Encode tag first. */
- output[0] = tag;
- }
- /* Encode the length. */
- return SetLength(len, output ? output + ASN_TAG_SZ : NULL) + ASN_TAG_SZ;
- }
- /* Encode a SEQUENCE header in DER.
- *
- * @param [in] len Length of data in SEQUENCE.
- * @param [out] output Buffer to encode into.
- * @return Number of bytes encoded.
- */
- word32 SetSequence(word32 len, byte* output)
- {
- return SetHeader(ASN_SEQUENCE | ASN_CONSTRUCTED, len, output);
- }
- /* Encode an OCTET STRING header in DER.
- *
- * @param [in] len Length of data in OCTET STRING.
- * @param [out] output Buffer to encode into.
- * @return Number of bytes encoded.
- */
- word32 SetOctetString(word32 len, byte* output)
- {
- return SetHeader(ASN_OCTET_STRING, len, output);
- }
- /* Encode a SET header in DER.
- *
- * @param [in] len Length of data in SET.
- * @param [out] output Buffer to encode into.
- * @return Number of bytes encoded.
- */
- word32 SetSet(word32 len, byte* output)
- {
- return SetHeader(ASN_SET | ASN_CONSTRUCTED, len, output);
- }
- /* Encode an implicit context specific header in DER.
- *
- * Implicit means that it is constructed only if the included ASN.1 item is.
- *
- * @param [in] tag Tag for the implicit ASN.1 item.
- * @param [in] number Context specific number.
- * @param [in] len Length of data in SET.
- * @param [out] output Buffer to encode into.
- * @return Number of bytes encoded.
- */
- word32 SetImplicit(byte tag, byte number, word32 len, byte* output)
- {
- tag = (byte)(((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0)
- | ASN_CONTEXT_SPECIFIC | number);
- return SetHeader(tag, len, output);
- }
- /* Encode an explicit context specific header in DER.
- *
- * Explicit means that there will be an ASN.1 item underneath.
- *
- * @param [in] number Context specific number.
- * @param [in] len Length of data in SET.
- * @param [out] output Buffer to encode into.
- * @return Number of bytes encoded.
- */
- word32 SetExplicit(byte number, word32 len, byte* output)
- {
- return SetHeader((byte)(ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | number),
- len, output);
- }
- #if defined(OPENSSL_EXTRA)
- /* Encode an Othername into DER.
- *
- * @param [in] name Pointer to the WOLFSSL_ASN1_OTHERNAME to be encoded.
- * @param [out] output Buffer to encode into. If NULL, don't encode.
- * @return Number of bytes encoded or WOLFSSL_FAILURE if name parameter is bad.
- */
- word32 SetOthername(void *name, byte *output)
- {
- WOLFSSL_ASN1_OTHERNAME *nm = (WOLFSSL_ASN1_OTHERNAME *)name;
- char *nameStr = NULL;
- int nameSz = 0;
- word32 len = 0;
- if ((nm == NULL) || (nm->value == NULL)) {
- WOLFSSL_MSG("otherName value is NULL");
- return WOLFSSL_FAILURE;
- }
- nameStr = nm->value->value.utf8string->data;
- nameSz = nm->value->value.utf8string->length;
- len = nm->type_id->objSz +
- SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2, NULL) +
- SetHeader(CTC_UTF8, nameSz, NULL) + nameSz;
- if (output != NULL) {
- /* otherName OID */
- XMEMCPY(output, nm->type_id->obj, nm->type_id->objSz);
- output += nm->type_id->objSz;
- output += SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2,
- output);
- output += SetHeader(CTC_UTF8, nameSz, output);
- XMEMCPY(output, nameStr, nameSz);
- }
- return len;
- }
- #endif /* OPENSSL_EXTRA */
- #ifdef HAVE_ECC
- /* Determines whether the signature algorithm is using ECDSA.
- *
- * @param [in] algoOID Signature algorithm identifier.
- * @return 1 when algorithm is using ECDSA.
- * @return 0 otherwise.
- */
- static WC_INLINE int IsSigAlgoECDSA(word32 algoOID)
- {
- /* ECDSA sigAlgo must not have ASN1 NULL parameters */
- if (algoOID == CTC_SHAwECDSA || algoOID == CTC_SHA256wECDSA ||
- algoOID == CTC_SHA384wECDSA || algoOID == CTC_SHA512wECDSA) {
- return 1;
- }
- return 0;
- }
- #endif
- /* Determines if OID is for an EC signing algorithm including ECDSA and EdDSA
- * and post-quantum algorithms.
- *
- * @param [in] algoOID Algorithm OID.
- * @return 1 when is EC signing algorithm.
- * @return 0 otherwise.
- */
- static WC_INLINE int IsSigAlgoECC(word32 algoOID)
- {
- (void)algoOID;
- return (0
- #ifdef HAVE_ECC
- || IsSigAlgoECDSA(algoOID)
- #endif
- #ifdef WOLFSSL_SM2
- || (algoOID == SM2k)
- #endif
- #ifdef HAVE_ED25519
- || (algoOID == ED25519k)
- #endif
- #ifdef HAVE_CURVE25519
- || (algoOID == X25519k)
- #endif
- #ifdef HAVE_ED448
- || (algoOID == ED448k)
- #endif
- #ifdef HAVE_CURVE448
- || (algoOID == X448k)
- #endif
- #ifdef HAVE_PQC
- #ifdef HAVE_FACON
- || (algoOID == FALCON_LEVEL1k)
- || (algoOID == FALCON_LEVEL5k)
- #endif
- #ifdef HAVE_DILITHIUM
- || (algoOID == DILITHIUM_LEVEL2k)
- || (algoOID == DILITHIUM_LEVEL3k)
- || (algoOID == DILITHIUM_LEVEL5k)
- #endif
- #ifdef HAVE_SPHINCS
- || (algoOID == SPHINCS_FAST_LEVEL1k)
- || (algoOID == SPHINCS_FAST_LEVEL3k)
- || (algoOID == SPHINCS_FAST_LEVEL5k)
- || (algoOID == SPHINCS_SMALL_LEVEL1k)
- || (algoOID == SPHINCS_SMALL_LEVEL3k)
- || (algoOID == SPHINCS_SMALL_LEVEL5k)
- #endif
- #endif /* HAVE_PQC */
- );
- }
- /* Encode an algorithm identifier.
- *
- * [algoOID, type] is unique.
- *
- * @param [in] algoOID Algorithm identifier.
- * @param [out] output Buffer to hold encoding.
- * @param [in] type Type of OID being encoded.
- * @param [in] curveSz Add extra space for curve data.
- * @return Encoded data size on success.
- * @return 0 when dynamic memory allocation fails.
- */
- word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 tagSz, idSz, seqSz, algoSz = 0;
- const byte* algoName = 0;
- byte ID_Length[1 + MAX_LENGTH_SZ];
- byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
- word32 length = 0;
- tagSz = (type == oidHashType ||
- (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
- (type == oidKeyType && algoOID == RSAk)) ? 2U : 0U;
- algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
- if (algoName == NULL) {
- WOLFSSL_MSG("Unknown Algorithm");
- return 0;
- }
- idSz = (word32)SetObjectId((int)algoSz, ID_Length);
- seqSz = SetSequence(idSz + algoSz + tagSz + (word32)curveSz, seqArray);
- /* Copy only algo to output for DSA keys */
- if (algoOID == DSAk && output) {
- XMEMCPY(output, ID_Length, idSz);
- XMEMCPY(output + idSz, algoName, algoSz);
- if (tagSz == 2)
- SetASNNull(&output[seqSz + idSz + algoSz]);
- }
- else if (output) {
- XMEMCPY(output, seqArray, seqSz);
- XMEMCPY(output + seqSz, ID_Length, idSz);
- XMEMCPY(output + seqSz + idSz, algoName, algoSz);
- if (tagSz == 2)
- SetASNNull(&output[seqSz + idSz + algoSz]);
- }
- if (algoOID == DSAk)
- length = idSz + algoSz + tagSz;
- else
- length = seqSz + idSz + algoSz + tagSz;
- return length;
- #else
- DECL_ASNSETDATA(dataASN, algoIdASN_Length);
- int ret = 0;
- const byte* algoName = 0;
- word32 algoSz = 0;
- CALLOC_ASNSETDATA(dataASN, algoIdASN_Length, ret, NULL);
- algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
- if (algoName == NULL) {
- WOLFSSL_MSG("Unknown Algorithm");
- }
- else {
- int sz;
- int o = 0;
- /* Set the OID and OID type to encode. */
- SetASN_OID(&dataASN[ALGOIDASN_IDX_OID], (word32)algoOID, (word32)type);
- /* Hashes, signatures not ECC and keys not RSA output NULL tag. */
- if (!(type == oidHashType ||
- (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
- (type == oidKeyType && algoOID == RSAk))) {
- /* Don't put out NULL DER item. */
- dataASN[ALGOIDASN_IDX_NULL].noOut = 1;
- }
- if (algoOID == DSAk) {
- /* Don't include SEQUENCE for DSA keys. */
- o = 1;
- }
- else if (curveSz > 0) {
- /* Don't put out NULL DER item. */
- dataASN[ALGOIDASN_IDX_NULL].noOut = 0;
- /* Include space for extra data of length curveSz.
- * Subtract 1 for sequence and 1 for length encoding. */
- SetASN_Buffer(&dataASN[ALGOIDASN_IDX_NULL], NULL,
- (word32)curveSz - 2);
- }
- /* Calculate size of encoding. */
- ret = SizeASN_Items(algoIdASN + o, dataASN + o,
- (int)algoIdASN_Length - (int)o, &sz);
- if (ret == 0 && output != NULL) {
- /* Encode into buffer. */
- SetASN_Items(algoIdASN + o, dataASN + o,
- (int)algoIdASN_Length - (int)o, output);
- if (curveSz > 0) {
- /* Return size excluding curve data. */
- sz = (int)(dataASN[o].offset -
- dataASN[ALGOIDASN_IDX_NULL].offset);
- }
- }
- if (ret == 0) {
- /* Return encoded size. */
- ret = sz;
- }
- else {
- /* Unsigned return type so 0 indicates error. */
- ret = 0;
- }
- }
- FREE_ASNSETDATA(dataASN, NULL);
- return (word32)ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* Always encode PKCS#1 v1.5 RSA signature and compare to encoded data. */
- /* ASN.1 template for DigestInfo for a PKCS#1 v1.5 RSA signature.
- * PKCS#1 v2.2: RFC 8017, A.2.4 - DigestInfo
- */
- static const ASNItem digestInfoASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* digestAlgorithm */
- /* DIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* DIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
- /* DIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
- /* digest */
- /* DIGEST */ { 1, ASN_OCTET_STRING, 0, 0, 0 }
- };
- enum {
- DIGESTINFOASN_IDX_SEQ = 0,
- DIGESTINFOASN_IDX_DIGALGO_SEQ,
- DIGESTINFOASN_IDX_DIGALGO_OID,
- DIGESTINFOASN_IDX_DIGALGO_NULL,
- DIGESTINFOASN_IDX_DIGEST
- };
- /* Number of items in ASN.1 template for DigestInfo for RSA. */
- #define digestInfoASN_Length (sizeof(digestInfoASN) / sizeof(ASNItem))
- #endif
- /* Encode signature.
- *
- * @param [out] out Buffer to hold encoding.
- * @param [in] digest Buffer holding digest.
- * @param [in] digSz Length of digest in bytes.
- * @return Encoded data size on success.
- * @return 0 when dynamic memory allocation fails.
- */
- word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz,
- int hashOID)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- byte digArray[MAX_ENCODED_DIG_SZ];
- byte algoArray[MAX_ALGO_SZ];
- byte seqArray[MAX_SEQ_SZ];
- word32 encDigSz, algoSz, seqSz;
- encDigSz = SetDigest(digest, digSz, digArray);
- algoSz = SetAlgoID(hashOID, algoArray, oidHashType, 0);
- seqSz = SetSequence(encDigSz + algoSz, seqArray);
- XMEMCPY(out, seqArray, seqSz);
- XMEMCPY(out + seqSz, algoArray, algoSz);
- XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
- return encDigSz + algoSz + seqSz;
- #else
- DECL_ASNSETDATA(dataASN, digestInfoASN_Length);
- int ret = 0;
- int sz;
- unsigned char dgst[WC_MAX_DIGEST_SIZE];
- CALLOC_ASNSETDATA(dataASN, digestInfoASN_Length, ret, NULL);
- if (ret == 0) {
- /* Set hash OID and type. */
- SetASN_OID(&dataASN[DIGESTINFOASN_IDX_DIGALGO_OID], (word32)hashOID,
- oidHashType);
- /* Set digest. */
- if (digest == out) {
- XMEMCPY(dgst, digest, digSz);
- digest = dgst;
- }
- SetASN_Buffer(&dataASN[DIGESTINFOASN_IDX_DIGEST], digest, digSz);
- /* Calculate size of encoding. */
- ret = SizeASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, &sz);
- }
- if (ret == 0) {
- /* Encode PKCS#1 v1.5 RSA signature. */
- SetASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, out);
- ret = sz;
- }
- else {
- /* Unsigned return type so 0 indicates error. */
- ret = 0;
- }
- FREE_ASNSETDATA(dataASN, NULL);
- return (word32)ret;
- #endif
- }
- #ifndef NO_CERTS
- int wc_GetCTC_HashOID(int type)
- {
- int ret;
- enum wc_HashType hType;
- hType = wc_HashTypeConvert(type);
- ret = wc_HashGetOID(hType);
- if (ret < 0) {
- ret = 0; /* backwards compatibility */
- }
- return ret;
- }
- /* Initialize a signature context object.
- *
- * Object used for signing and verifying a certificate signature.
- *
- * @param [in, out] sigCtx Signature context object.
- * @param [in] heap Dynamic memory hint.
- * @param [in] devId Hardware device identifier.
- */
- void InitSignatureCtx(SignatureCtx* sigCtx, void* heap, int devId)
- {
- if (sigCtx) {
- XMEMSET(sigCtx, 0, sizeof(SignatureCtx));
- sigCtx->devId = devId;
- sigCtx->heap = heap;
- }
- }
- /* Free dynamic data in a signature context object.
- *
- * @param [in, out] sigCtx Signature context object.
- */
- void FreeSignatureCtx(SignatureCtx* sigCtx)
- {
- if (sigCtx == NULL)
- return;
- if (sigCtx->digest) {
- XFREE(sigCtx->digest, sigCtx->heap, DYNAMIC_TYPE_DIGEST);
- sigCtx->digest = NULL;
- }
- #if !(defined(NO_RSA) && defined(NO_DSA))
- if (sigCtx->sigCpy) {
- XFREE(sigCtx->sigCpy, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
- sigCtx->sigCpy = NULL;
- }
- #endif
- #ifndef NO_ASN_CRYPT
- if (sigCtx->key.ptr) {
- switch (sigCtx->keyOID) {
- #ifndef NO_RSA
- #ifdef WC_RSA_PSS
- case RSAPSSk:
- #endif
- case RSAk:
- wc_FreeRsaKey(sigCtx->key.rsa);
- XFREE(sigCtx->key.rsa, sigCtx->heap, DYNAMIC_TYPE_RSA);
- sigCtx->key.rsa = NULL;
- break;
- #endif /* !NO_RSA */
- #ifndef NO_DSA
- case DSAk:
- wc_FreeDsaKey(sigCtx->key.dsa);
- XFREE(sigCtx->key.dsa, sigCtx->heap, DYNAMIC_TYPE_DSA);
- sigCtx->key.dsa = NULL;
- break;
- #endif
- #ifdef HAVE_ECC
- case ECDSAk:
- #ifdef WOLFSSL_SM2
- case SM2k:
- #endif
- #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
- defined(WC_ASYNC_ENABLE_ECC)
- if (sigCtx->key.ecc->nb_ctx != NULL) {
- XFREE(sigCtx->key.ecc->nb_ctx, sigCtx->heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- }
- #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
- WC_ASYNC_ENABLE_ECC */
- wc_ecc_free(sigCtx->key.ecc);
- XFREE(sigCtx->key.ecc, sigCtx->heap, DYNAMIC_TYPE_ECC);
- sigCtx->key.ecc = NULL;
- break;
- #endif /* HAVE_ECC */
- #ifdef HAVE_ED25519
- case ED25519k:
- wc_ed25519_free(sigCtx->key.ed25519);
- XFREE(sigCtx->key.ed25519, sigCtx->heap, DYNAMIC_TYPE_ED25519);
- sigCtx->key.ed25519 = NULL;
- break;
- #endif /* HAVE_ED25519 */
- #ifdef HAVE_ED448
- case ED448k:
- wc_ed448_free(sigCtx->key.ed448);
- XFREE(sigCtx->key.ed448, sigCtx->heap, DYNAMIC_TYPE_ED448);
- sigCtx->key.ed448 = NULL;
- break;
- #endif /* HAVE_ED448 */
- #if defined(HAVE_PQC)
- #if defined(HAVE_FALCON)
- case FALCON_LEVEL1k:
- case FALCON_LEVEL5k:
- wc_falcon_free(sigCtx->key.falcon);
- XFREE(sigCtx->key.falcon, sigCtx->heap,
- DYNAMIC_TYPE_FALCON);
- sigCtx->key.falcon = NULL;
- break;
- #endif /* HAVE_FALCON */
- #if defined(HAVE_DILITHIUM)
- case DILITHIUM_LEVEL2k:
- case DILITHIUM_LEVEL3k:
- case DILITHIUM_LEVEL5k:
- wc_dilithium_free(sigCtx->key.dilithium);
- XFREE(sigCtx->key.dilithium, sigCtx->heap,
- DYNAMIC_TYPE_DILITHIUM);
- sigCtx->key.dilithium = NULL;
- break;
- #endif /* HAVE_DILITHIUM */
- #if defined(HAVE_SPHINCS)
- case SPHINCS_FAST_LEVEL1k:
- case SPHINCS_FAST_LEVEL3k:
- case SPHINCS_FAST_LEVEL5k:
- case SPHINCS_SMALL_LEVEL1k:
- case SPHINCS_SMALL_LEVEL3k:
- case SPHINCS_SMALL_LEVEL5k:
- wc_sphincs_free(sigCtx->key.sphincs);
- XFREE(sigCtx->key.sphincs, sigCtx->heap,
- DYNAMIC_TYPE_SPHINCS);
- sigCtx->key.sphincs = NULL;
- break;
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- default:
- break;
- } /* switch (keyOID) */
- sigCtx->key.ptr = NULL;
- }
- #endif
- /* reset state, we are done */
- sigCtx->state = SIG_STATE_BEGIN;
- }
- #if !defined(NO_ASN_CRYPT) && !defined(NO_HASH_WRAPPER)
- static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID,
- byte* digest, int* typeH, int* digestSz, int verify)
- {
- int ret = 0;
- switch (sigOID) {
- #if defined(WOLFSSL_MD2)
- case CTC_MD2wRSA:
- if (!verify) {
- ret = HASH_TYPE_E;
- WOLFSSL_MSG("MD2 not supported for signing");
- }
- else if ((ret = wc_Md2Hash(buf, bufSz, digest)) == 0) {
- *typeH = MD2h;
- *digestSz = MD2_DIGEST_SIZE;
- }
- break;
- #endif
- #ifndef NO_MD5
- case CTC_MD5wRSA:
- if ((ret = wc_Md5Hash(buf, bufSz, digest)) == 0) {
- *typeH = MD5h;
- *digestSz = WC_MD5_DIGEST_SIZE;
- }
- break;
- #endif
- #ifndef NO_SHA
- case CTC_SHAwRSA:
- case CTC_SHAwDSA:
- case CTC_SHAwECDSA:
- if ((ret = wc_ShaHash(buf, bufSz, digest)) == 0) {
- *typeH = SHAh;
- *digestSz = WC_SHA_DIGEST_SIZE;
- }
- break;
- #endif
- #ifdef WOLFSSL_SHA224
- case CTC_SHA224wRSA:
- case CTC_SHA224wECDSA:
- if ((ret = wc_Sha224Hash(buf, bufSz, digest)) == 0) {
- *typeH = SHA224h;
- *digestSz = WC_SHA224_DIGEST_SIZE;
- }
- break;
- #endif
- #ifndef NO_SHA256
- case CTC_SHA256wRSA:
- case CTC_SHA256wECDSA:
- case CTC_SHA256wDSA:
- if ((ret = wc_Sha256Hash(buf, bufSz, digest)) == 0) {
- *typeH = SHA256h;
- *digestSz = WC_SHA256_DIGEST_SIZE;
- }
- break;
- #endif
- #ifdef WOLFSSL_SHA384
- case CTC_SHA384wRSA:
- case CTC_SHA384wECDSA:
- if ((ret = wc_Sha384Hash(buf, bufSz, digest)) == 0) {
- *typeH = SHA384h;
- *digestSz = WC_SHA384_DIGEST_SIZE;
- }
- break;
- #endif
- #ifdef WOLFSSL_SHA512
- case CTC_SHA512wRSA:
- case CTC_SHA512wECDSA:
- if ((ret = wc_Sha512Hash(buf, bufSz, digest)) == 0) {
- *typeH = SHA512h;
- *digestSz = WC_SHA512_DIGEST_SIZE;
- }
- break;
- #endif
- #ifdef WOLFSSL_SHA3
- #ifndef WOLFSSL_NOSHA3_224
- case CTC_SHA3_224wRSA:
- case CTC_SHA3_224wECDSA:
- if ((ret = wc_Sha3_224Hash(buf, bufSz, digest)) == 0) {
- *typeH = SHA3_224h;
- *digestSz = WC_SHA3_224_DIGEST_SIZE;
- }
- break;
- #endif
- #ifndef WOLFSSL_NOSHA3_256
- case CTC_SHA3_256wRSA:
- case CTC_SHA3_256wECDSA:
- if ((ret = wc_Sha3_256Hash(buf, bufSz, digest)) == 0) {
- *typeH = SHA3_256h;
- *digestSz = WC_SHA3_256_DIGEST_SIZE;
- }
- break;
- #endif
- #ifndef WOLFSSL_NOSHA3_384
- case CTC_SHA3_384wRSA:
- case CTC_SHA3_384wECDSA:
- if ((ret = wc_Sha3_384Hash(buf, bufSz, digest)) == 0) {
- *typeH = SHA3_384h;
- *digestSz = WC_SHA3_384_DIGEST_SIZE;
- }
- break;
- #endif
- #ifndef WOLFSSL_NOSHA3_512
- case CTC_SHA3_512wRSA:
- case CTC_SHA3_512wECDSA:
- if ((ret = wc_Sha3_512Hash(buf, bufSz, digest)) == 0) {
- *typeH = SHA3_512h;
- *digestSz = WC_SHA3_512_DIGEST_SIZE;
- }
- break;
- #endif
- #endif
- #if defined(WOLFSSL_SM2) & defined(WOLFSSL_SM3)
- case CTC_SM3wSM2:
- if ((ret = wc_Sm3Hash(buf, bufSz, digest)) == 0) {
- *typeH = SM3h;
- *digestSz = WC_SM3_DIGEST_SIZE;
- }
- break;
- #endif
- #ifdef HAVE_ED25519
- case CTC_ED25519:
- /* Hashes done in signing operation.
- * Two dependent hashes with prefixes performed.
- */
- break;
- #endif
- #ifdef HAVE_ED448
- case CTC_ED448:
- /* Hashes done in signing operation.
- * Two dependent hashes with prefixes performed.
- */
- break;
- #endif
- #ifdef HAVE_PQC
- #ifdef HAVE_FALCON
- case CTC_FALCON_LEVEL1:
- case CTC_FALCON_LEVEL5:
- /* Hashes done in signing operation. */
- break;
- #endif
- #ifdef HAVE_DILITHIUM
- case CTC_DILITHIUM_LEVEL2:
- case CTC_DILITHIUM_LEVEL3:
- case CTC_DILITHIUM_LEVEL5:
- /* Hashes done in signing operation. */
- break;
- #endif
- #ifdef HAVE_SPHINCS
- case CTC_SPHINCS_FAST_LEVEL1:
- case CTC_SPHINCS_FAST_LEVEL3:
- case CTC_SPHINCS_FAST_LEVEL5:
- case CTC_SPHINCS_SMALL_LEVEL1:
- case CTC_SPHINCS_SMALL_LEVEL3:
- case CTC_SPHINCS_SMALL_LEVEL5:
- /* Hashes done in signing operation. */
- break;
- #endif
- #endif /* HAVE_PQC */
- default:
- ret = HASH_TYPE_E;
- WOLFSSL_MSG("Hash for Signature has unsupported type");
- }
- (void)buf;
- (void)bufSz;
- (void)sigOID;
- (void)digest;
- (void)digestSz;
- (void)typeH;
- (void)verify;
- return ret;
- }
- #endif /* !NO_ASN_CRYPT && !NO_HASH_WRAPPER */
- /* Return codes: 0=Success, Negative (see error-crypt.h), ASN_SIG_CONFIRM_E */
- static int ConfirmSignature(SignatureCtx* sigCtx,
- const byte* buf, word32 bufSz,
- const byte* key, word32 keySz, word32 keyOID,
- const byte* sig, word32 sigSz, word32 sigOID,
- const byte* sigParams, word32 sigParamsSz,
- byte* rsaKeyIdx)
- {
- int ret = 0;
- #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
- CertAttribute* certatt = NULL;
- #endif
- if (sigCtx == NULL || buf == NULL || bufSz == 0 || key == NULL ||
- keySz == 0 || sig == NULL || sigSz == 0) {
- return BAD_FUNC_ARG;
- }
- (void)key;
- (void)keySz;
- (void)sig;
- (void)sigSz;
- (void)sigParams;
- (void)sigParamsSz;
- WOLFSSL_ENTER("ConfirmSignature");
- #if !defined(WOLFSSL_RENESAS_TSIP_TLS) && !defined(WOLFSSL_RENESAS_SCEPROTECT)
- (void)rsaKeyIdx;
- #else
- #if !defined(NO_RSA) || defined(HAVE_ECC)
- certatt = (CertAttribute*)&sigCtx->CertAtt;
- #endif
- if (certatt) {
- certatt->keyIndex = rsaKeyIdx;
- certatt->cert = buf;
- certatt->certSz = bufSz;
- }
- #endif
- #ifndef NO_ASN_CRYPT
- switch (sigCtx->state) {
- case SIG_STATE_BEGIN:
- {
- sigCtx->keyOID = keyOID; /* must set early for cleanup */
- sigCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, sigCtx->heap,
- DYNAMIC_TYPE_DIGEST);
- if (sigCtx->digest == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- #if !defined(NO_RSA) && defined(WC_RSA_PSS)
- /* RSA PSS Defaults */
- sigCtx->hash = WC_HASH_TYPE_SHA;
- sigCtx->mgf = WC_MGF1SHA1;
- sigCtx->saltLen = 20;
- #endif
- sigCtx->state = SIG_STATE_HASH;
- } /* SIG_STATE_BEGIN */
- FALL_THROUGH;
- case SIG_STATE_HASH:
- {
- #if !defined(NO_RSA) && defined(WC_RSA_PSS)
- if (sigOID == RSAPSSk) {
- word32 fakeSigOID = 0;
- ret = DecodeRsaPssParams(sigParams, sigParamsSz, &sigCtx->hash,
- &sigCtx->mgf, &sigCtx->saltLen);
- if (ret != 0) {
- goto exit_cs;
- }
- ret = RsaPssHashOidToSigOid(sigCtx->hash, &fakeSigOID);
- if (ret != 0) {
- goto exit_cs;
- }
- /* Decode parameters. */
- ret = HashForSignature(buf, bufSz, fakeSigOID, sigCtx->digest,
- &sigCtx->typeH, &sigCtx->digestSz, 1);
- if (ret != 0) {
- goto exit_cs;
- }
- }
- else
- #endif
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- if (sigOID == CTC_SM3wSM2) {
- ; /* SM2 hash requires public key. Done later. */
- }
- else
- #endif
- {
- ret = HashForSignature(buf, bufSz, sigOID, sigCtx->digest,
- &sigCtx->typeH, &sigCtx->digestSz, 1);
- if (ret != 0) {
- goto exit_cs;
- }
- }
- sigCtx->state = SIG_STATE_KEY;
- } /* SIG_STATE_HASH */
- FALL_THROUGH;
- case SIG_STATE_KEY:
- {
- switch (keyOID) {
- #ifndef NO_RSA
- #ifdef WC_RSA_PSS
- case RSAPSSk:
- #endif
- case RSAk:
- {
- word32 idx = 0;
- sigCtx->key.rsa = (RsaKey*)XMALLOC(sizeof(RsaKey),
- sigCtx->heap, DYNAMIC_TYPE_RSA);
- if (sigCtx->key.rsa == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if ((ret = wc_InitRsaKey_ex(sigCtx->key.rsa, sigCtx->heap,
- sigCtx->devId)) != 0) {
- goto exit_cs;
- }
- sigCtx->sigCpy = (byte*)XMALLOC(sigSz, sigCtx->heap,
- DYNAMIC_TYPE_SIGNATURE);
- if (sigCtx->sigCpy == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if (sigSz > MAX_ENCODED_SIG_SZ) {
- WOLFSSL_MSG("Verify Signature is too big");
- ERROR_OUT(BUFFER_E, exit_cs);
- }
- if ((ret = wc_RsaPublicKeyDecode(key, &idx, sigCtx->key.rsa,
- keySz)) != 0) {
- WOLFSSL_MSG("ASN Key decode error RSA");
- WOLFSSL_ERROR_VERBOSE(ret);
- goto exit_cs;
- }
- XMEMCPY(sigCtx->sigCpy, sig, sigSz);
- sigCtx->out = NULL;
- #ifdef WOLFSSL_ASYNC_CRYPT
- sigCtx->asyncDev = &sigCtx->key.rsa->asyncDev;
- #endif
- break;
- }
- #endif /* !NO_RSA */
- #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
- case DSAk:
- {
- word32 idx = 0;
- if (sigSz < DSA_MIN_SIG_SIZE) {
- WOLFSSL_MSG("Verify Signature is too small");
- ERROR_OUT(BUFFER_E, exit_cs);
- }
- sigCtx->key.dsa = (DsaKey*)XMALLOC(sizeof(DsaKey),
- sigCtx->heap, DYNAMIC_TYPE_DSA);
- if (sigCtx->key.dsa == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if ((ret = wc_InitDsaKey_h(sigCtx->key.dsa, sigCtx->heap)) != 0) {
- WOLFSSL_MSG("wc_InitDsaKey_h error");
- goto exit_cs;
- }
- sigCtx->sigCpy = (byte*)XMALLOC(sigSz,
- sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
- if (sigCtx->sigCpy == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if ((ret = wc_DsaPublicKeyDecode(key, &idx, sigCtx->key.dsa,
- keySz)) != 0) {
- WOLFSSL_MSG("ASN Key decode error DSA");
- WOLFSSL_ERROR_VERBOSE(ret);
- goto exit_cs;
- }
- if (sigSz != DSA_160_SIG_SIZE &&
- sigSz != DSA_256_SIG_SIZE) {
- /* Try to parse it as the contents of a bitstring */
- #ifdef WOLFSSL_SMALL_STACK
- mp_int* r;
- mp_int* s;
- #else
- mp_int r[1];
- mp_int s[1];
- #endif
- int rSz;
- int sSz;
- #ifdef WOLFSSL_SMALL_STACK
- r = (mp_int*)XMALLOC(sizeof(*r), sigCtx->heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (r == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- s = (mp_int*)XMALLOC(sizeof(*s), sigCtx->heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (s == NULL) {
- XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- #endif
- if ((ret = mp_init_multi(r, s, NULL, NULL, NULL, NULL)) != MP_OKAY) {
- goto exit_cs;
- }
- idx = 0;
- if (DecodeECC_DSA_Sig(sig + idx, sigSz - idx, r, s)
- != 0) {
- WOLFSSL_MSG("DSA Sig is in unrecognized or "
- "incorrect format");
- mp_free(r);
- mp_free(s);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
- }
- rSz = mp_unsigned_bin_size(r);
- sSz = mp_unsigned_bin_size(s);
- if (rSz + sSz > (int)sigSz) {
- WOLFSSL_MSG("DSA Sig is in unrecognized or "
- "incorrect format");
- mp_free(r);
- mp_free(s);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
- }
- if (mp_to_unsigned_bin(r, sigCtx->sigCpy) != MP_OKAY ||
- mp_to_unsigned_bin(s,
- sigCtx->sigCpy + rSz) != MP_OKAY) {
- WOLFSSL_MSG("DSA Sig is in unrecognized or "
- "incorrect format");
- mp_free(r);
- mp_free(s);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
- }
- mp_free(r);
- mp_free(s);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- }
- else {
- XMEMCPY(sigCtx->sigCpy, sig, sigSz);
- }
- break;
- }
- #endif /* !NO_DSA && !HAVE_SELFTEST */
- #ifdef HAVE_ECC
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- case SM2k:
- #endif
- case ECDSAk:
- {
- word32 idx = 0;
- #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
- defined(WC_ASYNC_ENABLE_ECC)
- ecc_nb_ctx_t* nbCtx;
- #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
- WC_ASYNC_ENABLE_ECC */
- sigCtx->verify = 0;
- sigCtx->key.ecc = (ecc_key*)XMALLOC(sizeof(ecc_key),
- sigCtx->heap, DYNAMIC_TYPE_ECC);
- if (sigCtx->key.ecc == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if ((ret = wc_ecc_init_ex(sigCtx->key.ecc, sigCtx->heap,
- sigCtx->devId)) < 0) {
- goto exit_cs;
- }
- #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
- defined(WC_ASYNC_ENABLE_ECC)
- nbCtx = (ecc_nb_ctx_t*)XMALLOC(sizeof(ecc_nb_ctx_t),
- sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (nbCtx == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- else {
- ret = wc_ecc_set_nonblock(sigCtx->key.ecc, nbCtx);
- if (ret != 0) {
- goto exit_cs;
- }
- }
- #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
- WC_ASYNC_ENABLE_ECC */
- ret = wc_EccPublicKeyDecode(key, &idx, sigCtx->key.ecc,
- keySz);
- if (ret < 0) {
- WOLFSSL_MSG("ASN Key import error ECC");
- WOLFSSL_ERROR_VERBOSE(ret);
- goto exit_cs;
- }
- #ifdef WOLFSSL_ASYNC_CRYPT
- sigCtx->asyncDev = &sigCtx->key.ecc->asyncDev;
- #endif
- break;
- }
- #endif /* HAVE_ECC */
- #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
- case ED25519k:
- {
- sigCtx->verify = 0;
- sigCtx->key.ed25519 = (ed25519_key*)XMALLOC(
- sizeof(ed25519_key), sigCtx->heap,
- DYNAMIC_TYPE_ED25519);
- if (sigCtx->key.ed25519 == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if ((ret = wc_ed25519_init_ex(sigCtx->key.ed25519,
- sigCtx->heap, sigCtx->devId)) < 0) {
- goto exit_cs;
- }
- if ((ret = wc_ed25519_import_public(key, keySz,
- sigCtx->key.ed25519)) < 0) {
- WOLFSSL_MSG("ASN Key import error ED25519");
- WOLFSSL_ERROR_VERBOSE(ret);
- goto exit_cs;
- }
- #ifdef WOLFSSL_ASYNC_CRYPT
- sigCtx->asyncDev = &sigCtx->key.ed25519->asyncDev;
- #endif
- break;
- }
- #endif
- #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
- case ED448k:
- {
- sigCtx->verify = 0;
- sigCtx->key.ed448 = (ed448_key*)XMALLOC(
- sizeof(ed448_key), sigCtx->heap,
- DYNAMIC_TYPE_ED448);
- if (sigCtx->key.ed448 == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if ((ret = wc_ed448_init(sigCtx->key.ed448)) < 0) {
- goto exit_cs;
- }
- if ((ret = wc_ed448_import_public(key, keySz,
- sigCtx->key.ed448)) < 0) {
- WOLFSSL_MSG("ASN Key import error ED448");
- WOLFSSL_ERROR_VERBOSE(ret);
- goto exit_cs;
- }
- #ifdef WOLFSSL_ASYNC_CRYPT
- sigCtx->asyncDev = &sigCtx->key.ed448->asyncDev;
- #endif
- break;
- }
- #endif
- #if defined(HAVE_PQC)
- #if defined(HAVE_FALCON)
- case FALCON_LEVEL1k:
- {
- sigCtx->verify = 0;
- sigCtx->key.falcon =
- (falcon_key*)XMALLOC(sizeof(falcon_key),
- sigCtx->heap,
- DYNAMIC_TYPE_FALCON);
- if (sigCtx->key.falcon == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
- goto exit_cs;
- }
- if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 1))
- < 0) {
- goto exit_cs;
- }
- if ((ret = wc_falcon_import_public(key, keySz,
- sigCtx->key.falcon)) < 0) {
- WOLFSSL_MSG("ASN Key import error Falcon Level 1");
- WOLFSSL_ERROR_VERBOSE(ret);
- goto exit_cs;
- }
- break;
- }
- case FALCON_LEVEL5k:
- {
- sigCtx->verify = 0;
- sigCtx->key.falcon =
- (falcon_key*)XMALLOC(sizeof(falcon_key),
- sigCtx->heap,
- DYNAMIC_TYPE_FALCON);
- if (sigCtx->key.falcon == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
- goto exit_cs;
- }
- if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 5))
- < 0) {
- goto exit_cs;
- }
- if ((ret = wc_falcon_import_public(key, keySz,
- sigCtx->key.falcon)) < 0) {
- WOLFSSL_MSG("ASN Key import error Falcon Level 5");
- WOLFSSL_ERROR_VERBOSE(ret);
- goto exit_cs;
- }
- break;
- }
- #endif /* HAVE_FALCON */
- #if defined(HAVE_DILITHIUM)
- case DILITHIUM_LEVEL2k:
- {
- sigCtx->verify = 0;
- sigCtx->key.dilithium =
- (dilithium_key*)XMALLOC(sizeof(dilithium_key),
- sigCtx->heap,
- DYNAMIC_TYPE_DILITHIUM);
- if (sigCtx->key.dilithium == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
- goto exit_cs;
- }
- if ((ret = wc_dilithium_set_level(
- sigCtx->key.dilithium, 2))
- < 0) {
- goto exit_cs;
- }
- if ((ret = wc_dilithium_import_public(key, keySz,
- sigCtx->key.dilithium)) < 0) {
- WOLFSSL_MSG("ASN Key import error Dilithium Level 2");
- goto exit_cs;
- }
- break;
- }
- case DILITHIUM_LEVEL3k:
- {
- sigCtx->verify = 0;
- sigCtx->key.dilithium =
- (dilithium_key*)XMALLOC(sizeof(dilithium_key),
- sigCtx->heap,
- DYNAMIC_TYPE_DILITHIUM);
- if (sigCtx->key.dilithium == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
- goto exit_cs;
- }
- if ((ret = wc_dilithium_set_level(
- sigCtx->key.dilithium, 3))
- < 0) {
- goto exit_cs;
- }
- if ((ret = wc_dilithium_import_public(key, keySz,
- sigCtx->key.dilithium)) < 0) {
- WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
- goto exit_cs;
- }
- break;
- }
- case DILITHIUM_LEVEL5k:
- {
- sigCtx->verify = 0;
- sigCtx->key.dilithium =
- (dilithium_key*)XMALLOC(sizeof(dilithium_key),
- sigCtx->heap,
- DYNAMIC_TYPE_DILITHIUM);
- if (sigCtx->key.dilithium == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
- goto exit_cs;
- }
- if ((ret = wc_dilithium_set_level(
- sigCtx->key.dilithium, 5))
- < 0) {
- goto exit_cs;
- }
- if ((ret = wc_dilithium_import_public(key, keySz,
- sigCtx->key.dilithium)) < 0) {
- WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
- goto exit_cs;
- }
- break;
- }
- #endif /* HAVE_DILITHIUM */
- #if defined(HAVE_SPHINCS)
- case SPHINCS_FAST_LEVEL1k:
- {
- sigCtx->verify = 0;
- sigCtx->key.sphincs =
- (sphincs_key*)XMALLOC(sizeof(sphincs_key),
- sigCtx->heap,
- DYNAMIC_TYPE_SPHINCS);
- if (sigCtx->key.sphincs == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
- goto exit_cs;
- }
- if ((ret = wc_sphincs_set_level_and_optim(
- sigCtx->key.sphincs, 1, FAST_VARIANT))
- < 0) {
- goto exit_cs;
- }
- if ((ret = wc_sphincs_import_public(key, keySz,
- sigCtx->key.sphincs)) < 0) {
- WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
- goto exit_cs;
- }
- break;
- }
- case SPHINCS_FAST_LEVEL3k:
- {
- sigCtx->verify = 0;
- sigCtx->key.sphincs =
- (sphincs_key*)XMALLOC(sizeof(sphincs_key),
- sigCtx->heap,
- DYNAMIC_TYPE_SPHINCS);
- if (sigCtx->key.sphincs == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
- goto exit_cs;
- }
- if ((ret = wc_sphincs_set_level_and_optim(
- sigCtx->key.sphincs, 3, FAST_VARIANT))
- < 0) {
- goto exit_cs;
- }
- if ((ret = wc_sphincs_import_public(key, keySz,
- sigCtx->key.sphincs)) < 0) {
- WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
- goto exit_cs;
- }
- break;
- }
- case SPHINCS_FAST_LEVEL5k:
- {
- sigCtx->verify = 0;
- sigCtx->key.sphincs =
- (sphincs_key*)XMALLOC(sizeof(sphincs_key),
- sigCtx->heap,
- DYNAMIC_TYPE_SPHINCS);
- if (sigCtx->key.sphincs == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
- goto exit_cs;
- }
- if ((ret = wc_sphincs_set_level_and_optim(
- sigCtx->key.sphincs, 5, FAST_VARIANT))
- < 0) {
- goto exit_cs;
- }
- if ((ret = wc_sphincs_import_public(key, keySz,
- sigCtx->key.sphincs)) < 0) {
- WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
- goto exit_cs;
- }
- break;
- }
- case SPHINCS_SMALL_LEVEL1k:
- {
- sigCtx->verify = 0;
- sigCtx->key.sphincs =
- (sphincs_key*)XMALLOC(sizeof(sphincs_key),
- sigCtx->heap,
- DYNAMIC_TYPE_SPHINCS);
- if (sigCtx->key.sphincs == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
- goto exit_cs;
- }
- if ((ret = wc_sphincs_set_level_and_optim(
- sigCtx->key.sphincs, 1, SMALL_VARIANT))
- < 0) {
- goto exit_cs;
- }
- if ((ret = wc_sphincs_import_public(key, keySz,
- sigCtx->key.sphincs)) < 0) {
- WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
- goto exit_cs;
- }
- break;
- }
- case SPHINCS_SMALL_LEVEL3k:
- {
- sigCtx->verify = 0;
- sigCtx->key.sphincs =
- (sphincs_key*)XMALLOC(sizeof(sphincs_key),
- sigCtx->heap,
- DYNAMIC_TYPE_SPHINCS);
- if (sigCtx->key.sphincs == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
- goto exit_cs;
- }
- if ((ret = wc_sphincs_set_level_and_optim(
- sigCtx->key.sphincs, 3, SMALL_VARIANT))
- < 0) {
- goto exit_cs;
- }
- if ((ret = wc_sphincs_import_public(key, keySz,
- sigCtx->key.sphincs)) < 0) {
- WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
- goto exit_cs;
- }
- break;
- }
- case SPHINCS_SMALL_LEVEL5k:
- {
- sigCtx->verify = 0;
- sigCtx->key.sphincs =
- (sphincs_key*)XMALLOC(sizeof(sphincs_key),
- sigCtx->heap,
- DYNAMIC_TYPE_SPHINCS);
- if (sigCtx->key.sphincs == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
- goto exit_cs;
- }
- if ((ret = wc_sphincs_set_level_and_optim(
- sigCtx->key.sphincs, 5, SMALL_VARIANT))
- < 0) {
- goto exit_cs;
- }
- if ((ret = wc_sphincs_import_public(key, keySz,
- sigCtx->key.sphincs)) < 0) {
- WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
- goto exit_cs;
- }
- break;
- }
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- default:
- WOLFSSL_MSG("Verify Key type unknown");
- ret = ASN_UNKNOWN_OID_E;
- WOLFSSL_ERROR_VERBOSE(ret);
- break;
- } /* switch (keyOID) */
- if (ret != 0) {
- goto exit_cs;
- }
- sigCtx->state = SIG_STATE_DO;
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (sigCtx->devId != INVALID_DEVID && sigCtx->asyncDev && sigCtx->asyncCtx) {
- /* make sure event is initialized */
- WOLF_EVENT* event = &sigCtx->asyncDev->event;
- ret = wolfAsync_EventInit(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL,
- sigCtx->asyncCtx, WC_ASYNC_FLAG_CALL_AGAIN);
- }
- #endif
- } /* SIG_STATE_KEY */
- FALL_THROUGH;
- case SIG_STATE_DO:
- {
- switch (keyOID) {
- #ifndef NO_RSA
- case RSAk:
- #ifdef WC_RSA_PSS
- case RSAPSSk:
- if (sigOID == RSAPSSk) {
- /* TODO: pkCbRsaPss - RSA PSS callback. */
- ret = wc_RsaPSS_VerifyInline_ex(sigCtx->sigCpy, sigSz,
- &sigCtx->out, sigCtx->hash, sigCtx->mgf,
- sigCtx->saltLen, sigCtx->key.rsa);
- }
- else
- #endif
- {
- #if defined(HAVE_PK_CALLBACKS)
- if (sigCtx->pkCbRsa) {
- ret = sigCtx->pkCbRsa(
- sigCtx->sigCpy, sigSz, &sigCtx->out,
- key, keySz,
- sigCtx->pkCtxRsa);
- }
- #if !defined(WOLFSSL_RENESAS_SCEPROTECT) && \
- !defined(WOLFSSL_RENESAS_TSIP_TLS)
- else
- #else
- if (!sigCtx->pkCbRsa || ret == CRYPTOCB_UNAVAILABLE)
- #endif /* WOLFSSL_RENESAS_SCEPROTECT */
- #endif /* HAVE_PK_CALLBACKS */
- {
- ret = wc_RsaSSL_VerifyInline(sigCtx->sigCpy, sigSz,
- &sigCtx->out, sigCtx->key.rsa);
- }
- }
- break;
- #endif /* !NO_RSA */
- #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
- case DSAk:
- {
- ret = wc_DsaVerify(sigCtx->digest, sigCtx->sigCpy,
- sigCtx->key.dsa, &sigCtx->verify);
- break;
- }
- #endif /* !NO_DSA && !HAVE_SELFTEST */
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- case SM2k:
- {
- /* OpenSSL creates signature without CERT_SIG_ID. */
- ret = wc_ecc_sm2_create_digest(CERT_SIG_ID, 0, buf, bufSz,
- WC_HASH_TYPE_SM3, sigCtx->digest, WC_SM3_DIGEST_SIZE,
- sigCtx->key.ecc);
- if (ret == 0) {
- sigCtx->typeH = SM3h;
- sigCtx->digestSz = WC_SM3_DIGEST_SIZE;
- }
- else {
- WOLFSSL_MSG("SM2wSM3 create digest failed");
- WOLFSSL_ERROR_VERBOSE(ret);
- goto exit_cs;
- }
- ret = wc_ecc_sm2_verify_hash(sig, sigSz, sigCtx->digest,
- sigCtx->digestSz, &sigCtx->verify, sigCtx->key.ecc);
- break;
- }
- #endif
- #if defined(HAVE_ECC) && defined(HAVE_ECC_VERIFY)
- case ECDSAk:
- {
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- if (sigOID == CTC_SM3wSM2) {
- ret = wc_ecc_sm2_create_digest(CERT_SIG_ID,
- CERT_SIG_ID_SZ, buf, bufSz, WC_HASH_TYPE_SM3,
- sigCtx->digest, WC_SM3_DIGEST_SIZE,
- sigCtx->key.ecc);
- if (ret == 0) {
- sigCtx->typeH = SM3h;
- sigCtx->digestSz = WC_SM3_DIGEST_SIZE;
- }
- else {
- WOLFSSL_MSG("SM2wSM3 create digest failed");
- WOLFSSL_ERROR_VERBOSE(ret);
- goto exit_cs;
- }
- ret = wc_ecc_sm2_verify_hash(sig, sigSz, sigCtx->digest,
- sigCtx->digestSz, &sigCtx->verify, sigCtx->key.ecc);
- }
- else
- #endif
- #if defined(HAVE_PK_CALLBACKS)
- if (sigCtx->pkCbEcc) {
- ret = sigCtx->pkCbEcc(
- sig, sigSz,
- sigCtx->digest, (unsigned int)sigCtx->digestSz,
- key, keySz, &sigCtx->verify,
- sigCtx->pkCtxEcc);
- }
- #if !defined(WOLFSSL_RENESAS_SCEPROTECT) && \
- !defined(WOLFSSL_RENESAS_TSIP_TLS)
- else
- #else
- if (!sigCtx->pkCbEcc || ret == CRYPTOCB_UNAVAILABLE)
- #endif /* WOLFSSL_RENESAS_SCEPROTECT */
- #endif /* HAVE_PK_CALLBACKS */
- {
- ret = wc_ecc_verify_hash(sig, sigSz, sigCtx->digest,
- (word32)sigCtx->digestSz, &sigCtx->verify,
- sigCtx->key.ecc);
- }
- break;
- }
- #endif /* HAVE_ECC */
- #if defined(HAVE_ED25519) && defined(HAVE_ED25519_VERIFY)
- case ED25519k:
- {
- ret = wc_ed25519_verify_msg(sig, sigSz, buf, bufSz,
- &sigCtx->verify, sigCtx->key.ed25519);
- break;
- }
- #endif
- #if defined(HAVE_ED448) && defined(HAVE_ED448_VERIFY)
- case ED448k:
- {
- ret = wc_ed448_verify_msg(sig, sigSz, buf, bufSz,
- &sigCtx->verify, sigCtx->key.ed448,
- NULL, 0);
- break;
- }
- #endif
- #if defined(HAVE_PQC)
- #if defined(HAVE_FALCON)
- case FALCON_LEVEL1k:
- case FALCON_LEVEL5k:
- {
- ret = wc_falcon_verify_msg(sig, sigSz, buf, bufSz,
- &sigCtx->verify,
- sigCtx->key.falcon);
- break;
- }
- #endif /* HAVE_FALCON */
- #if defined(HAVE_DILITHIUM)
- case DILITHIUM_LEVEL2k:
- case DILITHIUM_LEVEL3k:
- case DILITHIUM_LEVEL5k:
- {
- ret = wc_dilithium_verify_msg(sig, sigSz, buf, bufSz,
- &sigCtx->verify,
- sigCtx->key.dilithium);
- break;
- }
- #endif /* HAVE_DILITHIUM */
- #if defined(HAVE_SPHINCS)
- case SPHINCS_FAST_LEVEL1k:
- case SPHINCS_FAST_LEVEL3k:
- case SPHINCS_FAST_LEVEL5k:
- case SPHINCS_SMALL_LEVEL1k:
- case SPHINCS_SMALL_LEVEL3k:
- case SPHINCS_SMALL_LEVEL5k:
- {
- ret = wc_sphincs_verify_msg(sig, sigSz, buf, bufSz,
- &sigCtx->verify,
- sigCtx->key.sphincs);
- break;
- }
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- default:
- break;
- } /* switch (keyOID) */
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- goto exit_cs;
- }
- #endif
- if (ret < 0) {
- /* treat all errors as ASN_SIG_CONFIRM_E */
- ret = ASN_SIG_CONFIRM_E;
- WOLFSSL_ERROR_VERBOSE(ret);
- goto exit_cs;
- }
- sigCtx->state = SIG_STATE_CHECK;
- } /* SIG_STATE_DO */
- FALL_THROUGH;
- case SIG_STATE_CHECK:
- {
- switch (keyOID) {
- #ifndef NO_RSA
- case RSAk:
- #ifdef WC_RSA_PSS
- case RSAPSSk:
- if (sigOID == RSAPSSk) {
- #if (defined(HAVE_SELFTEST) && \
- (!defined(HAVE_SELFTEST_VERSION) || \
- (HAVE_SELFTEST_VERSION < 2))) || \
- (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
- (HAVE_FIPS_VERSION < 2))
- ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
- sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
- sigCtx->saltLen);
- #elif (defined(HAVE_SELFTEST) && \
- (HAVE_SELFTEST_VERSION == 2)) || \
- (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
- (HAVE_FIPS_VERSION == 2))
- ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
- sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
- sigCtx->saltLen, 0);
- #else
- ret = wc_RsaPSS_CheckPadding_ex2(sigCtx->digest,
- (word32)sigCtx->digestSz, sigCtx->out, (word32)ret, sigCtx->hash,
- sigCtx->saltLen, wc_RsaEncryptSize(sigCtx->key.rsa) * 8,
- sigCtx->heap);
- #endif
- break;
- }
- else
- #endif
- {
- int encodedSigSz, verifySz;
- #if defined(WOLFSSL_RENESAS_TSIP_TLS) || \
- defined(WOLFSSL_RENESAS_SCEPROTECT)
- if (sigCtx->CertAtt.verifyByTSIP_SCE == 1) break;
- #endif
- #ifdef WOLFSSL_SMALL_STACK
- byte* encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
- sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (encodedSig == NULL) {
- ERROR_OUT(MEMORY_E, exit_cs);
- }
- #else
- byte encodedSig[MAX_ENCODED_SIG_SZ];
- #endif
- verifySz = ret;
- /* make sure we're right justified */
- encodedSigSz = (int)wc_EncodeSignature(encodedSig,
- sigCtx->digest, (word32)sigCtx->digestSz,
- sigCtx->typeH);
- if (encodedSigSz == verifySz && sigCtx->out != NULL &&
- XMEMCMP(sigCtx->out, encodedSig,
- (size_t)encodedSigSz) == 0) {
- ret = 0;
- }
- else {
- WOLFSSL_MSG("RSA SSL verify match encode error");
- ret = ASN_SIG_CONFIRM_E;
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(encodedSig, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- break;
- }
- #endif /* NO_RSA */
- #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
- case DSAk:
- {
- if (sigCtx->verify == 1) {
- ret = 0;
- }
- else {
- WOLFSSL_MSG("DSA Verify didn't match");
- ret = ASN_SIG_CONFIRM_E;
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- break;
- }
- #endif /* !NO_DSA && !HAVE_SELFTEST */
- #ifdef HAVE_ECC
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- case SM2k:
- #endif
- case ECDSAk:
- {
- if (sigCtx->verify == 1) {
- ret = 0;
- }
- else {
- WOLFSSL_MSG("ECC Verify didn't match");
- ret = ASN_SIG_CONFIRM_E;
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- break;
- }
- #endif /* HAVE_ECC */
- #ifdef HAVE_ED25519
- case ED25519k:
- {
- if (sigCtx->verify == 1) {
- ret = 0;
- }
- else {
- WOLFSSL_MSG("ED25519 Verify didn't match");
- ret = ASN_SIG_CONFIRM_E;
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- break;
- }
- #endif /* HAVE_ED25519 */
- #ifdef HAVE_ED448
- case ED448k:
- {
- if (sigCtx->verify == 1) {
- ret = 0;
- }
- else {
- WOLFSSL_MSG("ED448 Verify didn't match");
- ret = ASN_SIG_CONFIRM_E;
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- break;
- }
- #endif /* HAVE_ED448 */
- #ifdef HAVE_PQC
- #ifdef HAVE_FALCON
- case FALCON_LEVEL1k:
- {
- if (sigCtx->verify == 1) {
- ret = 0;
- }
- else {
- WOLFSSL_MSG("FALCON_LEVEL1 Verify didn't match");
- ret = ASN_SIG_CONFIRM_E;
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- break;
- }
- case FALCON_LEVEL5k:
- {
- if (sigCtx->verify == 1) {
- ret = 0;
- }
- else {
- WOLFSSL_MSG("FALCON_LEVEL5 Verify didn't match");
- ret = ASN_SIG_CONFIRM_E;
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- break;
- }
- #endif /* HAVE_FALCON */
- #ifdef HAVE_DILITHIUM
- case DILITHIUM_LEVEL2k:
- {
- if (sigCtx->verify == 1) {
- ret = 0;
- }
- else {
- WOLFSSL_MSG("DILITHIUM_LEVEL2 Verify didn't match");
- ret = ASN_SIG_CONFIRM_E;
- }
- break;
- }
- case DILITHIUM_LEVEL3k:
- {
- if (sigCtx->verify == 1) {
- ret = 0;
- }
- else {
- WOLFSSL_MSG("DILITHIUM_LEVEL3 Verify didn't match");
- ret = ASN_SIG_CONFIRM_E;
- }
- break;
- }
- case DILITHIUM_LEVEL5k:
- {
- if (sigCtx->verify == 1) {
- ret = 0;
- }
- else {
- WOLFSSL_MSG("DILITHIUM_LEVEL5 Verify didn't match");
- ret = ASN_SIG_CONFIRM_E;
- }
- break;
- }
- #endif /* HAVE_DILITHIUM */
- #ifdef HAVE_SPHINCS
- case SPHINCS_FAST_LEVEL1k:
- {
- if (sigCtx->verify == 1) {
- ret = 0;
- }
- else {
- WOLFSSL_MSG("SPHINCS_FAST_LEVEL1 Verify didn't match");
- ret = ASN_SIG_CONFIRM_E;
- }
- break;
- }
- case SPHINCS_FAST_LEVEL3k:
- {
- if (sigCtx->verify == 1) {
- ret = 0;
- }
- else {
- WOLFSSL_MSG("SPHINCS_FAST_LEVEL3 Verify didn't match");
- ret = ASN_SIG_CONFIRM_E;
- }
- break;
- }
- case SPHINCS_FAST_LEVEL5k:
- {
- if (sigCtx->verify == 1) {
- ret = 0;
- }
- else {
- WOLFSSL_MSG("SPHINCS_FAST_LEVEL5 Verify didn't match");
- ret = ASN_SIG_CONFIRM_E;
- }
- break;
- }
- case SPHINCS_SMALL_LEVEL1k:
- {
- if (sigCtx->verify == 1) {
- ret = 0;
- }
- else {
- WOLFSSL_MSG("SPHINCS_SMALL_LEVEL1 Verify didn't match");
- ret = ASN_SIG_CONFIRM_E;
- }
- break;
- }
- case SPHINCS_SMALL_LEVEL3k:
- {
- if (sigCtx->verify == 1) {
- ret = 0;
- }
- else {
- WOLFSSL_MSG("SPHINCS_SMALL_LEVEL3 Verify didn't match");
- ret = ASN_SIG_CONFIRM_E;
- }
- break;
- }
- case SPHINCS_SMALL_LEVEL5k:
- {
- if (sigCtx->verify == 1) {
- ret = 0;
- }
- else {
- WOLFSSL_MSG("SPHINCS_SMALL_LEVEL5 Verify didn't match");
- ret = ASN_SIG_CONFIRM_E;
- }
- break;
- }
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- default:
- break;
- } /* switch (keyOID) */
- break;
- } /* SIG_STATE_CHECK */
- default:
- break;
- } /* switch (sigCtx->state) */
- exit_cs:
- #endif /* !NO_ASN_CRYPT */
- (void)keyOID;
- (void)sigOID;
- WOLFSSL_LEAVE("ConfirmSignature", ret);
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E)
- return ret;
- #endif
- FreeSignatureCtx(sigCtx);
- return ret;
- }
- #ifndef IGNORE_NAME_CONSTRAINTS
- static int MatchBaseName(int type, const char* name, int nameSz,
- const char* base, int baseSz)
- {
- if (base == NULL || baseSz <= 0 || name == NULL || nameSz <= 0 ||
- name[0] == '.' || nameSz < baseSz ||
- (type != ASN_RFC822_TYPE && type != ASN_DNS_TYPE &&
- type != ASN_DIR_TYPE)) {
- return 0;
- }
- if (type == ASN_DIR_TYPE)
- return XMEMCMP(name, base, (size_t)baseSz) == 0;
- /* If an email type, handle special cases where the base is only
- * a domain, or is an email address itself. */
- if (type == ASN_RFC822_TYPE) {
- const char* p = NULL;
- int count = 0;
- if (base[0] != '.') {
- p = base;
- count = 0;
- /* find the '@' in the base */
- while (*p != '@' && count < baseSz) {
- count++;
- p++;
- }
- /* No '@' in base, reset p to NULL */
- if (count >= baseSz)
- p = NULL;
- }
- if (p == NULL) {
- /* Base isn't an email address, it is a domain name,
- * wind the name forward one character past its '@'. */
- p = name;
- count = 0;
- while (*p != '@' && count < baseSz) {
- count++;
- p++;
- }
- if (count < baseSz && *p == '@') {
- name = p + 1;
- nameSz -= count + 1;
- }
- }
- }
- /* RFC 5280 section 4.2.1.10
- * "...Any DNS name that can be constructed by simply adding zero or more
- * labels to the left-hand side of the name satisfies the name constraint."
- * i.e www.host.example.com works for host.example.com name constraint and
- * host1.example.com does not. */
- if (type == ASN_DNS_TYPE || (type == ASN_RFC822_TYPE && base[0] == '.')) {
- int szAdjust = nameSz - baseSz;
- name += szAdjust;
- nameSz -= szAdjust;
- }
- while (nameSz > 0) {
- if (XTOLOWER((unsigned char)*name++) !=
- XTOLOWER((unsigned char)*base++))
- return 0;
- nameSz--;
- }
- return 1;
- }
- /* Search through the list to find if the name is permitted.
- * name The DNS name to search for
- * dnsList The list to search through
- * nameType Type of DNS name to currently searching
- * return 1 if found in list or if not needed
- * return 0 if not found in the list but is needed
- */
- static int PermittedListOk(DNS_entry* name, Base_entry* dnsList, byte nameType)
- {
- Base_entry* current = dnsList;
- int match = 0;
- int need = 0;
- int ret = 1; /* is ok unless needed and no match found */
- while (current != NULL) {
- if (current->type == nameType) {
- need = 1; /* restriction on permitted names is set for this type */
- if (name->len >= current->nameSz &&
- MatchBaseName(nameType, name->name, name->len,
- current->name, current->nameSz)) {
- match = 1; /* found the current name in the permitted list*/
- break;
- }
- }
- current = current->next;
- }
- /* check if permitted name restriction was set and no matching name found */
- if (need && !match)
- ret = 0;
- return ret;
- }
- /* Search through the list to find if the name is excluded.
- * name The DNS name to search for
- * dnsList The list to search through
- * nameType Type of DNS name to currently searching
- * return 1 if found in list and 0 if not found in the list
- */
- static int IsInExcludedList(DNS_entry* name, Base_entry* dnsList, byte nameType)
- {
- int ret = 0; /* default of not found in the list */
- Base_entry* current = dnsList;
- while (current != NULL) {
- if (current->type == nameType) {
- if (name->len >= current->nameSz &&
- MatchBaseName(nameType, name->name, name->len,
- current->name, current->nameSz)) {
- ret = 1;
- break;
- }
- }
- current = current->next;
- }
- return ret;
- }
- static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert)
- {
- const byte nameTypes[] = {ASN_RFC822_TYPE, ASN_DNS_TYPE, ASN_DIR_TYPE};
- int i;
- if (signer == NULL || cert == NULL)
- return 0;
- if (signer->excludedNames == NULL && signer->permittedNames == NULL)
- return 1;
- for (i=0; i < (int)sizeof(nameTypes); i++) {
- byte nameType = nameTypes[i];
- DNS_entry* name = NULL;
- DNS_entry subjectDnsName; /* temporary node used for subject name */
- XMEMSET(&subjectDnsName, 0, sizeof(DNS_entry));
- switch (nameType) {
- case ASN_DNS_TYPE:
- /* Should it also consider CN in subject? It could use
- * subjectDnsName too */
- name = cert->altNames;
- break;
- case ASN_RFC822_TYPE:
- /* Shouldn't it validade E= in subject as well? */
- name = cert->altEmailNames;
- /* Add subject email for checking. */
- if (cert->subjectEmail != NULL) {
- /* RFC 5280 section 4.2.1.10
- * "When constraints are imposed on the rfc822Name name
- * form, but the certificate does not include a subject
- * alternative name, the rfc822Name constraint MUST be
- * applied to the attribute of type emailAddress in the
- * subject distinguished name" */
- subjectDnsName.next = NULL;
- subjectDnsName.type = ASN_RFC822_TYPE;
- subjectDnsName.len = cert->subjectEmailLen;
- subjectDnsName.name = (char *)cert->subjectEmail;
- }
- break;
- case ASN_DIR_TYPE:
- #ifndef WOLFSSL_NO_ASN_STRICT
- name = cert->altDirNames;
- #endif
- /* RFC 5280 section 4.2.1.10
- "Restrictions of the form directoryName MUST be
- applied to the subject field .... and to any names
- of type directoryName in the subjectAltName
- extension"
- */
- if (cert->subjectRaw != NULL) {
- subjectDnsName.next = NULL;
- subjectDnsName.type = ASN_DIR_TYPE;
- subjectDnsName.len = cert->subjectRawLen;
- subjectDnsName.name = (char *)cert->subjectRaw;
- }
- break;
- default:
- /* Other types of names are ignored for now.
- * Shouldn't it be rejected if it there is a altNamesByType[nameType]
- * and signer->extNameConstraintCrit is set? */
- return 0;
- }
- while (name != NULL) {
- if (IsInExcludedList(name, signer->excludedNames, nameType) == 1) {
- WOLFSSL_MSG("Excluded name was found!");
- return 0;
- }
- /* Check against the permitted list */
- if (PermittedListOk(name, signer->permittedNames, nameType) != 1) {
- WOLFSSL_MSG("Permitted name was not found!");
- return 0;
- }
- name = name->next;
- }
- /* handle comparing against subject name too */
- if (subjectDnsName.len > 0 && subjectDnsName.name != NULL) {
- if (IsInExcludedList(&subjectDnsName, signer->excludedNames,
- nameType) == 1) {
- WOLFSSL_MSG("Excluded name was found!");
- return 0;
- }
- /* Check against the permitted list */
- if (PermittedListOk(&subjectDnsName, signer->permittedNames,
- nameType) != 1) {
- WOLFSSL_MSG("Permitted name was not found!");
- return 0;
- }
- }
- }
- return 1;
- }
- #endif /* IGNORE_NAME_CONSTRAINTS */
- #ifndef WOLFSSL_ASN_TEMPLATE
- static void AddAltName(DecodedCert* cert, DNS_entry* dnsEntry)
- {
- #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
- dnsEntry->next = NULL;
- if (cert->altNames == NULL) {
- /* First on list */
- cert->altNames = dnsEntry;
- }
- else {
- DNS_entry* temp = cert->altNames;
- /* Find end */
- for (; (temp->next != NULL); temp = temp->next);
- /* Add to end */
- temp->next = dnsEntry;
- }
- #else
- dnsEntry->next = cert->altNames;
- cert->altNames = dnsEntry;
- #endif
- }
- #endif
- #ifdef WOLFSSL_ASN_TEMPLATE
- #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
- /* ASN.1 template for OtherName of an X.509 certificate.
- * X.509: RFC 5280, 4.2.1.6 - OtherName (without implicit outer SEQUENCE).
- * HW Name: RFC 4108, 5 - Hardware Module Name
- * Only support HW Name where the type is a HW serial number.
- *
- * Other Names handled for FPKI (Federal PKI) use:
- * UPN (Universal Principal Name), a non-standard Other Name
- * (RFC3280 sec 4.2.1.7). Often used with FIPS 201 smartcard login.
- * FASC-N (Federal Agency Smart Credential Number), defined in the document
- * fpki-x509-cert-policy-common.pdf. Used for a smart card ID.
- */
- static const ASNItem otherNameASN[] = {
- /* TYPEID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
- /* VALUE */ { 0, ASN_CONTEXT_SPECIFIC | ASN_OTHERNAME_VALUE, 1, 1, 0 },
- /* UPN */ { 1, ASN_UTF8STRING, 0, 0, 2 },
- /* FASC-N */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
- /* HWN_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 2 },
- /* HWN_TYPE */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
- /* HWN_NUM */ { 2, ASN_OCTET_STRING, 0, 0, 0 }
- };
- enum {
- OTHERNAMEASN_IDX_TYPEID = 0,
- OTHERNAMEASN_IDX_VALUE,
- OTHERNAMEASN_IDX_UPN,
- OTHERNAMEASN_IDX_FASCN,
- OTHERNAMEASN_IDX_HWN_SEQ,
- OTHERNAMEASN_IDX_HWN_TYPE,
- OTHERNAMEASN_IDX_HWN_NUM
- };
- /* Number of items in ASN.1 template for OtherName of an X.509 certificate. */
- #define otherNameASN_Length (sizeof(otherNameASN) / sizeof(ASNItem))
- #ifdef WOLFSSL_SEP
- static int DecodeSEP(ASNGetData* dataASN, DecodedCert* cert)
- {
- int ret = 0;
- word32 oidLen, serialLen;
- oidLen = dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.length;
- serialLen = dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.length;
- /* Allocate space for HW type OID. */
- cert->hwType = (byte*)XMALLOC(oidLen, cert->heap,
- DYNAMIC_TYPE_X509_EXT);
- if (cert->hwType == NULL)
- ret = MEMORY_E;
- if (ret == 0) {
- /* Copy, into cert HW type OID */
- XMEMCPY(cert->hwType,
- dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.data, oidLen);
- cert->hwTypeSz = (int)oidLen;
- /* TODO: check this is the HW serial number OID - no test data. */
- /* Allocate space for HW serial number, +1 for null terminator. */
- cert->hwSerialNum = (byte*)XMALLOC(serialLen + 1, cert->heap,
- DYNAMIC_TYPE_X509_EXT);
- if (cert->hwSerialNum == NULL) {
- WOLFSSL_MSG("\tOut of Memory");
- ret = MEMORY_E;
- }
- }
- if (ret == 0) {
- /* Copy into cert HW serial number. */
- XMEMCPY(cert->hwSerialNum,
- dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.data, serialLen);
- cert->hwSerialNum[serialLen] = '\0';
- cert->hwSerialNumSz = (int)serialLen;
- }
- return ret;
- }
- #endif /* WOLFSSL_SEP */
- static int DecodeOtherHelper(ASNGetData* dataASN, DecodedCert* cert, int oid)
- {
- DNS_entry* entry = NULL;
- int ret = 0;
- word32 bufLen = 0;
- const char* buf = NULL;
- switch (oid) {
- #ifdef WOLFSSL_FPKI
- case FASCN_OID:
- bufLen = dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.length;
- buf = (const char*)dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.data;
- break;
- #endif /* WOLFSSL_FPKI */
- case UPN_OID:
- bufLen = dataASN[OTHERNAMEASN_IDX_UPN].data.ref.length;
- buf = (const char*)dataASN[OTHERNAMEASN_IDX_UPN].data.ref.data;
- break;
- default:
- WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
- ret = ASN_UNKNOWN_OID_E;
- break;
- }
- if (ret == 0) {
- ret = SetDNSEntry(cert, buf, (int)bufLen, ASN_OTHER_TYPE, &entry);
- if (ret == 0) {
- #ifdef WOLFSSL_FPKI
- entry->oidSum = oid;
- #endif
- AddDNSEntryToList(&cert->altNames, entry);
- }
- }
- return ret;
- }
- /* Decode data with OtherName format from after implicit SEQUENCE.
- *
- * @param [in, out] cert Certificate object.
- * @param [in] input Buffer containing encoded OtherName.
- * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
- * On out, index after OtherName.
- * @param [in] maxIdx Maximum index of data in buffer.
- * @return 0 on success.
- * @return MEMORY_E on dynamic memory allocation failure.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return ASN_PARSE_E when OID does is not HW Name.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- * @return BUFFER_E when data in buffer is too small.
- */
- static int DecodeOtherName(DecodedCert* cert, const byte* input,
- word32* inOutIdx, word32 maxIdx)
- {
- DECL_ASNGETDATA(dataASN, otherNameASN_Length);
- int ret = 0;
- CALLOC_ASNGETDATA(dataASN, otherNameASN_Length, ret, cert->heap);
- if (ret == 0) {
- /* Check the first OID is a recognized Alt Cert Name type. */
- GetASN_OID(&dataASN[OTHERNAMEASN_IDX_TYPEID], oidCertAltNameType);
- /* Parse OtherName. */
- ret = GetASN_Items(otherNameASN, dataASN, otherNameASN_Length, 1, input,
- inOutIdx, maxIdx);
- }
- if (ret == 0) {
- /* Ensure expected OID. */
- switch (dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum) {
- #ifdef WOLFSSL_SEP
- case HW_NAME_OID:
- /* Only support HW serial number. */
- GetASN_OID(&dataASN[OTHERNAMEASN_IDX_HWN_TYPE], oidIgnoreType);
- ret = DecodeSEP(dataASN, cert);
- break;
- #endif /* WOLFSSL_SEP */
- #ifdef WOLFSSL_FPKI
- case FASCN_OID:
- #endif /* WOLFSSL_FPKI */
- case UPN_OID:
- ret = DecodeOtherHelper(dataASN, cert,
- (int)dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum);
- break;
- default:
- WOLFSSL_MSG("\tunsupported OID skipping");
- break;
- }
- }
- FREE_ASNGETDATA(dataASN, cert->heap);
- return ret;
- }
- #endif /* WOLFSSL_SEP || WOLFSSL_FPKI */
- /* Decode a GeneralName.
- *
- * @param [in] input Buffer containing encoded OtherName.
- * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
- * On out, index after OtherName.
- * @param [in] len Length of data in buffer.
- * @param [in] cert Decoded certificate object.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- * @return MEMORY_E when dynamic memory allocation fails.
- */
- static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag,
- int len, DecodedCert* cert)
- {
- int ret = 0;
- word32 idx = *inOutIdx;
- /* GeneralName choice: dnsName */
- if (tag == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
- ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_DNS_TYPE,
- &cert->altNames);
- if (ret == 0) {
- idx += (word32)len;
- }
- }
- #ifndef IGNORE_NAME_CONSTRAINTS
- /* GeneralName choice: directoryName */
- else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
- int strLen;
- word32 idxDir = idx;
- /* Expecting a SEQUENCE using up all data. */
- if (GetASN_Sequence(input, &idxDir, &strLen, idx + (word32)len, 1) < 0)
- {
- WOLFSSL_MSG("\tfail: seq length");
- return ASN_PARSE_E;
- }
- ret = SetDNSEntry(cert, (const char*)(input + idxDir), strLen,
- ASN_DIR_TYPE, &cert->altDirNames);
- if (ret == 0) {
- idx += (word32)len;
- }
- }
- /* GeneralName choice: rfc822Name */
- else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
- ret = SetDNSEntry(cert, (const char*)(input + idx), len,
- ASN_RFC822_TYPE, &cert->altEmailNames);
- if (ret == 0) {
- idx += (word32)len;
- }
- }
- /* GeneralName choice: uniformResourceIdentifier */
- else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
- WOLFSSL_MSG("\tPutting URI into list but not using");
- #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
- /* Verify RFC 5280 Sec 4.2.1.6 rule:
- "The name MUST NOT be a relative URI"
- As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
- a scheme and hier-part. So the only strict requirement is a ':'
- being present after the scheme. If a '/' is present as part of the
- hier-part, it must come after the ':' (see RFC 3986 Sec 3). */
- {
- int i;
- /* skip past scheme (i.e http,ftp,...) finding first ':' char */
- for (i = 0; i < len; i++) {
- if (input[idx + (word32)i] == ':') {
- break;
- }
- if (input[idx + (word32)i] == '/') {
- i = len; /* error, found relative path since '/' was
- * encountered before ':'. Returning error
- * value in next if statement. */
- }
- }
- /* test hier-part is empty */
- if (i == 0 || i == len) {
- WOLFSSL_MSG("\tEmpty or malformed URI");
- WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
- return ASN_ALT_NAME_E;
- }
- /* test if scheme is missing */
- if (input[idx + (word32)i] != ':') {
- WOLFSSL_MSG("\tAlt Name must be absolute URI");
- WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
- return ASN_ALT_NAME_E;
- }
- }
- #endif
- ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_URI_TYPE,
- &cert->altNames);
- if (ret == 0) {
- idx += (word32)len;
- }
- }
- #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || \
- defined(WOLFSSL_IP_ALT_NAME)
- /* GeneralName choice: iPAddress */
- else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
- ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_IP_TYPE,
- &cert->altNames);
- if (ret == 0) {
- idx += len;
- }
- }
- #endif /* WOLFSSL_QT || OPENSSL_ALL */
- #endif /* IGNORE_NAME_CONSTRAINTS */
- #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
- /* GeneralName choice: otherName */
- else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
- /* TODO: test data for code path */
- ret = DecodeOtherName(cert, input, &idx, idx + (word32)len);
- }
- #endif
- /* GeneralName choice: dNSName, x400Address, ediPartyName,
- * registeredID */
- else {
- WOLFSSL_MSG("\tUnsupported name type, skipping");
- idx += (word32)len;
- }
- if (ret == 0) {
- /* Return index of next encoded byte. */
- *inOutIdx = idx;
- }
- return ret;
- }
- /* ASN.1 choices for GeneralName.
- * X.509: RFC 5280, 4.2.1.6 - GeneralName.
- */
- static const byte generalNameChoice[] = {
- ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0,
- ASN_CONTEXT_SPECIFIC | 1,
- ASN_CONTEXT_SPECIFIC | 2,
- ASN_CONTEXT_SPECIFIC | 3,
- ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 4,
- ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 5,
- ASN_CONTEXT_SPECIFIC | 6,
- ASN_CONTEXT_SPECIFIC | 7,
- ASN_CONTEXT_SPECIFIC | 8,
- 0
- };
- /* ASN.1 template for GeneralName.
- * X.509: RFC 5280, 4.2.1.6 - GeneralName.
- */
- static const ASNItem altNameASN[] = {
- { 0, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 0 }
- };
- enum {
- ALTNAMEASN_IDX_GN = 0
- };
- /* Number of items in ASN.1 template for GeneralName. */
- #define altNameASN_Length (sizeof(altNameASN) / sizeof(ASNItem))
- #endif /* WOLFSSL_ASN_TEMPLATE */
- #if defined(WOLFSSL_SEP) && !defined(WOLFSSL_ASN_TEMPLATE)
- /* return 0 on success */
- static int DecodeSepHwAltName(DecodedCert* cert, const byte* input,
- word32* idxIn, word32 sz)
- {
- word32 idx = *idxIn;
- int strLen;
- int ret;
- byte tag;
- /* Certificates issued with this OID in the subject alt name are for
- * verifying signatures created on a module.
- * RFC 4108 Section 5. */
- if (cert->hwType != NULL) {
- WOLFSSL_MSG("\tAlready seen Hardware Module Name");
- return ASN_PARSE_E;
- }
- if (GetASNTag(input, &idx, &tag, sz) < 0) {
- return ASN_PARSE_E;
- }
- if (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
- WOLFSSL_MSG("\twrong type");
- return ASN_PARSE_E;
- }
- if (GetLength(input, &idx, &strLen, sz) < 0) {
- WOLFSSL_MSG("\tfail: str len");
- return ASN_PARSE_E;
- }
- if (GetSequence(input, &idx, &strLen, sz) < 0) {
- WOLFSSL_MSG("\tBad Sequence");
- return ASN_PARSE_E;
- }
- ret = GetASNObjectId(input, &idx, &strLen, sz);
- if (ret != 0) {
- WOLFSSL_MSG("\tbad OID");
- return ret;
- }
- cert->hwType = (byte*)XMALLOC((size_t)strLen, cert->heap,
- DYNAMIC_TYPE_X509_EXT);
- if (cert->hwType == NULL) {
- WOLFSSL_MSG("\tOut of Memory");
- return MEMORY_E;
- }
- XMEMCPY(cert->hwType, &input[idx], (size_t)strLen);
- cert->hwTypeSz = strLen;
- idx += (word32)strLen;
- ret = GetOctetString(input, &idx, &strLen, sz);
- if (ret < 0) {
- XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
- cert->hwType = NULL;
- return ret;
- }
- cert->hwSerialNum = (byte*)XMALLOC((size_t)strLen + 1, cert->heap,
- DYNAMIC_TYPE_X509_EXT);
- if (cert->hwSerialNum == NULL) {
- WOLFSSL_MSG("\tOut of Memory");
- XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
- cert->hwType = NULL;
- return MEMORY_E;
- }
- XMEMCPY(cert->hwSerialNum, &input[idx], (size_t)strLen);
- cert->hwSerialNum[strLen] = '\0';
- cert->hwSerialNumSz = strLen;
- idx += (word32)strLen;
- *idxIn = idx;
- return 0;
- }
- #endif /* WOLFSSL_SEP */
- #if !defined(WOLFSSL_ASN_TEMPLATE)
- /* return 0 on success */
- static int DecodeConstructedOtherName(DecodedCert* cert, const byte* input,
- word32* idx, word32 sz, int oid)
- {
- int ret = 0;
- int strLen = 0;
- byte tag;
- DNS_entry* dnsEntry = NULL;
- if (GetASNTag(input, idx, &tag, sz) < 0) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0 && (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- dnsEntry = AltNameNew(cert->heap);
- if (dnsEntry == NULL) {
- WOLFSSL_MSG("\tOut of Memory");
- return MEMORY_E;
- }
- switch (oid) {
- #ifdef WOLFSSL_FPKI
- case FASCN_OID:
- ret = GetOctetString(input, idx, &strLen, sz);
- if (ret > 0) {
- ret = 0;
- }
- break;
- #endif /* WOLFSSL_FPKI */
- case UPN_OID:
- if (GetASNTag(input, idx, &tag, sz) < 0) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0 &&
- tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
- tag != ASN_IA5_STRING) {
- WOLFSSL_MSG("Was expecting a string for UPN");
- ret = ASN_PARSE_E;
- }
- if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
- WOLFSSL_MSG("Was expecting a string for UPN");
- ret = ASN_PARSE_E;
- }
- break;
- default:
- WOLFSSL_MSG("Unknown constructed other name, skipping");
- XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
- dnsEntry = NULL;
- }
- }
- if (ret == 0 && dnsEntry != NULL) {
- dnsEntry->type = ASN_OTHER_TYPE;
- dnsEntry->len = strLen;
- dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
- DYNAMIC_TYPE_ALTNAME);
- #ifdef WOLFSSL_FPKI
- dnsEntry->oidSum = oid;
- #endif /* WOLFSSL_FPKI */
- if (dnsEntry->name == NULL) {
- WOLFSSL_MSG("\tOut of Memory");
- ret = MEMORY_E;
- }
- else {
- XMEMCPY(dnsEntry->name, &input[*idx], (size_t)strLen);
- dnsEntry->name[strLen] = '\0';
- AddAltName(cert, dnsEntry);
- }
- }
- if (ret == 0) {
- *idx += (word32)strLen;
- }
- else {
- XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
- }
- return ret;
- }
- #endif
- /* Decode subject alternative names extension.
- *
- * RFC 5280 4.2.1.6. Subject Alternative Name
- *
- * @param [in] input Buffer holding encoded data.
- * @param [in] sz Size of encoded data in bytes.
- * @param [in, out] cert Decoded certificate object.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- * @return MEMORY_E when dynamic memory allocation fails.
- */
- static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0;
- int length = 0;
- WOLFSSL_ENTER("DecodeAltNames");
- if (GetSequence(input, &idx, &length, sz) < 0) {
- WOLFSSL_MSG("\tBad Sequence");
- return ASN_PARSE_E;
- }
- if (length == 0) {
- /* RFC 5280 4.2.1.6. Subject Alternative Name
- If the subjectAltName extension is present, the sequence MUST
- contain at least one entry. */
- WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
- return ASN_PARSE_E;
- }
- #ifdef OPENSSL_ALL
- cert->extSubjAltNameSrc = input;
- cert->extSubjAltNameSz = sz;
- #endif
- cert->weOwnAltNames = 1;
- while (length > 0) {
- byte current_byte;
- /* Verify idx can't overflow input buffer */
- if (idx >= (word32)sz) {
- WOLFSSL_MSG("\tBad Index");
- return BUFFER_E;
- }
- current_byte = input[idx++];
- length--;
- /* Save DNS Type names in the altNames list. */
- /* Save Other Type names in the cert's OidMap */
- if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
- DNS_entry* dnsEntry;
- int strLen;
- word32 lenStartIdx = idx;
- if (GetLength(input, &idx, &strLen, sz) < 0) {
- WOLFSSL_MSG("\tfail: str length");
- return ASN_PARSE_E;
- }
- length -= (int)(idx - lenStartIdx);
- dnsEntry = AltNameNew(cert->heap);
- if (dnsEntry == NULL) {
- WOLFSSL_MSG("\tOut of Memory");
- return MEMORY_E;
- }
- dnsEntry->type = ASN_DNS_TYPE;
- dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
- DYNAMIC_TYPE_ALTNAME);
- if (dnsEntry->name == NULL) {
- WOLFSSL_MSG("\tOut of Memory");
- XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
- return MEMORY_E;
- }
- dnsEntry->len = strLen;
- XMEMCPY(dnsEntry->name, &input[idx], (size_t)strLen);
- dnsEntry->name[strLen] = '\0';
- AddAltName(cert, dnsEntry);
- length -= strLen;
- idx += (word32)strLen;
- }
- #ifndef IGNORE_NAME_CONSTRAINTS
- else if (current_byte ==
- (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
- DNS_entry* dirEntry;
- int strLen;
- word32 lenStartIdx = idx;
- if (GetLength(input, &idx, &strLen, sz) < 0) {
- WOLFSSL_MSG("\tfail: str length");
- return ASN_PARSE_E;
- }
- if (GetSequence(input, &idx, &strLen, sz) < 0) {
- WOLFSSL_MSG("\tfail: seq length");
- return ASN_PARSE_E;
- }
- length -= (int)(idx - lenStartIdx);
- dirEntry = AltNameNew(cert->heap);
- if (dirEntry == NULL) {
- WOLFSSL_MSG("\tOut of Memory");
- return MEMORY_E;
- }
- dirEntry->type = ASN_DIR_TYPE;
- dirEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
- DYNAMIC_TYPE_ALTNAME);
- if (dirEntry->name == NULL) {
- WOLFSSL_MSG("\tOut of Memory");
- XFREE(dirEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
- return MEMORY_E;
- }
- dirEntry->len = strLen;
- XMEMCPY(dirEntry->name, &input[idx], (size_t)strLen);
- dirEntry->name[strLen] = '\0';
- dirEntry->next = cert->altDirNames;
- cert->altDirNames = dirEntry;
- length -= strLen;
- idx += (word32)strLen;
- }
- else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
- DNS_entry* emailEntry;
- int strLen;
- word32 lenStartIdx = idx;
- if (GetLength(input, &idx, &strLen, sz) < 0) {
- WOLFSSL_MSG("\tfail: str length");
- return ASN_PARSE_E;
- }
- length -= (int)(idx - lenStartIdx);
- emailEntry = AltNameNew(cert->heap);
- if (emailEntry == NULL) {
- WOLFSSL_MSG("\tOut of Memory");
- return MEMORY_E;
- }
- emailEntry->type = ASN_RFC822_TYPE;
- emailEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
- DYNAMIC_TYPE_ALTNAME);
- if (emailEntry->name == NULL) {
- WOLFSSL_MSG("\tOut of Memory");
- XFREE(emailEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
- return MEMORY_E;
- }
- emailEntry->len = strLen;
- XMEMCPY(emailEntry->name, &input[idx], (size_t)strLen);
- emailEntry->name[strLen] = '\0';
- emailEntry->next = cert->altEmailNames;
- cert->altEmailNames = emailEntry;
- length -= strLen;
- idx += (word32)strLen;
- }
- else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
- DNS_entry* uriEntry;
- int strLen;
- word32 lenStartIdx = idx;
- WOLFSSL_MSG("\tPutting URI into list but not using");
- if (GetLength(input, &idx, &strLen, sz) < 0) {
- WOLFSSL_MSG("\tfail: str length");
- return ASN_PARSE_E;
- }
- length -= (int)(idx - lenStartIdx);
- /* check that strLen at index is not past input buffer */
- if ((word32)strLen + idx > sz) {
- return BUFFER_E;
- }
- #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
- /* Verify RFC 5280 Sec 4.2.1.6 rule:
- "The name MUST NOT be a relative URI"
- As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
- a scheme and hier-part. So the only strict requirement is a ':'
- being present after the scheme. If a '/' is present as part of the
- hier-part, it must come after the ':' (see RFC 3986 Sec 3). */
- {
- word32 i;
- /* skip past scheme (i.e http,ftp,...) finding first ':' char */
- for (i = 0; i < (word32)strLen; i++) {
- if (input[idx + i] == ':') {
- break;
- }
- if (input[idx + i] == '/') {
- WOLFSSL_MSG("\tAlt Name must be absolute URI");
- WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
- return ASN_ALT_NAME_E;
- }
- }
- /* test hier-part is empty */
- if (i == 0 || i == (word32)strLen) {
- WOLFSSL_MSG("\tEmpty or malformed URI");
- WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
- return ASN_ALT_NAME_E;
- }
- /* test if scheme is missing */
- if (input[idx + i] != ':') {
- WOLFSSL_MSG("\tAlt Name must be absolute URI");
- WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
- return ASN_ALT_NAME_E;
- }
- }
- #endif
- uriEntry = AltNameNew(cert->heap);
- if (uriEntry == NULL) {
- WOLFSSL_MSG("\tOut of Memory");
- return MEMORY_E;
- }
- uriEntry->type = ASN_URI_TYPE;
- uriEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
- DYNAMIC_TYPE_ALTNAME);
- if (uriEntry->name == NULL) {
- WOLFSSL_MSG("\tOut of Memory");
- XFREE(uriEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
- return MEMORY_E;
- }
- uriEntry->len = strLen;
- XMEMCPY(uriEntry->name, &input[idx], (size_t)strLen);
- uriEntry->name[strLen] = '\0';
- AddAltName(cert, uriEntry);
- length -= strLen;
- idx += (word32)strLen;
- }
- #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
- else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
- DNS_entry* ipAddr;
- int strLen;
- word32 lenStartIdx = idx;
- WOLFSSL_MSG("Decoding Subject Alt. Name: IP Address");
- if (GetLength(input, &idx, &strLen, sz) < 0) {
- WOLFSSL_MSG("\tfail: str length");
- return ASN_PARSE_E;
- }
- length -= (idx - lenStartIdx);
- /* check that strLen at index is not past input buffer */
- if (strLen + idx > sz) {
- return BUFFER_E;
- }
- ipAddr = AltNameNew(cert->heap);
- if (ipAddr == NULL) {
- WOLFSSL_MSG("\tOut of Memory");
- return MEMORY_E;
- }
- ipAddr->type = ASN_IP_TYPE;
- ipAddr->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
- DYNAMIC_TYPE_ALTNAME);
- if (ipAddr->name == NULL) {
- WOLFSSL_MSG("\tOut of Memory");
- XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
- return MEMORY_E;
- }
- ipAddr->len = strLen;
- XMEMCPY(ipAddr->name, &input[idx], strLen);
- ipAddr->name[strLen] = '\0';
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
- if (GenerateDNSEntryIPString(ipAddr, cert->heap) != 0) {
- WOLFSSL_MSG("\tOut of Memory for IP string");
- XFREE(ipAddr->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
- XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
- return MEMORY_E;
- }
- #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
- AddAltName(cert, ipAddr);
- length -= strLen;
- idx += (word32)strLen;
- }
- #endif /* WOLFSSL_QT || OPENSSL_ALL */
- #endif /* IGNORE_NAME_CONSTRAINTS */
- else if (current_byte ==
- (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
- int strLen;
- word32 lenStartIdx = idx;
- word32 oid = 0;
- int ret = 0;
- if (GetLength(input, &idx, &strLen, sz) < 0) {
- WOLFSSL_MSG("\tfail: other name length");
- return ASN_PARSE_E;
- }
- /* Consume the rest of this sequence. */
- length -= (int)(((word32)strLen + idx - lenStartIdx));
- if (GetObjectId(input, &idx, &oid, oidCertAltNameType, sz) < 0) {
- WOLFSSL_MSG("\tbad OID");
- return ASN_PARSE_E;
- }
- /* handle parsing other type alt names */
- switch (oid) {
- #ifdef WOLFSSL_SEP
- case HW_NAME_OID:
- ret = DecodeSepHwAltName(cert, input, &idx, sz);
- if (ret != 0)
- return ret;
- break;
- #endif /* WOLFSSL_SEP */
- #ifdef WOLFSSL_FPKI
- case FASCN_OID:
- case UPN_OID:
- ret = DecodeConstructedOtherName(cert, input, &idx, sz,
- oid);
- if (ret != 0)
- return ret;
- break;
- #endif /* WOLFSSL_FPKI */
- default:
- WOLFSSL_MSG("\tUnsupported other name type, skipping");
- if (GetLength(input, &idx, &strLen, sz) < 0) {
- /* check to skip constructed other names too */
- if (DecodeConstructedOtherName(cert, input, &idx, sz,
- (int)oid) != 0) {
- WOLFSSL_MSG("\tfail: unsupported other name length");
- return ASN_PARSE_E;
- }
- }
- else {
- idx += (word32)strLen;
- }
- }
- (void)ret;
- }
- else {
- int strLen;
- word32 lenStartIdx = idx;
- WOLFSSL_MSG("\tUnsupported name type, skipping");
- if (GetLength(input, &idx, &strLen, sz) < 0) {
- WOLFSSL_MSG("\tfail: unsupported name length");
- return ASN_PARSE_E;
- }
- length -= (int)((word32)strLen + idx - lenStartIdx);
- idx += (word32)strLen;
- }
- }
- return 0;
- #else
- word32 idx = 0;
- int length = 0;
- int ret = 0;
- WOLFSSL_ENTER("DecodeAltNames");
- /* Get SEQUENCE and expect all data to be accounted for. */
- if (GetASN_Sequence(input, &idx, &length, sz, 1) != 0) {
- WOLFSSL_MSG("\tBad Sequence");
- ret = ASN_PARSE_E;
- }
- if ((ret == 0) && (length == 0)) {
- /* RFC 5280 4.2.1.6. Subject Alternative Name
- If the subjectAltName extension is present, the sequence MUST
- contain at least one entry. */
- WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- #ifdef OPENSSL_ALL
- cert->extSubjAltNameSrc = input;
- cert->extSubjAltNameSz = sz;
- #endif
- cert->weOwnAltNames = 1;
- if ((word32)length + idx != sz) {
- ret = ASN_PARSE_E;
- }
- }
- while ((ret == 0) && (idx < sz)) {
- ASNGetData dataASN[altNameASN_Length];
- /* Clear dynamic data items. */
- XMEMSET(dataASN, 0, sizeof(dataASN));
- /* Parse GeneralName with the choices supported. */
- GetASN_Choice(&dataASN[ALTNAMEASN_IDX_GN], generalNameChoice);
- /* Decode a GeneralName choice. */
- ret = GetASN_Items(altNameASN, dataASN, altNameASN_Length, 0, input,
- &idx, sz);
- if (ret == 0) {
- ret = DecodeGeneralName(input, &idx, dataASN[ALTNAMEASN_IDX_GN].tag,
- (int)dataASN[ALTNAMEASN_IDX_GN].length, cert);
- }
- }
- return ret;
- #endif
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for BasicContraints.
- * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
- */
- static const ASNItem basicConsASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* CA */ { 1, ASN_BOOLEAN, 0, 0, 1 },
- /* PLEN */ { 1, ASN_INTEGER, 0, 0, 1 }
- };
- enum {
- BASICCONSASN_IDX_SEQ = 0,
- BASICCONSASN_IDX_CA,
- BASICCONSASN_IDX_PLEN
- };
- /* Number of items in ASN.1 template for BasicContraints. */
- #define basicConsASN_Length (sizeof(basicConsASN) / sizeof(ASNItem))
- #endif
- /* Decode basic constraints extension in a certificate.
- *
- * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
- *
- * @param [in] input Buffer holding data.
- * @param [in] sz Size of data in buffer.
- * @param [in, out] cert Certificate object.
- * @return 0 on success.
- * @return MEMORY_E on dynamic memory allocation failure.
- * @return ASN_PARSE_E when CA boolean is present and false (default is false).
- * @return ASN_PARSE_E when CA boolean is not present unless
- * WOLFSSL_X509_BASICCONS_INT is defined. Only a CA extension.
- * @return ASN_PARSE_E when path length more than 7 bits.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- */
- static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0;
- int length = 0;
- int ret;
- WOLFSSL_ENTER("DecodeBasicCaConstraint");
- if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
- WOLFSSL_MSG("\tfail: bad SEQUENCE");
- return ASN_PARSE_E;
- }
- if (length == 0)
- return 0;
- /* If the basic ca constraint is false, this extension may be named, but
- * left empty. So, if the length is 0, just return. */
- ret = GetBoolean(input, &idx, (word32)sz);
- /* Removed logic for WOLFSSL_X509_BASICCONS_INT which was mistreating the
- * pathlen value as if it were the CA Boolean value 7/2/2021 - KH.
- * When CA Boolean not asserted use the default value "False" */
- if (ret < 0) {
- WOLFSSL_MSG("\tfail: constraint not valid BOOLEAN, set default FALSE");
- ret = 0;
- }
- cert->isCA = ret ? 1 : 0;
- /* If there isn't any more data, return. */
- if (idx >= (word32)sz) {
- return 0;
- }
- ret = GetInteger7Bit(input, &idx, (word32)sz);
- if (ret < 0)
- return ret;
- cert->pathLength = (byte)ret;
- cert->pathLengthSet = 1;
- return 0;
- #else
- DECL_ASNGETDATA(dataASN, basicConsASN_Length);
- int ret = 0;
- word32 idx = 0;
- byte isCA = 0;
- WOLFSSL_ENTER("DecodeBasicCaConstraints");
- CALLOC_ASNGETDATA(dataASN, basicConsASN_Length, ret, cert->heap);
- if (ret == 0) {
- /* Get the CA boolean and path length when present. */
- GetASN_Boolean(&dataASN[BASICCONSASN_IDX_CA], &isCA);
- GetASN_Int8Bit(&dataASN[BASICCONSASN_IDX_PLEN], &cert->pathLength);
- ret = GetASN_Items(basicConsASN, dataASN, basicConsASN_Length, 1, input,
- &idx, (word32)sz);
- }
- /* Empty SEQUENCE is OK - nothing to store. */
- if ((ret == 0) && (dataASN[BASICCONSASN_IDX_SEQ].length != 0)) {
- /* Bad encoding when CA Boolean is false
- * (default when not present). */
- if ((dataASN[BASICCONSASN_IDX_CA].length != 0) && (!isCA)) {
- WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
- ret = ASN_PARSE_E;
- }
- /* Path length must be a 7-bit value. */
- if ((ret == 0) && (cert->pathLength >= (1 << 7))) {
- WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
- ret = ASN_PARSE_E;
- }
- /* Store CA boolean and whether a path length was seen. */
- if (ret == 0) {
- /* isCA in certificate is a 1 bit of a byte. */
- cert->isCA = isCA ? 1 : 0;
- cert->pathLengthSet = (dataASN[BASICCONSASN_IDX_PLEN].length > 0);
- }
- }
- FREE_ASNGETDATA(dataASN, cert->heap);
- return ret;
- #endif
- }
- static int DecodePolicyConstraints(const byte* input, int sz, DecodedCert* cert)
- {
- word32 idx = 0;
- int length = 0;
- int skipLength = 0;
- int ret;
- byte tag;
- WOLFSSL_ENTER("DecodePolicyConstraints");
- if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
- WOLFSSL_MSG("\tfail: bad SEQUENCE");
- return ASN_PARSE_E;
- }
- if (length == 0)
- return ASN_PARSE_E;
- if (GetASNTag(input, &idx, &tag, (word32)sz) < 0) {
- WOLFSSL_MSG("\tfail: bad TAG");
- return ASN_PARSE_E;
- }
- if (tag == (ASN_CONTEXT_SPECIFIC | 0)) {
- /* requireExplicitPolicy */
- cert->extPolicyConstRxpSet = 1;
- }
- else if (tag == (ASN_CONTEXT_SPECIFIC | 1)) {
- /* inhibitPolicyMapping */
- cert->extPolicyConstIpmSet = 1;
- }
- else {
- WOLFSSL_MSG("\tfail: invalid TAG");
- return ASN_PARSE_E;
- }
- ret = GetLength(input, &idx, &skipLength, (word32)sz);
- if (ret < 0) {
- WOLFSSL_MSG("\tfail: invalid length");
- return ret;
- }
- if (skipLength > 1) {
- WOLFSSL_MSG("\tfail: skip value too big");
- return BUFFER_E;
- }
- if (idx >= (word32)sz) {
- WOLFSSL_MSG("\tfail: no policy const skip to read");
- return BUFFER_E;
- }
- cert->policyConstSkip = input[idx];
- return 0;
- }
- /* Context-Specific value for: DistributionPoint.distributionPoint
- * From RFC5280 SS4.2.1.13, Distribution Point */
- #define DISTRIBUTION_POINT (ASN_CONTEXT_SPECIFIC | 0)
- /* Context-Specific value for: DistributionPoint.DistributionPointName.fullName
- * From RFC3280 SS4.2.1.13, Distribution Point Name */
- #define CRLDP_FULL_NAME (ASN_CONTEXT_SPECIFIC | 0)
- /* Context-Specific value for choice: GeneralName.uniformResourceIdentifier
- * From RFC3280 SS4.2.1.7, GeneralName */
- #define GENERALNAME_URI (ASN_CONTEXT_SPECIFIC | 6)
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for CRL distribution points.
- * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
- */
- static const ASNItem crlDistASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* DP_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* Distribution point name */
- /* DP_DISTPOINT */ { 2, DISTRIBUTION_POINT, 1, 1, 1 },
- /* fullName */
- /* DP_DISTPOINT_FN */ { 3, CRLDP_FULL_NAME, 1, 1, 2 },
- /* DP_DISTPOINT_FN_GN */ { 4, GENERALNAME_URI, 0, 0, 0 },
- /* nameRelativeToCRLIssuer */
- /* DP_DISTPOINT_RN */ { 3, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
- /* reasons: IMPLICIT BIT STRING */
- /* DP_REASONS */ { 2, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
- /* cRLIssuer */
- /* DP_CRLISSUER */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 1 },
- };
- enum {
- CRLDISTASN_IDX_SEQ = 0,
- CRLDISTASN_IDX_DP_SEQ,
- CRLDISTASN_IDX_DP_DISTPOINT,
- CRLDISTASN_IDX_DP_DISTPOINT_FN,
- CRLDISTASN_IDX_DP_DISTPOINT_FN_GN,
- CRLDISTASN_IDX_DP_DISTPOINT_RN, /* Relative name */
- CRLDISTASN_IDX_DP_REASONS,
- CRLDISTASN_IDX_DP_CRLISSUER
- };
- /* Number of items in ASN.1 template for CRL distribution points. */
- #define crlDistASN_Length (sizeof(crlDistASN) / sizeof(ASNItem))
- #endif
- /* Decode CRL distribution point extension in a certificate.
- *
- * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
- *
- * @param [in] input Buffer holding data.
- * @param [in] sz Size of data in buffer.
- * @param [in, out] cert Certificate object.
- * @return 0 on success.
- * @return MEMORY_E on dynamic memory allocation failure.
- * @return ASN_PARSE_E when invalid bits of reason are set.
- * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
- * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- */
- static int DecodeCrlDist(const byte* input, word32 sz, DecodedCert* cert)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0, localIdx;
- int length = 0;
- byte tag = 0;
- WOLFSSL_ENTER("DecodeCrlDist");
- cert->extCrlInfoRaw = input;
- cert->extCrlInfoRawSz = (int)sz;
- /* Unwrap the list of Distribution Points*/
- if (GetSequence(input, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- /* Unwrap a single Distribution Point */
- if (GetSequence(input, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- /* The Distribution Point has three explicit optional members
- * First check for a DistributionPointName
- */
- localIdx = idx;
- if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
- tag == (ASN_CONSTRUCTED | DISTRIBUTION_POINT))
- {
- idx++;
- if (GetLength(input, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- localIdx = idx;
- if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
- tag == (ASN_CONSTRUCTED | CRLDP_FULL_NAME))
- {
- idx++;
- if (GetLength(input, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- localIdx = idx;
- if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
- tag == GENERALNAME_URI)
- {
- idx++;
- if (GetLength(input, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- cert->extCrlInfoSz = length;
- cert->extCrlInfo = input + idx;
- idx += (word32)length;
- }
- else
- /* This isn't a URI, skip it. */
- idx += (word32)length;
- }
- else {
- /* This isn't a FULLNAME, skip it. */
- idx += (word32)length;
- }
- }
- /* Check for reasonFlags */
- localIdx = idx;
- if (idx < (word32)sz &&
- GetASNTag(input, &localIdx, &tag, sz) == 0 &&
- tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
- {
- idx++;
- if (GetLength(input, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- idx += (word32)length;
- }
- /* Check for cRLIssuer */
- localIdx = idx;
- if (idx < (word32)sz &&
- GetASNTag(input, &localIdx, &tag, sz) == 0 &&
- tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
- {
- idx++;
- if (GetLength(input, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- idx += (word32)length;
- }
- if (idx < (word32)sz)
- {
- WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
- "but we only use the first one.");
- }
- return 0;
- #else
- DECL_ASNGETDATA(dataASN, crlDistASN_Length);
- word32 idx = 0;
- int ret = 0;
- #ifdef CRLDP_VALIDATE_DATA
- word16 reason;
- #endif
- WOLFSSL_ENTER("DecodeCrlDist");
- CALLOC_ASNGETDATA(dataASN, crlDistASN_Length, ret, cert->heap);
- cert->extCrlInfoRaw = input;
- cert->extCrlInfoRawSz = (int)sz;
- if (ret == 0) {
- /* Get the GeneralName choice */
- GetASN_Choice(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN], generalNameChoice);
- /* Parse CRL distribtion point. */
- ret = GetASN_Items(crlDistASN, dataASN, crlDistASN_Length, 0, input,
- &idx, sz);
- }
- if (ret == 0) {
- /* If the choice was a URI, store it in certificate. */
- if (dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN].tag == GENERALNAME_URI) {
- word32 sz32;
- GetASN_GetConstRef(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN],
- &cert->extCrlInfo, &sz32);
- cert->extCrlInfoSz = (int)sz32;
- }
- #ifdef CRLDP_VALIDATE_DATA
- if (dataASN[CRLDISTASN_IDX_DP_REASONS].data.ref.data != NULL) {
- /* TODO: test case */
- /* Validate ReasonFlags. */
- ret = GetASN_BitString_Int16Bit(&dataASN[CRLDISTASN_IDX_DP_REASONS],
- &reason);
- /* First bit (LSB) unused and eight other bits defined. */
- if ((ret == 0) && ((reason >> 9) || (reason & 0x01))) {
- WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
- ret = ASN_PARSE_E;
- }
- }
- #endif
- }
- /* Only parsing the first one. */
- if (ret == 0 && idx < (word32)sz) {
- WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
- "but we only use the first one.");
- }
- /* TODO: validate other points. */
- FREE_ASNGETDATA(dataASN, cert->heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for the access description.
- * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
- */
- static const ASNItem accessDescASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* accessMethod */
- /* METH */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* accessLocation: GeneralName */
- /* LOC */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
- };
- enum {
- ACCESSDESCASN_IDX_SEQ = 0,
- ACCESSDESCASN_IDX_METH,
- ACCESSDESCASN_IDX_LOC
- };
- /* Number of items in ASN.1 template for the access description. */
- #define accessDescASN_Length (sizeof(accessDescASN) / sizeof(ASNItem))
- #endif
- /* Decode authority information access extension in a certificate.
- *
- * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
- *
- * @param [in] input Buffer holding data.
- * @param [in] sz Size of data in buffer.
- * @param [in, out] cert Certificate object.
- * @return 0 on success.
- * @return MEMORY_E on dynamic memory allocation failure.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- */
- static int DecodeAuthInfo(const byte* input, word32 sz, DecodedCert* cert)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0;
- int length = 0;
- int count = 0;
- byte b = 0;
- word32 oid;
- WOLFSSL_ENTER("DecodeAuthInfo");
- /* Unwrap the list of AIAs */
- if (GetSequence(input, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- while ((idx < (word32)sz) && (count < MAX_AIA_SZ)) {
- /* Unwrap a single AIA */
- if (GetSequence(input, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- oid = 0;
- if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0) {
- return ASN_PARSE_E;
- }
- /* Only supporting URIs right now. */
- if (GetASNTag(input, &idx, &b, sz) < 0)
- return ASN_PARSE_E;
- if (GetLength(input, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- /* Set ocsp entry */
- if (b == GENERALNAME_URI && oid == AIA_OCSP_OID)
- {
- cert->extAuthInfoSz = length;
- cert->extAuthInfo = input + idx;
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
- count++;
- #else
- break;
- #endif
- }
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
- /* Set CaIssuers entry */
- else if ((b == GENERALNAME_URI) && oid == AIA_CA_ISSUER_OID)
- {
- cert->extAuthInfoCaIssuerSz = length;
- cert->extAuthInfoCaIssuer = input + idx;
- count++;
- }
- #endif
- idx += (word32)length;
- }
- return 0;
- #else
- word32 idx = 0;
- int length = 0;
- int count = 0;
- int ret = 0;
- WOLFSSL_ENTER("DecodeAuthInfo");
- /* Unwrap the list of AIAs */
- if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
- ret = ASN_PARSE_E;
- }
- while ((ret == 0) && (idx < (word32)sz) && (count < MAX_AIA_SZ)) {
- ASNGetData dataASN[accessDescASN_Length];
- /* Clear dynamic data and retrieve OID and name. */
- XMEMSET(dataASN, 0, sizeof(dataASN));
- GetASN_OID(&dataASN[ACCESSDESCASN_IDX_METH], oidCertAuthInfoType);
- GetASN_Choice(&dataASN[ACCESSDESCASN_IDX_LOC], generalNameChoice);
- /* Parse AccessDescription. */
- ret = GetASN_Items(accessDescASN, dataASN, accessDescASN_Length, 0,
- input, &idx, sz);
- if (ret == 0) {
- word32 sz32;
- /* Check we have OCSP and URI. */
- if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum == AIA_OCSP_OID) &&
- (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
- /* Store URI for OCSP lookup. */
- GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
- &cert->extAuthInfo, &sz32);
- cert->extAuthInfoSz = (int)sz32;
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
- count++;
- #else
- break;
- #endif
- }
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
- /* Check we have CA Issuer and URI. */
- else if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum ==
- AIA_CA_ISSUER_OID) &&
- (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
- /* Set CaIssuers entry */
- GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
- &cert->extAuthInfoCaIssuer, &sz32);
- cert->extAuthInfoCaIssuerSz = sz32;
- count++;
- }
- #endif
- /* Otherwise skip. */
- }
- }
- return ret;
- #endif
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for AuthorityKeyIdentifier.
- * X.509: RFC 5280, 4.2.1.1 - Authority Key Identifier.
- */
- static const ASNItem authKeyIdASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* keyIdentifier */
- /* KEYID */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_KEYID, 0, 0, 1 },
- /* authorityCertIssuer */
- /* ISSUER */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_ISSUER, 1, 0, 1 },
- /* authorityCertSerialNumber */
- /* SERIAL */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_SERIAL, 0, 0, 1 },
- };
- enum {
- AUTHKEYIDASN_IDX_SEQ = 0,
- AUTHKEYIDASN_IDX_KEYID,
- AUTHKEYIDASN_IDX_ISSUER,
- AUTHKEYIDASN_IDX_SERIAL
- };
- /* Number of items in ASN.1 template for AuthorityKeyIdentifier. */
- #define authKeyIdASN_Length (sizeof(authKeyIdASN) / sizeof(ASNItem))
- #endif
- /* Decode authority information access extension in a certificate.
- *
- * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
- *
- * @param [in] input Buffer holding data.
- * @param [in] sz Size of data in buffer.
- * @param [in, out] cert Certificate object.
- * @return 0 on success.
- * @return MEMORY_E on dynamic memory allocation failure.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- */
- static int DecodeAuthKeyId(const byte* input, word32 sz, DecodedCert* cert)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0;
- int length = 0;
- byte tag;
- WOLFSSL_ENTER("DecodeAuthKeyId");
- if (GetSequence(input, &idx, &length, sz) < 0) {
- WOLFSSL_MSG("\tfail: should be a SEQUENCE");
- return ASN_PARSE_E;
- }
- if (GetASNTag(input, &idx, &tag, sz) < 0) {
- return ASN_PARSE_E;
- }
- if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
- WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
- cert->extAuthKeyIdSet = 0;
- return 0;
- }
- if (GetLength(input, &idx, &length, sz) <= 0) {
- WOLFSSL_MSG("\tfail: extension data length");
- return ASN_PARSE_E;
- }
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- #ifdef WOLFSSL_AKID_NAME
- cert->extRawAuthKeyIdSrc = input;
- cert->extRawAuthKeyIdSz = sz;
- #endif
- cert->extAuthKeyIdSrc = &input[idx];
- cert->extAuthKeyIdSz = length;
- #endif /* OPENSSL_EXTRA */
- return GetHashId(input + idx, length, cert->extAuthKeyId,
- HashIdAlg(cert->signatureOID));
- #else
- DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
- int ret = 0;
- word32 idx = 0;
- WOLFSSL_ENTER("DecodeAuthKeyId");
- CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, cert->heap);
- if (ret == 0) {
- /* Parse an authority key identifier. */
- ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
- &idx, sz);
- }
- if (ret == 0) {
- /* Key id is optional. */
- if (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data == NULL) {
- WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
- }
- else {
- #ifdef OPENSSL_EXTRA
- /* Store the authority key id. */
- #ifdef WOLFSSL_AKID_NAME
- cert->extRawAuthKeyIdSrc = input;
- cert->extRawAuthKeyIdSz = sz;
- #endif
- GetASN_GetConstRef(&dataASN[AUTHKEYIDASN_IDX_KEYID], &cert->extAuthKeyIdSrc,
- &cert->extAuthKeyIdSz);
- #endif /* OPENSSL_EXTRA */
- /* Get the hash or hash of the hash if wrong size. */
- ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
- (int)dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
- cert->extAuthKeyId, HashIdAlg(cert->signatureOID));
- }
- }
- FREE_ASNGETDATA(dataASN, cert->heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- /* Decode subject key id extension in a certificate.
- *
- * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
- *
- * @param [in] input Buffer holding data.
- * @param [in] sz Size of data in buffer.
- * @param [in, out] cert Certificate object.
- * @return 0 on success.
- * @return ASN_PARSE_E when the OCTET_STRING tag is not found or length is
- * invalid.
- * @return MEMORY_E on dynamic memory allocation failure.
- */
- static int DecodeSubjKeyId(const byte* input, word32 sz, DecodedCert* cert)
- {
- word32 idx = 0;
- int length = 0;
- int ret = 0;
- WOLFSSL_ENTER("DecodeSubjKeyId");
- ret = GetOctetString(input, &idx, &length, sz);
- if (ret > 0) {
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- cert->extSubjKeyIdSrc = &input[idx];
- cert->extSubjKeyIdSz = length;
- #endif /* OPENSSL_EXTRA */
- /* Get the hash or hash of the hash if wrong size. */
- ret = GetHashId(input + idx, length, cert->extSubjKeyId,
- HashIdAlg(cert->signatureOID));
- }
- return ret;
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for KeyUsage.
- * X.509: RFC 5280, 4.2.1.3 - Key Usage.
- */
- static const ASNItem keyUsageASN[] = {
- /* STR */ { 0, ASN_BIT_STRING, 0, 0, 0 },
- };
- enum {
- KEYUSAGEASN_IDX_STR = 0
- };
- /* Number of items in ASN.1 template for KeyUsage. */
- #define keyUsageASN_Length (sizeof(keyUsageASN) / sizeof(ASNItem))
- #endif
- /* Decode key usage extension in a certificate.
- *
- * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
- *
- * @param [in] input Buffer holding data.
- * @param [in] sz Size of data in buffer.
- * @param [in, out] cert Certificate object.
- * @return 0 on success.
- * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return MEMORY_E on dynamic memory allocation failure.
- */
- static int DecodeKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0;
- int length;
- int ret;
- WOLFSSL_ENTER("DecodeKeyUsage");
- ret = CheckBitString(input, &idx, &length, sz, 0, NULL);
- if (ret != 0)
- return ret;
- if (length == 0 || length > 2)
- return ASN_PARSE_E;
- cert->extKeyUsage = (word16)(input[idx]);
- if (length == 2)
- cert->extKeyUsage |= (word16)(input[idx+1] << 8);
- return 0;
- #else
- ASNGetData dataASN[keyUsageASN_Length];
- word32 idx = 0;
- WOLFSSL_ENTER("DecodeKeyUsage");
- /* Clear dynamic data and set where to store extended key usage. */
- XMEMSET(dataASN, 0, sizeof(dataASN));
- GetASN_Int16Bit(&dataASN[KEYUSAGEASN_IDX_STR], &cert->extKeyUsage);
- /* Parse key usage. */
- return GetASN_Items(keyUsageASN, dataASN, keyUsageASN_Length, 0, input,
- &idx, sz);
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for KeyPurposeId.
- * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
- */
- static const ASNItem keyPurposeIdASN[] = {
- /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
- };
- enum {
- KEYPURPOSEIDASN_IDX_OID = 0
- };
- /* Number of items in ASN.1 template for KeyPurposeId. */
- #define keyPurposeIdASN_Length (sizeof(keyPurposeIdASN) / sizeof(ASNItem))
- #endif
- /* Decode extended key usage extension in a certificate.
- *
- * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
- *
- * @param [in] input Buffer holding data.
- * @param [in] sz Size of data in buffer.
- * @param [in, out] cert Certificate object.
- * @return 0 on success.
- * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return MEMORY_E on dynamic memory allocation failure.
- */
- static int DecodeExtKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0, oid;
- int length, ret;
- WOLFSSL_ENTER("DecodeExtKeyUsage");
- if (GetSequence(input, &idx, &length, sz) < 0) {
- WOLFSSL_MSG("\tfail: should be a SEQUENCE");
- return ASN_PARSE_E;
- }
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- cert->extExtKeyUsageSrc = input + idx;
- cert->extExtKeyUsageSz = length;
- #endif
- while (idx < (word32)sz) {
- ret = GetObjectId(input, &idx, &oid, oidCertKeyUseType, sz);
- if (ret == ASN_UNKNOWN_OID_E)
- continue;
- else if (ret < 0)
- return ret;
- switch (oid) {
- case EKU_ANY_OID:
- cert->extExtKeyUsage |= EXTKEYUSE_ANY;
- break;
- case EKU_SERVER_AUTH_OID:
- cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
- break;
- case EKU_CLIENT_AUTH_OID:
- cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
- break;
- case EKU_CODESIGNING_OID:
- cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
- break;
- case EKU_EMAILPROTECT_OID:
- cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
- break;
- case EKU_TIMESTAMP_OID:
- cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
- break;
- case EKU_OCSP_SIGN_OID:
- cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
- break;
- #ifdef WOLFSSL_WOLFSSH
- case EKU_SSH_CLIENT_AUTH_OID:
- cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_CLIENT_AUTH;
- break;
- case EKU_SSH_MSCL_OID:
- cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_MSCL;
- break;
- case EKU_SSH_KP_CLIENT_AUTH_OID:
- cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_KP_CLIENT_AUTH;
- break;
- #endif /* WOLFSSL_WOLFSSH */
- default:
- break;
- }
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- cert->extExtKeyUsageCount++;
- #endif
- }
- return 0;
- #else
- word32 idx = 0;
- int length;
- int ret = 0;
- WOLFSSL_ENTER("DecodeExtKeyUsage");
- /* Strip SEQUENCE OF and expect to account for all the data. */
- if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
- WOLFSSL_MSG("\tfail: should be a SEQUENCE");
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- /* Keep reference for WOLFSSL_X509. */
- cert->extExtKeyUsageSrc = input + idx;
- cert->extExtKeyUsageSz = length;
- #endif
- }
- /* Check all OIDs. */
- while ((ret == 0) && (idx < (word32)sz)) {
- ASNGetData dataASN[keyPurposeIdASN_Length];
- /* Clear dynamic data items and set OID type expected. */
- XMEMSET(dataASN, 0, sizeof(dataASN));
- GetASN_OID(&dataASN[KEYPURPOSEIDASN_IDX_OID], oidIgnoreType);
- /* Decode KeyPurposeId. */
- ret = GetASN_Items(keyPurposeIdASN, dataASN, keyPurposeIdASN_Length, 0,
- input, &idx, sz);
- /* Skip unknown OIDs. */
- if (ret == ASN_UNKNOWN_OID_E) {
- ret = 0;
- }
- else if (ret == 0) {
- /* Store the bit for the OID. */
- switch (dataASN[KEYPURPOSEIDASN_IDX_OID].data.oid.sum) {
- case EKU_ANY_OID:
- cert->extExtKeyUsage |= EXTKEYUSE_ANY;
- break;
- case EKU_SERVER_AUTH_OID:
- cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
- break;
- case EKU_CLIENT_AUTH_OID:
- cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
- break;
- case EKU_CODESIGNING_OID:
- cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
- break;
- case EKU_EMAILPROTECT_OID:
- cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
- break;
- case EKU_TIMESTAMP_OID:
- cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
- break;
- case EKU_OCSP_SIGN_OID:
- cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
- break;
- }
- #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- /* Keep count for WOLFSSL_X509. */
- cert->extExtKeyUsageCount++;
- #endif
- }
- }
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #ifndef IGNORE_NETSCAPE_CERT_TYPE
- static int DecodeNsCertType(const byte* input, int sz, DecodedCert* cert)
- {
- word32 idx = 0;
- int len = 0;
- WOLFSSL_ENTER("DecodeNsCertType");
- if (CheckBitString(input, &idx, &len, (word32)sz, 0, NULL) < 0)
- return ASN_PARSE_E;
- /* Don't need to worry about unused bits as CheckBitString makes sure
- * they're zero. */
- if (idx < (word32)sz)
- cert->nsCertType = input[idx];
- else
- return ASN_PARSE_E;
- return 0;
- }
- #endif
- #ifndef IGNORE_NAME_CONSTRAINTS
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for GeneralSubtree.
- * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
- */
- static const ASNItem subTreeASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* base GeneralName */
- /* BASE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
- /* minimum BaseDistance DEFAULT 0*/
- /* MIN */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MIN, 0, 0, 1 },
- /* maximum BaseDistance OPTIONAL */
- /* MAX */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MAX, 0, 0, 1 },
- };
- enum {
- SUBTREEASN_IDX_SEQ = 0,
- SUBTREEASN_IDX_BASE,
- SUBTREEASN_IDX_MIN,
- SUBTREEASN_IDX_MAX
- };
- /* Number of items in ASN.1 template for GeneralSubtree. */
- #define subTreeASN_Length (sizeof(subTreeASN) / sizeof(ASNItem))
- #endif
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* Decode the Subtree's GeneralName.
- *
- * @param [in] input Buffer holding data.
- * @param [in] sz Size of data in buffer.
- * @param [in] tag BER tag on GeneralName.
- * @param [in, out] head Linked list of subtree names.
- * @param [in] heap Dynamic memory hint.
- * @return 0 on success.
- * @return MEMORY_E when dynamic memory allocation fails.
- * @return ASN_PARSE_E when SEQUENCE is not found as expected.
- */
- static int DecodeSubtreeGeneralName(const byte* input, word32 sz, byte tag,
- Base_entry** head, void* heap)
- {
- Base_entry* entry;
- word32 nameIdx = 0;
- word32 len = sz;
- int strLen;
- int ret = 0;
- (void)heap;
- /* if constructed has leading sequence */
- if ((tag & ASN_CONSTRUCTED) == ASN_CONSTRUCTED) {
- ret = GetASN_Sequence(input, &nameIdx, &strLen, sz, 0);
- if (ret < 0) {
- ret = ASN_PARSE_E;
- }
- else {
- len = (word32)strLen;
- ret = 0;
- }
- }
- if (ret == 0) {
- /* TODO: consider one malloc. */
- /* Allocate Base Entry object. */
- entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
- DYNAMIC_TYPE_ALTNAME);
- if (entry == NULL) {
- ret = MEMORY_E;
- }
- }
- if (ret == 0) {
- /* Allocate name. */
- entry->name = (char*)XMALLOC(len + 1, heap, DYNAMIC_TYPE_ALTNAME);
- if (entry->name == NULL) {
- XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
- ret = MEMORY_E;
- }
- }
- if (ret == 0) {
- /* Store name, size and tag in object. */
- XMEMCPY(entry->name, &input[nameIdx], len);
- entry->name[len] = '\0';
- entry->nameSz = (int)len;
- entry->type = tag & ASN_TYPE_MASK;
- /* Put entry at front of linked list. */
- entry->next = *head;
- *head = entry;
- }
- return ret;
- }
- #endif
- /* Decode a subtree of a name constraints in a certificate.
- *
- * X.509: RFC 5280, 4.2.1.10 - Name Contraints.
- *
- * @param [in] input Buffer holding data.
- * @param [in] sz Size of data in buffer.
- * @param [in, out] head Linked list of subtree names.
- * @param [in] heap Dynamic memory hint.
- * @return 0 on success.
- * @return MEMORY_E when dynamic memory allocation fails.
- * @return ASN_PARSE_E when SEQUENCE is not found as expected.
- */
- static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head,
- void* heap)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0;
- int ret = 0;
- (void)heap;
- while (idx < (word32)sz) {
- int seqLength, strLength;
- word32 nameIdx;
- byte b, bType;
- if (GetSequence(input, &idx, &seqLength, sz) < 0) {
- WOLFSSL_MSG("\tfail: should be a SEQUENCE");
- return ASN_PARSE_E;
- }
- if (idx >= (word32)sz) {
- WOLFSSL_MSG("\tfail: expecting tag");
- return ASN_PARSE_E;
- }
- nameIdx = idx;
- b = input[nameIdx++];
- if (GetLength(input, &nameIdx, &strLength, sz) <= 0) {
- WOLFSSL_MSG("\tinvalid length");
- return ASN_PARSE_E;
- }
- /* Get type, LSB 4-bits */
- bType = (byte)(b & ASN_TYPE_MASK);
- if (bType == ASN_DNS_TYPE || bType == ASN_RFC822_TYPE ||
- bType == ASN_DIR_TYPE) {
- Base_entry* entry;
- /* if constructed has leading sequence */
- if (b & ASN_CONSTRUCTED) {
- if (GetSequence(input, &nameIdx, &strLength, sz) < 0) {
- WOLFSSL_MSG("\tfail: constructed be a SEQUENCE");
- return ASN_PARSE_E;
- }
- }
- entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
- DYNAMIC_TYPE_ALTNAME);
- if (entry == NULL) {
- WOLFSSL_MSG("allocate error");
- return MEMORY_E;
- }
- entry->name = (char*)XMALLOC((size_t)strLength+1, heap,
- DYNAMIC_TYPE_ALTNAME);
- if (entry->name == NULL) {
- WOLFSSL_MSG("allocate error");
- XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
- return MEMORY_E;
- }
- XMEMCPY(entry->name, &input[nameIdx], (size_t)strLength);
- entry->name[strLength] = '\0';
- entry->nameSz = strLength;
- entry->type = bType;
- entry->next = *head;
- *head = entry;
- }
- idx += (word32)seqLength;
- }
- return ret;
- #else
- DECL_ASNGETDATA(dataASN, subTreeASN_Length);
- word32 idx = 0;
- int ret = 0;
- (void)heap;
- ALLOC_ASNGETDATA(dataASN, subTreeASN_Length, ret, heap);
- /* Process all subtrees. */
- while ((ret == 0) && (idx < (word32)sz)) {
- byte minVal = 0;
- byte maxVal = 0;
- /* Clear dynamic data and set choice for GeneralName and location to
- * store minimum and maximum.
- */
- XMEMSET(dataASN, 0, sizeof(*dataASN) * subTreeASN_Length);
- GetASN_Choice(&dataASN[SUBTREEASN_IDX_BASE], generalNameChoice);
- GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MIN], &minVal);
- GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MAX], &maxVal);
- /* Parse GeneralSubtree. */
- ret = GetASN_Items(subTreeASN, dataASN, subTreeASN_Length, 0, input,
- &idx, sz);
- if (ret == 0) {
- byte t = dataASN[SUBTREEASN_IDX_BASE].tag;
- /* Check GeneralName tag is one of the types we can handle. */
- if (t == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE) ||
- t == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE) ||
- t == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
- /* Parse the general name and store a new entry. */
- ret = DecodeSubtreeGeneralName(input +
- GetASNItem_DataIdx(dataASN[SUBTREEASN_IDX_BASE], input),
- dataASN[SUBTREEASN_IDX_BASE].length, t, head, heap);
- }
- /* Skip entry. */
- }
- }
- FREE_ASNGETDATA(dataASN, heap);
- return ret;
- #endif
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for NameConstraints.
- * X.509: RFC 5280, 4.2.1.10 - Name Contraints.
- */
- static const ASNItem nameConstraintsASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* permittedSubtrees */
- /* PERMIT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
- /* excludededSubtrees */
- /* EXCLUDE */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
- };
- enum {
- NAMECONSTRAINTSASN_IDX_SEQ = 0,
- NAMECONSTRAINTSASN_IDX_PERMIT,
- NAMECONSTRAINTSASN_IDX_EXCLUDE
- };
- /* Number of items in ASN.1 template for NameConstraints. */
- #define nameConstraintsASN_Length (sizeof(nameConstraintsASN) / sizeof(ASNItem))
- #endif
- /* Decode name constraints extension in a certificate.
- *
- * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
- *
- * @param [in] input Buffer holding data.
- * @param [in] sz Size of data in buffer.
- * @param [in, out] cert Certificate object.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return MEMORY_E on dynamic memory allocation failure.
- */
- static int DecodeNameConstraints(const byte* input, word32 sz,
- DecodedCert* cert)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0;
- int length = 0;
- WOLFSSL_ENTER("DecodeNameConstraints");
- if (GetSequence(input, &idx, &length, sz) < 0) {
- WOLFSSL_MSG("\tfail: should be a SEQUENCE");
- return ASN_PARSE_E;
- }
- while (idx < (word32)sz) {
- byte b = input[idx++];
- Base_entry** subtree = NULL;
- if (GetLength(input, &idx, &length, sz) <= 0) {
- WOLFSSL_MSG("\tinvalid length");
- return ASN_PARSE_E;
- }
- if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
- subtree = &cert->permittedNames;
- else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
- subtree = &cert->excludedNames;
- else {
- WOLFSSL_MSG("\tinvalid subtree");
- return ASN_PARSE_E;
- }
- if (DecodeSubtree(input + idx, (word32)length, subtree,
- cert->heap) < 0) {
- WOLFSSL_MSG("\terror parsing subtree");
- return ASN_PARSE_E;
- }
- idx += (word32)length;
- }
- return 0;
- #else
- DECL_ASNGETDATA(dataASN, nameConstraintsASN_Length);
- word32 idx = 0;
- int ret = 0;
- CALLOC_ASNGETDATA(dataASN, nameConstraintsASN_Length, ret, cert->heap);
- if (ret == 0) {
- /* Parse NameConstraints. */
- ret = GetASN_Items(nameConstraintsASN, dataASN,
- nameConstraintsASN_Length, 1, input, &idx, sz);
- }
- if (ret == 0) {
- /* If there was a permittedSubtrees then parse it. */
- if (dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data != NULL) {
- ret = DecodeSubtree(
- dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data,
- dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.length,
- &cert->permittedNames, cert->heap);
- }
- }
- if (ret == 0) {
- /* If there was a excludedSubtrees then parse it. */
- if (dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data != NULL) {
- ret = DecodeSubtree(
- dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data,
- dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.length,
- &cert->excludedNames, cert->heap);
- }
- }
- FREE_ASNGETDATA(dataASN, cert->heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #endif /* IGNORE_NAME_CONSTRAINTS */
- #if (defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_SEP)) || \
- defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- /* Decode ITU-T X.690 OID format to a string representation
- * return string length */
- int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz)
- {
- word32 val, inIdx = 0, outIdx = 0;
- int w = 0;
- if (out == NULL || in == NULL || outSz < 4 || inSz < 2)
- return BAD_FUNC_ARG;
- /* The first byte expands into b/40 dot b%40. */
- val = in[inIdx++];
- w = XSNPRINTF(out, outSz, "%u.%u", val / 40, val % 40);
- if (w < 0) {
- w = BUFFER_E;
- goto exit;
- }
- outIdx += w;
- val = 0;
- while (inIdx < inSz && outIdx < outSz) {
- /* extract the next OID digit from in to val */
- /* first bit is used to set if value is coded on 1 or multiple bytes */
- if (in[inIdx] & 0x80) {
- val += in[inIdx] & 0x7F;
- val *= 128;
- }
- else {
- /* write val as text into out */
- val += in[inIdx];
- w = XSNPRINTF(out + outIdx, outSz - outIdx, ".%u", val);
- if (w < 0 || (word32)w > outSz - outIdx) {
- w = BUFFER_E;
- goto exit;
- }
- outIdx += w;
- val = 0;
- }
- inIdx++;
- }
- if (outIdx == outSz)
- outIdx--;
- out[outIdx] = 0;
- w = (int)outIdx;
- exit:
- return w;
- }
- #endif /* WOLFSSL_CERT_EXT && !WOLFSSL_SEP */
- #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_QT)
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for PolicyInformation.
- * X.509: RFC 5280, 4.2.1.4 - Certificate Policies.
- */
- static const ASNItem policyInfoASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* policyIdentifier */
- /* ID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* policyQualifiers */
- /* QUALI */ { 1, ASN_SEQUENCE, 1, 0, 1 },
- };
- enum {
- POLICYINFOASN_IDX_SEQ = 0,
- POLICYINFOASN_IDX_ID,
- POLICYINFOASN_IDX_QUALI
- };
- /* Number of items in ASN.1 template for PolicyInformation. */
- #define policyInfoASN_Length (sizeof(policyInfoASN) / sizeof(ASNItem))
- #endif
- /* Reference: https://tools.ietf.org/html/rfc5280#section-4.2.1.4 */
- static int DecodeCertPolicy(const byte* input, word32 sz, DecodedCert* cert)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0;
- word32 oldIdx;
- int policy_length = 0;
- int ret;
- int total_length = 0;
- #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
- !defined(WOLFSSL_DUP_CERTPOL)
- int i;
- #endif
- WOLFSSL_ENTER("DecodeCertPolicy");
- #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
- /* Check if cert is null before dereferencing below */
- if (cert == NULL)
- return BAD_FUNC_ARG;
- #else
- (void)cert;
- #endif
- #if defined(WOLFSSL_CERT_EXT)
- cert->extCertPoliciesNb = 0;
- #endif
- if (GetSequence(input, &idx, &total_length, sz) < 0) {
- WOLFSSL_MSG("\tGet CertPolicy total seq failed");
- return ASN_PARSE_E;
- }
- /* Validate total length */
- if (total_length > (int)(sz - idx)) {
- WOLFSSL_MSG("\tCertPolicy length mismatch");
- return ASN_PARSE_E;
- }
- /* Unwrap certificatePolicies */
- do {
- int length = 0;
- if (GetSequence(input, &idx, &policy_length, sz) < 0) {
- WOLFSSL_MSG("\tGet CertPolicy seq failed");
- return ASN_PARSE_E;
- }
- oldIdx = idx;
- ret = GetASNObjectId(input, &idx, &length, sz);
- if (ret != 0)
- return ret;
- policy_length -= (int)(idx - oldIdx);
- if (length > 0) {
- /* Verify length won't overrun buffer */
- if (length > (int)(sz - idx)) {
- WOLFSSL_MSG("\tCertPolicy length exceeds input buffer");
- return ASN_PARSE_E;
- }
- #if defined(WOLFSSL_SEP)
- cert->deviceType = (byte*)XMALLOC((size_t)length, cert->heap,
- DYNAMIC_TYPE_X509_EXT);
- if (cert->deviceType == NULL) {
- WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
- return MEMORY_E;
- }
- cert->deviceTypeSz = length;
- XMEMCPY(cert->deviceType, input + idx, (size_t)length);
- break;
- #elif defined(WOLFSSL_CERT_EXT)
- /* decode cert policy */
- if (DecodePolicyOID(cert->extCertPolicies[
- cert->extCertPoliciesNb], MAX_CERTPOL_SZ,
- input + idx, length) <= 0) {
- WOLFSSL_MSG("\tCouldn't decode CertPolicy");
- WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
- return ASN_PARSE_E;
- }
- #ifndef WOLFSSL_DUP_CERTPOL
- /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
- * NOT appear more than once in a certificate policies
- * extension". This is a sanity check for duplicates.
- * extCertPolicies should only have OID values, additional
- * qualifiers need to be stored in a separate array. */
- for (i = 0; i < cert->extCertPoliciesNb; i++) {
- if (XMEMCMP(cert->extCertPolicies[i],
- cert->extCertPolicies[cert->extCertPoliciesNb],
- MAX_CERTPOL_SZ) == 0) {
- WOLFSSL_MSG("Duplicate policy OIDs not allowed");
- WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
- WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
- return CERTPOLICIES_E;
- }
- }
- #endif /* !WOLFSSL_DUP_CERTPOL */
- cert->extCertPoliciesNb++;
- #else
- WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
- return 0;
- #endif
- }
- idx += (word32)policy_length;
- } while((int)idx < total_length
- #if defined(WOLFSSL_CERT_EXT)
- && cert->extCertPoliciesNb < MAX_CERTPOL_NB
- #endif
- );
- WOLFSSL_LEAVE("DecodeCertPolicy", 0);
- return 0;
- #else /* WOLFSSL_ASN_TEMPLATE */
- word32 idx = 0;
- int ret = 0;
- int total_length = 0;
- #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
- !defined(WOLFSSL_DUP_CERTPOL)
- int i;
- #endif
- WOLFSSL_ENTER("DecodeCertPolicy");
- #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
- /* Check if cert is null before dereferencing below */
- if (cert == NULL)
- ret = BAD_FUNC_ARG;
- #endif
- if (ret == 0) {
- #if defined(WOLFSSL_CERT_EXT)
- cert->extCertPoliciesNb = 0;
- #endif
- /* Strip SEQUENCE OF and check using all data. */
- if (GetASN_Sequence(input, &idx, &total_length, (word32)sz, 1) < 0)
- {
- ret = ASN_PARSE_E;
- }
- }
- /* Unwrap certificatePolicies */
- while ((ret == 0) && ((int)idx < total_length)
- #if defined(WOLFSSL_CERT_EXT)
- && (cert->extCertPoliciesNb < MAX_CERTPOL_NB)
- #endif
- ) {
- ASNGetData dataASN[policyInfoASN_Length];
- byte* data = NULL;
- word32 length = 0;
- /* Clear dynamic data and check OID is a cert policy type. */
- XMEMSET(dataASN, 0, sizeof(dataASN));
- GetASN_OID(&dataASN[POLICYINFOASN_IDX_ID], oidCertPolicyType);
- ret = GetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length, 1,
- input, &idx, (word32)sz);
- if (ret == 0) {
- /* Get the OID. */
- GetASN_OIDData(&dataASN[POLICYINFOASN_IDX_ID], &data, &length);
- if (length == 0) {
- ret = ASN_PARSE_E;
- }
- }
- #if defined(WOLFSSL_SEP)
- /* Store OID in device type. */
- if (ret == 0) {
- cert->deviceType = (byte*)XMALLOC(length, cert->heap,
- DYNAMIC_TYPE_X509_EXT);
- if (cert->deviceType == NULL) {
- WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
- ret = MEMORY_E;
- }
- }
- if (ret == 0) {
- /* Store device type data and length. */
- cert->deviceTypeSz = (int)length;
- XMEMCPY(cert->deviceType, data, length);
- break;
- }
- #elif defined(WOLFSSL_CERT_EXT)
- if (ret == 0) {
- /* Decode cert policy. */
- if (DecodePolicyOID(
- cert->extCertPolicies[cert->extCertPoliciesNb],
- MAX_CERTPOL_SZ, data, length) <= 0) {
- WOLFSSL_MSG("\tCouldn't decode CertPolicy");
- WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
- ret = ASN_PARSE_E;
- }
- }
- #ifndef WOLFSSL_DUP_CERTPOL
- /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
- * NOT appear more than once in a certificate policies
- * extension". This is a sanity check for duplicates.
- * extCertPolicies should only have OID values, additional
- * qualifiers need to be stored in a seperate array. */
- for (i = 0; (ret == 0) && (i < cert->extCertPoliciesNb); i++) {
- if (XMEMCMP(cert->extCertPolicies[i],
- cert->extCertPolicies[cert->extCertPoliciesNb],
- MAX_CERTPOL_SZ) == 0) {
- WOLFSSL_MSG("Duplicate policy OIDs not allowed");
- WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
- WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
- ret = CERTPOLICIES_E;
- }
- }
- #endif /* !defined(WOLFSSL_DUP_CERTPOL) */
- if (ret == 0) {
- /* Keep count of policies seen. */
- cert->extCertPoliciesNb++;
- }
- #else
- (void)data;
- WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
- break;
- #endif
- }
- WOLFSSL_LEAVE("DecodeCertPolicy", 0);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #endif /* WOLFSSL_SEP */
- #ifdef WOLFSSL_SUBJ_DIR_ATTR
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for subject dir attribute.
- * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
- */
- static const ASNItem subjDirAttrASN[] = {
- /* SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
- /* PLEN */ { 2, ASN_SET, 1, 0, 0 },
- };
- enum {
- SUBJDIRATTRASN_IDX_SEQ = 0,
- SUBJDIRATTRASN_IDX_OID,
- SUBJDIRATTRASN_IDX_SET,
- };
- /* Number of items in ASN.1 template for BasicContraints. */
- #define subjDirAttrASN_Length (sizeof(subjDirAttrASN) / sizeof(ASNItem))
- #endif
- /* Decode subject directory attributes extension in a certificate.
- *
- * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
- *
- * @param [in] input Buffer holding data.
- * @param [in] sz Size of data in buffer.
- * @param [in, out] cert Certificate object.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- */
- static int DecodeSubjDirAttr(const byte* input, int sz, DecodedCert* cert)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0;
- int length = 0;
- int ret = 0;
- WOLFSSL_ENTER("DecodeSubjDirAttr");
- #ifdef OPENSSL_ALL
- cert->extSubjDirAttrSrc = input;
- cert->extSubjDirAttrSz = sz;
- #endif /* OPENSSL_ALL */
- /* Unwrap the list of Attributes */
- if (GetSequence(input, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- if (length == 0) {
- /* RFC 5280 4.2.1.8. Subject Directory Attributes
- If the subjectDirectoryAttributes extension is present, the
- sequence MUST contain at least one entry. */
- WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
- return ASN_PARSE_E;
- }
- /* length is the length of the list contents */
- while (idx < (word32)sz) {
- word32 oid;
- if (GetSequence(input, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- if (GetObjectId(input, &idx, &oid, oidSubjDirAttrType, sz) < 0)
- return ASN_PARSE_E;
- if (GetSet(input, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- /* There may be more than one countryOfCitizenship, but save the
- * first one for now. */
- if (oid == SDA_COC_OID) {
- byte tag;
- if (GetHeader(input, &tag, &idx, &length, sz, 1) < 0)
- return ASN_PARSE_E;
- if (length != COUNTRY_CODE_LEN)
- return ASN_PARSE_E;
- if (tag == ASN_PRINTABLE_STRING) {
- XMEMCPY(cert->countryOfCitizenship,
- input + idx, COUNTRY_CODE_LEN);
- cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
- }
- }
- idx += length;
- }
- return ret;
- #else
- DECL_ASNGETDATA(dataASN, subjDirAttrASN_Length);
- int ret = 0;
- word32 idx = 0;
- int length;
- WOLFSSL_ENTER("DecodeSubjDirAttr");
- CALLOC_ASNGETDATA(dataASN, subjDirAttrASN_Length, ret, cert->heap);
- /* Strip outer SEQUENCE. */
- if ((ret == 0) && (GetSequence(input, &idx, &length, sz) < 0)) {
- ret = ASN_PARSE_E;
- }
- /* Handle each inner SEQUENCE. */
- while ((ret == 0) && (idx < (word32)sz)) {
- ret = GetASN_Items(subjDirAttrASN, dataASN, subjDirAttrASN_Length, 1,
- input, &idx, sz);
- /* There may be more than one countryOfCitizenship, but save the
- * first one for now. */
- if ((ret == 0) &&
- (dataASN[SUBJDIRATTRASN_IDX_OID].data.oid.sum == SDA_COC_OID)) {
- int cuLen;
- word32 setIdx = 0;
- byte* setData;
- word32 setLen;
- GetASN_GetRef(&dataASN[SUBJDIRATTRASN_IDX_SET], &setData, &setLen);
- if (GetASNHeader(setData, ASN_PRINTABLE_STRING, &setIdx, &cuLen,
- setLen) < 0) {
- ret = ASN_PARSE_E;
- }
- if ((ret == 0) && (cuLen != COUNTRY_CODE_LEN)) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- XMEMCPY(cert->countryOfCitizenship, setData + setIdx, cuLen);
- cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
- }
- }
- }
- FREE_ASNGETDATA(dataASN, cert->heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #endif /* WOLFSSL_SUBJ_DIR_ATTR */
- #ifdef WOLFSSL_SUBJ_INFO_ACC
- /* Decode subject infomation access extension in a certificate.
- *
- * X.509: RFC 5280, 4.2.2.2 - Subject Information Access.
- *
- * @param [in] input Buffer holding data.
- * @param [in] sz Size of data in buffer.
- * @param [in, out] cert Certificate object.
- * @return 0 on success.
- * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return MEMORY_E on dynamic memory allocation failure.
- */
- static int DecodeSubjInfoAcc(const byte* input, int sz, DecodedCert* cert)
- {
- word32 idx = 0;
- int length = 0;
- int ret = 0;
- WOLFSSL_ENTER("DecodeSubjInfoAcc");
- #ifdef OPENSSL_ALL
- cert->extSubjAltNameSrc = input;
- cert->extSubjAltNameSz = sz;
- #endif /* OPENSSL_ALL */
- /* Unwrap SubjectInfoAccessSyntax, the list of AccessDescriptions */
- if (GetSequence(input, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- if (length == 0) {
- /* RFC 5280 4.2.2.2. Subject Information Access
- If the subjectInformationAccess extension is present, the
- sequence MUST contain at least one entry. */
- WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
- return ASN_PARSE_E;
- }
- /* Per fpkx-x509-cert-profile-common... section 5.3.
- * [The] subjectInfoAccess extension must contain at least one
- * instance of the id-ad-caRepository access method containing a
- * publicly accessible HTTP URI which returns as certs-only
- * CMS.
- */
- while (idx < (word32)sz) {
- word32 oid = 0;
- byte b;
- /* Unwrap an AccessDescription */
- if (GetSequence(input, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- /* Get the accessMethod */
- if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0)
- return ASN_PARSE_E;
- /* Only supporting URIs right now. */
- if (GetASNTag(input, &idx, &b, sz) < 0)
- return ASN_PARSE_E;
- if (GetLength(input, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- /* Set caRepo entry */
- if (b == GENERALNAME_URI && oid == AIA_CA_REPO_OID) {
- cert->extSubjInfoAccCaRepoSz = length;
- cert->extSubjInfoAccCaRepo = input + idx;
- break;
- }
- idx += length;
- }
- if (cert->extSubjInfoAccCaRepo == NULL ||
- cert->extSubjInfoAccCaRepoSz == 0) {
- WOLFSSL_MSG("SubjectInfoAccess missing an URL.");
- ret = ASN_PARSE_E;
- }
- WOLFSSL_LEAVE("DecodeSubjInfoAcc", ret);
- return ret;
- }
- #endif /* WOLFSSL_SUBJ_INFO_ACC */
- /* Macro to check if bit is set, if not sets and return success.
- Otherwise returns failure */
- /* Macro required here because bit-field operation */
- #ifndef WOLFSSL_NO_ASN_STRICT
- #define VERIFY_AND_SET_OID(bit) \
- if ((bit) == 0) \
- (bit) = 1; \
- else \
- return ASN_OBJECT_ID_E;
- #else
- /* With no strict defined, the verify is skipped */
- #define VERIFY_AND_SET_OID(bit) bit = 1;
- #endif
- /* Parse extension type specific data based on OID sum.
- *
- * Supported extensions:
- * Basic Constraints - BASIC_CA_OID
- * CRL Distribution Points - CRL_DIST_OID
- * Authority Information Access - AUTH_INFO_OID
- * Subject Alternative Name - ALT_NAMES_OID
- * Authority Key Identifier - AUTH_KEY_OID
- * Subject Key Identifier - SUBJ_KEY_OID
- * Certificate Policies - CERT_POLICY_OID (conditional parsing)
- * Key Usage - KEY_USAGE_OID
- * Extended Key Usage - EXT_KEY_USAGE_OID
- * Name Constraints - NAME_CONS_OID
- * Inhibit anyPolicy - INHIBIT_ANY_OID
- * Netscape Certificate Type - NETSCAPE_CT_OID (able to be excluded)
- * OCSP no check - OCSP_NOCHECK_OID (when compiling OCSP)
- * Subject Directory Attributes - SUBJ_DIR_ATTR_OID
- * Subject Information Access - SUBJ_INFO_ACC_OID
- * Unsupported extensions from RFC 5280:
- * 4.2.1.5 - Policy mappings
- * 4.2.1.7 - Issuer Alternative Name
- * 4.2.1.11 - Policy Constraints
- * 4.2.1.15 - Freshest CRL
- *
- * @param [in] input Buffer containing extension type specific data.
- * @param [in] length Length of data.
- * @param [in] oid OID sum for extension.
- * @param [in] critical Whether extension is critical.
- * @param [in, out] cert Certificate object.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoding is invalid.
- * @return MEMORY_E on dynamic memory allocation failure.
- * @return Other negative values on error.
- */
- static int DecodeExtensionType(const byte* input, word32 length, word32 oid,
- byte critical, DecodedCert* cert,
- int *isUnknownExt)
- {
- int ret = 0;
- word32 idx = 0;
- if (isUnknownExt != NULL)
- *isUnknownExt = 0;
- switch (oid) {
- /* Basic Constraints. */
- case BASIC_CA_OID:
- VERIFY_AND_SET_OID(cert->extBasicConstSet);
- cert->extBasicConstCrit = critical ? 1 : 0;
- if (DecodeBasicCaConstraint(input, (int)length, cert) < 0) {
- ret = ASN_PARSE_E;
- }
- break;
- /* CRL Distribution point. */
- case CRL_DIST_OID:
- VERIFY_AND_SET_OID(cert->extCRLdistSet);
- cert->extCRLdistCrit = critical ? 1 : 0;
- if (DecodeCrlDist(input, length, cert) < 0) {
- ret = ASN_PARSE_E;
- }
- break;
- /* Authority information access. */
- case AUTH_INFO_OID:
- VERIFY_AND_SET_OID(cert->extAuthInfoSet);
- cert->extAuthInfoCrit = critical ? 1 : 0;
- if (DecodeAuthInfo(input, length, cert) < 0) {
- ret = ASN_PARSE_E;
- }
- break;
- /* Subject alternative name. */
- case ALT_NAMES_OID:
- VERIFY_AND_SET_OID(cert->extSubjAltNameSet);
- cert->extSubjAltNameCrit = critical ? 1 : 0;
- ret = DecodeAltNames(input, length, cert);
- break;
- /* Authority Key Identifier. */
- case AUTH_KEY_OID:
- VERIFY_AND_SET_OID(cert->extAuthKeyIdSet);
- cert->extAuthKeyIdCrit = critical ? 1 : 0;
- #ifndef WOLFSSL_ALLOW_CRIT_SKID
- /* This check is added due to RFC 5280 section 4.2.1.1
- * stating that conforming CA's must mark this extension
- * as non-critical. When parsing extensions check that
- * certificate was made in compliance with this. */
- if (critical) {
- WOLFSSL_MSG("Critical Auth Key ID is not allowed");
- WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
- ret = ASN_CRIT_EXT_E;
- }
- #endif
- if ((ret == 0) && (DecodeAuthKeyId(input, length, cert) < 0)) {
- ret = ASN_PARSE_E;
- }
- break;
- /* Subject Key Identifier. */
- case SUBJ_KEY_OID:
- VERIFY_AND_SET_OID(cert->extSubjKeyIdSet);
- cert->extSubjKeyIdCrit = critical ? 1 : 0;
- #ifndef WOLFSSL_ALLOW_CRIT_SKID
- /* This check is added due to RFC 5280 section 4.2.1.2
- * stating that conforming CA's must mark this extension
- * as non-critical. When parsing extensions check that
- * certificate was made in compliance with this. */
- if (critical) {
- WOLFSSL_MSG("Critical Subject Key ID is not allowed");
- WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
- ret = ASN_CRIT_EXT_E;
- }
- #endif
- if ((ret == 0) && (DecodeSubjKeyId(input, length, cert) < 0)) {
- ret = ASN_PARSE_E;
- }
- break;
- /* Certificate policies. */
- case CERT_POLICY_OID:
- #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT)
- VERIFY_AND_SET_OID(cert->extCertPolicySet);
- #if defined(OPENSSL_EXTRA) || \
- defined(OPENSSL_EXTRA_X509_SMALL)
- cert->extCertPolicyCrit = critical ? 1 : 0;
- #endif
- #endif
- #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || \
- defined(WOLFSSL_QT)
- if (DecodeCertPolicy(input, length, cert) < 0) {
- ret = ASN_PARSE_E;
- }
- #else
- WOLFSSL_MSG("Certificate Policy extension not supported yet.");
- #endif
- break;
- /* Key usage. */
- case KEY_USAGE_OID:
- VERIFY_AND_SET_OID(cert->extKeyUsageSet);
- cert->extKeyUsageCrit = critical ? 1 : 0;
- if (DecodeKeyUsage(input, length, cert) < 0) {
- ret = ASN_PARSE_E;
- }
- break;
- /* Extended key usage. */
- case EXT_KEY_USAGE_OID:
- VERIFY_AND_SET_OID(cert->extExtKeyUsageSet);
- cert->extExtKeyUsageCrit = critical ? 1 : 0;
- if (DecodeExtKeyUsage(input, length, cert) < 0) {
- ret = ASN_PARSE_E;
- }
- break;
- #ifndef IGNORE_NAME_CONSTRAINTS
- /* Name constraints. */
- case NAME_CONS_OID:
- #ifndef WOLFSSL_NO_ASN_STRICT
- /* Verify RFC 5280 Sec 4.2.1.10 rule:
- "The name constraints extension,
- which MUST be used only in a CA certificate" */
- if (!cert->isCA) {
- WOLFSSL_MSG("Name constraints allowed only for CA certs");
- WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
- ret = ASN_NAME_INVALID_E;
- }
- #endif
- VERIFY_AND_SET_OID(cert->extNameConstraintSet);
- cert->extNameConstraintCrit = critical ? 1 : 0;
- if (DecodeNameConstraints(input, length, cert) < 0) {
- ret = ASN_PARSE_E;
- }
- break;
- #endif /* IGNORE_NAME_CONSTRAINTS */
- /* Inhibit anyPolicy. */
- case INHIBIT_ANY_OID:
- VERIFY_AND_SET_OID(cert->inhibitAnyOidSet);
- WOLFSSL_MSG("Inhibit anyPolicy extension not supported yet.");
- break;
- #ifndef IGNORE_NETSCAPE_CERT_TYPE
- /* Netscape's certificate type. */
- case NETSCAPE_CT_OID:
- if (DecodeNsCertType(input, (int)length, cert) < 0)
- ret = ASN_PARSE_E;
- break;
- #endif
- #ifdef HAVE_OCSP
- /* OCSP no check. */
- case OCSP_NOCHECK_OID:
- VERIFY_AND_SET_OID(cert->ocspNoCheckSet);
- ret = GetASNNull(input, &idx, length);
- if (ret != 0) {
- ret = ASN_PARSE_E;
- }
- break;
- #endif
- case POLICY_CONST_OID:
- VERIFY_AND_SET_OID(cert->extPolicyConstSet);
- cert->extPolicyConstCrit = critical ? 1 : 0;
- if (DecodePolicyConstraints(&input[idx], (int)length, cert) < 0)
- return ASN_PARSE_E;
- break;
- #ifdef WOLFSSL_SUBJ_DIR_ATTR
- case SUBJ_DIR_ATTR_OID:
- VERIFY_AND_SET_OID(cert->extSubjDirAttrSet);
- if (DecodeSubjDirAttr(&input[idx], length, cert) < 0)
- return ASN_PARSE_E;
- break;
- #endif
- #ifdef WOLFSSL_SUBJ_INFO_ACC
- case SUBJ_INFO_ACC_OID:
- VERIFY_AND_SET_OID(cert->extSubjInfoAccSet);
- if (DecodeSubjInfoAcc(&input[idx], length, cert) < 0)
- return ASN_PARSE_E;
- break;
- #endif
- default:
- if (isUnknownExt != NULL)
- *isUnknownExt = 1;
- #ifndef WOLFSSL_NO_ASN_STRICT
- /* While it is a failure to not support critical extensions,
- * still parse the certificate ignoring the unsupported
- * extension to allow caller to accept it with the verify
- * callback. */
- if (critical) {
- WOLFSSL_ERROR_VERBOSE(ASN_CRIT_EXT_E);
- ret = ASN_CRIT_EXT_E;
- }
- #endif
- break;
- }
- return ret;
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for extensions.
- * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
- */
- static const ASNItem certExtHdrASN[] = {
- /* EXTTAG */ { 0, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 0 },
- /* EXTSEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- };
- enum {
- CERTEXTHDRASN_IDX_EXTTAG = 0,
- CERTEXTHDRASN_IDX_EXTSEQ
- };
- /* Number of itesm in ASN.1 template for extensions. */
- #define certExtHdrASN_Length (sizeof(certExtHdrASN) / sizeof(ASNItem))
- /* ASN.1 template for Extension.
- * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
- */
- static const ASNItem certExtASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* Extension object id */
- /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* critical - when true, must be parseable. */
- /* CRIT */ { 1, ASN_BOOLEAN, 0, 0, 1 },
- /* Data for extension - leave index at start of data. */
- /* VAL */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
- };
- enum {
- CERTEXTASN_IDX_SEQ = 0,
- CERTEXTASN_IDX_OID,
- CERTEXTASN_IDX_CRIT,
- CERTEXTASN_IDX_VAL
- };
- /* Number of items in ASN.1 template for Extension. */
- #define certExtASN_Length (sizeof(certExtASN) / sizeof(ASNItem))
- #endif
- #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \
- && defined(HAVE_OID_DECODING)
- int wc_SetUnknownExtCallback(DecodedCert* cert,
- wc_UnknownExtCallback cb) {
- if (cert == NULL) {
- return BAD_FUNC_ARG;
- }
- cert->unknownExtCallback = cb;
- return 0;
- }
- #endif
- /*
- * Processing the Certificate Extensions. This does not modify the current
- * index. It is works starting with the recorded extensions pointer.
- */
- static int DecodeCertExtensions(DecodedCert* cert)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret = 0;
- word32 idx = 0;
- word32 sz = (word32)cert->extensionsSz;
- const byte* input = cert->extensions;
- int length;
- word32 oid;
- byte critical = 0;
- byte criticalFail = 0;
- byte tag = 0;
- WOLFSSL_ENTER("DecodeCertExtensions");
- if (input == NULL || sz == 0)
- return BAD_FUNC_ARG;
- #ifdef WOLFSSL_CERT_REQ
- if (!cert->isCSR)
- #endif
- { /* Not included in CSR */
- if (GetASNTag(input, &idx, &tag, sz) < 0) {
- return ASN_PARSE_E;
- }
- if (tag != ASN_EXTENSIONS) {
- WOLFSSL_MSG("\tfail: should be an EXTENSIONS");
- return ASN_PARSE_E;
- }
- if (GetLength(input, &idx, &length, sz) < 0) {
- WOLFSSL_MSG("\tfail: invalid length");
- return ASN_PARSE_E;
- }
- }
- if (GetSequence(input, &idx, &length, sz) < 0) {
- WOLFSSL_MSG("\tfail: should be a SEQUENCE (1)");
- return ASN_PARSE_E;
- }
- while (idx < (word32)sz) {
- word32 localIdx;
- if (GetSequence(input, &idx, &length, sz) < 0) {
- WOLFSSL_MSG("\tfail: should be a SEQUENCE");
- return ASN_PARSE_E;
- }
- oid = 0;
- if ((ret = GetObjectId(input, &idx, &oid, oidCertExtType, sz)) < 0) {
- WOLFSSL_MSG("\tfail: OBJECT ID");
- return ret;
- }
- /* check for critical flag */
- critical = 0;
- if ((idx + 1) > (word32)sz) {
- WOLFSSL_MSG("\tfail: malformed buffer");
- return BUFFER_E;
- }
- localIdx = idx;
- if (GetASNTag(input, &localIdx, &tag, sz) == 0) {
- if (tag == ASN_BOOLEAN) {
- ret = GetBoolean(input, &idx, sz);
- if (ret < 0) {
- WOLFSSL_MSG("\tfail: critical boolean");
- return ret;
- }
- critical = (byte)ret;
- }
- }
- /* process the extension based on the OID */
- ret = GetOctetString(input, &idx, &length, sz);
- if (ret < 0) {
- WOLFSSL_MSG("\tfail: bad OCTET STRING");
- return ret;
- }
- ret = DecodeExtensionType(input + idx, (word32)length, oid, critical,
- cert, NULL);
- if (ret == ASN_CRIT_EXT_E) {
- ret = 0;
- criticalFail = 1;
- }
- if (ret < 0)
- goto end;
- idx += (word32)length;
- }
- ret = criticalFail ? ASN_CRIT_EXT_E : 0;
- end:
- return ret;
- #else
- DECL_ASNGETDATA(dataASN, certExtASN_Length);
- ASNGetData dataExtsASN[certExtHdrASN_Length];
- int ret = 0;
- const byte* input = cert->extensions;
- int sz = cert->extensionsSz;
- word32 idx = 0;
- int criticalRet = 0;
- int offset = 0;
- WOLFSSL_ENTER("DecodeCertExtensions");
- if (input == NULL || sz == 0)
- ret = BAD_FUNC_ARG;
- ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, cert->heap);
- #ifdef WOLFSSL_CERT_REQ
- if (cert->isCSR) {
- offset = CERTEXTHDRASN_IDX_EXTSEQ;
- }
- #endif
- if (ret == 0) {
- /* Clear dynamic data. */
- XMEMSET(dataExtsASN, 0, sizeof(dataExtsASN));
- /* Parse extensions header. */
- ret = GetASN_Items(certExtHdrASN + offset, dataExtsASN + offset,
- (int)(certExtHdrASN_Length - (size_t)offset), 0,
- input, &idx, (word32)sz);
- }
- /* Parse each extension. */
- while ((ret == 0) && (idx < (word32)sz)) {
- byte critical = 0;
- int isUnknownExt = 0;
- /* Clear dynamic data. */
- XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
- /* Ensure OID is an extention type. */
- GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
- /* Set criticality variable. */
- GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
- /* Parse extension wrapper. */
- ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
- &idx, (word32)sz);
- if (ret == 0) {
- word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
- word32 length = dataASN[CERTEXTASN_IDX_VAL].length;
- /* Decode the extension by type. */
- ret = DecodeExtensionType(input + idx, length, oid, critical, cert,
- &isUnknownExt);
- #if defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_DECODING)
- if (isUnknownExt && (cert->unknownExtCallback != NULL)) {
- word16 decOid[MAX_OID_SZ];
- word32 decOidSz = sizeof(decOid);
- ret = DecodeObjectId(
- dataASN[CERTEXTASN_IDX_OID].data.oid.data,
- dataASN[CERTEXTASN_IDX_OID].data.oid.length,
- decOid, &decOidSz);
- if (ret != 0) {
- /* Should never get here as the extension was successfully
- * decoded earlier. Something might be corrupted. */
- WOLFSSL_MSG("DecodeObjectId() failed. Corruption?");
- WOLFSSL_ERROR(ret);
- }
- ret = cert->unknownExtCallback(decOid, decOidSz, critical,
- dataASN[CERTEXTASN_IDX_VAL].data.buffer.data,
- dataASN[CERTEXTASN_IDX_VAL].length);
- }
- #endif
- (void)isUnknownExt;
- /* Move index on to next extension. */
- idx += length;
- }
- /* Don't fail criticality until all other extensions have been checked.
- */
- if (ret == ASN_CRIT_EXT_E) {
- criticalRet = ASN_CRIT_EXT_E;
- ret = 0;
- }
- }
- if (ret == 0) {
- /* Use criticality return. */
- ret = criticalRet;
- }
- FREE_ASNGETDATA(dataASN, cert->heap);
- return ret;
- #endif
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN template for an X509 certificate.
- * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
- */
- static const ASNItem x509CertASN[] = {
- /* Certificate ::= SEQUENCE */
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* tbsCertificate TBSCertificate */
- /* TBSCertificate ::= SEQUENCE */
- /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* version [0] EXPLICT Version DEFAULT v1 */
- /* TBS_VER */ { 2, ASN_CONTEXT_SPECIFIC | ASN_X509_CERT_VERSION, 1, 1, 1 },
- /* Version ::= INTEGER { v1(0), v2(1), v3(2) */
- /* TBS_VER_INT */ { 3, ASN_INTEGER, 0, 0, 0 },
- /* serialNumber CertificateSerialNumber */
- /* CetificateSerialNumber ::= INTEGER */
- /* TBS_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
- /* signature AlgorithmIdentifier */
- /* AlgorithmIdentifier ::= SEQUENCE */
- /* TBS_ALGOID_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
- /* Algorithm OBJECT IDENTIFIER */
- /* TBS_ALGOID_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
- /* parameters ANY defined by algorithm OPTIONAL */
- /* TBS_ALGOID_PARAMS_NULL */ { 3, ASN_TAG_NULL, 0, 0, 2 },
- #ifdef WC_RSA_PSS
- /* TBS_ALGOID_PARAMS */ { 3, ASN_SEQUENCE, 1, 0, 2 },
- #endif
- /* issuer Name */
- /* TBS_ISSUER_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
- /* validity Validity */
- /* Validity ::= SEQUENCE */
- /* TBS_VALIDITY_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
- /* notBefore Time */
- /* Time :: CHOICE { UTCTime, GeneralizedTime } */
- /* TBS_VALIDITY_NOTB_UTC */ { 3, ASN_UTC_TIME, 0, 0, 2 },
- /* TBS_VALIDITY_NOTB_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 2 },
- /* notAfter Time */
- /* Time :: CHOICE { UTCTime, GeneralizedTime } */
- /* TBS_VALIDITY_NOTA_UTC */ { 3, ASN_UTC_TIME, 0, 0, 3 },
- /* TBS_VALIDITY_NOTA_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 3 },
- /* subject Name */
- /* TBS_SUBJECT_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
- /* subjectPublicKeyInfo SubjectPublicKeyInfo */
- /* TBS_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
- /* algorithm AlgorithmIdentifier */
- /* AlgorithmIdentifier ::= SEQUENCE */
- /* TBS_SPUBKEYINFO_ALGO_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
- /* Algorithm OBJECT IDENTIFIER */
- /* TBS_SPUBKEYINFO_ALGO_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
- /* parameters ANY defined by algorithm OPTIONAL */
- /* TBS_SPUBKEYINFO_ALGO_NULL */ { 4, ASN_TAG_NULL, 0, 0, 2 },
- /* TBS_SPUBKEYINFO_ALGO_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 2 },
- #ifdef WC_RSA_PSS
- /* TBS_SPUBKEYINFO_ALGO_P_SEQ */ { 4, ASN_SEQUENCE, 1, 0, 2 },
- #endif
- /* subjectPublicKey BIT STRING */
- /* TBS_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
- /* issuerUniqueID UniqueIdentfier OPTIONAL */
- /* TBS_ISSUERUID */ { 2, ASN_CONTEXT_SPECIFIC | 1, 0, 0, 1 },
- /* subjectUniqueID UniqueIdentfier OPTIONAL */
- /* TBS_SUBJECTUID */ { 2, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 1 },
- /* extensions Extensions OPTIONAL */
- /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 1 },
- /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
- /* signatureAlgorithm AlgorithmIdentifier */
- /* AlgorithmIdentifier ::= SEQUENCE */
- /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* Algorithm OBJECT IDENTIFIER */
- /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
- /* parameters ANY defined by algorithm OPTIONAL */
- /* SIGALGO_PARAMS_NULL */ { 2, ASN_TAG_NULL, 0, 0, 2 },
- #ifdef WC_RSA_PSS
- /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
- #endif
- /* signature BIT STRING */
- /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
- };
- enum {
- X509CERTASN_IDX_SEQ = 0,
- X509CERTASN_IDX_TBS_SEQ,
- X509CERTASN_IDX_TBS_VER,
- X509CERTASN_IDX_TBS_VER_INT,
- X509CERTASN_IDX_TBS_SERIAL,
- X509CERTASN_IDX_TBS_ALGOID_SEQ,
- X509CERTASN_IDX_TBS_ALGOID_OID,
- X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL,
- #ifdef WC_RSA_PSS
- X509CERTASN_IDX_TBS_ALGOID_PARAMS,
- #endif
- X509CERTASN_IDX_TBS_ISSUER_SEQ,
- X509CERTASN_IDX_TBS_VALIDITY_SEQ,
- X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC,
- X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT,
- X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC,
- X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT,
- X509CERTASN_IDX_TBS_SUBJECT_SEQ,
- X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ,
- X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
- X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID,
- X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_NULL,
- X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID,
- #ifdef WC_RSA_PSS
- X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_P_SEQ,
- #endif
- X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY,
- X509CERTASN_IDX_TBS_ISSUERUID,
- X509CERTASN_IDX_TBS_SUBJECTUID,
- X509CERTASN_IDX_TBS_EXT,
- X509CERTASN_IDX_TBS_EXT_SEQ,
- X509CERTASN_IDX_SIGALGO_SEQ,
- X509CERTASN_IDX_SIGALGO_OID,
- X509CERTASN_IDX_SIGALGO_PARAMS_NULL,
- #ifdef WC_RSA_PSS
- X509CERTASN_IDX_SIGALGO_PARAMS,
- #endif
- X509CERTASN_IDX_SIGNATURE,
- WOLF_ENUM_DUMMY_LAST_ELEMENT(X509CERTASN_IDX)
- };
- /* Number of items in ASN template for an X509 certificate. */
- #define x509CertASN_Length (sizeof(x509CertASN) / sizeof(ASNItem))
- /* Check the data data.
- *
- * @param [in] dataASN ASN template dynamic data item.
- * @param [in] dataType BEFORE or AFTER date.
- * @return 0 on success.
- * @return ASN_TIME_E when BER tag is nor UTC or GENERALIZED time.
- * @return ASN_DATE_SZ_E when time data is not supported.
- * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
- * @return ASN_AFTER_DATE_E when AFTER date is invalid.
- */
- static int CheckDate(ASNGetData *dataASN, int dateType)
- {
- int ret = 0;
- /* Check BER tag is valid. */
- if ((dataASN->tag != ASN_UTC_TIME) &&
- (dataASN->tag != ASN_GENERALIZED_TIME)) {
- ret = ASN_TIME_E;
- }
- /* Check date length is valid. */
- if ((ret == 0) && ((dataASN->length > MAX_DATE_SIZE) ||
- (dataASN->length < MIN_DATE_SIZE))) {
- ret = ASN_DATE_SZ_E;
- }
- #ifndef NO_ASN_TIME_CHECK
- /* Check date is a valid string and BEFORE or AFTER now. */
- if ((ret == 0) &&
- (!XVALIDATE_DATE(dataASN->data.ref.data, dataASN->tag, dateType))) {
- if (dateType == BEFORE) {
- ret = ASN_BEFORE_DATE_E;
- }
- else {
- ret = ASN_AFTER_DATE_E;
- }
- }
- #endif
- (void)dateType;
- return ret;
- }
- /* Decode a certificate. Internal/non-public API.
- *
- * @param [in] cert Certificate object.
- * @param [in] verify Whether to verify dates before and after now.
- * @param [out] criticalExt Critical extension return code.
- * @param [out] badDateRet Bad date return code.
- * @param [in] stopAtPubKey Stop parsing before subkectPublicKeyInfo.
- * @param [in] stopAfterPubKey Stop parsing after subkectPublicKeyInfo.
- * @return 0 on success.
- * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
- * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
- * @return ASN_DATE_SZ_E when time data is not supported.
- * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
- * @return ASN_AFTER_DATE_E when AFTER date is invalid.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- */
- static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
- int* badDateRet, int stopAtPubKey,
- int stopAfterPubKey)
- {
- DECL_ASNGETDATA(dataASN, x509CertASN_Length);
- int ret = 0;
- int badDate = 0;
- byte version;
- word32 idx;
- word32 serialSz;
- const unsigned char* issuer = NULL;
- word32 issuerSz = 0;
- const unsigned char* subject = NULL;
- word32 subjectSz = 0;
- word32 pubKeyOffset = 0;
- word32 pubKeyEnd = 0;
- int done = 0;
- CALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
- if (ret == 0) {
- version = 0;
- serialSz = EXTERNAL_SERIAL_SIZE;
- /* Get the version and put the serial number into the buffer. */
- GetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT], &version);
- GetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
- &serialSz);
- /* Check OID types for signature, algorithm, ECC curve and sigAlg. */
- GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
- GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
- oidKeyType);
- GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
- oidCurveType);
- GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
- /* Parse the X509 certificate. */
- ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1,
- cert->source, &cert->srcIdx, cert->maxIdx);
- #ifdef WOLFSSL_CLANG_TIDY
- /* work around clang-tidy false positive re cert->source. */
- if ((ret == 0) && (cert->source == NULL)) {
- ret = ASN_PARSE_E;
- }
- #endif
- }
- /* Check version is valid/supported - can't be negative. */
- if ((ret == 0) && (version > MAX_X509_VERSION)) {
- WOLFSSL_MSG("Unexpected certificate version");
- WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- int i;
- pubKeyOffset = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset;
- /* Set fields extracted from data. */
- cert->version = version;
- cert->serialSz = (int)serialSz;
- cert->signatureOID = dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum;
- cert->keyOID = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID].data.oid.sum;
- cert->certBegin = dataASN[X509CERTASN_IDX_TBS_SEQ].offset;
- /* No bad date error - don't always care. */
- badDate = 0;
- /* Find the item with the BEFORE date and check it. */
- i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].tag != 0)
- ? X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC
- : X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT;
- if ((CheckDate(&dataASN[i], BEFORE) < 0) && verify) {
- badDate = ASN_BEFORE_DATE_E;
- }
- /* Store reference to BEFOREdate. */
- cert->beforeDate = GetASNItem_Addr(dataASN[i], cert->source);
- cert->beforeDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);
- /* Find the item with the AFTER date and check it. */
- i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].tag != 0)
- ? X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC
- : X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT;
- if ((CheckDate(&dataASN[i], AFTER) < 0) && verify) {
- badDate = ASN_AFTER_DATE_E;
- }
- /* Store reference to AFTER date. */
- cert->afterDate = GetASNItem_Addr(dataASN[i], cert->source);
- cert->afterDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);
- /* Get the issuer name. */
- issuer = cert->source + dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
- issuerSz = dataASN[X509CERTASN_IDX_TBS_VALIDITY_SEQ].offset -
- dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
- /* Get the subject name. */
- subject = cert->source +
- dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
- subjectSz = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset -
- dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
- }
- if ((ret == 0) && stopAtPubKey) {
- /* Return any bad date error through badDateRet and return offset of
- * subjectPublicKeyInfo.
- */
- if (badDateRet != NULL) {
- *badDateRet = badDate;
- }
- done = 1;
- }
- if ((ret == 0) && (!done)) {
- /* Store the signature information. */
- cert->sigIndex = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
- GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE],
- &cert->signature, &cert->sigLength);
- /* Make sure 'signature' and 'signatureAlgorithm' are the same. */
- if (dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum
- != cert->signatureOID) {
- WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
- ret = ASN_SIG_OID_E;
- }
- /* Parameters not allowed after ECDSA or EdDSA algorithm OID. */
- else if (IsSigAlgoECC(cert->signatureOID)) {
- if ((dataASN[X509CERTASN_IDX_SIGALGO_PARAMS_NULL].tag != 0)
- #ifdef WC_RSA_PSS
- || (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0)
- #endif
- ) {
- WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
- ret = ASN_PARSE_E;
- }
- }
- #ifdef WC_RSA_PSS
- /* Check parameters starting with a SEQUENCE. */
- else if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
- word32 oid = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
- word32 sigAlgParamsSz = 0;
- /* Parameters only with RSA PSS. */
- if (oid != CTC_RSASSAPSS) {
- WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- const byte* tbsParams;
- word32 tbsParamsSz;
- const byte* sigAlgParams;
- /* Check RSA PSS parameters are the same. */
- tbsParams =
- GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
- cert->source);
- tbsParamsSz =
- GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
- cert->source);
- sigAlgParams =
- GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
- cert->source);
- sigAlgParamsSz =
- GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
- cert->source);
- if ((tbsParamsSz != sigAlgParamsSz) ||
- (XMEMCMP(tbsParams, sigAlgParams, tbsParamsSz) != 0)) {
- WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
- ret = ASN_PARSE_E;
- }
- }
- if (ret == 0) {
- /* Store parameters for use in signature verification. */
- cert->sigParamsIndex =
- dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].offset;
- cert->sigParamsLength = sigAlgParamsSz;
- }
- }
- #endif
- }
- if ((ret == 0) && (!done)) {
- pubKeyEnd = dataASN[X509CERTASN_IDX_TBS_ISSUERUID].offset;
- if (stopAfterPubKey) {
- /* Return any bad date error through badDateRed and return offset
- * after subjectPublicKeyInfo.
- */
- if (badDateRet != NULL) {
- *badDateRet = badDate;
- }
- done = 1;
- }
- }
- if ((ret == 0) && (!done) &&
- (dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data != NULL)) {
- #ifndef ALLOW_V1_EXTENSIONS
- /* Certificate extensions were only defined in version 2. */
- if (cert->version < 2) {
- WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
- WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
- ret = ASN_VERSION_E;
- }
- #endif
- if (ret == 0) {
- /* Save references to extension data. */
- cert->extensions = GetASNItem_Addr(
- dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
- cert->extensionsSz = (int)GetASNItem_Length(
- dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
- cert->extensionsIdx = dataASN[X509CERTASN_IDX_TBS_EXT].offset;
- /* Advance past extensions. */
- cert->srcIdx = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
- }
- }
- /* Dispose of memory before allocating for extension decoding. */
- FREE_ASNGETDATA(dataASN, cert->heap);
- if ((ret == 0) && (issuer != NULL)) {
- idx = 0;
- /* Put issuer into cert and calculate hash. */
- ret = GetCertName(cert, cert->issuer, cert->issuerHash, ISSUER, issuer,
- &idx, issuerSz);
- }
- if ((ret == 0) && (subject != NULL)) {
- idx = 0;
- /* Put subject into cert and calculate hash. */
- ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
- subject, &idx, subjectSz);
- }
- if (ret == 0) {
- /* Determine if self signed by comparing issuer and subject hashes. */
- #ifdef WOLFSSL_CERT_REQ
- if (cert->isCSR) {
- cert->selfSigned = 1;
- }
- else
- #endif
- {
- cert->selfSigned = (XMEMCMP(cert->issuerHash, cert->subjectHash,
- KEYID_SIZE) == 0);
- }
- if (stopAtPubKey) {
- ret = (int)pubKeyOffset;
- }
- }
- if ((ret == 0) && (!stopAtPubKey)) {
- /* Parse the public key. */
- idx = pubKeyOffset;
- ret = GetCertKey(cert, cert->source, &idx, pubKeyEnd);
- }
- if ((ret == 0) && (!stopAtPubKey) && (!stopAfterPubKey) &&
- (cert->extensions != NULL)) {
- /* Decode the extension data starting at [3]. */
- ret = DecodeCertExtensions(cert);
- if (criticalExt != NULL) {
- if (ret == ASN_CRIT_EXT_E) {
- /* Return critical extension not recognized. */
- *criticalExt = ret;
- ret = 0;
- }
- else {
- /* No critical extension error. */
- *criticalExt = 0;
- }
- }
- }
- if ((ret == 0) && (!done) && (badDate != 0)) {
- /* Parsed whole certificate fine but return any date errors. */
- ret = badDate;
- }
- return ret;
- }
- /* Decode BER/DER data into certificate object.
- *
- * BER/DER data information held in source, srcIdx and maxIdx fields of
- * certificate object.
- *
- * @param [in] cert Decoded certificate object.
- * @param [in] verify Whether to find CA and verify certificate.
- * @param [in] criticalExt Any error for critical extensions not recognized.
- * @return 0 on success.
- * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
- * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
- * @return ASN_DATE_SZ_E when time data is not supported.
- * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
- * @return ASN_AFTER_DATE_E when AFTER date is invalid.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- */
- int DecodeCert(DecodedCert* cert, int verify, int* criticalExt)
- {
- return DecodeCertInternal(cert, verify, criticalExt, NULL, 0, 0);
- }
- #ifdef WOLFSSL_CERT_REQ
- /* ASN.1 template for certificate request Attribute.
- * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
- */
- static const ASNItem reqAttrASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* type */
- /* TYPE */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* values */
- /* VALS */ { 1, ASN_SET, 1, 0, 0 },
- };
- enum {
- REQATTRASN_IDX_SEQ = 0,
- REQATTRASN_IDX_TYPE,
- REQATTRASN_IDX_VALS
- };
- /* Number of items in ASN.1 template for certificate request Attribute. */
- #define reqAttrASN_Length (sizeof(reqAttrASN) / sizeof(ASNItem))
- /* ASN.1 template for a string choice. */
- static const ASNItem strAttrASN[] = {
- { 0, 0, 0, 0, 0 },
- };
- enum {
- STRATTRASN_IDX_STR = 0
- };
- /* Number of items in ASN.1 template for a string choice. */
- #define strAttrASN_Length (sizeof(strAttrASN) / sizeof(ASNItem))
- /* ASN.1 choices for types for a string in an attribute. */
- static const byte strAttrChoice[] = {
- ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, 0
- };
- /* Decode a certificate request attribute's value.
- *
- * @param [in] cert Certificate request object.
- * @param [out] criticalExt Critical extension return code.
- * @param [in] oid OID decribing which attribute was found.
- * @param [in] aIdx Index into certificate source to start parsing.
- * @param [in] input Attribute value data.
- * @param [in] maxIdx Maximum index to parse to.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- */
- static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt,
- word32 oid, word32 aIdx, const byte* input, word32 maxIdx)
- {
- int ret = 0;
- word32 idx = 0;
- ASNGetData strDataASN[strAttrASN_Length];
- switch (oid) {
- case PKCS9_CONTENT_TYPE_OID:
- /* Clear dynamic data and specify choices acceptable. */
- XMEMSET(strDataASN, 0, sizeof(strDataASN));
- GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
- /* Parse a string. */
- ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
- 1, input, &idx, maxIdx);
- if (ret == 0) {
- /* Store references to password data. */
- cert->contentType =
- (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
- cert->contentTypeLen =
- (int)strDataASN[STRATTRASN_IDX_STR].data.ref.length;
- }
- break;
- /* A password by which the entity may request certificate revocation.
- * PKCS#9: RFC 2985, 5.4.1 - Challenge password
- */
- case CHALLENGE_PASSWORD_OID:
- /* Clear dynamic data and specify choices acceptable. */
- XMEMSET(strDataASN, 0, sizeof(strDataASN));
- GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
- /* Parse a string. */
- ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
- 1, input, &idx, maxIdx);
- if (ret == 0) {
- /* Store references to password data. */
- cert->cPwd =
- (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
- cert->cPwdLen = (int)strDataASN[STRATTRASN_IDX_STR].
- data.ref.length;
- }
- break;
- /* Requested serial number to issue with.
- * PKCS#9: RFC 2985, 5.2.10 - Serial Number
- * (References: ISO/IEC 9594-6:1997)
- */
- case SERIAL_NUMBER_OID:
- /* Clear dynamic data and specify choices acceptable. */
- XMEMSET(strDataASN, 0, sizeof(strDataASN));
- GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
- /* Parse a string. */
- ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
- 1, input, &idx, maxIdx);
- if (ret == 0) {
- /* Store references to serial number. */
- cert->sNum =
- (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
- cert->sNumLen = (int)strDataASN[STRATTRASN_IDX_STR].
- data.ref.length;
- /* Store serial number if small enough. */
- if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
- XMEMCPY(cert->serial, cert->sNum, (size_t)cert->sNumLen);
- cert->serialSz = cert->sNumLen;
- }
- }
- break;
- /* Certificate extensions to be included in generated certificate.
- * PKCS#9: RFC 2985, 5.4.2 - Extension request
- */
- case EXTENSION_REQUEST_OID:
- /* Store references to all extensions. */
- cert->extensions = input;
- cert->extensionsSz = (int)maxIdx;
- cert->extensionsIdx = aIdx;
- /* Decode and validate extensions. */
- ret = DecodeCertExtensions(cert);
- if (ret == ASN_CRIT_EXT_E) {
- /* Return critical extension not recognized. */
- *criticalExt = ret;
- ret = 0;
- }
- else {
- /* No critical extension error. */
- *criticalExt = 0;
- }
- break;
- default:
- ret = ASN_PARSE_E;
- break;
- }
- return ret;
- }
- /* Decode attributes of a BER encoded certificate request.
- *
- * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
- *
- * Outer sequence has been removed.
- *
- * @param [in] cert Certificate request object.
- * @param [out] criticalExt Critical extension return code.
- * @param [in] idx Index into certificate source to start parsing.
- * @param [in] maxIdx Maximum index to parse to.
- * @return 0 on success.
- * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- */
- static int DecodeCertReqAttributes(DecodedCert* cert, int* criticalExt,
- word32 idx, word32 maxIdx)
- {
- DECL_ASNGETDATA(dataASN, reqAttrASN_Length);
- int ret = 0;
- WOLFSSL_ENTER("DecodeCertReqAttributes");
- ALLOC_ASNGETDATA(dataASN, reqAttrASN_Length, ret, cert->heap);
- /* Parse each attribute until all data used up. */
- while ((ret == 0) && (idx < maxIdx)) {
- /* Clear dynamic data. */
- XMEMSET(dataASN, 0, sizeof(ASNGetData) * reqAttrASN_Length);
- GetASN_OID(&dataASN[REQATTRASN_IDX_TYPE], oidIgnoreType);
- /* Parse an attribute. */
- ret = GetASN_Items(reqAttrASN, dataASN, reqAttrASN_Length, 0,
- cert->source, &idx, maxIdx);
- /* idx is now at end of attribute data. */
- if (ret == 0) {
- ret = DecodeCertReqAttrValue(cert, criticalExt,
- dataASN[REQATTRASN_IDX_TYPE].data.oid.sum,
- GetASNItem_DataIdx(dataASN[REQATTRASN_IDX_VALS], cert->source),
- dataASN[REQATTRASN_IDX_VALS].data.ref.data,
- dataASN[REQATTRASN_IDX_VALS].data.ref.length);
- }
- }
- FREE_ASNGETDATA(dataASN, cert->heap);
- return ret;
- }
- /* ASN.1 template for a certificate request.
- * PKCS#10: RFC 2986, 4.1 - CertificationRequestInfo
- * PKCS#10: RFC 2986, 4.2 - CertificationRequest
- */
- static const ASNItem certReqASN[] = {
- /* CertificationRequest */
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* CertificationRequestInfo */
- /* INFO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* version INTEGER { v1(0), v2(1), v3(2) */
- /* INFO_VER */ { 2, ASN_INTEGER, 0, 0, 0 },
- /* subject Name */
- /* INFO_SUBJ_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
- /* subjectPublicKeyInfo SubjectPublicKeyInfo */
- /* INFO_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
- /* algorithm AlgorithmIdentifier */
- /* INFO_SPUBKEYINFO_ALGOID_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
- /* Algorithm OBJECT IDENTIFIER */
- /* INFO_SPUBKEYINFO_ALGOID_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
- /* parameters ANY defined by algorithm OPTIONAL */
- /* INFO_SPUBKEYINFO_ALGOID_NULL */ { 4, ASN_TAG_NULL, 0, 0, 1 },
- /* INFO_SPUBKEYINFO_ALGOID_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 1 },
- /* INFO_SPUBKEYINFO_ALGOID_PARAMS */ { 4, ASN_SEQUENCE, 1, 0, 1 },
- /* subjectPublicKey BIT STRING */
- /* INFO_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
- /* attributes [0] Attributes */
- /* INFO_ATTRS */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
- /* signatureAlgorithm AlgorithmIdentifier */
- /* INFO_SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* Algorithm OBJECT IDENTIFIER */
- /* INFO_SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
- /* parameters ANY defined by algorithm OPTIONAL */
- /* INFO_SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
- /* signature BIT STRING */
- /* INFO_SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
- };
- enum {
- CERTREQASN_IDX_SEQ = 0,
- CERTREQASN_IDX_INFO_SEQ,
- CERTREQASN_IDX_INFO_VER,
- CERTREQASN_IDX_INFO_SUBJ_SEQ,
- CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ,
- CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_SEQ,
- CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID,
- CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_NULL,
- CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID,
- CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_PARAMS,
- CERTREQASN_IDX_INFO_SPUBKEYINFO_PUBKEY,
- CERTREQASN_IDX_INFO_ATTRS,
- CERTREQASN_IDX_INFO_SIGALGO_SEQ,
- CERTREQASN_IDX_INFO_SIGALGO_OID,
- CERTREQASN_IDX_INFO_SIGALGO_NULL,
- CERTREQASN_IDX_INFO_SIGNATURE
- };
- /* Number of items in ASN.1 template for a certificate request. */
- #define certReqASN_Length (sizeof(certReqASN) / sizeof(ASNItem))
- /* Parse BER encoded certificate request.
- *
- * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
- *
- * @param [in] cert Certificate request object.
- * @param [out] criticalExt Critical extension return code.
- * @return 0 on success.
- * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return BUFFER_E when data in buffer is too small.
- * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
- * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
- * non-zero length.
- * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
- * @return MEMORY_E on dynamic memory allocation failure.
- */
- static int DecodeCertReq(DecodedCert* cert, int* criticalExt)
- {
- DECL_ASNGETDATA(dataASN, certReqASN_Length);
- int ret = 0;
- byte version;
- word32 idx;
- CALLOC_ASNGETDATA(dataASN, certReqASN_Length, ret, cert->heap);
- if (ret == 0) {
- /* Default version is 0. */
- version = 0;
- /* Set version var and OID types to expect. */
- GetASN_Int8Bit(&dataASN[CERTREQASN_IDX_INFO_VER], &version);
- GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
- oidKeyType);
- GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
- oidCurveType);
- GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
- /* Parse a certificate request. */
- ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1,
- cert->source, &cert->srcIdx, cert->maxIdx);
- }
- /* Check version is valid/supported - can't be negative. */
- if ((ret == 0) && (version > MAX_X509_VERSION)) {
- WOLFSSL_MSG("Unexpected certificate request version");
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- /* Set fields of certificate request. */
- cert->version = version;
- cert->signatureOID =
- dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
- cert->keyOID =
- dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID].data.oid.sum;
- cert->certBegin = dataASN[CERTREQASN_IDX_INFO_SEQ].offset;
- /* Parse the subject name. */
- idx = dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ].offset;
- ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
- cert->source, &idx,
- dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset);
- }
- if (ret == 0) {
- /* Parse the certificate request Attributes. */
- ret = DecodeCertReqAttributes(cert, criticalExt,
- GetASNItem_DataIdx(dataASN[CERTREQASN_IDX_INFO_ATTRS],
- cert->source),
- dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset);
- }
- if (ret == 0) {
- /* Parse the certificate request's key. */
- idx = dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset;
- ret = GetCertKey(cert, cert->source, &idx,
- dataASN[CERTREQASN_IDX_INFO_ATTRS].offset);
- }
- if (ret == 0) {
- /* Store references to signature. */
- cert->sigIndex = dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset;
- GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE],
- &cert->signature, &cert->sigLength);
- }
- FREE_ASNGETDATA(dataASN, cert->heap);
- return ret;
- }
- #endif /* WOLFSSL_CERT_REQ */
- #endif
- int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
- {
- int ret;
- #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
- defined(WOLFSSL_DYN_CERT)
- char* ptr;
- #endif
- ret = ParseCertRelative(cert, type, verify, cm);
- if (ret < 0)
- return ret;
- #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
- defined(WOLFSSL_DYN_CERT)
- /* cert->subjectCN not stored as copy of WOLFSSL_NO_MALLOC defind */
- if (cert->subjectCNLen > 0) {
- ptr = (char*)XMALLOC((size_t)cert->subjectCNLen + 1, cert->heap,
- DYNAMIC_TYPE_SUBJECT_CN);
- if (ptr == NULL)
- return MEMORY_E;
- XMEMCPY(ptr, cert->subjectCN, (size_t)cert->subjectCNLen);
- ptr[cert->subjectCNLen] = '\0';
- cert->subjectCN = ptr;
- cert->subjectCNStored = 1;
- }
- #endif
- #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
- defined(WOLFSSL_DYN_CERT)
- /* cert->publicKey not stored as copy if WOLFSSL_NO_MALLOC defined */
- if ((cert->keyOID == RSAk
- #ifdef WC_RSA_PSS
- || cert->keyOID == RSAPSSk
- #endif
- ) && cert->publicKey != NULL && cert->pubKeySize > 0) {
- ptr = (char*)XMALLOC(cert->pubKeySize, cert->heap,
- DYNAMIC_TYPE_PUBLIC_KEY);
- if (ptr == NULL)
- return MEMORY_E;
- XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
- cert->publicKey = (byte *)ptr;
- cert->pubKeyStored = 1;
- }
- #endif
- return ret;
- }
- int wc_ParseCert(DecodedCert* cert, int type, int verify, void* cm)
- {
- return ParseCert(cert, type, verify, cm);
- }
- #if !defined(OPENSSL_EXTRA) && !defined(OPENSSL_EXTRA_X509_SMALL) && \
- !defined(GetCA)
- /* from SSL proper, for locking can't do find here anymore.
- * brought in from internal.h if built with compat layer.
- * if defined(GetCA), it's a predefined macro and these prototypes
- * would conflict.
- */
- #ifdef __cplusplus
- extern "C" {
- #endif
- Signer* GetCA(void* signers, byte* hash);
- #ifndef NO_SKID
- Signer* GetCAByName(void* signers, byte* hash);
- #endif
- #ifdef __cplusplus
- }
- #endif
- #endif /* !OPENSSL_EXTRA && !OPENSSL_EXTRA_X509_SMALL && !GetCA */
- #if defined(WOLFCRYPT_ONLY)
- /* dummy functions, not using wolfSSL so don't need actual ones */
- Signer* GetCA(void* signers, byte* hash)
- {
- (void)hash;
- return (Signer*)signers;
- }
- #ifndef NO_SKID
- Signer* GetCAByName(void* signers, byte* hash)
- {
- (void)hash;
- return (Signer*)signers;
- }
- #endif /* NO_SKID */
- #endif /* WOLFCRYPT_ONLY */
- #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
- static Signer* GetCABySubjectAndPubKey(DecodedCert* cert, void* cm)
- {
- Signer* ca = NULL;
- if (cert->extSubjKeyIdSet)
- ca = GetCA(cm, cert->extSubjKeyId);
- if (ca == NULL)
- ca = GetCAByName(cm, cert->subjectHash);
- if (ca) {
- if ((ca->pubKeySize == cert->pubKeySize) &&
- (XMEMCMP(ca->publicKey, cert->publicKey, ca->pubKeySize) == 0)) {
- return ca;
- }
- }
- return NULL;
- }
- #endif
- #if defined(WOLFSSL_SMALL_CERT_VERIFY) || defined(OPENSSL_EXTRA)
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* Get the Hash of the Authority Key Identifier from the list of extensions.
- *
- * @param [in] input Input data.
- * @param [in] maxIdx Maximum index for data.
- * @param [in] sigOID Signature OID for determining hash algorithm.
- * @param [out] hash Hash of AKI.
- * @param [out] set Whether the hash buffer was set.
- * @param [in] heap Dynamic memory allocation hint.
- * @return 0 on success.
- * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
- * is invalid.
- * @return MEMORY_E on dynamic memory allocation failure.
- */
- static int GetAKIHash(const byte* input, word32 maxIdx, int sigOID,
- byte* hash, int* set, void* heap)
- {
- /* AKI and Certificate Extenion ASN.1 templates are the same length. */
- DECL_ASNGETDATA(dataASN, certExtASN_Length);
- int ret = 0;
- word32 idx = 0;
- word32 extEndIdx;
- byte* extData;
- word32 extDataSz;
- byte critical;
- ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, heap);
- (void)heap;
- extEndIdx = idx + maxIdx;
- /* Step through each extension looking for AKI. */
- while ((ret == 0) && (idx < extEndIdx)) {
- /* Clear dynamic data and check for certificate extension type OIDs. */
- XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
- GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
- /* Set criticality variable. */
- GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
- /* Parse an extension. */
- ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
- &idx, extEndIdx);
- if (ret == 0) {
- /* Get reference to extension data and move index on past this
- * extension. */
- GetASN_GetRef(&dataASN[CERTEXTASN_IDX_VAL], &extData, &extDataSz);
- idx += extDataSz;
- /* Check whether we have the AKI extension. */
- if (dataASN[CERTEXTASN_IDX_OID].data.oid.sum == AUTH_KEY_OID) {
- /* Clear dynamic data. */
- XMEMSET(dataASN, 0, sizeof(*dataASN) * authKeyIdASN_Length);
- /* Start parsing extension data from the start. */
- idx = 0;
- /* Parse AKI extension data. */
- ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length,
- 1, extData, &idx, extDataSz);
- if ((ret == 0) &&
- (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data
- != NULL)) {
- /* We parsed successfully and have data. */
- *set = 1;
- /* Get the hash or hash of the hash if wrong size. */
- ret = GetHashId(
- dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
- dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
- hash, sigOID);
- }
- break;
- }
- }
- }
- FREE_ASNGETDATA(dataASN, heap);
- return ret;
- }
- #endif
- /* Only quick step through the certificate to find fields that are then used
- * in certificate signature verification.
- * Must use the signature OID from the signed part of the certificate.
- * Works also on certificate signing requests.
- *
- * This is only for minimizing dynamic memory usage during TLS certificate
- * chain processing.
- * Doesn't support:
- * OCSP Only: alt lookup using subject and pub key w/o sig check
- */
- static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap,
- void* cm, const byte* pubKey, word32 pubKeySz, int pubKeyOID, int req)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- #ifndef WOLFSSL_SMALL_STACK
- SignatureCtx sigCtx[1];
- #else
- SignatureCtx* sigCtx;
- #endif
- byte hash[KEYID_SIZE];
- Signer* ca = NULL;
- word32 idx = 0;
- int len;
- word32 tbsCertIdx = 0;
- word32 sigIndex = 0;
- word32 signatureOID = 0;
- word32 oid = 0;
- word32 issuerIdx = 0;
- word32 issuerSz = 0;
- #ifndef NO_SKID
- int extLen = 0;
- word32 extIdx = 0;
- word32 extEndIdx = 0;
- int extAuthKeyIdSet = 0;
- #endif
- int ret = 0;
- word32 localIdx;
- byte tag;
- const byte* sigParams = NULL;
- word32 sigParamsSz = 0;
- if (cert == NULL) {
- return BAD_FUNC_ARG;
- }
- #ifdef WOLFSSL_SMALL_STACK
- sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, DYNAMIC_TYPE_SIGNATURE);
- if (sigCtx == NULL)
- return MEMORY_E;
- #endif
- InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
- /* Certificate SEQUENCE */
- if (GetSequence(cert, &idx, &len, certSz) < 0)
- ret = ASN_PARSE_E;
- if (ret == 0) {
- tbsCertIdx = idx;
- /* TBSCertificate SEQUENCE */
- if (GetSequence(cert, &idx, &len, certSz) < 0)
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- sigIndex = len + idx;
- if ((idx + 1) > certSz)
- ret = BUFFER_E;
- }
- if (ret == 0) {
- /* version - optional */
- localIdx = idx;
- if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
- if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
- idx++;
- if (GetLength(cert, &idx, &len, certSz) < 0)
- ret = ASN_PARSE_E;
- idx += len;
- }
- }
- }
- if (ret == 0) {
- /* serialNumber */
- if (GetASNHeader(cert, ASN_INTEGER, &idx, &len, certSz) < 0)
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- idx += len;
- /* signature */
- if (!req) {
- if (GetAlgoId(cert, &idx, &signatureOID, oidSigType, certSz) < 0)
- ret = ASN_PARSE_E;
- #ifdef WC_RSA_PSS
- else if (signatureOID == CTC_RSASSAPSS) {
- int start = idx;
- sigParams = cert + idx;
- if (GetSequence(cert, &idx, &len, certSz) < 0)
- ret = ASN_PARSE_E;
- if (ret == 0) {
- idx += len;
- sigParamsSz = idx - start;
- }
- }
- #endif
- }
- }
- if (ret == 0) {
- issuerIdx = idx;
- /* issuer for cert or subject for csr */
- if (GetSequence(cert, &idx, &len, certSz) < 0)
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- issuerSz = len + idx - issuerIdx;
- }
- #ifndef NO_SKID
- if (!req && ret == 0) {
- idx += len;
- /* validity */
- if (GetSequence(cert, &idx, &len, certSz) < 0)
- ret = ASN_PARSE_E;
- }
- if (!req && ret == 0) {
- idx += len;
- /* subject */
- if (GetSequence(cert, &idx, &len, certSz) < 0)
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- idx += len;
- /* subjectPublicKeyInfo */
- if (GetSequence(cert, &idx, &len, certSz) < 0)
- ret = ASN_PARSE_E;
- }
- if (req && ret == 0) {
- idx += len;
- /* attributes */
- if (GetASNHeader_ex(cert,
- ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &idx,
- &len, certSz, 1) < 0)
- ret = ASN_PARSE_E;
- }
- if (!req) {
- if (ret == 0) {
- idx += len;
- if ((idx + 1) > certSz)
- ret = BUFFER_E;
- }
- if (ret == 0) {
- /* issuerUniqueID - optional */
- localIdx = idx;
- if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
- if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) {
- idx++;
- if (GetLength(cert, &idx, &len, certSz) < 0)
- ret = ASN_PARSE_E;
- idx += len;
- }
- }
- }
- if (ret == 0) {
- if ((idx + 1) > certSz)
- ret = BUFFER_E;
- }
- if (ret == 0) {
- /* subjectUniqueID - optional */
- localIdx = idx;
- if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
- if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)) {
- idx++;
- if (GetLength(cert, &idx, &len, certSz) < 0)
- ret = ASN_PARSE_E;
- idx += len;
- }
- }
- }
- if (ret == 0) {
- if ((idx + 1) > certSz)
- ret = BUFFER_E;
- }
- /* extensions - optional */
- localIdx = idx;
- if (ret == 0 && GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
- tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)) {
- idx++;
- if (GetLength(cert, &idx, &extLen, certSz) < 0)
- ret = ASN_PARSE_E;
- if (ret == 0) {
- if (GetSequence(cert, &idx, &extLen, certSz) < 0)
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- extEndIdx = idx + extLen;
- /* Check each extension for the ones we want. */
- while (ret == 0 && idx < extEndIdx) {
- if (GetSequence(cert, &idx, &len, certSz) < 0)
- ret = ASN_PARSE_E;
- if (ret == 0) {
- extIdx = idx;
- if (GetObjectId(cert, &extIdx, &oid, oidCertExtType,
- certSz) < 0) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- if ((extIdx + 1) > certSz)
- ret = BUFFER_E;
- }
- }
- if (ret == 0) {
- localIdx = extIdx;
- if (GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
- tag == ASN_BOOLEAN) {
- if (GetBoolean(cert, &extIdx, certSz) < 0)
- ret = ASN_PARSE_E;
- }
- }
- if (ret == 0) {
- if (GetOctetString(cert, &extIdx, &extLen, certSz) < 0)
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- switch (oid) {
- case AUTH_KEY_OID:
- if (GetSequence(cert, &extIdx, &extLen, certSz) < 0)
- ret = ASN_PARSE_E;
- if (ret == 0 && (extIdx + 1) >= certSz)
- ret = BUFFER_E;
- if (ret == 0 &&
- GetASNTag(cert, &extIdx, &tag, certSz) == 0 &&
- tag == (ASN_CONTEXT_SPECIFIC | 0)) {
- if (GetLength(cert, &extIdx, &extLen, certSz) <= 0)
- ret = ASN_PARSE_E;
- if (ret == 0) {
- extAuthKeyIdSet = 1;
- /* Get the hash or hash of the hash if wrong
- * size. */
- ret = GetHashId(cert + extIdx, extLen,
- hash, HashIdAlg(signatureOID));
- }
- }
- break;
- default:
- break;
- }
- }
- idx += len;
- }
- }
- }
- }
- else if (ret == 0) {
- idx += len;
- }
- if (ret == 0 && pubKey == NULL) {
- if (extAuthKeyIdSet)
- ca = GetCA(cm, hash);
- if (ca == NULL) {
- ret = CalcHashId_ex(cert + issuerIdx, issuerSz, hash,
- HashIdAlg(signatureOID));
- if (ret == 0)
- ca = GetCAByName(cm, hash);
- }
- }
- #else
- if (ret == 0 && pubKey == NULL) {
- ret = CalcHashId_ex(cert + issuerIdx, issuerSz, hash,
- HashIdAlg(signatureOID));
- if (ret == 0)
- ca = GetCA(cm, hash);
- }
- #endif /* !NO_SKID */
- if (ca == NULL && pubKey == NULL)
- ret = ASN_NO_SIGNER_E;
- if (ret == 0) {
- idx = sigIndex;
- /* signatureAlgorithm */
- if (GetAlgoId(cert, &idx, &oid, oidSigType, certSz) < 0)
- ret = ASN_PARSE_E;
- #ifdef WC_RSA_PSS
- else if (signatureOID == CTC_RSASSAPSS) {
- word32 sz = idx;
- const byte* params = cert + idx;
- if (GetSequence(cert, &idx, &len, certSz) < 0)
- ret = ASN_PARSE_E;
- if (ret == 0) {
- idx += len;
- sz = idx - sz;
- if (req) {
- if ((sz != sigParamsSz) ||
- (XMEMCMP(sigParams, params, sz) != 0)) {
- ret = ASN_PARSE_E;
- }
- }
- else {
- sigParams = params;
- sigParamsSz = sz;
- }
- }
- }
- #endif
- /* In CSR signature data is not present in body */
- if (req)
- signatureOID = oid;
- }
- if (ret == 0) {
- if (oid != signatureOID)
- ret = ASN_SIG_OID_E;
- }
- if (ret == 0) {
- /* signatureValue */
- if (CheckBitString(cert, &idx, &len, certSz, 1, NULL) < 0)
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- if (pubKey != NULL) {
- ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
- sigIndex - tbsCertIdx, pubKey, pubKeySz, pubKeyOID,
- cert + idx, len, signatureOID, sigParams, sigParamsSz, NULL);
- }
- else {
- ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
- sigIndex - tbsCertIdx, ca->publicKey, ca->pubKeySize,
- ca->keyOID, cert + idx, len, signatureOID, sigParams,
- sigParamsSz, NULL);
- }
- if (ret != 0) {
- WOLFSSL_ERROR_VERBOSE(ret);
- WOLFSSL_MSG("Confirm signature failed");
- }
- }
- FreeSignatureCtx(sigCtx);
- #ifdef WOLFSSL_SMALL_STACK
- if (sigCtx != NULL)
- XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
- #endif
- return ret;
- #else /* WOLFSSL_ASN_TEMPLATE */
- /* X509 ASN.1 template longer than Certificate Request template. */
- DECL_ASNGETDATA(dataASN, x509CertASN_Length);
- #ifndef WOLFSSL_SMALL_STACK
- SignatureCtx sigCtx[1];
- #else
- SignatureCtx* sigCtx = NULL;
- #endif
- byte hash[KEYID_SIZE];
- Signer* ca = NULL;
- int ret = 0;
- word32 idx = 0;
- #ifndef NO_SKID
- int extAuthKeyIdSet = 0;
- #endif
- const byte* tbs = NULL;
- word32 tbsSz = 0;
- #ifdef WC_RSA_PSS
- const byte* tbsParams = NULL;
- word32 tbsParamsSz = 0;
- #endif
- const byte* sig = NULL;
- word32 sigSz = 0;
- word32 sigOID = 0;
- const byte* sigParams = NULL;
- word32 sigParamsSz = 0;
- const byte* caName = NULL;
- word32 caNameLen = 0;
- #ifndef NO_SKID
- const byte* akiData = NULL;
- word32 akiLen = 0;
- #endif
- (void)req;
- (void)heap;
- if (cert == NULL) {
- ret = BAD_FUNC_ARG;
- }
- ALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, heap);
- if ((ret == 0) && (!req)) {
- /* Clear dynamic data for certificate items. */
- XMEMSET(dataASN, 0, sizeof(ASNGetData) * x509CertASN_Length);
- /* Set OID types expected for signature and public key. */
- GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
- GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
- oidKeyType);
- GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
- oidCurveType);
- GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
- /* Parse certificate. */
- ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1, cert,
- &idx, certSz);
- /* Check signature OIDs match. */
- if ((ret == 0) && dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum
- != dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum) {
- ret = ASN_SIG_OID_E;
- }
- /* Store the data for verification in the certificate. */
- if (ret == 0) {
- tbs = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
- tbsSz = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
- caName = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
- cert);
- caNameLen = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
- cert);
- sigOID = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
- #ifdef WC_RSA_PSS
- if (dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].tag != 0) {
- tbsParams =
- GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
- cert);
- tbsParamsSz =
- GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
- cert);
- }
- if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
- sigParams =
- GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
- cert);
- sigParamsSz =
- GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
- cert);
- }
- #endif
- GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE], &sig, &sigSz);
- #ifdef WC_RSA_PSS
- if (tbsParamsSz != sigParamsSz) {
- ret = ASN_PARSE_E;
- }
- else if ((tbsParamsSz > 0) && (sigOID != CTC_RSASSAPSS)) {
- ret = ASN_PARSE_E;
- }
- else if ((tbsParamsSz > 0) &&
- (XMEMCMP(tbsParams, sigParams, tbsParamsSz) != 0)) {
- ret = ASN_PARSE_E;
- }
- #endif
- }
- }
- else if (ret == 0) {
- #ifndef WOLFSSL_CERT_REQ
- ret = NOT_COMPILED_IN;
- #else
- /* Clear dynamic data for certificate request items. */
- XMEMSET(dataASN, 0, sizeof(ASNGetData) * certReqASN_Length);
- /* Set OID types expected for signature and public key. */
- GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
- oidKeyType);
- GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
- oidCurveType);
- GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
- /* Parse certificate request. */
- ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1, cert,
- &idx, certSz);
- if (ret == 0) {
- /* Store the data for verification in the certificate. */
- tbs = GetASNItem_Addr(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
- tbsSz = GetASNItem_Length(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
- caName = GetASNItem_Addr(
- dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
- caNameLen = GetASNItem_Length(
- dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
- sigOID = dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
- #ifdef WC_RSA_PSS
- sigParams = GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
- cert);
- sigParamsSz =
- GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
- cert);
- #endif
- GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE], &sig,
- &sigSz);
- }
- #endif
- }
- #ifndef NO_SKID
- if ((ret == 0) && (pubKey == NULL) && !req) {
- akiData = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data;
- akiLen = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.length;
- }
- #endif
- FREE_ASNGETDATA(dataASN, heap);
- /* If no public passed, then find the CA. */
- if ((ret == 0) && (pubKey == NULL)) {
- #ifndef NO_SKID
- /* Find the AKI extension in list of extensions and get hash. */
- if ((!req) && (akiData != NULL)) {
- /* TODO: test case */
- ret = GetAKIHash(akiData, akiLen, sigOID, hash, &extAuthKeyIdSet,
- heap);
- }
- /* Get the CA by hash one was found. */
- if (extAuthKeyIdSet) {
- ca = GetCA(cm, hash);
- }
- if (ca == NULL)
- #endif
- {
- /* Try hash of issuer name. */
- ret = CalcHashId_ex(caName, caNameLen, hash, HashIdAlg(sigOID));
- if (ret == 0) {
- ca = GetCAByName(cm, hash);
- }
- }
- if (ca != NULL) {
- /* Extract public key information. */
- pubKey = ca->publicKey;
- pubKeySz = ca->pubKeySize;
- pubKeyOID = ca->keyOID;
- }
- else {
- /* No public key to verify with. */
- ret = ASN_NO_SIGNER_E;
- }
- }
- if (ret == 0) {
- #ifdef WOLFSSL_SMALL_STACK
- sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap,
- DYNAMIC_TYPE_SIGNATURE);
- if (sigCtx == NULL) {
- ret = MEMORY_E;
- }
- if (ret == 0)
- #endif
- {
- InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
- /* Check signature. */
- ret = ConfirmSignature(sigCtx, tbs, tbsSz, pubKey, pubKeySz,
- pubKeyOID, sig, sigSz, sigOID, sigParams, sigParamsSz, NULL);
- if (ret != 0) {
- WOLFSSL_MSG("Confirm signature failed");
- }
- FreeSignatureCtx(sigCtx);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
- #endif
- }
- }
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #ifdef OPENSSL_EXTRA
- /* Call CheckCertSignature_ex using a public key buffer for verification
- */
- int CheckCertSignaturePubKey(const byte* cert, word32 certSz, void* heap,
- const byte* pubKey, word32 pubKeySz, int pubKeyOID)
- {
- return CheckCertSignature_ex(cert, certSz, heap, NULL,
- pubKey, pubKeySz, pubKeyOID, 0);
- }
- int wc_CheckCertSigPubKey(const byte* cert, word32 certSz, void* heap,
- const byte* pubKey, word32 pubKeySz, int pubKeyOID)
- {
- return CheckCertSignaturePubKey(cert, certSz, heap, pubKey, pubKeySz,
- pubKeyOID);
- }
- #ifdef WOLFSSL_CERT_REQ
- int CheckCSRSignaturePubKey(const byte* cert, word32 certSz, void* heap,
- const byte* pubKey, word32 pubKeySz, int pubKeyOID)
- {
- return CheckCertSignature_ex(cert, certSz, heap, NULL,
- pubKey, pubKeySz, pubKeyOID, 1);
- }
- #endif /* WOLFSSL_CERT_REQ */
- #endif /* OPENSSL_EXTRA */
- #ifdef WOLFSSL_SMALL_CERT_VERIFY
- /* Call CheckCertSignature_ex using a certificate manager (cm)
- */
- int CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm)
- {
- return CheckCertSignature_ex(cert, certSz, heap, cm, NULL, 0, 0, 0);
- }
- #endif /* WOLFSSL_SMALL_CERT_VERIFY */
- #endif /* WOLFSSL_SMALL_CERT_VERIFY || OPENSSL_EXTRA */
- #if (defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) || \
- (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)))
- /* ASN.1 DER decode instruction. */
- typedef struct DecodeInstr {
- /* Tag expected. */
- byte tag;
- /* Operation to perform: step in or go over */
- byte op:1;
- /* ASN.1 item is optional. */
- byte optional:1;
- } DecodeInstr;
- /* Step into ASN.1 item. */
- #define DECODE_INSTR_IN 0
- /* Step over ASN.1 item. */
- #define DECODE_INSTR_OVER 1
- /* Get the public key data from the DER encoded X.509 certificate.
- *
- * Assumes data has previously been parsed for complete validity.
- *
- * @param [in] cert DER encoded X.509 certificate data.
- * @param [in] certSz Length of DER encoding.
- * @param [out] pubKey Public key data. (From the BIT_STRING.)
- * @param [out] pubKeySz Length of public key data in bytes.
- * @return 0 on success.
- * @return BAD_FUNC_ARG when cert, pubKey or pubKeySz is NULL.
- * @return ASN_PARSE_E when certificate encoding is invalid.
- */
- int wc_CertGetPubKey(const byte* cert, word32 certSz,
- const unsigned char** pubKey, word32* pubKeySz)
- {
- int ret = 0;
- int l;
- word32 o = 0;
- int i;
- static DecodeInstr ops[] = {
- /* Outer SEQ */
- { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
- /* TBSCertificate: SEQ */
- { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
- /* Version: [0] */
- { ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_X509_CERT_VERSION,
- DECODE_INSTR_OVER, 1 },
- /* CertificateSerialNumber: INT */
- { ASN_INTEGER, DECODE_INSTR_OVER, 0 },
- /* AlgorithmIdentifier: SEQ */
- { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
- /* issuer: SEQ */
- { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
- /* Validity: SEQ */
- { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
- /* subject: SEQ */
- { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
- /* subjectPublicKeyInfo SEQ */
- { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
- /* AlgorithmIdentifier: SEQ */
- { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
- /* PublicKey: BIT_STRING */
- { ASN_BIT_STRING, DECODE_INSTR_IN , 0 },
- };
- /* Validate parameters. */
- if ((cert == NULL) || (pubKey == NULL) || (pubKeySz == NULL)) {
- ret = BAD_FUNC_ARG;
- }
- /* Process each instruction to take us to public key data. */
- for (i = 0; (ret == 0) && (i < (int)(sizeof(ops) / sizeof(*ops))); i++) {
- DecodeInstr op = ops[i];
- /* Check the current ASN.1 item has the expected tag. */
- if (cert[o] != op.tag) {
- /* If not optional then error, otherwise skip op. */
- if (!op.optional) {
- ret = ASN_PARSE_E;
- }
- }
- else {
- /* Move past tag. */
- o++;
- /* Get the length of ASN.1 item and move past length encoding. */
- if (GetLength(cert, &o, &l, certSz) < 0) {
- ret = ASN_PARSE_E;
- }
- /* Skip data if required. */
- else if (op.op == DECODE_INSTR_OVER) {
- o += l;
- }
- }
- }
- if (ret == 0) {
- /* Return the public key data and length.
- * Skip first byte of BIT_STRING data: unused bits. */
- *pubKey = cert + o + 1;
- *pubKeySz = l - 1;
- }
- return ret;
- }
- #endif
- int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
- {
- int ret = 0;
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 confirmOID = 0;
- #ifdef WOLFSSL_CERT_REQ
- int len = 0;
- #endif
- #endif
- #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
- int idx = 0;
- #endif
- byte* sce_tsip_encRsaKeyIdx;
- if (cert == NULL) {
- return BAD_FUNC_ARG;
- }
- #ifdef WOLFSSL_CERT_REQ
- if (type == CERTREQ_TYPE)
- cert->isCSR = 1;
- #endif
- if (cert->sigCtx.state == SIG_STATE_BEGIN) {
- #ifndef WOLFSSL_ASN_TEMPLATE
- cert->badDate = 0;
- cert->criticalExt = 0;
- if ((ret = DecodeToKey(cert, verify)) < 0) {
- if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
- cert->badDate = ret;
- if (verify == VERIFY_SKIP_DATE)
- ret = 0;
- }
- else
- return ret;
- }
- WOLFSSL_MSG("Parsed Past Key");
- #ifdef WOLFSSL_CERT_REQ
- /* Read attributes */
- if (cert->isCSR) {
- if (GetASNHeader_ex(cert->source,
- ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &cert->srcIdx,
- &len, cert->maxIdx, 1) < 0) {
- WOLFSSL_MSG("GetASNHeader_ex error");
- return ASN_PARSE_E;
- }
- if (len) {
- word32 attrMaxIdx = cert->srcIdx + (word32)len;
- word32 oid;
- byte tag;
- if (attrMaxIdx > cert->maxIdx) {
- WOLFSSL_MSG("Attribute length greater than CSR length");
- return ASN_PARSE_E;
- }
- while (cert->srcIdx < attrMaxIdx) {
- /* Attributes have the structure:
- * SEQ -> OID -> SET -> ATTRIBUTE */
- if (GetSequence(cert->source, &cert->srcIdx, &len,
- attrMaxIdx) < 0) {
- WOLFSSL_MSG("attr GetSequence error");
- return ASN_PARSE_E;
- }
- if (GetObjectId(cert->source, &cert->srcIdx, &oid,
- oidCsrAttrType, attrMaxIdx) < 0) {
- WOLFSSL_MSG("attr GetObjectId error");
- return ASN_PARSE_E;
- }
- if (GetSet(cert->source, &cert->srcIdx, &len,
- attrMaxIdx) < 0) {
- WOLFSSL_MSG("attr GetSet error");
- return ASN_PARSE_E;
- }
- switch (oid) {
- case PKCS9_CONTENT_TYPE_OID:
- if (GetHeader(cert->source, &tag,
- &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
- WOLFSSL_MSG("attr GetHeader error");
- return ASN_PARSE_E;
- }
- if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
- tag != ASN_IA5_STRING) {
- WOLFSSL_MSG("Unsupported attribute value format");
- return ASN_PARSE_E;
- }
- cert->contentType = (char*)cert->source + cert->srcIdx;
- cert->contentTypeLen = len;
- cert->srcIdx += (word32)len;
- break;
- case CHALLENGE_PASSWORD_OID:
- if (GetHeader(cert->source, &tag,
- &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
- WOLFSSL_MSG("attr GetHeader error");
- return ASN_PARSE_E;
- }
- if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
- tag != ASN_IA5_STRING) {
- WOLFSSL_MSG("Unsupported attribute value format");
- return ASN_PARSE_E;
- }
- cert->cPwd = (char*)cert->source + cert->srcIdx;
- cert->cPwdLen = len;
- cert->srcIdx += (word32)len;
- break;
- case SERIAL_NUMBER_OID:
- if (GetHeader(cert->source, &tag,
- &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
- WOLFSSL_MSG("attr GetHeader error");
- return ASN_PARSE_E;
- }
- if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
- tag != ASN_IA5_STRING) {
- WOLFSSL_MSG("Unsupported attribute value format");
- return ASN_PARSE_E;
- }
- cert->sNum = (char*)cert->source + cert->srcIdx;
- cert->sNumLen = len;
- cert->srcIdx += (word32)len;
- if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
- XMEMCPY(cert->serial, cert->sNum,
- (size_t)cert->sNumLen);
- cert->serialSz = cert->sNumLen;
- }
- break;
- case DNQUALIFIER_OID:
- if (GetHeader(cert->source, &tag,
- &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
- WOLFSSL_MSG("attr GetHeader error");
- return ASN_PARSE_E;
- }
- cert->dnQualifier = (char*)cert->source + cert->srcIdx;
- cert->dnQualifierLen = len;
- cert->srcIdx += (word32)len;
- break;
- case INITIALS_OID:
- if (GetHeader(cert->source, &tag,
- &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
- WOLFSSL_MSG("attr GetHeader error");
- return ASN_PARSE_E;
- }
- cert->initials = (char*)cert->source + cert->srcIdx;
- cert->initialsLen = len;
- cert->srcIdx += (word32)len;
- break;
- case SURNAME_OID:
- if (GetHeader(cert->source, &tag,
- &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
- WOLFSSL_MSG("attr GetHeader error");
- return ASN_PARSE_E;
- }
- cert->surname = (char*)cert->source + cert->srcIdx;
- cert->surnameLen = len;
- cert->srcIdx += (word32)len;
- break;
- case GIVEN_NAME_OID:
- if (GetHeader(cert->source, &tag,
- &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
- WOLFSSL_MSG("attr GetHeader error");
- return ASN_PARSE_E;
- }
- cert->givenName = (char*)cert->source + cert->srcIdx;
- cert->givenNameLen = len;
- cert->srcIdx += (word32)len;
- break;
- case UNSTRUCTURED_NAME_OID:
- if (GetHeader(cert->source, &tag,
- &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
- WOLFSSL_MSG("attr GetHeader error");
- return ASN_PARSE_E;
- }
- cert->unstructuredName =
- (char*)cert->source + cert->srcIdx;
- cert->unstructuredNameLen = len;
- cert->srcIdx += (word32)len;
- break;
- case EXTENSION_REQUEST_OID:
- /* save extensions */
- cert->extensions = &cert->source[cert->srcIdx];
- cert->extensionsSz = len;
- cert->extensionsIdx = cert->srcIdx; /* for potential later use */
- if ((ret = DecodeCertExtensions(cert)) < 0) {
- if (ret == ASN_CRIT_EXT_E) {
- cert->criticalExt = ret;
- }
- else {
- return ret;
- }
- }
- cert->srcIdx += (word32)len;
- break;
- default:
- WOLFSSL_MSG("Unsupported attribute type");
- WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
- return ASN_PARSE_E;
- }
- }
- }
- }
- #endif
- if (cert->srcIdx < cert->sigIndex) {
- #ifndef ALLOW_V1_EXTENSIONS
- if (cert->version < 2) {
- WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
- WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
- return ASN_VERSION_E;
- }
- #endif
- /* save extensions */
- cert->extensions = &cert->source[cert->srcIdx];
- cert->extensionsSz = (int)(cert->sigIndex - cert->srcIdx);
- cert->extensionsIdx = cert->srcIdx; /* for potential later use */
- if ((ret = DecodeCertExtensions(cert)) < 0) {
- if (ret == ASN_CRIT_EXT_E)
- cert->criticalExt = ret;
- else
- return ret;
- }
- #ifdef HAVE_OCSP
- if (verify == VERIFY_OCSP_CERT) {
- /* trust for the lifetime of the responder's cert*/
- if (cert->ocspNoCheckSet)
- verify = VERIFY;
- else
- verify = VERIFY_OCSP;
- }
- #endif
- /* advance past extensions */
- cert->srcIdx = cert->sigIndex;
- }
- if ((ret = GetSigAlg(cert,
- #ifdef WOLFSSL_CERT_REQ
- !cert->isCSR ? &confirmOID : &cert->signatureOID,
- #else
- &confirmOID,
- #endif
- cert->maxIdx)) < 0) {
- return ret;
- }
- if ((ret = GetSignature(cert)) < 0) {
- return ret;
- }
- if (confirmOID != cert->signatureOID
- #ifdef WOLFSSL_CERT_REQ
- && !cert->isCSR
- #endif
- ) {
- WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
- return ASN_SIG_OID_E;
- }
- #else
- #ifdef WOLFSSL_CERT_REQ
- if (cert->isCSR) {
- ret = DecodeCertReq(cert, &cert->criticalExt);
- if (ret < 0) {
- return ret;
- }
- }
- else
- #endif
- {
- ret = DecodeCert(cert, verify, &cert->criticalExt);
- if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
- cert->badDate = ret;
- if (verify == VERIFY_SKIP_DATE)
- ret = 0;
- }
- else if (ret < 0) {
- WOLFSSL_ERROR_VERBOSE(ret);
- return ret;
- }
- }
- #endif
- #ifndef NO_SKID
- if (cert->extSubjKeyIdSet == 0 && cert->publicKey != NULL &&
- cert->pubKeySize > 0) {
- if (cert->signatureOID == CTC_SM3wSM2) {
- /* TODO: GmSSL creates IDs this way but whole public key info
- * block should be hashed. */
- ret = CalcHashId_ex(cert->publicKey + cert->pubKeySize - 65, 65,
- cert->extSubjKeyId, HashIdAlg(cert->signatureOID));
- }
- else {
- ret = CalcHashId_ex(cert->publicKey, cert->pubKeySize,
- cert->extSubjKeyId, HashIdAlg(cert->signatureOID));
- }
- if (ret != 0) {
- WOLFSSL_ERROR_VERBOSE(ret);
- return ret;
- }
- }
- #endif /* !NO_SKID */
- if (!cert->selfSigned || (verify != NO_VERIFY && type != CA_TYPE &&
- type != TRUSTED_PEER_TYPE)) {
- cert->ca = NULL;
- #ifndef NO_SKID
- if (cert->extAuthKeyIdSet) {
- cert->ca = GetCA(cm, cert->extAuthKeyId);
- }
- if (cert->ca == NULL && cert->extSubjKeyIdSet
- && verify != VERIFY_OCSP) {
- cert->ca = GetCA(cm, cert->extSubjKeyId);
- }
- if (cert->ca != NULL && XMEMCMP(cert->issuerHash,
- cert->ca->subjectNameHash, KEYID_SIZE) != 0) {
- cert->ca = NULL;
- }
- if (cert->ca == NULL) {
- cert->ca = GetCAByName(cm, cert->issuerHash);
- /* If AKID is available then this CA doesn't have the public
- * key required */
- if (cert->ca && cert->extAuthKeyIdSet) {
- WOLFSSL_MSG("CA SKID doesn't match AKID");
- cert->ca = NULL;
- }
- }
- /* OCSP Only: alt lookup using subject and pub key w/o sig check */
- #ifdef WOLFSSL_NO_TRUSTED_CERTS_VERIFY
- if (cert->ca == NULL && verify == VERIFY_OCSP) {
- cert->ca = GetCABySubjectAndPubKey(cert, cm);
- if (cert->ca) {
- ret = 0; /* success */
- goto exit_pcr;
- }
- }
- #endif /* WOLFSSL_NO_TRUSTED_CERTS_VERIFY */
- #else
- cert->ca = GetCA(cm, cert->issuerHash);
- #endif /* !NO_SKID */
- if (cert->ca) {
- WOLFSSL_MSG("CA found");
- }
- }
- if (cert->selfSigned) {
- cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
- } else {
- /* RFC 5280 Section 4.2.1.9:
- *
- * load/receive check
- *
- * 1) Is CA boolean set?
- * No - SKIP CHECK
- * Yes - Check key usage
- * 2) Is Key usage extension present?
- * No - goto 3
- * Yes - check keyCertSign assertion
- * 2.a) Is keyCertSign asserted?
- * No - goto 4
- * Yes - goto 3
- * 3) Is pathLen set?
- * No - goto 4
- * Yes - check pathLen against maxPathLen.
- * 3.a) Is pathLen less than maxPathLen?
- * No - goto 4
- * Yes - set maxPathLen to pathLen and EXIT
- * 4) Is maxPathLen > 0?
- * Yes - Reduce by 1
- * No - ERROR
- */
- if (cert->ca && cert->pathLengthSet) {
- int checkPathLen = 0;
- int decrementMaxPathLen = 0;
- cert->maxPathLen = cert->pathLength;
- if (cert->isCA) {
- WOLFSSL_MSG("\tCA boolean set");
- if (cert->extKeyUsageSet) {
- WOLFSSL_MSG("\tExtension Key Usage Set");
- if ((cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) != 0) {
- checkPathLen = 1;
- }
- else {
- decrementMaxPathLen = 1;
- }
- }
- else {
- checkPathLen = 1;
- } /* !cert->ca check */
- } /* cert is not a CA (assuming entity cert) */
- if (checkPathLen && cert->pathLengthSet) {
- if (cert->pathLength < cert->ca->maxPathLen) {
- WOLFSSL_MSG("\tmaxPathLen status: set to pathLength");
- cert->maxPathLen = cert->pathLength;
- }
- else {
- decrementMaxPathLen = 1;
- }
- }
- if (decrementMaxPathLen && cert->ca->maxPathLen > 0) {
- WOLFSSL_MSG("\tmaxPathLen status: reduce by 1");
- cert->maxPathLen = (byte)(cert->ca->maxPathLen - 1);
- if (verify != NO_VERIFY && type != CA_TYPE &&
- type != TRUSTED_PEER_TYPE) {
- WOLFSSL_MSG("\tmaxPathLen status: OK");
- }
- } else if (decrementMaxPathLen && cert->ca->maxPathLen == 0) {
- cert->maxPathLen = 0;
- if (verify != NO_VERIFY && type != CA_TYPE &&
- type != TRUSTED_PEER_TYPE) {
- WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
- WOLFSSL_MSG("\tmaxPathLen status: ERROR");
- WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_INV_E);
- return ASN_PATHLEN_INV_E;
- }
- }
- } else if (cert->ca && cert->isCA) {
- /* case where cert->pathLength extension is not set */
- if (cert->ca->maxPathLen > 0) {
- cert->maxPathLen = (byte)(cert->ca->maxPathLen - 1);
- } else {
- cert->maxPathLen = 0;
- if (verify != NO_VERIFY && type != CA_TYPE &&
- type != TRUSTED_PEER_TYPE) {
- WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
- WOLFSSL_MSG("\tmaxPathLen status: ERROR");
- WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_INV_E);
- return ASN_PATHLEN_INV_E;
- }
- }
- }
- }
- #ifdef HAVE_OCSP
- if (verify != NO_VERIFY && type != CA_TYPE &&
- type != TRUSTED_PEER_TYPE) {
- if (cert->ca) {
- /* Need the CA's public key hash for OCSP */
- XMEMCPY(cert->issuerKeyHash, cert->ca->subjectKeyHash,
- KEYID_SIZE);
- }
- }
- #endif /* HAVE_OCSP */
- }
- #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
- /* prepare for TSIP TLS cert verification API use */
- if (cert->keyOID == RSAk) {
- /* to call TSIP API, it needs keys position info in bytes */
- if ((ret = RsaPublicKeyDecodeRawIndex(cert->publicKey, (word32*)&idx,
- cert->pubKeySize,
- &cert->sigCtx.CertAtt.pubkey_n_start,
- &cert->sigCtx.CertAtt.pubkey_n_len,
- &cert->sigCtx.CertAtt.pubkey_e_start,
- &cert->sigCtx.CertAtt.pubkey_e_len)) != 0) {
- WOLFSSL_MSG("Decoding index from cert failed.");
- return ret;
- }
- cert->sigCtx.CertAtt.certBegin = cert->certBegin;
- }
- else if (cert->keyOID == ECDSAk) {
- cert->sigCtx.CertAtt.certBegin = cert->certBegin;
- }
- /* check if we can use TSIP for cert verification */
- /* if the ca is verified as tsip root ca. */
- /* TSIP can only handle 2048 bits(256 byte) key. */
- if (cert->ca && Renesas_cmn_checkCA(cert->ca->cm_idx) != 0 &&
- (cert->sigCtx.CertAtt.pubkey_n_len == 256 ||
- cert->sigCtx.CertAtt.curve_id == ECC_SECP256R1)) {
- /* assign memory to encrypted tsip Rsa key index */
- if (!cert->sce_tsip_encRsaKeyIdx)
- cert->sce_tsip_encRsaKeyIdx =
- (byte*)XMALLOC(TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY,
- cert->heap, DYNAMIC_TYPE_RSA);
- if (cert->sce_tsip_encRsaKeyIdx == NULL)
- return MEMORY_E;
- }
- else {
- if (cert->ca) {
- /* TSIP isn't usable */
- if (Renesas_cmn_checkCA(cert->ca->cm_idx) == 0)
- WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't verified "
- "by TSIP.");
- else if (cert->sigCtx.CertAtt.pubkey_n_len != 256)
- WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't signed by "
- "RSA 2048.");
- else
- WOLFSSL_MSG("SCE-TSIP isn't usable");
- }
- cert->sce_tsip_encRsaKeyIdx = NULL;
- }
- sce_tsip_encRsaKeyIdx = cert->sce_tsip_encRsaKeyIdx;
- #else
- sce_tsip_encRsaKeyIdx = NULL;
- #endif
- if (verify != NO_VERIFY && type != CA_TYPE && type != TRUSTED_PEER_TYPE) {
- if (cert->ca) {
- if (verify == VERIFY || verify == VERIFY_OCSP ||
- verify == VERIFY_SKIP_DATE) {
- /* try to confirm/verify signature */
- if ((ret = ConfirmSignature(&cert->sigCtx,
- cert->source + cert->certBegin,
- cert->sigIndex - cert->certBegin,
- cert->ca->publicKey, cert->ca->pubKeySize,
- cert->ca->keyOID, cert->signature,
- cert->sigLength, cert->signatureOID,
- #ifdef WC_RSA_PSS
- cert->source + cert->sigParamsIndex,
- cert->sigParamsLength,
- #else
- NULL, 0,
- #endif
- sce_tsip_encRsaKeyIdx)) != 0) {
- if (ret != WC_PENDING_E) {
- WOLFSSL_MSG("Confirm signature failed");
- }
- WOLFSSL_ERROR_VERBOSE(ret);
- return ret;
- }
- }
- #ifndef IGNORE_NAME_CONSTRAINTS
- if (verify == VERIFY || verify == VERIFY_OCSP ||
- verify == VERIFY_NAME || verify == VERIFY_SKIP_DATE) {
- /* check that this cert's name is permitted by the signer's
- * name constraints */
- if (!ConfirmNameConstraints(cert->ca, cert)) {
- WOLFSSL_MSG("Confirm name constraint failed");
- WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
- return ASN_NAME_INVALID_E;
- }
- }
- #endif /* IGNORE_NAME_CONSTRAINTS */
- }
- #ifdef WOLFSSL_CERT_REQ
- else if (type == CERTREQ_TYPE) {
- if ((ret = ConfirmSignature(&cert->sigCtx,
- cert->source + cert->certBegin,
- cert->sigIndex - cert->certBegin,
- cert->publicKey, cert->pubKeySize,
- cert->keyOID, cert->signature,
- cert->sigLength, cert->signatureOID,
- #ifdef WC_RSA_PSS
- cert->source + cert->sigParamsIndex, cert->sigParamsLength,
- #else
- NULL, 0,
- #endif
- sce_tsip_encRsaKeyIdx)) != 0) {
- if (ret != WC_PENDING_E) {
- WOLFSSL_MSG("Confirm signature failed");
- }
- WOLFSSL_ERROR_VERBOSE(ret);
- return ret;
- }
- }
- #endif
- else {
- /* no signer */
- WOLFSSL_MSG("No CA signer to verify with");
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
- /* ret needs to be self-signer error for Qt compat */
- if (cert->selfSigned) {
- WOLFSSL_ERROR_VERBOSE(ASN_SELF_SIGNED_E);
- return ASN_SELF_SIGNED_E;
- }
- else
- #endif
- {
- WOLFSSL_ERROR_VERBOSE(ASN_NO_SIGNER_E);
- return ASN_NO_SIGNER_E;
- }
- }
- }
- #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
- exit_pcr:
- #endif
- if (cert->badDate != 0) {
- if (verify != VERIFY_SKIP_DATE) {
- return cert->badDate;
- }
- WOLFSSL_MSG("Date error: Verify option is skipping");
- }
- if (cert->criticalExt != 0)
- return cert->criticalExt;
- return ret;
- }
- /* Create and init an new signer */
- Signer* MakeSigner(void* heap)
- {
- Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
- DYNAMIC_TYPE_SIGNER);
- if (signer) {
- XMEMSET(signer, 0, sizeof(Signer));
- }
- (void)heap;
- return signer;
- }
- /* Free an individual signer.
- *
- * Used by Certificate Manager.
- *
- * @param [in, out] signer On in, signer object.
- * On out, pointer is no longer valid.
- * @param [in] heap Dynamic memory hint.
- */
- void FreeSigner(Signer* signer, void* heap)
- {
- (void)signer;
- (void)heap;
- XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
- XFREE((void*)signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
- #ifndef IGNORE_NAME_CONSTRAINTS
- if (signer->permittedNames)
- FreeNameSubtrees(signer->permittedNames, heap);
- if (signer->excludedNames)
- FreeNameSubtrees(signer->excludedNames, heap);
- #endif
- #ifdef WOLFSSL_SIGNER_DER_CERT
- FreeDer(&signer->derCert);
- #endif
- XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
- }
- /* Free the whole singer table with number of rows.
- *
- * Each table entry is a linked list of signers.
- * Used by Certificate Manager.
- *
- * @param [in, out] table Array of signer objects.
- * @param [in] rows Number of entries in table.
- * @param [in] heap Dynamic memory hint.
- */
- void FreeSignerTable(Signer** table, int rows, void* heap)
- {
- int i;
- for (i = 0; i < rows; i++) {
- Signer* signer = table[i];
- while (signer) {
- Signer* next = signer->next;
- FreeSigner(signer, heap);
- signer = next;
- }
- table[i] = NULL;
- }
- }
- #ifdef WOLFSSL_TRUST_PEER_CERT
- /* Free an individual trusted peer cert.
- *
- * @param [in, out] tp Trusted peer certificate object.
- * @param [in] heap Dynamic memory hint.
- */
- void FreeTrustedPeer(TrustedPeerCert* tp, void* heap)
- {
- if (tp == NULL) {
- return;
- }
- if (tp->name) {
- XFREE(tp->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
- }
- if (tp->sig) {
- XFREE(tp->sig, heap, DYNAMIC_TYPE_SIGNATURE);
- }
- #ifndef IGNORE_NAME_CONSTRAINTS
- if (tp->permittedNames)
- FreeNameSubtrees(tp->permittedNames, heap);
- if (tp->excludedNames)
- FreeNameSubtrees(tp->excludedNames, heap);
- #endif
- XFREE(tp, heap, DYNAMIC_TYPE_CERT);
- (void)heap;
- }
- /* Free the whole Trusted Peer linked list.
- *
- * Each table entry is a linked list of trusted peer certificates.
- * Used by Certificate Manager.
- *
- * @param [in, out] table Array of trusted peer certificate objects.
- * @param [in] rows Number of entries in table.
- * @param [in] heap Dynamic memory hint.
- */
- void FreeTrustedPeerTable(TrustedPeerCert** table, int rows, void* heap)
- {
- int i;
- for (i = 0; i < rows; i++) {
- TrustedPeerCert* tp = table[i];
- while (tp) {
- TrustedPeerCert* next = tp->next;
- FreeTrustedPeer(tp, heap);
- tp = next;
- }
- table[i] = NULL;
- }
- }
- #endif /* WOLFSSL_TRUST_PEER_CERT */
- #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7)
- int SetSerialNumber(const byte* sn, word32 snSz, byte* output,
- word32 outputSz, int maxSnSz)
- {
- int i;
- int snSzInt = (int)snSz;
- if (sn == NULL || output == NULL || snSzInt < 0)
- return BAD_FUNC_ARG;
- /* remove leading zeros */
- while (snSzInt > 0 && sn[0] == 0) {
- snSzInt--;
- sn++;
- }
- /* RFC 5280 - 4.1.2.2:
- * Serial numbers must be a positive value (and not zero) */
- if (snSzInt == 0) {
- WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
- return BAD_FUNC_ARG;
- }
- if (sn[0] & 0x80)
- maxSnSz--;
- /* truncate if input is too long */
- if (snSzInt > maxSnSz)
- snSzInt = maxSnSz;
- i = SetASNInt(snSzInt, sn[0], NULL);
- /* truncate if input is too long */
- if (snSzInt > (int)outputSz - i)
- snSzInt = (int)outputSz - i;
- /* sanity check number of bytes to copy */
- if (snSzInt <= 0) {
- return BUFFER_E;
- }
- /* write out ASN.1 Integer */
- (void)SetASNInt(snSzInt, sn[0], output);
- XMEMCPY(output + i, sn, (size_t)snSzInt);
- /* compute final length */
- i += snSzInt;
- return i;
- }
- #endif /* !WOLFSSL_ASN_TEMPLATE */
- #endif /* !NO_CERTS */
- #if defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS12) || \
- (defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT))
- int SetMyVersion(word32 version, byte* output, int header)
- {
- int i = 0;
- if (output == NULL)
- return BAD_FUNC_ARG;
- if (header) {
- output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
- output[i++] = 3;
- }
- output[i++] = ASN_INTEGER;
- output[i++] = 0x01;
- output[i++] = (byte)version;
- return i;
- }
- #endif
- #ifndef WOLFSSL_ASN_TEMPLATE
- int wc_GetSerialNumber(const byte* input, word32* inOutIdx,
- byte* serial, int* serialSz, word32 maxIdx)
- {
- int result = 0;
- int ret;
- WOLFSSL_ENTER("wc_GetSerialNumber");
- if (serial == NULL || input == NULL || serialSz == NULL) {
- return BAD_FUNC_ARG;
- }
- /* First byte is ASN type */
- if ((*inOutIdx+1) > maxIdx) {
- WOLFSSL_MSG("Bad idx first");
- return BUFFER_E;
- }
- ret = GetASNInt(input, inOutIdx, serialSz, maxIdx);
- if (ret != 0)
- return ret;
- if (*serialSz > EXTERNAL_SERIAL_SIZE || *serialSz <= 0) {
- WOLFSSL_MSG("Serial size bad");
- WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
- return ASN_PARSE_E;
- }
- /* return serial */
- XMEMCPY(serial, &input[*inOutIdx], (size_t)*serialSz);
- *inOutIdx += (word32)*serialSz;
- return result;
- }
- #endif
- #ifndef NO_CERTS
- /* TODO: consider moving PEM code out to a different file. */
- int AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
- {
- int ret = BAD_FUNC_ARG;
- if (pDer) {
- int dynType = 0;
- DerBuffer* der;
- /* Determine dynamic type */
- switch (type) {
- case CA_TYPE: dynType = DYNAMIC_TYPE_CA; break;
- case CERT_TYPE: dynType = DYNAMIC_TYPE_CERT; break;
- case CRL_TYPE: dynType = DYNAMIC_TYPE_CRL; break;
- case DSA_TYPE: dynType = DYNAMIC_TYPE_DSA; break;
- case ECC_TYPE: dynType = DYNAMIC_TYPE_ECC; break;
- case RSA_TYPE: dynType = DYNAMIC_TYPE_RSA; break;
- default: dynType = DYNAMIC_TYPE_KEY; break;
- }
- /* Setup new buffer */
- *pDer = (DerBuffer*)XMALLOC(sizeof(DerBuffer) + length, heap, dynType);
- if (*pDer == NULL) {
- return MEMORY_E;
- }
- XMEMSET(*pDer, 0, sizeof(DerBuffer) + length);
- der = *pDer;
- der->type = type;
- der->dynType = dynType; /* Cache this for FreeDer */
- der->heap = heap;
- der->buffer = (byte*)der + sizeof(DerBuffer);
- der->length = length;
- ret = 0; /* Success */
- }
- return ret;
- }
- void FreeDer(DerBuffer** pDer)
- {
- if (pDer && *pDer)
- {
- DerBuffer* der = (DerBuffer*)*pDer;
- /* ForceZero private keys */
- if (der->type == PRIVATEKEY_TYPE && der->buffer != NULL) {
- ForceZero(der->buffer, der->length);
- }
- der->buffer = NULL;
- der->length = 0;
- XFREE(der, der->heap, der->dynType);
- *pDer = NULL;
- }
- }
- int wc_AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
- {
- return AllocDer(pDer, length, type, heap);
- }
- void wc_FreeDer(DerBuffer** pDer)
- {
- FreeDer(pDer);
- }
- #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
- /* Note: If items added make sure MAX_X509_HEADER_SZ is
- updated to reflect maximum length and pem_struct_min_sz
- to reflect minimum size */
- wcchar BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
- wcchar END_CERT = "-----END CERTIFICATE-----";
- #ifdef WOLFSSL_CERT_REQ
- wcchar BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----";
- wcchar END_CERT_REQ = "-----END CERTIFICATE REQUEST-----";
- #endif
- #ifndef NO_DH
- wcchar BEGIN_DH_PARAM = "-----BEGIN DH PARAMETERS-----";
- wcchar END_DH_PARAM = "-----END DH PARAMETERS-----";
- wcchar BEGIN_X942_PARAM = "-----BEGIN X9.42 DH PARAMETERS-----";
- wcchar END_X942_PARAM = "-----END X9.42 DH PARAMETERS-----";
- #endif
- #ifndef NO_DSA
- wcchar BEGIN_DSA_PARAM = "-----BEGIN DSA PARAMETERS-----";
- wcchar END_DSA_PARAM = "-----END DSA PARAMETERS-----";
- #endif
- wcchar BEGIN_X509_CRL = "-----BEGIN X509 CRL-----";
- wcchar END_X509_CRL = "-----END X509 CRL-----";
- wcchar BEGIN_RSA_PRIV = "-----BEGIN RSA PRIVATE KEY-----";
- wcchar END_RSA_PRIV = "-----END RSA PRIVATE KEY-----";
- wcchar BEGIN_RSA_PUB = "-----BEGIN RSA PUBLIC KEY-----";
- wcchar END_RSA_PUB = "-----END RSA PUBLIC KEY-----";
- wcchar BEGIN_PRIV_KEY = "-----BEGIN PRIVATE KEY-----";
- wcchar END_PRIV_KEY = "-----END PRIVATE KEY-----";
- wcchar BEGIN_ENC_PRIV_KEY = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
- wcchar END_ENC_PRIV_KEY = "-----END ENCRYPTED PRIVATE KEY-----";
- #ifdef HAVE_ECC
- wcchar BEGIN_EC_PRIV = "-----BEGIN EC PRIVATE KEY-----";
- wcchar END_EC_PRIV = "-----END EC PRIVATE KEY-----";
- #ifdef OPENSSL_EXTRA
- wcchar BEGIN_EC_PARAM = "-----BEGIN EC PARAMETERS-----";
- wcchar END_EC_PARAM = "-----END EC PARAMETERS-----";
- #endif
- #endif
- #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
- !defined(NO_DSA)
- wcchar BEGIN_DSA_PRIV = "-----BEGIN DSA PRIVATE KEY-----";
- wcchar END_DSA_PRIV = "-----END DSA PRIVATE KEY-----";
- #endif
- #ifdef OPENSSL_EXTRA
- const char BEGIN_PRIV_KEY_PREFIX[] = "-----BEGIN";
- const char PRIV_KEY_SUFFIX[] = "PRIVATE KEY-----";
- const char END_PRIV_KEY_PREFIX[] = "-----END";
- #endif
- wcchar BEGIN_PUB_KEY = "-----BEGIN PUBLIC KEY-----";
- wcchar END_PUB_KEY = "-----END PUBLIC KEY-----";
- #if defined(HAVE_ED25519) || defined(HAVE_ED448)
- wcchar BEGIN_EDDSA_PRIV = "-----BEGIN EDDSA PRIVATE KEY-----";
- wcchar END_EDDSA_PRIV = "-----END EDDSA PRIVATE KEY-----";
- #endif
- #if defined(HAVE_PQC)
- #if defined(HAVE_FALCON)
- wcchar BEGIN_FALCON_LEVEL1_PRIV = "-----BEGIN FALCON_LEVEL1 PRIVATE KEY-----";
- wcchar END_FALCON_LEVEL1_PRIV = "-----END FALCON_LEVEL1 PRIVATE KEY-----";
- wcchar BEGIN_FALCON_LEVEL5_PRIV = "-----BEGIN FALCON_LEVEL5 PRIVATE KEY-----";
- wcchar END_FALCON_LEVEL5_PRIV = "-----END FALCON_LEVEL5 PRIVATE KEY-----";
- #endif /* HAVE_FALCON */
- #if defined(HAVE_DILITHIUM)
- wcchar BEGIN_DILITHIUM_LEVEL2_PRIV = "-----BEGIN DILITHIUM_LEVEL2 PRIVATE KEY-----";
- wcchar END_DILITHIUM_LEVEL2_PRIV = "-----END DILITHIUM_LEVEL2 PRIVATE KEY-----";
- wcchar BEGIN_DILITHIUM_LEVEL3_PRIV = "-----BEGIN DILITHIUM_LEVEL3 PRIVATE KEY-----";
- wcchar END_DILITHIUM_LEVEL3_PRIV = "-----END DILITHIUM_LEVEL3 PRIVATE KEY-----";
- wcchar BEGIN_DILITHIUM_LEVEL5_PRIV = "-----BEGIN DILITHIUM_LEVEL5 PRIVATE KEY-----";
- wcchar END_DILITHIUM_LEVEL5_PRIV = "-----END DILITHIUM_LEVEL5 PRIVATE KEY-----";
- #endif /* HAVE_DILITHIUM */
- #if defined(HAVE_SPHINCS)
- wcchar BEGIN_SPHINCS_FAST_LEVEL1_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
- wcchar END_SPHINCS_FAST_LEVEL1_PRIV = "-----END SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
- wcchar BEGIN_SPHINCS_FAST_LEVEL3_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
- wcchar END_SPHINCS_FAST_LEVEL3_PRIV = "-----END SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
- wcchar BEGIN_SPHINCS_FAST_LEVEL5_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
- wcchar END_SPHINCS_FAST_LEVEL5_PRIV = "-----END SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
- wcchar BEGIN_SPHINCS_SMALL_LEVEL1_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
- wcchar END_SPHINCS_SMALL_LEVEL1_PRIV = "-----END SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
- wcchar BEGIN_SPHINCS_SMALL_LEVEL3_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
- wcchar END_SPHINCS_SMALL_LEVEL3_PRIV = "-----END SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
- wcchar BEGIN_SPHINCS_SMALL_LEVEL5_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
- wcchar END_SPHINCS_SMALL_LEVEL5_PRIV = "-----END SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- const int pem_struct_min_sz = XSTR_SIZEOF("-----BEGIN X509 CRL-----"
- "-----END X509 CRL-----");
- #ifdef WOLFSSL_PEM_TO_DER
- static WC_INLINE const char* SkipEndOfLineChars(const char* line,
- const char* endOfLine)
- {
- /* eat end of line characters */
- while (line < endOfLine &&
- (line[0] == '\r' || line[0] == '\n')) {
- line++;
- }
- return line;
- }
- #endif
- int wc_PemGetHeaderFooter(int type, const char** header, const char** footer)
- {
- int ret = BAD_FUNC_ARG;
- switch (type) {
- case CA_TYPE: /* same as below */
- case TRUSTED_PEER_TYPE:
- case CERT_TYPE:
- if (header) *header = BEGIN_CERT;
- if (footer) *footer = END_CERT;
- ret = 0;
- break;
- case CRL_TYPE:
- if (header) *header = BEGIN_X509_CRL;
- if (footer) *footer = END_X509_CRL;
- ret = 0;
- break;
- #ifndef NO_DH
- case DH_PARAM_TYPE:
- if (header) *header = BEGIN_DH_PARAM;
- if (footer) *footer = END_DH_PARAM;
- ret = 0;
- break;
- case X942_PARAM_TYPE:
- if (header) *header = BEGIN_X942_PARAM;
- if (footer) *footer = END_X942_PARAM;
- ret = 0;
- break;
- #endif
- #ifndef NO_DSA
- case DSA_PARAM_TYPE:
- if (header) *header = BEGIN_DSA_PARAM;
- if (footer) *footer = END_DSA_PARAM;
- ret = 0;
- break;
- #endif
- #ifdef WOLFSSL_CERT_REQ
- case CERTREQ_TYPE:
- if (header) *header = BEGIN_CERT_REQ;
- if (footer) *footer = END_CERT_REQ;
- ret = 0;
- break;
- #endif
- #ifndef NO_DSA
- case DSA_TYPE:
- case DSA_PRIVATEKEY_TYPE:
- if (header) *header = BEGIN_DSA_PRIV;
- if (footer) *footer = END_DSA_PRIV;
- ret = 0;
- break;
- #endif
- #ifdef HAVE_ECC
- case ECC_TYPE:
- case ECC_PRIVATEKEY_TYPE:
- if (header) *header = BEGIN_EC_PRIV;
- if (footer) *footer = END_EC_PRIV;
- ret = 0;
- break;
- #ifdef OPENSSL_EXTRA
- case ECC_PARAM_TYPE:
- if (header) *header = BEGIN_EC_PARAM;
- if (footer) *footer = END_EC_PARAM;
- ret = 0;
- break;
- #endif
- #endif
- case RSA_TYPE:
- case PRIVATEKEY_TYPE:
- if (header) *header = BEGIN_RSA_PRIV;
- if (footer) *footer = END_RSA_PRIV;
- ret = 0;
- break;
- #ifdef HAVE_ED25519
- case ED25519_TYPE:
- #endif
- #ifdef HAVE_ED448
- case ED448_TYPE:
- #endif
- #if defined(HAVE_ED25519) || defined(HAVE_ED448)
- case EDDSA_PRIVATEKEY_TYPE:
- if (header) *header = BEGIN_EDDSA_PRIV;
- if (footer) *footer = END_EDDSA_PRIV;
- ret = 0;
- break;
- #endif
- #ifdef HAVE_PQC
- #ifdef HAVE_FALCON
- case FALCON_LEVEL1_TYPE:
- if (header) *header = BEGIN_FALCON_LEVEL1_PRIV;
- if (footer) *footer = END_FALCON_LEVEL1_PRIV;
- ret = 0;
- break;
- case FALCON_LEVEL5_TYPE:
- if (header) *header = BEGIN_FALCON_LEVEL5_PRIV;
- if (footer) *footer = END_FALCON_LEVEL5_PRIV;
- ret = 0;
- break;
- #endif /* HAVE_FALCON */
- #ifdef HAVE_DILITHIUM
- case DILITHIUM_LEVEL2_TYPE:
- if (header) *header = BEGIN_DILITHIUM_LEVEL2_PRIV;
- if (footer) *footer = END_DILITHIUM_LEVEL2_PRIV;
- ret = 0;
- break;
- case DILITHIUM_LEVEL3_TYPE:
- if (header) *header = BEGIN_DILITHIUM_LEVEL3_PRIV;
- if (footer) *footer = END_DILITHIUM_LEVEL3_PRIV;
- ret = 0;
- break;
- case DILITHIUM_LEVEL5_TYPE:
- if (header) *header = BEGIN_DILITHIUM_LEVEL5_PRIV;
- if (footer) *footer = END_DILITHIUM_LEVEL5_PRIV;
- ret = 0;
- break;
- #endif /* HAVE_DILITHIUM */
- #ifdef HAVE_SPHINCS
- case SPHINCS_FAST_LEVEL1_TYPE:
- if (header) *header = BEGIN_SPHINCS_FAST_LEVEL1_PRIV;
- if (footer) *footer = END_SPHINCS_FAST_LEVEL1_PRIV;
- ret = 0;
- break;
- case SPHINCS_FAST_LEVEL3_TYPE:
- if (header) *header = BEGIN_SPHINCS_FAST_LEVEL3_PRIV;
- if (footer) *footer = END_SPHINCS_FAST_LEVEL3_PRIV;
- ret = 0;
- break;
- case SPHINCS_FAST_LEVEL5_TYPE:
- if (header) *header = BEGIN_SPHINCS_FAST_LEVEL5_PRIV;
- if (footer) *footer = END_SPHINCS_FAST_LEVEL5_PRIV;
- ret = 0;
- break;
- case SPHINCS_SMALL_LEVEL1_TYPE:
- if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL1_PRIV;
- if (footer) *footer = END_SPHINCS_SMALL_LEVEL1_PRIV;
- ret = 0;
- break;
- case SPHINCS_SMALL_LEVEL3_TYPE:
- if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL3_PRIV;
- if (footer) *footer = END_SPHINCS_SMALL_LEVEL3_PRIV;
- ret = 0;
- break;
- case SPHINCS_SMALL_LEVEL5_TYPE:
- if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL5_PRIV;
- if (footer) *footer = END_SPHINCS_SMALL_LEVEL5_PRIV;
- ret = 0;
- break;
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- case PUBLICKEY_TYPE:
- case ECC_PUBLICKEY_TYPE:
- if (header) *header = BEGIN_PUB_KEY;
- if (footer) *footer = END_PUB_KEY;
- ret = 0;
- break;
- case RSA_PUBLICKEY_TYPE:
- if (header) *header = BEGIN_RSA_PUB;
- if (footer) *footer = END_RSA_PUB;
- ret = 0;
- break;
- #ifndef NO_DH
- case DH_PRIVATEKEY_TYPE:
- #endif
- case PKCS8_PRIVATEKEY_TYPE:
- if (header) *header = BEGIN_PRIV_KEY;
- if (footer) *footer = END_PRIV_KEY;
- ret = 0;
- break;
- case PKCS8_ENC_PRIVATEKEY_TYPE:
- if (header) *header = BEGIN_ENC_PRIV_KEY;
- if (footer) *footer = END_ENC_PRIV_KEY;
- ret = 0;
- break;
- default:
- break;
- }
- return ret;
- }
- #ifdef WOLFSSL_ENCRYPTED_KEYS
- static wcchar kProcTypeHeader = "Proc-Type";
- static wcchar kDecInfoHeader = "DEK-Info";
- #ifdef WOLFSSL_PEM_TO_DER
- #ifndef NO_DES3
- static wcchar kEncTypeDes = "DES-CBC";
- static wcchar kEncTypeDes3 = "DES-EDE3-CBC";
- #endif
- #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
- static wcchar kEncTypeAesCbc128 = "AES-128-CBC";
- #endif
- #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
- static wcchar kEncTypeAesCbc192 = "AES-192-CBC";
- #endif
- #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
- static wcchar kEncTypeAesCbc256 = "AES-256-CBC";
- #endif
- int wc_EncryptedInfoGet(EncryptedInfo* info, const char* cipherInfo)
- {
- int ret = 0;
- if (info == NULL || cipherInfo == NULL)
- return BAD_FUNC_ARG;
- /* determine cipher information */
- #ifndef NO_DES3
- if (XSTRCMP(cipherInfo, kEncTypeDes) == 0) {
- info->cipherType = WC_CIPHER_DES;
- info->keySz = DES_KEY_SIZE;
- /* DES_IV_SIZE is incorrectly 16 in FIPS v2. It should be 8, same as the
- * block size. */
- #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
- if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
- #else
- if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
- #endif
- }
- else if (XSTRCMP(cipherInfo, kEncTypeDes3) == 0) {
- info->cipherType = WC_CIPHER_DES3;
- info->keySz = DES3_KEY_SIZE;
- #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
- if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
- #else
- if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
- #endif
- }
- else
- #endif /* !NO_DES3 */
- #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
- if (XSTRCMP(cipherInfo, kEncTypeAesCbc128) == 0) {
- info->cipherType = WC_CIPHER_AES_CBC;
- info->keySz = AES_128_KEY_SIZE;
- if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
- }
- else
- #endif
- #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
- if (XSTRCMP(cipherInfo, kEncTypeAesCbc192) == 0) {
- info->cipherType = WC_CIPHER_AES_CBC;
- info->keySz = AES_192_KEY_SIZE;
- if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
- }
- else
- #endif
- #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
- if (XSTRCMP(cipherInfo, kEncTypeAesCbc256) == 0) {
- info->cipherType = WC_CIPHER_AES_CBC;
- info->keySz = AES_256_KEY_SIZE;
- if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
- }
- else
- #endif
- {
- ret = NOT_COMPILED_IN;
- }
- return ret;
- }
- int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer,
- size_t bufSz)
- {
- int err = 0;
- const char* bufferStart;
- const char* bufferEnd;
- char* line;
- if (info == NULL || pBuffer == NULL || bufSz == 0)
- return BAD_FUNC_ARG;
- bufferStart = *pBuffer;
- bufferEnd = bufferStart + bufSz;
- /* find encrypted info marker */
- line = XSTRNSTR(bufferStart, kProcTypeHeader,
- min((word32)bufSz, PEM_LINE_LEN));
- if (line != NULL) {
- word32 lineSz;
- char* finish;
- char* start;
- word32 startSz;
- const char* newline = NULL;
- if (line >= bufferEnd) {
- return BUFFER_E;
- }
- lineSz = (word32)(bufferEnd - line);
- /* find DEC-Info marker */
- start = XSTRNSTR(line, kDecInfoHeader, min(lineSz, PEM_LINE_LEN));
- if (start == NULL)
- return BUFFER_E;
- /* skip dec-info and ": " */
- start += XSTRLEN(kDecInfoHeader);
- if (start >= bufferEnd)
- return BUFFER_E;
- if (start[0] == ':') {
- start++;
- if (start >= bufferEnd)
- return BUFFER_E;
- }
- if (start[0] == ' ')
- start++;
- startSz = (word32)(bufferEnd - start);
- finish = XSTRNSTR(start, ",", min(startSz, PEM_LINE_LEN));
- if ((start != NULL) && (finish != NULL) && (start < finish)) {
- word32 finishSz;
- if (finish >= bufferEnd) {
- return BUFFER_E;
- }
- finishSz = (word32)(bufferEnd - finish);
- newline = XSTRNSTR(finish, "\r", min(finishSz, PEM_LINE_LEN));
- /* get cipher name */
- if (NAME_SZ < (finish - start)) /* buffer size of info->name */
- return BUFFER_E;
- if (XMEMCPY(info->name, start, (size_t)(finish - start)) == NULL)
- return BUFFER_E;
- info->name[finish - start] = '\0'; /* null term */
- /* populate info */
- err = wc_EncryptedInfoGet(info, info->name);
- if (err != 0)
- return err;
- /* get IV */
- if (finishSz < info->ivSz + 1)
- return BUFFER_E;
- if (newline == NULL) {
- newline = XSTRNSTR(finish, "\n", min(finishSz,
- PEM_LINE_LEN));
- }
- if ((newline != NULL) && (newline > finish)) {
- finish++;
- info->ivSz = (word32)(newline - finish);
- if (info->ivSz > IV_SZ)
- return BUFFER_E;
- if (XMEMCPY(info->iv, finish, info->ivSz) == NULL)
- return BUFFER_E;
- info->set = 1;
- }
- else
- return BUFFER_E;
- }
- else
- return BUFFER_E;
- /* eat end of line characters */
- newline = SkipEndOfLineChars(newline, bufferEnd);
- /* return new headerEnd */
- *pBuffer = newline;
- }
- return err;
- }
- #endif /* WOLFSSL_PEM_TO_DER */
- #ifdef WOLFSSL_DER_TO_PEM
- static int wc_EncryptedInfoAppend(char* dest, int destSz, char* cipherInfo)
- {
- if (cipherInfo != NULL) {
- int cipherInfoStrLen = (int)XSTRLEN((char*)cipherInfo);
- if (cipherInfoStrLen > HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3))
- cipherInfoStrLen = HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3);
- if (destSz - (int)XSTRLEN(dest) >= cipherInfoStrLen + (9+14+8+2+2+1)) {
- /* strncat's src length needs to include the NULL */
- XSTRNCAT(dest, kProcTypeHeader, 10);
- XSTRNCAT(dest, ": 4,ENCRYPTED\n", 15);
- XSTRNCAT(dest, kDecInfoHeader, 9);
- XSTRNCAT(dest, ": ", 3);
- XSTRNCAT(dest, cipherInfo, (size_t)destSz - XSTRLEN(dest) - 1);
- XSTRNCAT(dest, "\n\n", 4);
- }
- }
- return 0;
- }
- #endif /* WOLFSSL_DER_TO_PEM */
- #endif /* WOLFSSL_ENCRYPTED_KEYS */
- #ifdef WOLFSSL_DER_TO_PEM
- /* Used for compatibility API */
- WOLFSSL_ABI
- int wc_DerToPem(const byte* der, word32 derSz,
- byte* output, word32 outSz, int type)
- {
- return wc_DerToPemEx(der, derSz, output, outSz, NULL, type);
- }
- /* convert der buffer to pem into output, can't do inplace, der and output
- need to be different */
- int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz,
- byte *cipher_info, int type)
- {
- const char* headerStr = NULL;
- const char* footerStr = NULL;
- #ifdef WOLFSSL_SMALL_STACK
- char* header = NULL;
- char* footer = NULL;
- #else
- char header[MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE];
- char footer[MAX_X509_HEADER_SZ];
- #endif
- int headerLen = MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE;
- int footerLen = MAX_X509_HEADER_SZ;
- int i;
- int err;
- int outLen; /* return length or error */
- (void)cipher_info;
- if (der == output) /* no in place conversion */
- return BAD_FUNC_ARG;
- err = wc_PemGetHeaderFooter(type, &headerStr, &footerStr);
- if (err != 0)
- return err;
- #ifdef WOLFSSL_SMALL_STACK
- header = (char*)XMALLOC(headerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- if (header == NULL)
- return MEMORY_E;
- footer = (char*)XMALLOC(footerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- if (footer == NULL) {
- XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- return MEMORY_E;
- }
- #endif
- /* build header and footer based on type */
- XSTRNCPY(header, headerStr, (size_t)headerLen - 1);
- header[headerLen - 2] = 0;
- XSTRNCPY(footer, footerStr, (size_t)footerLen - 1);
- footer[footerLen - 2] = 0;
- /* add new line to end */
- XSTRNCAT(header, "\n", 2);
- XSTRNCAT(footer, "\n", 2);
- #ifdef WOLFSSL_ENCRYPTED_KEYS
- err = wc_EncryptedInfoAppend(header, headerLen, (char*)cipher_info);
- if (err != 0) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return err;
- }
- #endif
- headerLen = (int)XSTRLEN(header);
- footerLen = (int)XSTRLEN(footer);
- /* if null output and 0 size passed in then return size needed */
- if (!output && outSz == 0) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- outLen = 0;
- if ((err = Base64_Encode(der, derSz, NULL, (word32*)&outLen))
- != LENGTH_ONLY_E) {
- WOLFSSL_ERROR_VERBOSE(err);
- return err;
- }
- return headerLen + footerLen + outLen;
- }
- if (!der || !output) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return BAD_FUNC_ARG;
- }
- /* don't even try if outSz too short */
- if (outSz < (word32)headerLen + (word32)footerLen + derSz) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return BAD_FUNC_ARG;
- }
- /* header */
- XMEMCPY(output, header, (size_t)headerLen);
- i = headerLen;
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- /* body */
- outLen = (int)outSz - (headerLen + footerLen); /* input to Base64_Encode */
- if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- WOLFSSL_ERROR_VERBOSE(err);
- return err;
- }
- i += outLen;
- /* footer */
- if ( (i + footerLen) > (int)outSz) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return BAD_FUNC_ARG;
- }
- XMEMCPY(output + i, footer, (size_t)footerLen);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return outLen + headerLen + footerLen;
- }
- #endif /* WOLFSSL_DER_TO_PEM */
- #ifdef WOLFSSL_PEM_TO_DER
- /* Remove PEM header/footer, convert to ASN1, store any encrypted data
- info->consumed tracks of PEM bytes consumed in case multiple parts */
- int PemToDer(const unsigned char* buff, long longSz, int type,
- DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
- {
- const char* header = NULL;
- const char* footer = NULL;
- const char* headerEnd;
- const char* footerEnd;
- const char* consumedEnd;
- const char* bufferEnd = (const char*)(buff + longSz);
- long neededSz;
- int ret = 0;
- int sz = (int)longSz;
- int encrypted_key = 0;
- DerBuffer* der;
- word32 algId = 0;
- word32 idx;
- #ifdef OPENSSL_EXTRA
- char beginBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
- char endBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
- #endif
- WOLFSSL_ENTER("PemToDer");
- /* get PEM header and footer based on type */
- ret = wc_PemGetHeaderFooter(type, &header, &footer);
- if (ret != 0)
- return ret;
- /* map header if not found for type */
- for (;;) {
- headerEnd = XSTRNSTR((char*)buff, header, (word32)sz);
- if (headerEnd) {
- break;
- }
- if (type == PRIVATEKEY_TYPE) {
- if (header == BEGIN_RSA_PRIV) {
- header = BEGIN_PRIV_KEY;
- footer = END_PRIV_KEY;
- }
- else if (header == BEGIN_PRIV_KEY) {
- header = BEGIN_ENC_PRIV_KEY;
- footer = END_ENC_PRIV_KEY;
- }
- #ifdef HAVE_ECC
- else if (header == BEGIN_ENC_PRIV_KEY) {
- header = BEGIN_EC_PRIV;
- footer = END_EC_PRIV;
- }
- else if (header == BEGIN_EC_PRIV) {
- header = BEGIN_DSA_PRIV;
- footer = END_DSA_PRIV;
- }
- #endif
- #if defined(HAVE_ED25519) || defined(HAVE_ED448)
- #ifdef HAVE_ECC
- else if (header == BEGIN_DSA_PRIV) {
- #else
- else if (header == BEGIN_ENC_PRIV_KEY) {
- #endif
- header = BEGIN_EDDSA_PRIV;
- footer = END_EDDSA_PRIV;
- }
- #endif
- else {
- #ifdef WOLF_PRIVATE_KEY_ID
- /* allow loading a public key for use with crypto or PK callbacks */
- type = PUBLICKEY_TYPE;
- header = BEGIN_PUB_KEY;
- footer = END_PUB_KEY;
- #else
- break;
- #endif
- }
- }
- else if (type == PUBLICKEY_TYPE) {
- if (header == BEGIN_PUB_KEY) {
- header = BEGIN_RSA_PUB;
- footer = END_RSA_PUB;
- }
- else {
- break;
- }
- }
- #if defined(HAVE_ECC) && defined(OPENSSL_EXTRA)
- else if (type == ECC_PARAM_TYPE) {
- if (header == BEGIN_EC_PARAM) {
- header = BEGIN_EC_PARAM;
- footer = END_EC_PARAM;
- }
- else {
- break;
- }
- }
- #endif
- #ifdef HAVE_CRL
- else if ((type == CRL_TYPE) && (header != BEGIN_X509_CRL)) {
- header = BEGIN_X509_CRL;
- footer = END_X509_CRL;
- }
- #endif
- else {
- break;
- }
- }
- if (!headerEnd) {
- #ifdef OPENSSL_EXTRA
- if (type == PRIVATEKEY_TYPE) {
- /* see if there is a -----BEGIN * PRIVATE KEY----- header */
- headerEnd = XSTRNSTR((char*)buff, PRIV_KEY_SUFFIX, sz);
- if (headerEnd) {
- const char* beginEnd;
- int endLen;
- beginEnd = headerEnd + XSTR_SIZEOF(PRIV_KEY_SUFFIX);
- if (beginEnd >= (char*)buff + sz) {
- return BUFFER_E;
- }
- /* back up to BEGIN_PRIV_KEY_PREFIX */
- while (headerEnd > (char*)buff &&
- XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
- XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 &&
- *headerEnd != '\n') {
- headerEnd--;
- }
- if (headerEnd <= (char*)buff ||
- XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
- XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 ||
- beginEnd - headerEnd > PEM_LINE_LEN) {
- WOLFSSL_MSG("Couldn't find PEM header");
- WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
- return ASN_NO_PEM_HEADER;
- }
- /* headerEnd now points to beginning of header */
- XMEMCPY(beginBuf, headerEnd, beginEnd - headerEnd);
- beginBuf[beginEnd - headerEnd] = '\0';
- /* look for matching footer */
- footer = XSTRNSTR(beginEnd,
- beginBuf + XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX),
- (unsigned int)((char*)buff + sz - beginEnd));
- if (!footer) {
- WOLFSSL_MSG("Couldn't find PEM footer");
- WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
- return ASN_NO_PEM_HEADER;
- }
- footer -= XSTR_SIZEOF(END_PRIV_KEY_PREFIX);
- if (footer > (char*)buff + sz - XSTR_SIZEOF(END_PRIV_KEY_PREFIX)
- || XSTRNCMP(footer, END_PRIV_KEY_PREFIX,
- XSTR_SIZEOF(END_PRIV_KEY_PREFIX)) != 0) {
- WOLFSSL_MSG("Unexpected footer for PEM");
- return BUFFER_E;
- }
- endLen = (unsigned int)(beginEnd - headerEnd -
- (XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX) -
- XSTR_SIZEOF(END_PRIV_KEY_PREFIX)));
- XMEMCPY(endBuf, footer, endLen);
- endBuf[endLen] = '\0';
- header = beginBuf;
- footer = endBuf;
- headerEnd = beginEnd;
- }
- }
- if (!headerEnd) {
- WOLFSSL_MSG("Couldn't find PEM header");
- WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
- return ASN_NO_PEM_HEADER;
- }
- #else
- WOLFSSL_MSG("Couldn't find PEM header");
- return ASN_NO_PEM_HEADER;
- #endif
- } else {
- headerEnd += XSTRLEN(header);
- }
- /* eat end of line characters */
- headerEnd = SkipEndOfLineChars(headerEnd, bufferEnd);
- if (keyFormat) {
- /* keyFormat is Key_Sum enum */
- if (type == PRIVATEKEY_TYPE) {
- #ifndef NO_RSA
- if (header == BEGIN_RSA_PRIV)
- *keyFormat = RSAk;
- #endif
- #ifdef HAVE_ECC
- if (header == BEGIN_EC_PRIV)
- *keyFormat = ECDSAk;
- #endif
- #ifndef NO_DSA
- if (header == BEGIN_DSA_PRIV)
- *keyFormat = DSAk;
- #endif
- }
- #ifdef WOLF_PRIVATE_KEY_ID
- else if (type == PUBLICKEY_TYPE) {
- #ifndef NO_RSA
- if (header == BEGIN_RSA_PUB)
- *keyFormat = RSAk;
- #endif
- }
- #endif
- }
- #ifdef WOLFSSL_ENCRYPTED_KEYS
- if (info) {
- ret = wc_EncryptedInfoParse(info, &headerEnd,
- (size_t)(bufferEnd - headerEnd));
- if (ret < 0)
- return ret;
- if (info->set)
- encrypted_key = 1;
- }
- #endif /* WOLFSSL_ENCRYPTED_KEYS */
- /* find footer */
- footerEnd = XSTRNSTR(headerEnd, footer, (unsigned int)((char*)buff +
- sz - headerEnd));
- if (!footerEnd) {
- if (info)
- info->consumed = longSz; /* No more certs if no footer */
- return BUFFER_E;
- }
- consumedEnd = footerEnd + XSTRLEN(footer);
- if (consumedEnd < bufferEnd) { /* handle no end of line on last line */
- /* eat end of line characters */
- consumedEnd = SkipEndOfLineChars(consumedEnd, bufferEnd);
- /* skip possible null term */
- if (consumedEnd < bufferEnd && consumedEnd[0] == '\0')
- consumedEnd++;
- }
- if (info)
- info->consumed = (long)(consumedEnd - (const char*)buff);
- /* set up der buffer */
- neededSz = (long)(footerEnd - headerEnd);
- if (neededSz > sz || neededSz <= 0)
- return BUFFER_E;
- ret = AllocDer(pDer, (word32)neededSz, type, heap);
- if (ret < 0) {
- return ret;
- }
- der = *pDer;
- if (Base64_Decode((byte*)headerEnd, (word32)neededSz,
- der->buffer, &der->length) < 0) {
- WOLFSSL_ERROR(BUFFER_E);
- return BUFFER_E;
- }
- if ((header == BEGIN_PRIV_KEY
- #ifdef OPENSSL_EXTRA
- || header == beginBuf
- #endif
- #ifdef HAVE_ECC
- || header == BEGIN_EC_PRIV
- #endif
- ) && !encrypted_key)
- {
- /* detect pkcs8 key and get alg type */
- /* keep PKCS8 header */
- idx = 0;
- ret = ToTraditionalInline_ex(der->buffer, &idx, der->length, &algId);
- if (ret > 0) {
- if (keyFormat)
- *keyFormat = (int)algId;
- }
- else {
- /* ignore failure here and assume key is not pkcs8 wrapped */
- }
- return 0;
- }
- #ifdef WOLFSSL_ENCRYPTED_KEYS
- if (encrypted_key || header == BEGIN_ENC_PRIV_KEY) {
- int passwordSz = NAME_SZ;
- #ifdef WOLFSSL_SMALL_STACK
- char* password = NULL;
- #else
- char password[NAME_SZ];
- #endif
- if (!info || !info->passwd_cb) {
- WOLFSSL_MSG("No password callback set");
- WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
- return NO_PASSWORD;
- }
- #ifdef WOLFSSL_SMALL_STACK
- password = (char*)XMALLOC(passwordSz, heap, DYNAMIC_TYPE_STRING);
- if (password == NULL) {
- return MEMORY_E;
- }
- #endif
- /* get password */
- ret = info->passwd_cb(password, passwordSz, PEM_PASS_READ,
- info->passwd_userdata);
- if (ret >= 0) {
- passwordSz = ret;
- #ifdef WOLFSSL_CHECK_MEM_ZERO
- wc_MemZero_Add("PEM password", password, passwordSz);
- #endif
- /* convert and adjust length */
- if (header == BEGIN_ENC_PRIV_KEY) {
- #ifndef NO_PWDBASED
- ret = wc_DecryptPKCS8Key(der->buffer, der->length,
- password, passwordSz);
- if (ret > 0) {
- /* update length by decrypted content */
- der->length = (word32)ret;
- idx = 0;
- /* detect pkcs8 key and get alg type */
- /* keep PKCS8 header */
- ret = ToTraditionalInline_ex(der->buffer, &idx, der->length,
- &algId);
- if (ret >= 0) {
- if (keyFormat)
- *keyFormat = (int)algId;
- ret = 0;
- }
- }
- #else
- WOLFSSL_ERROR_VERBOSE(NOT_COMPILED_IN);
- ret = NOT_COMPILED_IN;
- #endif
- }
- /* decrypt the key */
- else {
- if (passwordSz == 0) {
- /* The key is encrypted but does not have a password */
- WOLFSSL_MSG("No password for encrypted key");
- WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
- ret = NO_PASSWORD;
- }
- else {
- #if ((defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_DES3)) || \
- (!defined(NO_AES) && defined(HAVE_AES_CBC) && \
- defined(HAVE_AES_DECRYPT))) && \
- !defined(NO_WOLFSSL_SKIP_TRAILING_PAD)
- int padVal = 0;
- #endif
- ret = wc_BufferKeyDecrypt(info, der->buffer, der->length,
- (byte*)password, passwordSz, WC_MD5);
- #ifndef NO_WOLFSSL_SKIP_TRAILING_PAD
- #ifndef NO_DES3
- if (info->cipherType == WC_CIPHER_DES3) {
- /* Assuming there is padding:
- * (der->length > 0 && der->length > DES_BLOCK_SIZE &&
- * (der->length % DES_BLOCK_SIZE) != 0)
- * and assuming the last value signifies the number of
- * padded bytes IE if last value is 0x08 then there are
- * 8 bytes of padding:
- * padVal = der->buffer[der->length-1];
- * then strip this padding before proceeding:
- * der->length -= padVal;
- */
- if (der->length > DES_BLOCK_SIZE &&
- (der->length % DES_BLOCK_SIZE) != 0) {
- padVal = der->buffer[der->length-1];
- if (padVal < DES_BLOCK_SIZE) {
- der->length -= (word32)padVal;
- }
- }
- }
- #endif /* !NO_DES3 */
- #if !defined(NO_AES) && defined(HAVE_AES_CBC) && \
- defined(HAVE_AES_DECRYPT)
- if (info->cipherType == WC_CIPHER_AES_CBC) {
- if (der->length > AES_BLOCK_SIZE) {
- padVal = der->buffer[der->length-1];
- if (padVal <= AES_BLOCK_SIZE) {
- der->length -= (word32)padVal;
- }
- }
- }
- #endif
- #endif /* !NO_WOLFSSL_SKIP_TRAILING_PAD */
- }
- }
- #ifdef OPENSSL_EXTRA
- if (ret) {
- PEMerr(0, PEM_R_BAD_DECRYPT);
- }
- #endif
- ForceZero(password, (word32)passwordSz);
- }
- #ifdef OPENSSL_EXTRA
- else {
- PEMerr(0, PEM_R_BAD_PASSWORD_READ);
- }
- #endif
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(password, heap, DYNAMIC_TYPE_STRING);
- #elif defined(WOLFSSL_CHECK_MEM_ZERO)
- wc_MemZero_Check(password, NAME_SZ);
- #endif
- }
- #endif /* WOLFSSL_ENCRYPTED_KEYS */
- return ret;
- }
- int wc_PemToDer(const unsigned char* buff, long longSz, int type,
- DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
- {
- int ret = PemToDer(buff, longSz, type, pDer, heap, info, keyFormat);
- #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
- if (ret == 0 && type == PRIVATEKEY_TYPE) {
- DerBuffer* der = *pDer;
- /* if a PKCS8 key header exists remove it */
- ret = ToTraditional(der->buffer, der->length);
- if (ret > 0) {
- der->length = (word32)ret;
- }
- ret = 0; /* ignore error removing PKCS8 header */
- }
- #endif
- return ret;
- }
- #ifdef WOLFSSL_ENCRYPTED_KEYS
- /* our KeyPemToDer password callback, password in userData */
- static int KeyPemToDerPassCb(char* passwd, int sz, int rw, void* userdata)
- {
- (void)rw;
- if (userdata == NULL)
- return 0;
- XSTRNCPY(passwd, (char*)userdata, (size_t)sz);
- return (int)min((word32)sz, (word32)XSTRLEN((char*)userdata));
- }
- #endif
- /* Return bytes written to buff or < 0 for error */
- int wc_KeyPemToDer(const unsigned char* pem, int pemSz,
- unsigned char* buff, int buffSz, const char* pass)
- {
- int ret;
- DerBuffer* der = NULL;
- #ifdef WOLFSSL_SMALL_STACK
- EncryptedInfo* info = NULL;
- #else
- EncryptedInfo info[1];
- #endif
- WOLFSSL_ENTER("wc_KeyPemToDer");
- if (pem == NULL || (buff != NULL && buffSz <= 0)) {
- WOLFSSL_MSG("Bad pem der args");
- return BAD_FUNC_ARG;
- }
- #ifdef WOLFSSL_SMALL_STACK
- info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
- DYNAMIC_TYPE_ENCRYPTEDINFO);
- if (info == NULL)
- return MEMORY_E;
- #endif
- XMEMSET(info, 0, sizeof(EncryptedInfo));
- #ifdef WOLFSSL_ENCRYPTED_KEYS
- info->passwd_cb = KeyPemToDerPassCb;
- info->passwd_userdata = (void*)pass;
- #else
- (void)pass;
- #endif
- ret = PemToDer(pem, pemSz, PRIVATEKEY_TYPE, &der, NULL, info, NULL);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
- #endif
- if (ret < 0 || der == NULL) {
- WOLFSSL_MSG("Bad Pem To Der");
- }
- else if (buff == NULL) {
- WOLFSSL_MSG("Return needed der buff length");
- ret = (int)der->length;
- }
- else if (der->length <= (word32)buffSz) {
- XMEMCPY(buff, der->buffer, der->length);
- ret = (int)der->length;
- }
- else {
- WOLFSSL_MSG("Bad der length");
- ret = BAD_FUNC_ARG;
- }
- FreeDer(&der);
- return ret;
- }
- /* Return bytes written to buff or < 0 for error */
- int wc_CertPemToDer(const unsigned char* pem, int pemSz,
- unsigned char* buff, int buffSz, int type)
- {
- int ret;
- DerBuffer* der = NULL;
- WOLFSSL_ENTER("wc_CertPemToDer");
- if (pem == NULL || buff == NULL || buffSz <= 0) {
- WOLFSSL_MSG("Bad pem der args");
- return BAD_FUNC_ARG;
- }
- if (type != CERT_TYPE && type != CA_TYPE && type != CERTREQ_TYPE) {
- WOLFSSL_MSG("Bad cert type");
- return BAD_FUNC_ARG;
- }
- ret = PemToDer(pem, pemSz, type, &der, NULL, NULL, NULL);
- if (ret < 0 || der == NULL) {
- WOLFSSL_MSG("Bad Pem To Der");
- }
- else {
- if (der->length <= (word32)buffSz) {
- XMEMCPY(buff, der->buffer, der->length);
- ret = (int)der->length;
- }
- else {
- WOLFSSL_MSG("Bad der length");
- ret = BAD_FUNC_ARG;
- }
- }
- FreeDer(&der);
- return ret;
- }
- #endif /* WOLFSSL_PEM_TO_DER */
- #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
- #ifdef WOLFSSL_PEM_TO_DER
- #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
- /* Return bytes written to buff, needed buff size if buff is NULL, or less than
- zero for error */
- int wc_PubKeyPemToDer(const unsigned char* pem, int pemSz,
- unsigned char* buff, int buffSz)
- {
- int ret;
- DerBuffer* der = NULL;
- WOLFSSL_ENTER("wc_PubKeyPemToDer");
- if (pem == NULL || (buff != NULL && buffSz <= 0)) {
- WOLFSSL_MSG("Bad pem der args");
- return BAD_FUNC_ARG;
- }
- ret = PemToDer(pem, pemSz, PUBLICKEY_TYPE, &der, NULL, NULL, NULL);
- if (ret < 0 || der == NULL) {
- WOLFSSL_MSG("Bad Pem To Der");
- }
- else if (buff == NULL) {
- WOLFSSL_MSG("Return needed der buff length");
- ret = (int)der->length;
- }
- else if (der->length <= (word32)buffSz) {
- XMEMCPY(buff, der->buffer, der->length);
- ret = (int)der->length;
- }
- else {
- WOLFSSL_MSG("Bad der length");
- ret = BAD_FUNC_ARG;
- }
- FreeDer(&der);
- return ret;
- }
- #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
- #endif /* WOLFSSL_PEM_TO_DER */
- #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_PEM_TO_DER)
- #ifdef WOLFSSL_CERT_GEN
- int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der)
- {
- #ifndef WOLFSSL_SMALL_STACK
- byte staticBuffer[FILE_BUFFER_SIZE];
- #endif
- byte* fileBuf = NULL;
- int ret = 0;
- XFILE file = XBADFILE;
- int dynamic = 0;
- long sz = 0;
- WOLFSSL_ENTER("wc_PemCertToDer");
- if (fileName == NULL) {
- ret = BAD_FUNC_ARG;
- }
- else {
- file = XFOPEN(fileName, "rb");
- if (file == XBADFILE) {
- ret = IO_FAILED_E;
- }
- }
- if (ret == 0) {
- if (XFSEEK(file, 0, XSEEK_END) != 0) {
- ret = IO_FAILED_E;
- }
- }
- if (ret == 0) {
- sz = XFTELL(file);
- if (sz <= 0) {
- ret = IO_FAILED_E;
- }
- }
- if (ret == 0) {
- if (XFSEEK(file, 0, XSEEK_SET) != 0) {
- ret = IO_FAILED_E;
- }
- }
- if (ret == 0) {
- #ifndef WOLFSSL_SMALL_STACK
- if (sz <= (long)sizeof(staticBuffer))
- fileBuf = staticBuffer;
- else
- #endif
- {
- fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
- if (fileBuf == NULL)
- ret = MEMORY_E;
- else
- dynamic = 1;
- }
- }
- if (ret == 0) {
- if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
- ret = IO_FAILED_E;
- }
- else {
- ret = PemToDer(fileBuf, sz, CA_TYPE, der, 0, NULL,NULL);
- }
- }
- if (file != XBADFILE)
- XFCLOSE(file);
- if (dynamic)
- XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
- return ret;
- }
- /* load pem cert from file into der buffer, return der size or error */
- int wc_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz)
- {
- int ret;
- DerBuffer* converted = NULL;
- ret = wc_PemCertToDer_ex(fileName, &converted);
- if (ret == 0) {
- if (converted->length < (word32)derSz) {
- XMEMCPY(derBuf, converted->buffer, converted->length);
- ret = (int)converted->length;
- }
- else
- ret = BUFFER_E;
- FreeDer(&converted);
- }
- return ret;
- }
- #endif /* WOLFSSL_CERT_GEN */
- #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
- /* load pem public key from file into der buffer, return der size or error */
- int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der)
- {
- #ifndef WOLFSSL_SMALL_STACK
- byte staticBuffer[FILE_BUFFER_SIZE];
- #endif
- byte* fileBuf = NULL;
- int dynamic = 0;
- int ret = 0;
- long sz = 0;
- XFILE file = XBADFILE;
- WOLFSSL_ENTER("wc_PemPubKeyToDer");
- if (fileName == NULL) {
- ret = BAD_FUNC_ARG;
- }
- else {
- file = XFOPEN(fileName, "rb");
- if (file == XBADFILE) {
- ret = IO_FAILED_E;
- }
- }
- if (ret == 0) {
- if (XFSEEK(file, 0, XSEEK_END) != 0) {
- ret = IO_FAILED_E;
- }
- }
- if (ret == 0) {
- sz = XFTELL(file);
- if (sz <= 0) {
- ret = IO_FAILED_E;
- }
- }
- if (ret == 0) {
- if (XFSEEK(file, 0, XSEEK_SET) != 0) {
- ret = IO_FAILED_E;
- }
- }
- if (ret == 0) {
- #ifndef WOLFSSL_SMALL_STACK
- if (sz <= (long)sizeof(staticBuffer))
- fileBuf = staticBuffer;
- else
- #endif
- {
- fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
- if (fileBuf == NULL)
- ret = MEMORY_E;
- else
- dynamic = 1;
- }
- }
- if (ret == 0) {
- if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
- ret = BUFFER_E;
- }
- else {
- ret = PemToDer(fileBuf, sz, PUBLICKEY_TYPE, der,
- 0, NULL, NULL);
- }
- }
- if (file != XBADFILE)
- XFCLOSE(file);
- if (dynamic)
- XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
- return ret;
- }
- /* load pem public key from file into der buffer, return der size or error */
- int wc_PemPubKeyToDer(const char* fileName,
- unsigned char* derBuf, int derSz)
- {
- int ret;
- DerBuffer* converted = NULL;
- ret = wc_PemPubKeyToDer_ex(fileName, &converted);
- if (ret == 0) {
- if (converted->length < (word32)derSz) {
- XMEMCPY(derBuf, converted->buffer, converted->length);
- ret = (int)converted->length;
- }
- else
- ret = BUFFER_E;
- FreeDer(&converted);
- }
- return ret;
- }
- #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
- #endif /* !NO_FILESYSTEM && WOLFSSL_PEM_TO_DER */
- /* Get public key in DER format from a populated DecodedCert struct.
- *
- * Users must call wc_InitDecodedCert() and wc_ParseCert() before calling
- * this API. wc_InitDecodedCert() accepts a DER/ASN.1 encoded certificate.
- * To convert a PEM cert to DER first use wc_CertPemToDer() before calling
- * wc_InitDecodedCert().
- *
- * cert - populated DecodedCert struct holding X.509 certificate
- * derKey - output buffer to place DER/ASN.1 encoded public key
- * derKeySz [IN/OUT] - size of derKey buffer on input, size of public key
- * on return. If derKey is passed in as NULL, derKeySz
- * will be set to required buffer size for public key
- * and LENGTH_ONLY_E will be returned from function.
- * Returns 0 on success, or negative error code on failure. LENGTH_ONLY_E
- * if derKey is NULL and returning length only.
- */
- int wc_GetPubKeyDerFromCert(struct DecodedCert* cert,
- byte* derKey, word32* derKeySz)
- {
- int ret = 0;
- /* derKey may be NULL to return length only */
- if (cert == NULL || derKeySz == NULL ||
- (derKey != NULL && *derKeySz == 0)) {
- return BAD_FUNC_ARG;
- }
- if (cert->publicKey == NULL) {
- WOLFSSL_MSG("DecodedCert does not contain public key\n");
- return BAD_FUNC_ARG;
- }
- /* if derKey is NULL, return required output buffer size in derKeySz */
- if (derKey == NULL) {
- *derKeySz = cert->pubKeySize;
- ret = LENGTH_ONLY_E;
- }
- if (ret == 0) {
- if (cert->pubKeySize > *derKeySz) {
- WOLFSSL_MSG("Output buffer not large enough for public key DER");
- ret = BAD_FUNC_ARG;
- }
- else {
- XMEMCPY(derKey, cert->publicKey, cert->pubKeySize);
- *derKeySz = cert->pubKeySize;
- }
- }
- return ret;
- }
- #ifdef WOLFSSL_FPKI
- /* Search through list for first matching alt name of the same type
- * If 'current' is null then the search starts at the head of the list
- * otherwise the search starts from the node after 'current' alt name.
- * Returns 0 on success
- */
- static DNS_entry* FindAltName(struct DecodedCert* cert, int nameType,
- DNS_entry* current)
- {
- DNS_entry* entry;
- if (current == NULL) {
- entry = cert->altNames;
- }
- else {
- entry = current->next;
- }
- /* cycle through alt names to check for needed types */
- while (entry != NULL) {
- if (entry->type == nameType) {
- break;
- }
- entry = entry->next;
- }
- return entry;
- }
- /* returns 0 on success */
- int wc_GetUUIDFromCert(struct DecodedCert* cert, byte* uuid, word32* uuidSz)
- {
- int ret = ALT_NAME_E;
- DNS_entry* id = NULL;
- do {
- id = FindAltName(cert, ASN_URI_TYPE, id);
- if (id != NULL) {
- /* check if URI string matches expected format for UUID */
- if (id->len != DEFAULT_UUID_SZ) {
- continue; /* size not right not a UUID URI */
- }
- if (XMEMCMP(id->name, "urn:uuid:", 9) != 0) {
- continue; /* beginning text not right for a UUID URI */
- }
- if (uuid == NULL) {
- *uuidSz = id->len;
- return LENGTH_ONLY_E;
- }
- if ((int)*uuidSz < id->len) {
- return BUFFER_E;
- }
- XMEMCPY(uuid, id->name, id->len);
- ret = 0; /* success */
- break;
- }
- } while (id != NULL);
- return ret;
- }
- /* reutrns 0 on success */
- int wc_GetFASCNFromCert(struct DecodedCert* cert, byte* fascn, word32* fascnSz)
- {
- int ret = ALT_NAME_E;
- DNS_entry* id = NULL;
- do {
- id = FindAltName(cert, ASN_OTHER_TYPE, id);
- if (id != NULL && id->oidSum == FASCN_OID) {
- if (fascn == NULL) {
- *fascnSz = id->len;
- return LENGTH_ONLY_E;
- }
- if ((int)*fascnSz < id->len) {
- return BUFFER_E;
- }
- XMEMCPY(fascn, id->name, id->len);
- ret = 0; /* success */
- }
- } while (id != NULL);
- return ret;
- }
- #endif /* WOLFSSL_FPKI */
- #if !defined(NO_RSA) && (defined(WOLFSSL_CERT_GEN) || \
- defined(WOLFSSL_KCAPI_RSA) || \
- ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA)))
- /* USER RSA ifdef portions used instead of refactor in consideration for
- possible fips build */
- /* Encode a public RSA key to output.
- *
- * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
- * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
- *
- * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
- * (RSAPublicKey).
- *
- * @param [out] output Buffer to put encoded data in.
- * @param [in] key RSA key object.
- * @param [in] outLen Size of the output buffer in bytes.
- * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
- * @return Size of encoded data in bytes on success.
- * @return BAD_FUNC_ARG when output or key is NULL, or outLen is less than
- * minimum length (5 bytes).
- * @return MEMORY_E when dynamic memory allocation failed.
- */
- static int SetRsaPublicKey(byte* output, RsaKey* key, int outLen,
- int with_header)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int nSz, eSz;
- word32 seqSz, algoSz = 0, headSz = 0, bitStringSz = 0, idx;
- byte seq[MAX_SEQ_SZ];
- byte headSeq[MAX_SEQ_SZ];
- byte bitString[1 + MAX_LENGTH_SZ + 1];
- byte algo[MAX_ALGO_SZ]; /* 20 bytes */
- if (key == NULL) {
- return BAD_FUNC_ARG;
- }
- #ifdef HAVE_USER_RSA
- nSz = SetASNIntRSA(key->n, NULL);
- #else
- nSz = SetASNIntMP(&key->n, MAX_RSA_INT_SZ, NULL);
- #endif
- if (nSz < 0)
- return nSz;
- #ifdef HAVE_USER_RSA
- eSz = SetASNIntRSA(key->e, NULL);
- #else
- eSz = SetASNIntMP(&key->e, MAX_RSA_INT_SZ, NULL);
- #endif
- if (eSz < 0)
- return eSz;
- seqSz = SetSequence((word32)(nSz + eSz), seq);
- /* headers */
- if (with_header) {
- algoSz = SetAlgoID(RSAk, algo, oidKeyType, 0);
- bitStringSz = SetBitString(seqSz + (word32)(nSz + eSz), 0, bitString);
- headSz = SetSequence((word32)(nSz + eSz) + seqSz + bitStringSz + algoSz,
- headSeq);
- }
- /* if getting length only */
- if (output == NULL) {
- return (int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz;
- }
- /* check output size */
- if (((int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz) > outLen) {
- return BUFFER_E;
- }
- /* write output */
- idx = 0;
- if (with_header) {
- /* header size */
- XMEMCPY(output + idx, headSeq, headSz);
- idx += headSz;
- /* algo */
- XMEMCPY(output + idx, algo, algoSz);
- idx += algoSz;
- /* bit string */
- XMEMCPY(output + idx, bitString, bitStringSz);
- idx += bitStringSz;
- }
- /* seq */
- XMEMCPY(output + idx, seq, seqSz);
- idx += seqSz;
- /* n */
- #ifdef HAVE_USER_RSA
- nSz = SetASNIntRSA(key->n, output + idx);
- #else
- nSz = SetASNIntMP(&key->n, nSz, output + idx);
- #endif
- idx += (word32)nSz;
- /* e */
- #ifdef HAVE_USER_RSA
- eSz = SetASNIntRSA(key->e, output + idx);
- #else
- eSz = SetASNIntMP(&key->e, eSz, output + idx);
- #endif
- idx += (word32)eSz;
- return (int)idx;
- #else
- DECL_ASNSETDATA(dataASN, rsaPublicKeyASN_Length);
- int sz = 0;
- int ret = 0;
- int o = 0;
- /* Check parameter validity. */
- if ((key == NULL) || ((output != NULL) && (outLen < MAX_SEQ_SZ))) {
- ret = BAD_FUNC_ARG;
- }
- CALLOC_ASNSETDATA(dataASN, rsaPublicKeyASN_Length, ret, key->heap);
- if (ret == 0) {
- if (!with_header) {
- /* Start encoding with items after header. */
- o = RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ;
- }
- /* Set OID for RSA key. */
- SetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], RSAk, oidKeyType);
- #ifdef WC_RSA_PSS
- dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].noOut = 1;
- #endif
- /* Set public key mp_ints. */
- #ifdef HAVE_USER_RSA
- SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], key->n);
- SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], key->e);
- #else
- SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], &key->n);
- SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], &key->e);
- #endif
- /* Calculate size of RSA public key. */
- ret = SizeASN_Items(rsaPublicKeyASN + o, dataASN + o,
- (int)rsaPublicKeyASN_Length - o, &sz);
- }
- /* Check output buffer is big enough for encoding. */
- if ((ret == 0) && (output != NULL) && (sz > outLen)) {
- ret = BUFFER_E;
- }
- if ((ret == 0) && (output != NULL)) {
- /* Encode RSA public key. */
- SetASN_Items(rsaPublicKeyASN + o, dataASN + o,
- (int)rsaPublicKeyASN_Length - o, output);
- }
- if (ret == 0) {
- /* Return size of encoding. */
- ret = sz;
- }
- FREE_ASNSETDATA(dataASN, key->heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- /* Calculate size of encoded public RSA key in bytes.
- *
- * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
- * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
- *
- * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
- * (RSAPublicKey).
- *
- * @param [in] key RSA key object.
- * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
- * @return Size of encoded data in bytes on success.
- * @return BAD_FUNC_ARG when key is NULL.
- * @return MEMORY_E when dynamic memory allocation failed.
- */
- int wc_RsaPublicKeyDerSize(RsaKey* key, int with_header)
- {
- return SetRsaPublicKey(NULL, key, 0, with_header);
- }
- /* Encode public RSA key in DER format.
- *
- * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
- * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
- *
- * @param [in] key RSA key object.
- * @param [out] output Buffer to put encoded data in.
- * @param [in] inLen Size of buffer in bytes.
- * @return Size of encoded data in bytes on success.
- * @return BAD_FUNC_ARG when key or output is NULL.
- * @return MEMORY_E when dynamic memory allocation failed.
- */
- int wc_RsaKeyToPublicDer(RsaKey* key, byte* output, word32 inLen)
- {
- return SetRsaPublicKey(output, key, (int)inLen, 1);
- }
- /* Returns public DER version of the RSA key. If with_header is 0 then only a
- * seq + n + e is returned in ASN.1 DER format */
- int wc_RsaKeyToPublicDer_ex(RsaKey* key, byte* output, word32 inLen,
- int with_header)
- {
- return SetRsaPublicKey(output, key, (int)inLen, with_header);
- }
- #endif /* !NO_RSA && (WOLFSSL_CERT_GEN || WOLFSSL_KCAPI_RSA ||
- ((OPENSSL_EXTRA || WOLFSSL_KEY_GEN) && !HAVE_USER_RSA))) */
- #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
- defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)) && \
- !defined(NO_RSA) && !defined(HAVE_USER_RSA)
- /* Encode private RSA key in DER format.
- *
- * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
- *
- * @param [in] key RSA key object.
- * @param [out] output Buffer to put encoded data in.
- * @param [in] inLen Size of buffer in bytes.
- * @return Size of encoded data in bytes on success.
- * @return BAD_FUNC_ARG when key is NULL or not a private key.
- * @return MEMORY_E when dynamic memory allocation failed.
- */
- int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret = 0, i;
- word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen = 0;
- word32 sizes[RSA_INTS];
- byte seq[MAX_SEQ_SZ];
- byte ver[MAX_VERSION_SZ];
- byte* tmps[RSA_INTS];
- if (key == NULL)
- return BAD_FUNC_ARG;
- if (key->type != RSA_PRIVATE)
- return BAD_FUNC_ARG;
- for (i = 0; i < RSA_INTS; i++)
- tmps[i] = NULL;
- /* write all big ints from key to DER tmps */
- for (i = 0; i < RSA_INTS; i++) {
- mp_int* keyInt = GetRsaInt(key, i);
- int mpSz;
- word32 rawLen;
- ret = mp_unsigned_bin_size(keyInt);
- if (ret < 0)
- return ret;
- rawLen = (word32)ret + 1;
- ret = 0;
- if (output != NULL) {
- tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
- DYNAMIC_TYPE_RSA);
- if (tmps[i] == NULL) {
- ret = MEMORY_E;
- break;
- }
- }
- mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, tmps[i]);
- if (mpSz < 0) {
- ret = mpSz;
- break;
- }
- sizes[i] = (word32)mpSz;
- intTotalLen += (word32)mpSz;
- }
- if (ret == 0) {
- /* make headers */
- ret = SetMyVersion(0, ver, FALSE);
- }
- if (ret >= 0) {
- verSz = (word32)ret;
- ret = 0;
- seqSz = SetSequence(verSz + intTotalLen, seq);
- outLen = seqSz + verSz + intTotalLen;
- if (output != NULL && outLen > inLen)
- ret = BUFFER_E;
- }
- if (ret == 0 && output != NULL) {
- word32 j;
- /* write to output */
- XMEMCPY(output, seq, seqSz);
- j = seqSz;
- XMEMCPY(output + j, ver, verSz);
- j += verSz;
- for (i = 0; i < RSA_INTS; i++) {
- XMEMCPY(output + j, tmps[i], sizes[i]);
- j += sizes[i];
- }
- }
- for (i = 0; i < RSA_INTS; i++) {
- if (tmps[i])
- XFREE(tmps[i], key->heap, DYNAMIC_TYPE_RSA);
- }
- if (ret == 0)
- ret = (int)outLen;
- return ret;
- #else
- DECL_ASNSETDATA(dataASN, rsaKeyASN_Length);
- int i;
- int sz = 0;
- int ret = 0;
- if ((key == NULL) || (key->type != RSA_PRIVATE)) {
- ret = BAD_FUNC_ARG;
- }
- CALLOC_ASNSETDATA(dataASN, rsaKeyASN_Length, ret, key->heap);
- if (ret == 0) {
- /* Set the version. */
- SetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], 0);
- /* Set all the mp_ints in private key. */
- for (i = 0; i < RSA_INTS; i++) {
- SetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i], GetRsaInt(key, i));
- }
- /* Calculate size of RSA private key encoding. */
- ret = SizeASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, &sz);
- }
- /* Check output buffer has enough space for encoding. */
- if ((ret == 0) && (output != NULL) && (sz > (int)inLen)) {
- ret = BAD_FUNC_ARG;
- }
- if ((ret == 0) && (output != NULL)) {
- /* Encode RSA private key. */
- SetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, output);
- }
- if (ret == 0) {
- /* Return size of encoding. */
- ret = sz;
- }
- FREE_ASNSETDATA(dataASN, key->heap);
- return ret;
- #endif
- }
- #endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA && !HAVE_USER_RSA */
- #ifdef WOLFSSL_CERT_GEN
- /* Initialize and Set Certificate defaults:
- version = 3 (0x2)
- serial = 0
- sigType = SHA_WITH_RSA
- issuer = blank
- daysValid = 500
- selfSigned = 1 (true) use subject as issuer
- subject = blank
- */
- int wc_InitCert_ex(Cert* cert, void* heap, int devId)
- {
- #ifdef WOLFSSL_MULTI_ATTRIB
- int i = 0;
- #endif
- if (cert == NULL) {
- return BAD_FUNC_ARG;
- }
- XMEMSET(cert, 0, sizeof(Cert));
- cert->version = 2; /* version 3 is hex 2 */
- #ifndef NO_SHA
- cert->sigType = CTC_SHAwRSA;
- #elif !defined(NO_SHA256)
- cert->sigType = CTC_SHA256wRSA;
- #else
- cert->sigType = 0;
- #endif
- cert->daysValid = 500;
- cert->selfSigned = 1;
- cert->keyType = RSA_KEY;
- cert->issuer.countryEnc = CTC_PRINTABLE;
- cert->issuer.stateEnc = CTC_UTF8;
- cert->issuer.streetEnc = CTC_UTF8;
- cert->issuer.localityEnc = CTC_UTF8;
- cert->issuer.surEnc = CTC_UTF8;
- #ifdef WOLFSSL_CERT_NAME_ALL
- cert->issuer.givenNameEnc = CTC_UTF8;
- cert->issuer.initialsEnc = CTC_UTF8;
- cert->issuer.dnQualifierEnc = CTC_UTF8;
- cert->issuer.dnNameEnc = CTC_UTF8;
- #endif
- cert->issuer.orgEnc = CTC_UTF8;
- cert->issuer.unitEnc = CTC_UTF8;
- cert->issuer.commonNameEnc = CTC_UTF8;
- cert->issuer.serialDevEnc = CTC_PRINTABLE;
- cert->issuer.userIdEnc = CTC_UTF8;
- cert->issuer.postalCodeEnc = CTC_UTF8;
- #ifdef WOLFSSL_CERT_EXT
- cert->issuer.busCatEnc = CTC_UTF8;
- cert->issuer.joiCEnc = CTC_UTF8;
- cert->issuer.joiStEnc = CTC_UTF8;
- #endif
- cert->subject.countryEnc = CTC_PRINTABLE;
- cert->subject.stateEnc = CTC_UTF8;
- cert->subject.streetEnc = CTC_UTF8;
- cert->subject.localityEnc = CTC_UTF8;
- cert->subject.surEnc = CTC_UTF8;
- #ifdef WOLFSSL_CERT_NAME_ALL
- cert->subject.givenNameEnc = CTC_UTF8;
- cert->subject.initialsEnc = CTC_UTF8;
- cert->subject.dnQualifierEnc = CTC_UTF8;
- cert->subject.dnNameEnc = CTC_UTF8;
- #endif
- cert->subject.orgEnc = CTC_UTF8;
- cert->subject.unitEnc = CTC_UTF8;
- cert->subject.commonNameEnc = CTC_UTF8;
- cert->subject.serialDevEnc = CTC_PRINTABLE;
- cert->subject.userIdEnc = CTC_UTF8;
- cert->subject.postalCodeEnc = CTC_UTF8;
- #ifdef WOLFSSL_CERT_EXT
- cert->subject.busCatEnc = CTC_UTF8;
- cert->subject.joiCEnc = CTC_UTF8;
- cert->subject.joiStEnc = CTC_UTF8;
- #endif
- #ifdef WOLFSSL_MULTI_ATTRIB
- for (i = 0; i < CTC_MAX_ATTRIB; i++) {
- cert->issuer.name[i].type = CTC_UTF8;
- cert->subject.name[i].type = CTC_UTF8;
- }
- #endif /* WOLFSSL_MULTI_ATTRIB */
- cert->heap = heap;
- (void)devId; /* future */
- return 0;
- }
- WOLFSSL_ABI
- int wc_InitCert(Cert* cert)
- {
- return wc_InitCert_ex(cert, NULL, INVALID_DEVID);
- }
- WOLFSSL_ABI
- Cert* wc_CertNew(void* heap)
- {
- Cert* certNew;
- certNew = (Cert*)XMALLOC(sizeof(Cert), heap, DYNAMIC_TYPE_CERT);
- if (certNew) {
- if (wc_InitCert_ex(certNew, heap, INVALID_DEVID) != 0) {
- XFREE(certNew, heap, DYNAMIC_TYPE_CERT);
- certNew = NULL;
- }
- }
- return certNew;
- }
- WOLFSSL_ABI
- void wc_CertFree(Cert* cert)
- {
- if (cert) {
- void* heap = cert->heap;
- ForceZero(cert, sizeof(Cert));
- XFREE(cert, heap, DYNAMIC_TYPE_CERT);
- (void)heap;
- }
- }
- /* DER encoded x509 Certificate */
- typedef struct DerCert {
- byte size[MAX_LENGTH_SZ]; /* length encoded */
- byte version[MAX_VERSION_SZ]; /* version encoded */
- byte serial[(int)CTC_SERIAL_SIZE + (int)MAX_LENGTH_SZ]; /* serial number encoded */
- byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
- byte issuer[WC_ASN_NAME_MAX]; /* issuer encoded */
- byte subject[WC_ASN_NAME_MAX]; /* subject encoded */
- byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
- byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa public key encoded */
- byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
- byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
- #ifdef WOLFSSL_CERT_EXT
- byte skid[MAX_KID_SZ]; /* Subject Key Identifier extension */
- byte akid[MAX_KID_SZ
- #ifdef WOLFSSL_AKID_NAME
- + sizeof(CertName) + CTC_SERIAL_SIZE
- #endif
- ]; /* Authority Key Identifier extension */
- byte keyUsage[MAX_KEYUSAGE_SZ]; /* Key Usage extension */
- byte extKeyUsage[MAX_EXTKEYUSAGE_SZ]; /* Extended Key Usage extension */
- #ifndef IGNORE_NETSCAPE_CERT_TYPE
- byte nsCertType[MAX_NSCERTTYPE_SZ]; /* Extended Key Usage extension */
- #endif
- byte certPolicies[MAX_CERTPOL_NB*MAX_CERTPOL_SZ]; /* Certificate Policies */
- byte crlInfo[CTC_MAX_CRLINFO_SZ]; /* CRL Distribution Points */
- #endif
- #ifdef WOLFSSL_CERT_REQ
- byte attrib[MAX_ATTRIB_SZ]; /* Cert req attributes encoded */
- #ifdef WOLFSSL_CUSTOM_OID
- byte extCustom[MAX_ATTRIB_SZ]; /* Encoded user oid and value */
- #endif
- #endif
- #ifdef WOLFSSL_ALT_NAMES
- byte altNames[CTC_MAX_ALT_SIZE]; /* Alternative Names encoded */
- #endif
- int sizeSz; /* encoded size length */
- int versionSz; /* encoded version length */
- int serialSz; /* encoded serial length */
- int sigAlgoSz; /* encoded sig algo length */
- int issuerSz; /* encoded issuer length */
- int subjectSz; /* encoded subject length */
- int validitySz; /* encoded validity length */
- int publicKeySz; /* encoded public key length */
- int caSz; /* encoded CA extension length */
- #ifdef WOLFSSL_CERT_EXT
- int skidSz; /* encoded SKID extension length */
- int akidSz; /* encoded SKID extension length */
- int keyUsageSz; /* encoded KeyUsage extension length */
- int extKeyUsageSz; /* encoded ExtendedKeyUsage extension length */
- #ifndef IGNORE_NETSCAPE_CERT_TYPE
- int nsCertTypeSz; /* encoded Netscape Certifcate Type
- * extension length */
- #endif
- int certPoliciesSz; /* encoded CertPolicies extension length*/
- int crlInfoSz; /* encoded CRL Dist Points length */
- #endif
- #ifdef WOLFSSL_ALT_NAMES
- int altNamesSz; /* encoded AltNames extension length */
- #endif
- int extensionsSz; /* encoded extensions total length */
- int total; /* total encoded lengths */
- #ifdef WOLFSSL_CERT_REQ
- int attribSz;
- #ifdef WOLFSSL_CUSTOM_OID
- int extCustomSz;
- #endif
- #endif
- } DerCert;
- #ifdef WOLFSSL_CERT_REQ
- #ifndef WOLFSSL_ASN_TEMPLATE
- /* Write a set header to output */
- static word32 SetPrintableString(word32 len, byte* output)
- {
- output[0] = ASN_PRINTABLE_STRING;
- return SetLength(len, output + 1) + 1;
- }
- static word32 SetUTF8String(word32 len, byte* output)
- {
- output[0] = ASN_UTF8STRING;
- return SetLength(len, output + 1) + 1;
- }
- #endif
- #endif /* WOLFSSL_CERT_REQ */
- #ifndef WOLFSSL_CERT_GEN_CACHE
- /* wc_SetCert_Free is only public when WOLFSSL_CERT_GEN_CACHE is not defined */
- static
- #endif
- WOLFSSL_ABI
- void wc_SetCert_Free(Cert* cert)
- {
- if (cert != NULL) {
- cert->der = NULL;
- if (cert->decodedCert) {
- FreeDecodedCert((DecodedCert*)cert->decodedCert);
- XFREE(cert->decodedCert, cert->heap, DYNAMIC_TYPE_DCERT);
- cert->decodedCert = NULL;
- }
- }
- }
- static int wc_SetCert_LoadDer(Cert* cert, const byte* der, word32 derSz,
- int devId)
- {
- int ret;
- if (cert == NULL) {
- ret = BAD_FUNC_ARG;
- }
- else {
- /* Allocate DecodedCert struct and Zero */
- cert->decodedCert = (void*)XMALLOC(sizeof(DecodedCert), cert->heap,
- DYNAMIC_TYPE_DCERT);
- if (cert->decodedCert == NULL) {
- ret = MEMORY_E;
- }
- else {
- XMEMSET(cert->decodedCert, 0, sizeof(DecodedCert));
- InitDecodedCert_ex((DecodedCert*)cert->decodedCert, der, derSz,
- cert->heap, devId);
- ret = ParseCertRelative((DecodedCert*)cert->decodedCert,
- CERT_TYPE, 0, NULL);
- if (ret >= 0) {
- cert->der = (byte*)der;
- }
- else {
- wc_SetCert_Free(cert);
- }
- }
- }
- return ret;
- }
- #endif /* WOLFSSL_CERT_GEN */
- #ifdef WOLFSSL_CERT_GEN
- #ifndef NO_ASN_TIME
- static WC_INLINE byte itob(int number)
- {
- return (byte)number + 0x30;
- }
- /* write time to output, format */
- static void SetTime(struct tm* date, byte* output)
- {
- int i = 0;
- output[i++] = itob((date->tm_year % 10000) / 1000);
- output[i++] = itob((date->tm_year % 1000) / 100);
- output[i++] = itob((date->tm_year % 100) / 10);
- output[i++] = itob( date->tm_year % 10);
- output[i++] = itob(date->tm_mon / 10);
- output[i++] = itob(date->tm_mon % 10);
- output[i++] = itob(date->tm_mday / 10);
- output[i++] = itob(date->tm_mday % 10);
- output[i++] = itob(date->tm_hour / 10);
- output[i++] = itob(date->tm_hour % 10);
- output[i++] = itob(date->tm_min / 10);
- output[i++] = itob(date->tm_min % 10);
- output[i++] = itob(date->tm_sec / 10);
- output[i++] = itob(date->tm_sec % 10);
- output[i] = 'Z'; /* Zulu profile */
- }
- #endif
- #ifndef WOLFSSL_ASN_TEMPLATE
- /* Copy Dates from cert, return bytes written */
- static int CopyValidity(byte* output, Cert* cert)
- {
- word32 seqSz;
- WOLFSSL_ENTER("CopyValidity");
- /* headers and output */
- seqSz = SetSequence((word32)(cert->beforeDateSz + cert->afterDateSz),
- output);
- if (output) {
- XMEMCPY(output + seqSz, cert->beforeDate, (size_t)cert->beforeDateSz);
- XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
- (size_t)cert->afterDateSz);
- }
- return (int)seqSz + cert->beforeDateSz + cert->afterDateSz;
- }
- #endif /* !WOLFSSL_ASN_TEMPLATE */
- /* Simple name OID size. */
- #define NAME_OID_SZ 3
- /* Domain name OIDs. */
- static const byte nameOid[][NAME_OID_SZ] = {
- { 0x55, 0x04, ASN_COUNTRY_NAME },
- { 0x55, 0x04, ASN_STATE_NAME },
- { 0x55, 0x04, ASN_STREET_ADDR },
- { 0x55, 0x04, ASN_LOCALITY_NAME },
- #ifdef WOLFSSL_CERT_NAME_ALL
- { 0x55, 0x04, ASN_NAME },
- { 0x55, 0x04, ASN_GIVEN_NAME },
- { 0x55, 0x04, ASN_INITIALS },
- { 0x55, 0x04, ASN_DNQUALIFIER },
- #endif
- { 0x55, 0x04, ASN_SUR_NAME },
- { 0x55, 0x04, ASN_ORG_NAME },
- { 0x00, 0x00, ASN_DOMAIN_COMPONENT}, /* not actual OID - see dcOid */
- /* list all DC values before OUs */
- { 0x55, 0x04, ASN_ORGUNIT_NAME },
- { 0x55, 0x04, ASN_COMMON_NAME },
- { 0x55, 0x04, ASN_SERIAL_NUMBER },
- #ifdef WOLFSSL_CERT_EXT
- { 0x55, 0x04, ASN_BUS_CAT },
- #endif
- { 0x55, 0x04, ASN_POSTAL_CODE },
- { 0x00, 0x00, ASN_EMAIL_NAME}, /* not actual OID - see attrEmailOid */
- { 0x00, 0x00, ASN_USER_ID}, /* not actual OID - see uidOid */
- #ifdef WOLFSSL_CUSTOM_OID
- { 0x00, 0x00, ASN_CUSTOM_NAME} /* OID comes from CertOidField */
- #endif
- };
- #define NAME_ENTRIES (int)(sizeof(nameOid)/NAME_OID_SZ)
- /* Get ASN Name from index */
- byte GetCertNameId(int idx)
- {
- if (idx < NAME_ENTRIES)
- return nameOid[idx][2];
- return 0;
- }
- /* Get Which Name from index */
- const char* GetOneCertName(CertName* name, int idx)
- {
- byte type = GetCertNameId(idx);
- switch (type) {
- case ASN_COUNTRY_NAME:
- return name->country;
- case ASN_STATE_NAME:
- return name->state;
- case ASN_STREET_ADDR:
- return name->street;
- case ASN_LOCALITY_NAME:
- return name->locality;
- #ifdef WOLFSSL_CERT_NAME_ALL
- case ASN_NAME:
- return name->dnName;
- case ASN_GIVEN_NAME:
- return name->givenName;
- case ASN_INITIALS:
- return name->initials;
- case ASN_DNQUALIFIER:
- return name->dnQualifier;
- #endif /* WOLFSSL_CERT_NAME_ALL */
- case ASN_SUR_NAME:
- return name->sur;
- case ASN_ORG_NAME:
- return name->org;
- case ASN_ORGUNIT_NAME:
- return name->unit;
- case ASN_COMMON_NAME:
- return name->commonName;
- case ASN_SERIAL_NUMBER:
- return name->serialDev;
- case ASN_USER_ID:
- return name->userId;
- case ASN_POSTAL_CODE:
- return name->postalCode;
- case ASN_EMAIL_NAME:
- return name->email;
- #ifdef WOLFSSL_CERT_EXT
- case ASN_BUS_CAT:
- return name->busCat;
- #endif
- #ifdef WOLFSSL_CUSTOM_OID
- case ASN_CUSTOM_NAME:
- return (const char*)name->custom.val;
- #endif
- default:
- return NULL;
- }
- }
- /* Get Which Name Encoding from index */
- static char GetNameType(CertName* name, int idx)
- {
- byte type = GetCertNameId(idx);
- switch (type) {
- case ASN_COUNTRY_NAME:
- return name->countryEnc;
- case ASN_STATE_NAME:
- return name->stateEnc;
- case ASN_STREET_ADDR:
- return name->streetEnc;
- case ASN_LOCALITY_NAME:
- return name->localityEnc;
- #ifdef WOLFSSL_CERT_NAME_ALL
- case ASN_NAME:
- return name->dnNameEnc;
- case ASN_GIVEN_NAME:
- return name->givenNameEnc;
- case ASN_INITIALS:
- return name->initialsEnc;
- case ASN_DNQUALIFIER:
- return name->dnQualifierEnc;
- #endif /* WOLFSSL_CERT_NAME_ALL */
- case ASN_SUR_NAME:
- return name->surEnc;
- case ASN_ORG_NAME:
- return name->orgEnc;
- case ASN_ORGUNIT_NAME:
- return name->unitEnc;
- case ASN_COMMON_NAME:
- return name->commonNameEnc;
- case ASN_SERIAL_NUMBER:
- return name->serialDevEnc;
- case ASN_USER_ID:
- return name->userIdEnc;
- case ASN_POSTAL_CODE:
- return name->postalCodeEnc;
- case ASN_EMAIL_NAME:
- return 0; /* special */
- #ifdef WOLFSSL_CERT_EXT
- case ASN_BUS_CAT:
- return name->busCatEnc;
- #endif
- #ifdef WOLFSSL_CUSTOM_OID
- case ASN_CUSTOM_NAME:
- return name->custom.enc;
- #endif
- default:
- return 0;
- }
- }
- #ifndef WOLFSSL_ASN_TEMPLATE
- /*
- Extensions ::= SEQUENCE OF Extension
- Extension ::= SEQUENCE {
- extnId OBJECT IDENTIFIER,
- critical BOOLEAN DEFAULT FALSE,
- extnValue OCTET STRING }
- */
- /* encode all extensions, return total bytes written */
- static int SetExtensions(byte* out, word32 outSz, int *IdxInOut,
- const byte* ext, int extSz)
- {
- if (out == NULL || IdxInOut == NULL || ext == NULL)
- return BAD_FUNC_ARG;
- if (outSz < (word32)(*IdxInOut+extSz))
- return BUFFER_E;
- XMEMCPY(&out[*IdxInOut], ext, (size_t)extSz); /* extensions */
- *IdxInOut += extSz;
- return *IdxInOut;
- }
- /* encode extensions header, return total bytes written */
- static int SetExtensionsHeader(byte* out, word32 outSz, word32 extSz)
- {
- byte sequence[MAX_SEQ_SZ];
- byte len[MAX_LENGTH_SZ];
- word32 seqSz, lenSz, idx = 0;
- if (out == NULL)
- return BAD_FUNC_ARG;
- if (outSz < 3)
- return BUFFER_E;
- seqSz = SetSequence(extSz, sequence);
- /* encode extensions length provided */
- lenSz = SetLength(extSz+seqSz, len);
- if (outSz < (word32)(lenSz+seqSz+1))
- return BUFFER_E;
- out[idx++] = ASN_EXTENSIONS; /* extensions id */
- XMEMCPY(&out[idx], len, lenSz); /* length */
- idx += lenSz;
- XMEMCPY(&out[idx], sequence, seqSz); /* sequence */
- idx += seqSz;
- return (int)idx;
- }
- /* encode CA basic constraints true with path length
- * return total bytes written */
- static int SetCaWithPathLen(byte* out, word32 outSz, byte pathLen)
- {
- /* ASN1->DER sequence for Basic Constraints True and path length */
- const byte caPathLenBasicConstASN1[] = {
- 0x30, 0x0F, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04,
- 0x08, 0x30, 0x06, 0x01, 0x01, 0xFF, 0x02, 0x01,
- 0x00
- };
- if (out == NULL)
- return BAD_FUNC_ARG;
- if (outSz < sizeof(caPathLenBasicConstASN1))
- return BUFFER_E;
- XMEMCPY(out, caPathLenBasicConstASN1, sizeof(caPathLenBasicConstASN1));
- out[sizeof(caPathLenBasicConstASN1)-1] = pathLen;
- return (int)sizeof(caPathLenBasicConstASN1);
- }
- /* encode CA basic constraints true
- * return total bytes written */
- static int SetCa(byte* out, word32 outSz)
- {
- /* ASN1->DER sequence for Basic Constraints True */
- const byte caBasicConstASN1[] = {
- 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
- 0x05, 0x30, 0x03, 0x01, 0x01, 0xff
- };
- if (out == NULL)
- return BAD_FUNC_ARG;
- if (outSz < sizeof(caBasicConstASN1))
- return BUFFER_E;
- XMEMCPY(out, caBasicConstASN1, sizeof(caBasicConstASN1));
- return (int)sizeof(caBasicConstASN1);
- }
- /* encode basic constraints without CA Boolean
- * return total bytes written */
- static int SetBC(byte* out, word32 outSz)
- {
- /* ASN1->DER sequence for Basic Constraint without CA Boolean */
- const byte BasicConstASN1[] = {
- 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
- 0x02, 0x30, 0x00
- };
- if (out == NULL)
- return BAD_FUNC_ARG;
- if (outSz < sizeof(BasicConstASN1))
- return BUFFER_E;
- XMEMCPY(out, BasicConstASN1, sizeof(BasicConstASN1));
- return (int)sizeof(BasicConstASN1);
- }
- #endif
- #ifdef WOLFSSL_CERT_EXT
- #ifndef WOLFSSL_ASN_TEMPLATE
- /* encode OID and associated value, return total bytes written */
- static int SetOidValue(byte* out, word32 outSz, const byte *oid, word32 oidSz,
- byte *in, word32 inSz)
- {
- word32 idx = 0;
- if (out == NULL || oid == NULL || in == NULL)
- return BAD_FUNC_ARG;
- if (outSz < 3)
- return BUFFER_E;
- /* sequence, + 1 => byte to put value size */
- idx = SetSequence(inSz + oidSz + 1, out);
- if ((idx + inSz + oidSz + 1) > outSz)
- return BUFFER_E;
- XMEMCPY(out+idx, oid, oidSz);
- idx += oidSz;
- out[idx++] = (byte)inSz;
- XMEMCPY(out+idx, in, inSz);
- return (int)(idx+inSz);
- }
- /* encode Subject Key Identifier, return total bytes written
- * RFC5280 : non-critical */
- static int SetSKID(byte* output, word32 outSz, const byte *input, word32 length)
- {
- byte skid_len[1 + MAX_LENGTH_SZ];
- byte skid_enc_len[MAX_LENGTH_SZ];
- word32 idx = 0, skid_lenSz, skid_enc_lenSz;
- const byte skid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04 };
- if (output == NULL || input == NULL)
- return BAD_FUNC_ARG;
- /* Octet String header */
- skid_lenSz = SetOctetString(length, skid_len);
- /* length of encoded value */
- skid_enc_lenSz = SetLength(length + skid_lenSz, skid_enc_len);
- if (outSz < 3)
- return BUFFER_E;
- idx = SetSequence(length + (word32)sizeof(skid_oid) + skid_lenSz +
- skid_enc_lenSz, output);
- if ((length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz) > outSz)
- return BUFFER_E;
- /* put oid */
- XMEMCPY(output+idx, skid_oid, sizeof(skid_oid));
- idx += sizeof(skid_oid);
- /* put encoded len */
- XMEMCPY(output+idx, skid_enc_len, skid_enc_lenSz);
- idx += skid_enc_lenSz;
- /* put octet header */
- XMEMCPY(output+idx, skid_len, skid_lenSz);
- idx += skid_lenSz;
- /* put value */
- XMEMCPY(output+idx, input, length);
- idx += length;
- return (int)idx;
- }
- /* encode Authority Key Identifier, return total bytes written
- * RFC5280 : non-critical */
- static int SetAKID(byte* output, word32 outSz, byte *input, word32 length,
- byte rawAkid)
- {
- int enc_valSz;
- byte enc_val_buf[MAX_KID_SZ];
- byte* enc_val;
- const byte akid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x23 };
- const byte akid_cs[] = { 0x80 };
- word32 inSeqSz, idx;
- (void)rawAkid;
- if (output == NULL || input == NULL)
- return BAD_FUNC_ARG;
- #ifdef WOLFSSL_AKID_NAME
- if (rawAkid) {
- enc_val = input;
- enc_valSz = length;
- }
- else
- #endif
- {
- enc_val = enc_val_buf;
- enc_valSz = (int)length + 3 + (int)sizeof(akid_cs);
- if (enc_valSz > (int)sizeof(enc_val_buf))
- return BAD_FUNC_ARG;
- /* sequence for ContentSpec & value */
- enc_valSz = SetOidValue(enc_val, (word32)enc_valSz, akid_cs,
- sizeof(akid_cs), input, length);
- if (enc_valSz <= 0)
- return enc_valSz;
- }
- /* The size of the extension sequence contents */
- inSeqSz = (word32)sizeof(akid_oid) +
- SetOctetString((word32)enc_valSz, NULL) + (word32)enc_valSz;
- if (SetSequence(inSeqSz, NULL) + inSeqSz > outSz)
- return BAD_FUNC_ARG;
- /* Write out the sequence header */
- idx = SetSequence(inSeqSz, output);
- /* Write out OID */
- XMEMCPY(output + idx, akid_oid, sizeof(akid_oid));
- idx += sizeof(akid_oid);
- /* Write out AKID */
- idx += SetOctetString((word32)enc_valSz, output + idx);
- XMEMCPY(output + idx, enc_val, (size_t)enc_valSz);
- return (int)idx + enc_valSz;
- }
- /* encode Key Usage, return total bytes written
- * RFC5280 : critical */
- static int SetKeyUsage(byte* output, word32 outSz, word16 input)
- {
- byte ku[5];
- word32 idx;
- const byte keyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0f,
- 0x01, 0x01, 0xff, 0x04};
- if (output == NULL)
- return BAD_FUNC_ARG;
- idx = SetBitString16Bit(input, ku);
- return SetOidValue(output, outSz, keyusage_oid, sizeof(keyusage_oid),
- ku, idx);
- }
- static int SetOjectIdValue(byte* output, word32 outSz, word32* idx,
- const byte* oid, word32 oidSz)
- {
- /* verify room */
- if (*idx + 2 + oidSz >= outSz)
- return ASN_PARSE_E;
- *idx += (word32)SetObjectId((int)oidSz, &output[*idx]);
- XMEMCPY(&output[*idx], oid, oidSz);
- *idx += oidSz;
- return 0;
- }
- #endif
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for extended key usage.
- * X.509: RFC 5280, 4.2.12 - Extended Key Usage
- * Dynamic creation of template for encoding.
- */
- static const ASNItem ekuASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- };
- enum {
- EKUASN_IDX_SEQ = 0,
- EKUASN_IDX_OID
- };
- /* OIDs corresponding to extended key usage. */
- struct {
- const byte* oid;
- word32 oidSz;
- } ekuOid[] = {
- { extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid) },
- { extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid) },
- { extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid) },
- { extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid) },
- { extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid) },
- { extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid) },
- };
- #define EKU_OID_LO 1
- #define EKU_OID_HI 6
- #endif /* WOLFSSL_ASN_TEMPLATE */
- /* encode Extended Key Usage (RFC 5280 4.2.1.12), return total bytes written */
- static int SetExtKeyUsage(Cert* cert, byte* output, word32 outSz, byte input)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0, oidListSz = 0, totalSz;
- int ret = 0;
- const byte extkeyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x25 };
- if (output == NULL)
- return BAD_FUNC_ARG;
- /* Skip to OID List */
- totalSz = 2 + sizeof(extkeyusage_oid) + 4;
- idx = totalSz;
- /* Build OID List */
- /* If any set, then just use it */
- if (input & EXTKEYUSE_ANY) {
- ret |= SetOjectIdValue(output, outSz, &idx,
- extExtKeyUsageAnyOid, sizeof(extExtKeyUsageAnyOid));
- }
- else {
- if (input & EXTKEYUSE_SERVER_AUTH)
- ret |= SetOjectIdValue(output, outSz, &idx,
- extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid));
- if (input & EXTKEYUSE_CLIENT_AUTH)
- ret |= SetOjectIdValue(output, outSz, &idx,
- extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid));
- if (input & EXTKEYUSE_CODESIGN)
- ret |= SetOjectIdValue(output, outSz, &idx,
- extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid));
- if (input & EXTKEYUSE_EMAILPROT)
- ret |= SetOjectIdValue(output, outSz, &idx,
- extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid));
- if (input & EXTKEYUSE_TIMESTAMP)
- ret |= SetOjectIdValue(output, outSz, &idx,
- extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid));
- if (input & EXTKEYUSE_OCSP_SIGN)
- ret |= SetOjectIdValue(output, outSz, &idx,
- extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid));
- #ifdef WOLFSSL_EKU_OID
- /* iterate through OID values */
- if (input & EXTKEYUSE_USER) {
- int i, sz;
- for (i = 0; i < CTC_MAX_EKU_NB; i++) {
- sz = cert->extKeyUsageOIDSz[i];
- if (sz > 0) {
- ret |= SetOjectIdValue(output, outSz, &idx,
- cert->extKeyUsageOID[i], sz);
- }
- }
- }
- #endif /* WOLFSSL_EKU_OID */
- }
- if (ret != 0)
- return ASN_PARSE_E;
- /* Calculate Sizes */
- oidListSz = idx - totalSz;
- totalSz = idx - 2; /* exclude first seq/len (2) */
- /* 1. Seq + Total Len (2) */
- idx = SetSequence(totalSz, output);
- /* 2. Object ID (2) */
- XMEMCPY(&output[idx], extkeyusage_oid, sizeof(extkeyusage_oid));
- idx += sizeof(extkeyusage_oid);
- /* 3. Octet String (2) */
- idx += SetOctetString(totalSz - idx, &output[idx]);
- /* 4. Seq + OidListLen (2) */
- idx += SetSequence(oidListSz, &output[idx]);
- /* 5. Oid List (already set in-place above) */
- idx += oidListSz;
- (void)cert;
- return (int)idx;
- #else
- /* TODO: consider calculating size of OBJECT_IDs, setting length into
- * SEQUENCE, encode SEQUENCE, encode OBJECT_IDs into buffer. */
- ASNSetData* dataASN;
- ASNItem* extKuASN = NULL;
- int asnIdx = 1;
- size_t cnt = 1 + EKU_OID_HI;
- int i;
- int ret = 0;
- int sz = 0;
- #ifdef WOLFSSL_EKU_OID
- cnt += CTC_MAX_EKU_NB;
- #endif
- /* Allocate memory for dynamic data items. */
- dataASN = (ASNSetData*)XMALLOC(cnt * sizeof(ASNSetData), cert->heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (dataASN == NULL) {
- ret = MEMORY_E;
- }
- if (ret == 0) {
- /* Allocate memory for dynamic ASN.1 template. */
- extKuASN = (ASNItem*)XMALLOC(cnt * sizeof(ASNItem), cert->heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (extKuASN == NULL) {
- ret = MEMORY_E;
- }
- }
- if (ret == 0) {
- /* Copy Sequence into dynamic ASN.1 template. */
- XMEMCPY(&extKuASN[EKUASN_IDX_SEQ], ekuASN, sizeof(ASNItem));
- /* Clear dynamic data. */
- XMEMSET(dataASN, 0, cnt * sizeof(ASNSetData));
- /* Build up the template and data. */
- /* If 'any' set, then just use it. */
- if ((input & EXTKEYUSE_ANY) == EXTKEYUSE_ANY) {
- /* Set template item. */
- XMEMCPY(&extKuASN[EKUASN_IDX_OID], &ekuASN[EKUASN_IDX_OID],
- sizeof(ASNItem));
- /* Set data item. */
- SetASN_Buffer(&dataASN[asnIdx], extExtKeyUsageAnyOid,
- sizeof(extExtKeyUsageAnyOid));
- asnIdx++;
- }
- else {
- /* Step through the flagged purposes. */
- for (i = EKU_OID_LO; i <= EKU_OID_HI; i++) {
- if ((input & (1 << i)) != 0) {
- /* Set template item. */
- XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
- sizeof(ASNItem));
- /* Set data item. */
- SetASN_Buffer(&dataASN[asnIdx], ekuOid[i - 1].oid,
- ekuOid[i - 1].oidSz);
- asnIdx++;
- }
- }
- #ifdef WOLFSSL_EKU_OID
- if (input & EXTKEYUSE_USER) {
- /* Iterate through OID values */
- for (i = 0; i < CTC_MAX_EKU_NB; i++) {
- sz = cert->extKeyUsageOIDSz[i];
- if (sz > 0) {
- /* Set template item. */
- XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
- sizeof(ASNItem));
- /* Set data item. */
- SetASN_Buffer(&dataASN[asnIdx], cert->extKeyUsageOID[i],
- sz);
- asnIdx++;
- }
- }
- }
- #endif /* WOLFSSL_EKU_OID */
- (void)cert;
- }
- /* Calculate size of encoding. */
- sz = 0;
- ret = SizeASN_Items(extKuASN, dataASN, asnIdx, &sz);
- }
- /* When buffer to write to, ensure it's big enough. */
- if ((ret == 0) && (output != NULL) && (sz > (int)outSz)) {
- ret = BUFFER_E;
- }
- if ((ret == 0) && (output != NULL)) {
- /* Encode extended key usage. */
- SetASN_Items(extKuASN, dataASN, asnIdx, output);
- }
- if (ret == 0) {
- /* Return the encoding size. */
- ret = sz;
- }
- /* Dispose of allocated data. */
- if (extKuASN != NULL) {
- XFREE(extKuASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
- }
- if (dataASN != NULL) {
- XFREE(dataASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
- }
- return ret;
- #endif
- }
- #ifndef IGNORE_NETSCAPE_CERT_TYPE
- #ifndef WOLFSSL_ASN_TEMPLATE
- static int SetNsCertType(Cert* cert, byte* output, word32 outSz, byte input)
- {
- word32 idx;
- byte unusedBits = 0;
- byte nsCertType = input;
- word32 totalSz;
- word32 bitStrSz;
- const byte nscerttype_oid[] = { 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
- 0x86, 0xF8, 0x42, 0x01, 0x01 };
- if (cert == NULL || output == NULL ||
- input == 0)
- return BAD_FUNC_ARG;
- totalSz = sizeof(nscerttype_oid);
- /* Get amount of lsb zero's */
- for (;(input & 1) == 0; input >>= 1)
- unusedBits++;
- /* 1 byte of NS Cert Type extension */
- bitStrSz = SetBitString(1, unusedBits, NULL) + 1;
- totalSz += SetOctetString(bitStrSz, NULL) + bitStrSz;
- if (SetSequence(totalSz, NULL) + totalSz > outSz)
- return BAD_FUNC_ARG;
- /* 1. Seq + Total Len */
- idx = SetSequence(totalSz, output);
- /* 2. Object ID */
- XMEMCPY(&output[idx], nscerttype_oid, sizeof(nscerttype_oid));
- idx += sizeof(nscerttype_oid);
- /* 3. Octet String */
- idx += SetOctetString(bitStrSz, &output[idx]);
- /* 4. Bit String */
- idx += SetBitString(1, unusedBits, &output[idx]);
- output[idx++] = nsCertType;
- return (int)idx;
- }
- #endif
- #endif
- #ifndef WOLFSSL_ASN_TEMPLATE
- static int SetCRLInfo(Cert* cert, byte* output, word32 outSz, byte* input,
- int inSz)
- {
- word32 idx;
- word32 totalSz;
- const byte crlinfo_oid[] = { 0x06, 0x03, 0x55, 0x1D, 0x1F };
- if (cert == NULL || output == NULL ||
- input == 0 || inSz <= 0)
- return BAD_FUNC_ARG;
- totalSz = (word32)sizeof(crlinfo_oid) + SetOctetString((word32)inSz, NULL) +
- (word32)inSz;
- if (SetSequence(totalSz, NULL) + totalSz > outSz)
- return BAD_FUNC_ARG;
- /* 1. Seq + Total Len */
- idx = SetSequence(totalSz, output);
- /* 2. Object ID */
- XMEMCPY(&output[idx], crlinfo_oid, sizeof(crlinfo_oid));
- idx += sizeof(crlinfo_oid);
- /* 3. Octet String */
- idx += SetOctetString((word32)inSz, &output[idx]);
- /* 4. CRL Info */
- XMEMCPY(&output[idx], input, (size_t)inSz);
- idx += (word32)inSz;
- return (int)idx;
- }
- #endif
- /* encode Certificate Policies, return total bytes written
- * each input value must be ITU-T X.690 formatted : a.b.c...
- * input must be an array of values with a NULL terminated for the latest
- * RFC5280 : non-critical */
- static int SetCertificatePolicies(byte *output,
- word32 outputSz,
- char input[MAX_CERTPOL_NB][MAX_CERTPOL_SZ],
- word16 nb_certpol,
- void* heap)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- byte oid[MAX_OID_SZ];
- byte der_oid[MAX_CERTPOL_NB][MAX_OID_SZ];
- byte out[MAX_CERTPOL_SZ];
- word32 oidSz;
- word32 outSz;
- word32 i = 0;
- word32 der_oidSz[MAX_CERTPOL_NB];
- int ret;
- const byte certpol_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x20, 0x04 };
- const byte oid_oid[] = { 0x06 };
- if (output == NULL || input == NULL || nb_certpol > MAX_CERTPOL_NB)
- return BAD_FUNC_ARG;
- for (i = 0; i < nb_certpol; i++) {
- oidSz = sizeof(oid);
- XMEMSET(oid, 0, oidSz);
- ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
- if (ret != 0)
- return ret;
- /* compute sequence value for the oid */
- ret = SetOidValue(der_oid[i], MAX_OID_SZ, oid_oid,
- sizeof(oid_oid), oid, oidSz);
- if (ret <= 0)
- return ret;
- else
- der_oidSz[i] = (word32)ret;
- }
- /* concatenate oid, keep two byte for sequence/size of the created value */
- for (i = 0, outSz = 2; i < nb_certpol; i++) {
- XMEMCPY(out+outSz, der_oid[i], der_oidSz[i]);
- outSz += der_oidSz[i];
- }
- /* add sequence */
- ret = (int)SetSequence(outSz-2, out);
- if (ret <= 0)
- return ret;
- /* add Policy OID to compute final value */
- return SetOidValue(output, outputSz, certpol_oid, sizeof(certpol_oid),
- out, outSz);
- #else
- int i;
- int ret = 0;
- byte oid[MAX_OID_SZ];
- word32 oidSz;
- word32 sz = 0;
- int piSz;
- if ((input == NULL) || (nb_certpol > MAX_CERTPOL_NB)) {
- ret = BAD_FUNC_ARG;
- }
- /* Put in policyIdentifier but not policyQualifiers. */
- for (i = 0; (ret == 0) && (i < nb_certpol); i++) {
- ASNSetData dataASN[policyInfoASN_Length];
- oidSz = sizeof(oid);
- XMEMSET(oid, 0, oidSz);
- dataASN[POLICYINFOASN_IDX_QUALI].noOut = 1;
- ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
- if (ret == 0) {
- XMEMSET(dataASN, 0, sizeof(dataASN));
- SetASN_Buffer(&dataASN[POLICYINFOASN_IDX_ID], oid, oidSz);
- ret = SizeASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
- &piSz);
- }
- if ((ret == 0) && (output != NULL) && (sz + (word32)piSz > outputSz)) {
- ret = BUFFER_E;
- }
- if (ret == 0) {
- if (output != NULL) {
- SetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
- output);
- output += piSz;
- }
- sz += (word32)piSz;
- }
- }
- if (ret == 0) {
- ret = (int)sz;
- }
- return ret;
- #endif
- }
- #endif /* WOLFSSL_CERT_EXT */
- #ifdef WOLFSSL_ALT_NAMES
- #ifndef WOLFSSL_ASN_TEMPLATE
- /* encode Alternative Names, return total bytes written */
- static int SetAltNames(byte *output, word32 outSz,
- const byte *input, word32 length, int critical)
- {
- byte san_len[1 + MAX_LENGTH_SZ];
- const byte san_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x11 };
- const byte san_crit[] = { 0x01, 0x01, 0xff };
- word32 seqSz, san_lenSz, idx = 0;
- if (output == NULL || input == NULL)
- return BAD_FUNC_ARG;
- if (outSz < length)
- return BUFFER_E;
- /* Octet String header */
- san_lenSz = SetOctetString(length, san_len);
- if (outSz < MAX_SEQ_SZ)
- return BUFFER_E;
- seqSz = length + (word32)sizeof(san_oid) + san_lenSz;
- if (critical)
- seqSz += sizeof(san_crit);
- idx = SetSequence(seqSz, output);
- if (seqSz > outSz)
- return BUFFER_E;
- /* put oid */
- XMEMCPY(output+idx, san_oid, sizeof(san_oid));
- idx += sizeof(san_oid);
- if (critical) {
- XMEMCPY(output+idx, san_crit, sizeof(san_crit));
- idx += sizeof(san_crit);
- }
- /* put octet header */
- XMEMCPY(output+idx, san_len, san_lenSz);
- idx += san_lenSz;
- /* put value */
- XMEMCPY(output+idx, input, length);
- idx += length;
- return (int)idx;
- }
- #endif /* WOLFSSL_ASN_TEMPLATE */
- int FlattenAltNames(byte* output, word32 outputSz, const DNS_entry* names)
- {
- word32 idx;
- const DNS_entry* curName;
- word32 namesSz = 0;
- #ifdef WOLFSSL_ALT_NAMES_NO_REV
- word32 i;
- #endif
- if (output == NULL)
- return BAD_FUNC_ARG;
- if (names == NULL)
- return 0;
- curName = names;
- do {
- namesSz += (word32)curName->len + 2 +
- ((curName->len < ASN_LONG_LENGTH) ? 0
- : BytePrecision((word32)curName->len));
- curName = curName->next;
- } while (curName != NULL);
- if (outputSz < MAX_SEQ_SZ + namesSz)
- return BUFFER_E;
- idx = SetSequence(namesSz, output);
- #ifdef WOLFSSL_ALT_NAMES_NO_REV
- namesSz += idx;
- i = namesSz;
- #endif
- curName = names;
- do {
- #ifdef WOLFSSL_ALT_NAMES_NO_REV
- word32 len = SetLength(curName->len, NULL);
- idx = i - curName->len - len - 1;
- i = idx;
- #endif
- output[idx] = (byte) (ASN_CONTEXT_SPECIFIC | curName->type);
- if (curName->type == ASN_DIR_TYPE || curName->type == ASN_OTHER_TYPE) {
- output[idx] |= ASN_CONSTRUCTED;
- }
- idx++;
- idx += SetLength((word32)curName->len, output + idx);
- XMEMCPY(output + idx, curName->name, (size_t)curName->len);
- #ifndef WOLFSSL_ALT_NAMES_NO_REV
- idx += (word32)curName->len;
- #endif
- curName = curName->next;
- } while (curName != NULL);
- #ifdef WOLFSSL_ALT_NAMES_NO_REV
- idx = namesSz;
- #endif
- return (int)idx;
- }
- #endif /* WOLFSSL_ALT_NAMES */
- #endif /* WOLFSSL_CERT_GEN */
- #if defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
- /* Simple domain name OID size. */
- #define DN_OID_SZ 3
- /* Encodes one attribute of the name (issuer/subject)
- *
- * name structure to hold result of encoding
- * nameStr value to be encoded
- * nameTag tag of encoding i.e CTC_UTF8
- * type id of attribute i.e ASN_COMMON_NAME
- * emailTag tag of email i.e CTC_UTF8
- * returns length on success
- */
- static int EncodeName(EncodedName* name, const char* nameStr,
- byte nameTag, byte type, byte emailTag, CertName* cname)
- {
- #if !defined(WOLFSSL_ASN_TEMPLATE)
- word32 idx = 0;
- /* bottom up */
- byte firstLen[1 + MAX_LENGTH_SZ];
- byte secondLen[MAX_LENGTH_SZ];
- byte sequence[MAX_SEQ_SZ];
- byte set[MAX_SET_SZ];
- word32 strLen;
- word32 thisLen;
- word32 firstSz, secondSz, seqSz, setSz;
- if (nameStr == NULL) {
- name->used = 0;
- return 0;
- }
- thisLen = strLen = (word32)XSTRLEN(nameStr);
- #ifdef WOLFSSL_CUSTOM_OID
- if (type == ASN_CUSTOM_NAME) {
- if (cname == NULL || cname->custom.oidSz == 0) {
- name->used = 0;
- return 0;
- }
- thisLen = strLen = (word32)cname->custom.valSz;
- }
- #else
- (void)cname;
- #endif
- if (strLen == 0) { /* no user data for this item */
- name->used = 0;
- return 0;
- }
- /* Restrict country code size */
- if (type == ASN_COUNTRY_NAME && strLen != CTC_COUNTRY_SIZE) {
- WOLFSSL_MSG("Country code size error");
- WOLFSSL_ERROR_VERBOSE(ASN_COUNTRY_SIZE_E);
- return ASN_COUNTRY_SIZE_E;
- }
- secondSz = SetLength(strLen, secondLen);
- thisLen += secondSz;
- switch (type) {
- case ASN_EMAIL_NAME: /* email */
- thisLen += (int)sizeof(attrEmailOid);
- firstSz = (int)sizeof(attrEmailOid);
- break;
- case ASN_DOMAIN_COMPONENT:
- thisLen += (int)sizeof(dcOid);
- firstSz = (int)sizeof(dcOid);
- break;
- case ASN_USER_ID:
- thisLen += (int)sizeof(uidOid);
- firstSz = (int)sizeof(uidOid);
- break;
- case ASN_FAVOURITE_DRINK:
- thisLen += (int)sizeof(fvrtDrk);
- firstSz = (int)sizeof(fvrtDrk);
- break;
- #ifdef WOLFSSL_CUSTOM_OID
- case ASN_CUSTOM_NAME:
- thisLen += cname->custom.oidSz;
- firstSz = cname->custom.oidSz;
- break;
- #endif
- default:
- thisLen += DN_OID_SZ;
- firstSz = DN_OID_SZ;
- }
- thisLen++; /* id type */
- firstSz = (word32)SetObjectId((int)firstSz, firstLen);
- thisLen += firstSz;
- seqSz = SetSequence(thisLen, sequence);
- thisLen += seqSz;
- setSz = SetSet(thisLen, set);
- thisLen += setSz;
- if (thisLen > (int)sizeof(name->encoded)) {
- return BUFFER_E;
- }
- /* store it */
- idx = 0;
- /* set */
- XMEMCPY(name->encoded, set, setSz);
- idx += setSz;
- /* seq */
- XMEMCPY(name->encoded + idx, sequence, seqSz);
- idx += seqSz;
- /* asn object id */
- XMEMCPY(name->encoded + idx, firstLen, firstSz);
- idx += firstSz;
- switch (type) {
- case ASN_EMAIL_NAME:
- /* email joint id */
- XMEMCPY(name->encoded + idx, attrEmailOid, sizeof(attrEmailOid));
- idx += (int)sizeof(attrEmailOid);
- name->encoded[idx++] = emailTag;
- break;
- case ASN_DOMAIN_COMPONENT:
- XMEMCPY(name->encoded + idx, dcOid, sizeof(dcOid)-1);
- idx += (int)sizeof(dcOid)-1;
- /* id type */
- name->encoded[idx++] = type;
- /* str type */
- name->encoded[idx++] = nameTag;
- break;
- case ASN_USER_ID:
- XMEMCPY(name->encoded + idx, uidOid, sizeof(uidOid));
- idx += (int)sizeof(uidOid);
- /* str type */
- name->encoded[idx++] = nameTag;
- break;
- case ASN_FAVOURITE_DRINK:
- XMEMCPY(name->encoded + idx, fvrtDrk, sizeof(fvrtDrk));
- idx += (int)sizeof(fvrtDrk);
- /* str type */
- name->encoded[idx++] = nameTag;
- break;
- #ifdef WOLFSSL_CUSTOM_OID
- case ASN_CUSTOM_NAME:
- XMEMCPY(name->encoded + idx, cname->custom.oid,
- cname->custom.oidSz);
- idx += cname->custom.oidSz;
- /* str type */
- name->encoded[idx++] = nameTag;
- break;
- #endif
- default:
- name->encoded[idx++] = 0x55;
- name->encoded[idx++] = 0x04;
- /* id type */
- name->encoded[idx++] = type;
- /* str type */
- name->encoded[idx++] = nameTag;
- }
- /* second length */
- XMEMCPY(name->encoded + idx, secondLen, secondSz);
- idx += secondSz;
- /* str value */
- XMEMCPY(name->encoded + idx, nameStr, strLen);
- idx += strLen;
- name->type = type;
- name->totalLen = (int)idx;
- name->used = 1;
- return (int)idx;
- #else
- DECL_ASNSETDATA(dataASN, rdnASN_Length);
- ASNItem namesASN[rdnASN_Length];
- byte dnOid[DN_OID_SZ] = { 0x55, 0x04, 0x00 };
- int ret = 0;
- int sz = 0;
- const byte* oid;
- word32 oidSz;
- word32 nameSz;
- /* Validate input parameters. */
- if ((name == NULL) || (nameStr == NULL)) {
- ret = BAD_FUNC_ARG;
- }
- CALLOC_ASNSETDATA(dataASN, rdnASN_Length, ret, NULL);
- if (ret == 0) {
- nameSz = (word32)XSTRLEN(nameStr);
- /* Copy the RDN encoding template. ASN.1 tag for the name string is set
- * based on type. */
- XMEMCPY(namesASN, rdnASN, sizeof(namesASN));
- /* Set OID and ASN.1 tag for name depending on type. */
- switch (type) {
- case ASN_EMAIL_NAME:
- /* email OID different to standard types. */
- oid = attrEmailOid;
- oidSz = sizeof(attrEmailOid);
- /* Use email specific type/tag. */
- nameTag = emailTag;
- break;
- case ASN_DOMAIN_COMPONENT:
- /* Domain component OID different to standard types. */
- oid = dcOid;
- oidSz = sizeof(dcOid);
- break;
- case ASN_USER_ID:
- /* Domain component OID different to standard types. */
- oid = uidOid;
- oidSz = sizeof(uidOid);
- break;
- case ASN_FAVOURITE_DRINK:
- oid = fvrtDrk;
- oidSz = sizeof(fvrtDrk);
- break;
- #ifdef WOLFSSL_CUSTOM_OID
- case ASN_CUSTOM_NAME:
- nameSz = cname->custom.valSz;
- oid = cname->custom.oid;
- oidSz = cname->custom.oidSz;
- break;
- #endif
- default:
- /* Construct OID using type. */
- dnOid[2] = type;
- oid = dnOid;
- oidSz = DN_OID_SZ;
- break;
- }
- /* Set OID corresponding to the name type. */
- SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
- /* Set name string. */
- SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], (const byte *)nameStr, nameSz);
- /* Set the ASN.1 tag for the name string. */
- namesASN[RDNASN_IDX_ATTR_VAL].tag = nameTag;
- /* Calculate size of encoded name and indexes of components. */
- ret = SizeASN_Items(namesASN, dataASN, rdnASN_Length, &sz);
- }
- /* Check if name's buffer is big enough. */
- if ((ret == 0) && (sz > (int)sizeof(name->encoded))) {
- ret = BUFFER_E;
- }
- if (ret == 0) {
- /* Encode name into the buffer. */
- SetASN_Items(namesASN, dataASN, rdnASN_Length, name->encoded);
- /* Cache the type and size, and set that it is used. */
- name->type = type;
- name->totalLen = sz;
- name->used = 1;
- /* Return size of encoding. */
- ret = sz;
- }
- (void)cname;
- FREE_ASNSETDATA(dataASN, NULL);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- /* canonical encoding one attribute of the name (issuer/subject)
- * call EncodeName with CTC_UTF8 for email type
- *
- * name structure to hold result of encoding
- * nameStr value to be encoded
- * nameType type of encoding i.e CTC_UTF8
- * type id of attribute i.e ASN_COMMON_NAME
- *
- * returns length on success
- */
- int wc_EncodeNameCanonical(EncodedName* name, const char* nameStr,
- char nameType, byte type)
- {
- return EncodeName(name, nameStr, (byte)nameType, type,
- ASN_UTF8STRING, NULL);
- }
- #endif /* WOLFSSL_CERT_GEN || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
- #ifdef WOLFSSL_CERT_GEN
- /* Encodes one attribute of the name (issuer/subject)
- * call we_EncodeName_ex with 0x16, IA5String for email type
- * name structure to hold result of encoding
- * nameStr value to be encoded
- * nameType type of encoding i.e CTC_UTF8
- * type id of attribute i.e ASN_COMMON_NAME
- *
- * returns length on success
- */
- int wc_EncodeName(EncodedName* name, const char* nameStr, char nameType,
- byte type)
- {
- return EncodeName(name, nameStr, (byte)nameType, type,
- ASN_IA5_STRING, NULL);
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- static void SetRdnItems(ASNItem* namesASN, ASNSetData* dataASN, const byte* oid,
- word32 oidSz, byte tag, const byte* data, word32 sz)
- {
- XMEMCPY(namesASN, rdnASN, sizeof(rdnASN));
- SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
- namesASN[RDNASN_IDX_ATTR_VAL].tag = tag;
- SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], data, sz);
- }
- #ifdef WOLFSSL_MULTI_ATTRIB
- static int FindMultiAttrib(CertName* name, int id, int* idx)
- {
- int i;
- for (i = *idx + 1; i < CTC_MAX_ATTRIB; i++) {
- if (name->name[i].sz > 0 && name->name[i].id == id) {
- break;
- }
- }
- if (i == CTC_MAX_ATTRIB) {
- i = -1;
- }
- *idx = i;
- return i >= 0;
- }
- #endif
- /* ASN.1 template for the SEQUENCE around the RDNs.
- * X.509: RFC 5280, 4.1.2.4 - RDNSequence
- */
- static const ASNItem nameASN[] = {
- { 0, ASN_SEQUENCE, 1, 1, 0 },
- };
- enum {
- NAMEASN_IDX_SEQ = 0
- };
- /* Number of items in ASN.1 template for the SEQUENCE around the RDNs. */
- #define nameASN_Length (sizeof(nameASN) / sizeof(ASNItem))
- static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN,
- int maxIdx, CertName* name)
- {
- int i;
- int idx;
- int ret = 0;
- word32 nameLen[NAME_ENTRIES];
- #ifdef WOLFSSL_MULTI_ATTRIB
- int j;
- #endif
- for (i = 0; i < NAME_ENTRIES; i++) {
- /* Keep name length to identify component is to be encoded. */
- const char* nameStr = GetOneCertName(name, i);
- nameLen[i] = nameStr ? (word32)XSTRLEN(nameStr) : 0;
- }
- idx = nameASN_Length;
- for (i = 0; i < NAME_ENTRIES; i++) {
- int type = GetCertNameId(i);
- #ifdef WOLFSSL_MULTI_ATTRIB
- j = -1;
- /* Put DomainComponents before OrgUnitName. */
- while (FindMultiAttrib(name, type, &j)) {
- if (GetCertNameId(i) != ASN_DOMAIN_COMPONENT) {
- continue;
- }
- if (dataASN != NULL && namesASN != NULL) {
- if (idx > maxIdx - (int)rdnASN_Length) {
- WOLFSSL_MSG("Wanted to write more ASN than allocated");
- ret = BUFFER_E;
- break;
- }
- /* Copy data into dynamic vars. */
- SetRdnItems(namesASN + idx, dataASN + idx, dcOid,
- sizeof(dcOid), (byte)name->name[j].type,
- (byte*)name->name[j].value,
- (word32)name->name[j].sz);
- }
- idx += (int)rdnASN_Length;
- }
- if (ret != 0)
- break;
- #endif
- if (nameLen[i] > 0) {
- if (dataASN != NULL) {
- if (idx > maxIdx - (int)rdnASN_Length) {
- WOLFSSL_MSG("Wanted to write more ASN than allocated");
- ret = BUFFER_E;
- break;
- }
- /* Write out first instance of attribute type. */
- if (type == ASN_EMAIL_NAME) {
- /* Copy email data into dynamic vars. */
- SetRdnItems(namesASN + idx, dataASN + idx, attrEmailOid,
- sizeof(attrEmailOid), ASN_IA5_STRING,
- (const byte*)GetOneCertName(name, i), nameLen[i]);
- }
- else if (type == ASN_USER_ID) {
- /* Copy userID data into dynamic vars. */
- SetRdnItems(namesASN + idx, dataASN + idx, uidOid,
- sizeof(uidOid), (byte)GetNameType(name, i),
- (const byte*)GetOneCertName(name, i), nameLen[i]);
- }
- else if (type == ASN_FAVOURITE_DRINK) {
- /* Copy favourite drink data into dynamic vars. */
- SetRdnItems(namesASN + idx, dataASN + idx, fvrtDrk,
- sizeof(fvrtDrk), (byte)GetNameType(name, i),
- (const byte*)GetOneCertName(name, i), nameLen[i]);
- }
- else if (type == ASN_CUSTOM_NAME) {
- #ifdef WOLFSSL_CUSTOM_OID
- SetRdnItems(namesASN + idx, dataASN + idx, name->custom.oid,
- name->custom.oidSz, name->custom.enc,
- name->custom.val, name->custom.valSz);
- #endif
- }
- else {
- /* Copy name data into dynamic vars. */
- SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
- NAME_OID_SZ, (byte)GetNameType(name, i),
- (const byte*)GetOneCertName(name, i), nameLen[i]);
- }
- }
- idx += (int)rdnASN_Length;
- }
- #ifdef WOLFSSL_MULTI_ATTRIB
- j = -1;
- /* Write all other attributes of this type. */
- while (FindMultiAttrib(name, type, &j)) {
- if (GetCertNameId(i) == ASN_DOMAIN_COMPONENT) {
- continue;
- }
- if (dataASN != NULL && namesASN != NULL) {
- if (idx > maxIdx - (int)rdnASN_Length) {
- WOLFSSL_MSG("Wanted to write more ASN than allocated");
- ret = BUFFER_E;
- break;
- }
- /* Copy data into dynamic vars. */
- SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
- NAME_OID_SZ, (byte)name->name[j].type,
- (byte*)name->name[j].value, (word32)name->name[j].sz);
- }
- idx += (int)rdnASN_Length;
- }
- if (ret != 0)
- break;
- #endif
- }
- if (ret == 0)
- ret = idx;
- return ret;
- }
- #endif
- /* encode CertName into output, return total bytes written */
- int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret;
- int i;
- word32 idx, totalBytes = 0;
- #ifdef WOLFSSL_SMALL_STACK
- EncodedName* names = NULL;
- #else
- EncodedName names[NAME_ENTRIES];
- #endif
- #ifdef WOLFSSL_MULTI_ATTRIB
- EncodedName addNames[CTC_MAX_ATTRIB];
- int j, type;
- #endif
- if (output == NULL || name == NULL)
- return BAD_FUNC_ARG;
- if (outputSz < 3)
- return BUFFER_E;
- #ifdef WOLFSSL_SMALL_STACK
- names = (EncodedName*)XMALLOC(sizeof(EncodedName) * NAME_ENTRIES, NULL,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (names == NULL)
- return MEMORY_E;
- #endif
- for (i = 0; i < NAME_ENTRIES; i++) {
- const char* nameStr = GetOneCertName(name, i);
- ret = EncodeName(&names[i], nameStr, (byte)GetNameType(name, i),
- GetCertNameId(i), ASN_IA5_STRING, name);
- if (ret < 0) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- WOLFSSL_MSG("EncodeName failed");
- return BUFFER_E;
- }
- totalBytes += (word32)ret;
- }
- #ifdef WOLFSSL_MULTI_ATTRIB
- for (i = 0; i < CTC_MAX_ATTRIB; i++) {
- if (name->name[i].sz > 0) {
- ret = EncodeName(&addNames[i], name->name[i].value,
- (byte)name->name[i].type, (byte)name->name[i].id,
- ASN_IA5_STRING, NULL);
- if (ret < 0) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- WOLFSSL_MSG("EncodeName on multiple attributes failed");
- return BUFFER_E;
- }
- totalBytes += (word32)ret;
- }
- else {
- addNames[i].used = 0;
- }
- }
- #endif /* WOLFSSL_MULTI_ATTRIB */
- /* header */
- idx = SetSequence(totalBytes, output);
- totalBytes += idx;
- if (totalBytes > WC_ASN_NAME_MAX) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- WOLFSSL_MSG("Total Bytes is greater than WC_ASN_NAME_MAX");
- return BUFFER_E;
- }
- for (i = 0; i < NAME_ENTRIES; i++) {
- #ifdef WOLFSSL_MULTI_ATTRIB
- type = GetCertNameId(i);
- for (j = 0; j < CTC_MAX_ATTRIB; j++) {
- if (name->name[j].sz > 0 && type == name->name[j].id) {
- if (outputSz < idx + (word32)addNames[j].totalLen) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- WOLFSSL_MSG("Not enough space left for DC value");
- return BUFFER_E;
- }
- XMEMCPY(output + idx, addNames[j].encoded,
- (size_t)addNames[j].totalLen);
- idx += (word32)addNames[j].totalLen;
- }
- }
- #endif /* WOLFSSL_MULTI_ATTRIB */
- if (names[i].used) {
- if (outputSz < idx + (word32)names[i].totalLen) {
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return BUFFER_E;
- }
- XMEMCPY(output + idx, names[i].encoded, (size_t)names[i].totalLen);
- idx += (word32)names[i].totalLen;
- }
- }
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- (void)heap;
- return (int)totalBytes;
- #else
- /* TODO: consider calculating size of entries, putting length into
- * SEQUENCE, encode SEQUENCE, encode entries into buffer. */
- ASNSetData* dataASN = NULL; /* Can't use DECL_ASNSETDATA. Always dynamic. */
- ASNItem* namesASN = NULL;
- word32 items = 0;
- int ret = 0;
- int sz = 0;
- /* Calculate length of name entries and size for allocating. */
- ret = SetNameRdnItems(NULL, NULL, 0, name);
- if (ret > 0) {
- items = (word32)ret;
- ret = 0;
- }
- /* Allocate dynamic data items. */
- dataASN = (ASNSetData*)XMALLOC(items * sizeof(ASNSetData), heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (dataASN == NULL) {
- ret = MEMORY_E;
- }
- else {
- /* Allocate dynamic ASN.1 template items. */
- namesASN = (ASNItem*)XMALLOC(items * sizeof(ASNItem), heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (namesASN == NULL) {
- ret = MEMORY_E;
- }
- }
- if (ret == 0) {
- /* Clear the dynamic data. */
- XMEMSET(dataASN, 0, items * sizeof(ASNSetData));
- /* Copy in the outer sequence. */
- XMEMCPY(namesASN, nameASN, sizeof(nameASN));
- ret = SetNameRdnItems(dataASN, namesASN, (int)items, name);
- if (ret == (int)items)
- ret = 0;
- else if (ret > 0) {
- WOLFSSL_MSG("SetNameRdnItems returned different length");
- ret = BUFFER_E;
- }
- }
- if (ret == 0) {
- /* Calculate size of encoding. */
- ret = SizeASN_Items(namesASN, dataASN, (int)items, &sz);
- }
- /* Check buffer size if passed in. */
- if (ret == 0 && output != NULL && sz > (int)outputSz) {
- ret = BUFFER_E;
- }
- if (ret == 0) {
- if (output != NULL) {
- /* Encode Name. */
- ret = SetASN_Items(namesASN, dataASN, (int)items, output);
- }
- else {
- /* Return the encoding size. */
- ret = sz;
- }
- }
- if (namesASN != NULL)
- XFREE(namesASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (dataASN != NULL)
- XFREE(dataASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
- (void)heap;
- return ret;
- #endif
- }
- int SetName(byte* output, word32 outputSz, CertName* name)
- {
- return SetNameEx(output, outputSz, name, NULL);
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- static int EncodePublicKey(int keyType, byte* output, int outLen,
- RsaKey* rsaKey, ecc_key* eccKey,
- ed25519_key* ed25519Key, ed448_key* ed448Key,
- DsaKey* dsaKey)
- {
- int ret = 0;
- (void)outLen;
- (void)rsaKey;
- (void)eccKey;
- (void)ed25519Key;
- (void)ed448Key;
- (void)dsaKey;
- switch (keyType) {
- #ifndef NO_RSA
- case RSA_KEY:
- ret = SetRsaPublicKey(output, rsaKey, outLen, 1);
- if (ret <= 0) {
- ret = PUBLIC_KEY_E;
- }
- break;
- #endif
- #ifdef HAVE_ECC
- case ECC_KEY:
- ret = SetEccPublicKey(output, eccKey, outLen, 1, 0);
- if (ret <= 0) {
- ret = PUBLIC_KEY_E;
- }
- break;
- #endif /* HAVE_ECC */
- #ifdef HAVE_ED25519
- case ED25519_KEY:
- ret = wc_Ed25519PublicKeyToDer(ed25519Key, output,
- (word32)outLen, 1);
- if (ret <= 0) {
- ret = PUBLIC_KEY_E;
- }
- break;
- #endif
- #ifdef HAVE_ED448
- case ED448_KEY:
- ret = wc_Ed448PublicKeyToDer(ed448Key, output, (word32)outLen, 1);
- if (ret <= 0) {
- ret = PUBLIC_KEY_E;
- }
- break;
- #endif
- default:
- ret = PUBLIC_KEY_E;
- break;
- }
- return ret;
- }
- /* ASN.1 template for certificate extensions.
- * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
- * All extensions supported for encoding are described.
- */
- static const ASNItem static_certExtsASN[] = {
- /* Basic Constraints Extension - 4.2.1.9 */
- /* BC_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* BC_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* BC_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
- /* BC_STR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
- /* cA */
- /* BC_CA */ { 3, ASN_BOOLEAN, 0, 0, 0 },
- /* pathLenConstraint */
- /* BC_PATHLEN */ { 3, ASN_INTEGER, 0, 0, 1 },
- /* Subject Alternative Name - 4.2.1.6 */
- /* SAN_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* SAN_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* SAN_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
- /* SAN_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
- /* Subject Key Identifier - 4.2.1.2 */
- /* SKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* SKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* SKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
- /* SKID_KEYID */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
- /* Authority Key Identifier - 4.2.1.1 */
- /* AKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* AKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* AKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
- /* AKID_STR_SEQ, */ { 2, ASN_SEQUENCE, 1, 1, 0 },
- /* AKID_KEYID */ { 3, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
- /* Key Usage - 4.2.1.3 */
- /* KU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* KU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* KU_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
- /* KU_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
- /* KU_USAGE */ { 2, ASN_BIT_STRING, 0, 0, 0 },
- /* Extended Key Usage - 4,2,1,12 */
- /* EKU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* EKU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* EKU_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
- /* Certificate Policies - 4.2.1.4 */
- /* POLICIES_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* POLICIES_OID, */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* POLICIES_STR, */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
- /* POLICIES_INFO */ { 2, ASN_SEQUENCE, 1, 0, 0 },
- /* Netscape Certificate Type */
- /* NSTYPE_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* NSTYPE_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* NSTYPE_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
- /* NSTYPE_USAGE, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
- /* CRLINFO_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* CRLINFO_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* CRLINFO_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
- /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
- };
- enum {
- CERTEXTSASN_IDX_BC_SEQ = 0,
- CERTEXTSASN_IDX_BC_OID,
- CERTEXTSASN_IDX_BC_STR,
- CERTEXTSASN_IDX_BC_STR_SEQ,
- CERTEXTSASN_IDX_BC_CA,
- CERTEXTSASN_IDX_BC_PATHLEN,
- CERTEXTSASN_IDX_SAN_SEQ,
- CERTEXTSASN_IDX_SAN_OID,
- CERTEXTSASN_IDX_SAN_CRIT,
- CERTEXTSASN_IDX_SAN_STR,
- CERTEXTSASN_IDX_SKID_SEQ,
- CERTEXTSASN_IDX_SKID_OID,
- CERTEXTSASN_IDX_SKID_STR,
- CERTEXTSASN_IDX_SKID_KEYID,
- CERTEXTSASN_IDX_AKID_SEQ,
- CERTEXTSASN_IDX_AKID_OID,
- CERTEXTSASN_IDX_AKID_STR,
- CERTEXTSASN_IDX_AKID_STR_SEQ,
- CERTEXTSASN_IDX_AKID_KEYID,
- CERTEXTSASN_IDX_KU_SEQ,
- CERTEXTSASN_IDX_KU_OID,
- CERTEXTSASN_IDX_KU_CRIT,
- CERTEXTSASN_IDX_KU_STR,
- CERTEXTSASN_IDX_KU_USAGE,
- CERTEXTSASN_IDX_EKU_SEQ,
- CERTEXTSASN_IDX_EKU_OID,
- CERTEXTSASN_IDX_EKU_STR,
- CERTEXTSASN_IDX_POLICIES_SEQ,
- CERTEXTSASN_IDX_POLICIES_OID,
- CERTEXTSASN_IDX_POLICIES_STR,
- CERTEXTSASN_IDX_POLICIES_INFO,
- CERTEXTSASN_IDX_NSTYPE_SEQ,
- CERTEXTSASN_IDX_NSTYPE_OID,
- CERTEXTSASN_IDX_NSTYPE_STR,
- CERTEXTSASN_IDX_NSTYPE_USAGE,
- CERTEXTSASN_IDX_CRLINFO_SEQ,
- CERTEXTSASN_IDX_CRLINFO_OID,
- CERTEXTSASN_IDX_CRLINFO_STR,
- CERTEXTSASN_IDX_CUSTOM_SEQ,
- CERTEXTSASN_IDX_CUSTOM_OID,
- CERTEXTSASN_IDX_CUSTOM_STR,
- CERTEXTSASN_IDX_START_CUSTOM
- };
- /* Number of items in ASN.1 template for certificate extensions. We multiply
- * by 4 because there are 4 things (seq, OID, crit flag, octet string). */
- #define certExtsASN_Length ((sizeof(static_certExtsASN) / sizeof(ASNItem)) \
- + (NUM_CUSTOM_EXT * 4))
- static const ASNItem customExtASN[] = {
- /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* CUSTOM_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
- /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
- };
- static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz,
- int forRequest)
- {
- DECL_ASNSETDATA(dataASN, certExtsASN_Length);
- int sz;
- int ret = 0;
- int i = 0;
- static const byte bcOID[] = { 0x55, 0x1d, 0x13 };
- #ifdef WOLFSSL_ALT_NAMES
- static const byte sanOID[] = { 0x55, 0x1d, 0x11 };
- #endif
- #ifdef WOLFSSL_CERT_EXT
- static const byte skidOID[] = { 0x55, 0x1d, 0x0e };
- static const byte akidOID[] = { 0x55, 0x1d, 0x23 };
- static const byte kuOID[] = { 0x55, 0x1d, 0x0f };
- static const byte ekuOID[] = { 0x55, 0x1d, 0x25 };
- static const byte cpOID[] = { 0x55, 0x1d, 0x20 };
- static const byte nsCertOID[] = { 0x60, 0x86, 0x48, 0x01,
- 0x86, 0xF8, 0x42, 0x01, 0x01 };
- static const byte crlInfoOID[] = { 0x55, 0x1D, 0x1F };
- #endif
- #ifdef WOLFSSL_SMALL_STACK
- #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
- byte *encodedOids;
- #endif
- ASNItem *certExtsASN = (ASNItem *)XMALLOC(certExtsASN_Length *
- sizeof(ASNItem), cert->heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (certExtsASN == NULL) {
- return MEMORY_E;
- }
- #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
- encodedOids = (byte *)XMALLOC(NUM_CUSTOM_EXT * MAX_OID_SZ, cert->heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (encodedOids == NULL) {
- XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
- return MEMORY_E;
- }
- #endif
- #else
- ASNItem certExtsASN[certExtsASN_Length];
- #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
- byte encodedOids[NUM_CUSTOM_EXT * MAX_OID_SZ];
- #endif
- #endif
- /* Clone static_certExtsASN into a certExtsASN and then fill the rest of it
- * with (NUM_CUSTOM_EXT*4) more ASNItems specifying extensions. See comment
- * above definition of certExtsASN_Length. */
- XMEMCPY(certExtsASN, static_certExtsASN, sizeof(static_certExtsASN));
- for (i = sizeof(static_certExtsASN) / sizeof(ASNItem);
- i < (int)certExtsASN_Length; i += 4) {
- XMEMCPY(&certExtsASN[i], customExtASN, sizeof(customExtASN));
- }
- (void)forRequest;
- CALLOC_ASNSETDATA(dataASN, certExtsASN_Length, ret, cert->heap);
- if (ret == 0) {
- if (cert->isCA) {
- /* Set Basic Constraints to be a Certificate Authority. */
- SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_BC_CA], 1);
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
- if (cert->pathLenSet
- #ifdef WOLFSSL_CERT_EXT
- && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
- #endif
- ) {
- SetASN_Int8Bit(&dataASN[CERTEXTSASN_IDX_BC_PATHLEN],
- cert->pathLen);
- }
- else {
- dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
- }
- }
- else if (cert->basicConstSet) {
- /* Set Basic Constraints to be a non Certificate Authority. */
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
- dataASN[CERTEXTSASN_IDX_BC_CA].noOut = 1;
- dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
- }
- else {
- /* Don't write out Basic Constraints extension items. */
- SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_BC_SEQ,
- CERTEXTSASN_IDX_BC_PATHLEN);
- }
- #ifdef WOLFSSL_ALT_NAMES
- if (cert->altNamesSz > 0) {
- /* Set Subject Alternative Name OID and data. */
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_OID],
- sanOID, sizeof(sanOID));
- if (cert->altNamesCrit) {
- SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_SAN_CRIT], 1);
- }
- else {
- dataASN[CERTEXTSASN_IDX_SAN_CRIT].noOut = 1;
- }
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_STR],
- cert->altNames, (word32)cert->altNamesSz);
- }
- else
- #endif
- {
- /* Don't write out Subject Alternative Name extension items. */
- SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SAN_SEQ,
- CERTEXTSASN_IDX_SAN_STR);
- }
- #ifdef WOLFSSL_CERT_EXT
- if (cert->skidSz > 0) {
- /* Set Subject Key Identifier OID and data. */
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_OID],
- skidOID, sizeof(skidOID));
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_KEYID],
- cert->skid, (word32)cert->skidSz);
- }
- else
- #endif
- {
- /* Don't write out Subject Key Identifier extension items. */
- SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SKID_SEQ,
- CERTEXTSASN_IDX_SKID_KEYID);
- }
- #ifdef WOLFSSL_CERT_EXT
- if (cert->akidSz > 0) {
- /* Set Authority Key Identifier OID and data. */
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_OID],
- akidOID, sizeof(akidOID));
- #ifdef WOLFSSL_AKID_NAME
- if (cert->rawAkid) {
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_STR],
- cert->akid, cert->akidSz);
- /* cert->akid contains the internal ext structure */
- SetASNItem_NoOutBelow(dataASN, certExtsASN,
- CERTEXTSASN_IDX_AKID_STR, certExtsASN_Length);
- }
- else
- #endif
- {
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_KEYID],
- cert->akid, (word32)cert->akidSz);
- }
- }
- else
- #endif
- {
- /* Don't write out Authority Key Identifier extension items. */
- SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_AKID_SEQ,
- CERTEXTSASN_IDX_AKID_KEYID);
- }
- #ifdef WOLFSSL_CERT_EXT
- if (cert->keyUsage != 0) {
- /* Set Key Usage OID, critical and value. */
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_KU_OID],
- kuOID, sizeof(kuOID));
- SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_KU_CRIT], 1);
- SetASN_Int16Bit(&dataASN[CERTEXTSASN_IDX_KU_USAGE],
- cert->keyUsage);
- }
- else
- #endif
- {
- /* Don't write out Key Usage extension items. */
- SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_KU_SEQ,
- CERTEXTSASN_IDX_KU_USAGE);
- }
- #ifdef WOLFSSL_CERT_EXT
- if (cert->extKeyUsage != 0) {
- /* Calculate size of Extended Key Usage data. */
- sz = SetExtKeyUsage(cert, NULL, 0, cert->extKeyUsage);
- if (sz <= 0) {
- ret = KEYUSAGE_E;
- }
- /* Set Extended Key Usage OID and data. */
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_OID],
- ekuOID, sizeof(ekuOID));
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_STR],
- NULL, (word32)sz);
- }
- else
- #endif
- {
- /* Don't write out Extended Key Usage extension items. */
- SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_EKU_SEQ,
- CERTEXTSASN_IDX_EKU_STR);
- }
- #ifdef WOLFSSL_CERT_EXT
- if ((!forRequest) && (cert->certPoliciesNb > 0)) {
- /* Calculate size of certificate policies. */
- sz = SetCertificatePolicies(NULL, 0, cert->certPolicies,
- cert->certPoliciesNb, cert->heap);
- if (sz > 0) {
- /* Set Certificate Policies OID. */
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_OID],
- cpOID, sizeof(cpOID));
- /* Make space for data. */
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_INFO],
- NULL, (word32)sz);
- }
- else {
- ret = CERTPOLICIES_E;
- }
- }
- else
- #endif
- {
- /* Don't write out Certificate Policies extension items. */
- SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_POLICIES_SEQ,
- CERTEXTSASN_IDX_POLICIES_INFO);
- }
- #if defined(WOLFSSL_CERT_EXT) && !defined(IGNORE_NETSCAPE_CERT_TYPE)
- /* Netscape Certificate Type */
- if (cert->nsCertType != 0) {
- /* Set Netscape Certificate Type OID and data. */
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_OID],
- nsCertOID, sizeof(nsCertOID));
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_USAGE],
- &cert->nsCertType, 1);
- }
- else
- #endif
- {
- /* Don't write out Netscape Certificate Type. */
- SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_NSTYPE_SEQ,
- CERTEXTSASN_IDX_NSTYPE_USAGE);
- }
- #ifdef WOLFSSL_CERT_EXT
- if (cert->crlInfoSz > 0) {
- /* Set CRL Distribution Points OID and data. */
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_OID],
- crlInfoOID, sizeof(crlInfoOID));
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_STR],
- cert->crlInfo, (word32)cert->crlInfoSz);
- }
- else
- #endif
- {
- /* Don't write out CRL Distribution Points. */
- SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CRLINFO_SEQ,
- CERTEXTSASN_IDX_CRLINFO_STR);
- }
- #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
- /* encode a custom oid and value */
- if (cert->extCustom.oidSz > 0) {
- /* Set CRL Distribution Points OID and data. */
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_OID],
- cert->extCustom.oid, cert->extCustom.oidSz);
- SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_STR],
- cert->extCustom.val, cert->extCustom.valSz);
- }
- else
- #endif
- {
- /* Don't write out custom OID. */
- SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CUSTOM_SEQ,
- CERTEXTSASN_IDX_CUSTOM_STR);
- }
- i = 0;
- #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
- for (; i < cert->customCertExtCount; i++) {
- int idx = CERTEXTSASN_IDX_START_CUSTOM + (i * 4);
- word32 encodedOidSz = MAX_OID_SZ;
- idx++; /* Skip one for for SEQ. */
- /* EncodePolicyOID() will never return error since we parsed this
- * OID when it was set. */
- EncodePolicyOID(&encodedOids[i * MAX_OID_SZ], &encodedOidSz,
- cert->customCertExt[i].oid, NULL);
- SetASN_Buffer(&dataASN[idx], &encodedOids[i * MAX_OID_SZ],
- encodedOidSz);
- idx++;
- if (cert->customCertExt[i].crit) {
- SetASN_Boolean(&dataASN[idx], 1);
- } else {
- dataASN[idx].noOut = 1;
- }
- idx++;
- SetASN_Buffer(&dataASN[idx], cert->customCertExt[i].val,
- cert->customCertExt[i].valSz);
- }
- #endif
- while (i < NUM_CUSTOM_EXT) {
- SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_START_CUSTOM + (i * 4),
- CERTEXTSASN_IDX_START_CUSTOM + (i * 4) + 3);
- i++;
- }
- }
- if (ret == 0) {
- /* Calculate size of encoded extensions. */
- ret = SizeASN_Items(certExtsASN, dataASN, certExtsASN_Length, &sz);
- }
- if (ret == 0) {
- /* Only SEQUENCE - don't encode extensions. */
- if (sz == 2) {
- sz = 0;
- }
- /* Check buffer is big enough. */
- else if ((output != NULL) && (sz > (int)maxSz)) {
- ret = BUFFER_E;
- }
- }
- if ((ret == 0) && (output != NULL) && (sz > 0)) {
- /* Encode certificate extensions into buffer. */
- SetASN_Items(certExtsASN, dataASN, certExtsASN_Length, output);
- #ifdef WOLFSSL_CERT_EXT
- if (cert->extKeyUsage != 0){
- /* Encode Extended Key Usage into space provided. */
- if (SetExtKeyUsage(cert,
- (byte*)dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.data,
- dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.length,
- cert->extKeyUsage) <= 0) {
- ret = KEYUSAGE_E;
- }
- }
- if ((!forRequest) && (cert->certPoliciesNb > 0)) {
- /* Encode Certificate Policies into space provided. */
- if (SetCertificatePolicies(
- (byte*)dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.data,
- dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.length,
- cert->certPolicies, cert->certPoliciesNb, cert->heap) <= 0) {
- ret = CERTPOLICIES_E;
- }
- }
- #endif
- }
- if (ret == 0) {
- /* Return the encoding size. */
- ret = sz;
- }
- FREE_ASNSETDATA(dataASN, cert->heap);
- #ifdef WOLFSSL_SMALL_STACK
- #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
- XFREE(encodedOids, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return ret;
- }
- #endif /* WOLFSSL_ASN_TEMPLATE */
- #ifndef WOLFSSL_ASN_TEMPLATE
- /* Set Date validity from now until now + daysValid
- * return size in bytes written to output, 0 on error */
- /* TODO https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.5
- * "MUST always encode certificate validity dates through the year 2049 as
- * UTCTime; certificate validity dates in 2050 or later MUST be encoded as
- * GeneralizedTime." */
- static int SetValidity(byte* output, int daysValid)
- {
- #ifndef NO_ASN_TIME
- byte before[MAX_DATE_SIZE];
- byte after[MAX_DATE_SIZE];
- word32 beforeSz, afterSz, seqSz;
- time_t now;
- time_t then;
- struct tm* tmpTime;
- struct tm* expandedTime;
- struct tm localTime;
- #if defined(NEED_TMP_TIME)
- /* for use with gmtime_r */
- struct tm tmpTimeStorage;
- tmpTime = &tmpTimeStorage;
- #else
- tmpTime = NULL;
- #endif
- (void)tmpTime;
- now = wc_Time(0);
- /* before now */
- before[0] = ASN_GENERALIZED_TIME;
- beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
- /* subtract 1 day of seconds for more compliance */
- then = now - 86400;
- expandedTime = XGMTIME(&then, tmpTime);
- if (expandedTime == NULL) {
- WOLFSSL_MSG("XGMTIME failed");
- return 0; /* error */
- }
- localTime = *expandedTime;
- /* adjust */
- localTime.tm_year += 1900;
- localTime.tm_mon += 1;
- SetTime(&localTime, before + beforeSz);
- beforeSz += ASN_GEN_TIME_SZ;
- after[0] = ASN_GENERALIZED_TIME;
- afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
- /* add daysValid of seconds */
- then = now + (daysValid * (time_t)86400);
- expandedTime = XGMTIME(&then, tmpTime);
- if (expandedTime == NULL) {
- WOLFSSL_MSG("XGMTIME failed");
- return 0; /* error */
- }
- localTime = *expandedTime;
- /* adjust */
- localTime.tm_year += 1900;
- localTime.tm_mon += 1;
- SetTime(&localTime, after + afterSz);
- afterSz += ASN_GEN_TIME_SZ;
- /* headers and output */
- seqSz = SetSequence(beforeSz + afterSz, output);
- XMEMCPY(output + seqSz, before, beforeSz);
- XMEMCPY(output + seqSz + beforeSz, after, afterSz);
- return (int)(seqSz + beforeSz + afterSz);
- #else
- (void)output;
- (void)daysValid;
- return NOT_COMPILED_IN;
- #endif
- }
- #else
- static int SetValidity(byte* before, byte* after, int daysValid)
- {
- #ifndef NO_ASN_TIME
- int ret = 0;
- time_t now;
- time_t then;
- struct tm* tmpTime;
- struct tm* expandedTime;
- struct tm localTime;
- #if defined(NEED_TMP_TIME)
- /* for use with gmtime_r */
- struct tm tmpTimeStorage;
- tmpTime = &tmpTimeStorage;
- #else
- tmpTime = NULL;
- #endif
- (void)tmpTime;
- now = wc_Time(0);
- /* subtract 1 day of seconds for more compliance */
- then = now - 86400;
- expandedTime = XGMTIME(&then, tmpTime);
- if (expandedTime == NULL) {
- WOLFSSL_MSG("XGMTIME failed");
- ret = DATE_E;
- }
- if (ret == 0) {
- localTime = *expandedTime;
- /* adjust */
- localTime.tm_year += 1900;
- localTime.tm_mon += 1;
- SetTime(&localTime, before);
- /* add daysValid of seconds */
- then = now + (daysValid * (time_t)86400);
- expandedTime = XGMTIME(&then, tmpTime);
- if (expandedTime == NULL) {
- WOLFSSL_MSG("XGMTIME failed");
- ret = DATE_E;
- }
- }
- if (ret == 0) {
- localTime = *expandedTime;
- /* adjust */
- localTime.tm_year += 1900;
- localTime.tm_mon += 1;
- SetTime(&localTime, after);
- }
- return ret;
- #else
- (void)before;
- (void)after;
- (void)daysValid;
- return NOT_COMPILED_IN;
- #endif
- }
- #endif /* WOLFSSL_ASN_TEMPLATE */
- #ifndef WOLFSSL_ASN_TEMPLATE
- /* encode info from cert into DER encoded format */
- static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey,
- WC_RNG* rng, DsaKey* dsaKey, ed25519_key* ed25519Key,
- ed448_key* ed448Key, falcon_key* falconKey,
- dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
- {
- int ret;
- if (cert == NULL || der == NULL || rng == NULL)
- return BAD_FUNC_ARG;
- /* make sure at least one key type is provided */
- if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
- dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
- dilithiumKey == NULL && sphincsKey == NULL) {
- return PUBLIC_KEY_E;
- }
- /* init */
- XMEMSET(der, 0, sizeof(DerCert));
- /* version */
- der->versionSz = SetMyVersion((word32)cert->version, der->version, TRUE);
- /* serial number (must be positive) */
- if (cert->serialSz == 0) {
- /* generate random serial */
- cert->serialSz = CTC_GEN_SERIAL_SZ;
- ret = wc_RNG_GenerateBlock(rng, cert->serial, (word32)cert->serialSz);
- if (ret != 0)
- return ret;
- /* Clear the top bit to avoid a negative value */
- cert->serial[0] &= 0x7f;
- }
- der->serialSz = SetSerialNumber(cert->serial, (word32)cert->serialSz,
- der->serial, sizeof(der->serial),
- CTC_SERIAL_SIZE);
- if (der->serialSz < 0)
- return der->serialSz;
- /* signature algo */
- der->sigAlgoSz = (int)SetAlgoID(cert->sigType, der->sigAlgo, oidSigType, 0);
- if (der->sigAlgoSz <= 0)
- return ALGO_ID_E;
- /* public key */
- #ifndef NO_RSA
- if (cert->keyType == RSA_KEY) {
- if (rsaKey == NULL)
- return PUBLIC_KEY_E;
- der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
- sizeof(der->publicKey), 1);
- }
- #endif
- #ifdef HAVE_ECC
- if (cert->keyType == ECC_KEY) {
- if (eccKey == NULL)
- return PUBLIC_KEY_E;
- der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
- sizeof(der->publicKey), 1, 0);
- }
- #endif
- #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
- if (cert->keyType == DSA_KEY) {
- if (dsaKey == NULL)
- return PUBLIC_KEY_E;
- der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
- sizeof(der->publicKey), 1);
- }
- #endif
- #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
- if (cert->keyType == ED25519_KEY) {
- if (ed25519Key == NULL)
- return PUBLIC_KEY_E;
- der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
- (word32)sizeof(der->publicKey), 1);
- }
- #endif
- #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
- if (cert->keyType == ED448_KEY) {
- if (ed448Key == NULL)
- return PUBLIC_KEY_E;
- der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
- (word32)sizeof(der->publicKey), 1);
- }
- #endif
- #if defined(HAVE_PQC)
- #if defined(HAVE_FALCON)
- if ((cert->keyType == FALCON_LEVEL1_KEY) ||
- (cert->keyType == FALCON_LEVEL5_KEY)) {
- if (falconKey == NULL)
- return PUBLIC_KEY_E;
- der->publicKeySz =
- wc_Falcon_PublicKeyToDer(falconKey, der->publicKey,
- (word32)sizeof(der->publicKey), 1);
- }
- #endif /* HAVE_FALCON */
- #if defined(HAVE_DILITHIUM)
- if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
- (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
- (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
- if (dilithiumKey == NULL)
- return PUBLIC_KEY_E;
- der->publicKeySz =
- wc_Dilithium_PublicKeyToDer(dilithiumKey, der->publicKey,
- (word32)sizeof(der->publicKey), 1);
- }
- #endif /* HAVE_DILITHIUM */
- #if defined(HAVE_SPHINCS)
- if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
- (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
- (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
- (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
- (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
- (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
- if (sphincsKey == NULL)
- return PUBLIC_KEY_E;
- der->publicKeySz =
- wc_Sphincs_PublicKeyToDer(sphincsKey, der->publicKey,
- (word32)sizeof(der->publicKey), 1);
- }
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- if (der->publicKeySz <= 0)
- return PUBLIC_KEY_E;
- der->validitySz = 0;
- /* copy date validity if already set in cert struct */
- if (cert->beforeDateSz && cert->afterDateSz) {
- der->validitySz = CopyValidity(der->validity, cert);
- if (der->validitySz <= 0)
- return DATE_E;
- }
- /* set date validity using daysValid if not set already */
- if (der->validitySz == 0) {
- der->validitySz = SetValidity(der->validity, cert->daysValid);
- if (der->validitySz <= 0)
- return DATE_E;
- }
- /* subject name */
- #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
- if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
- /* Use the raw subject */
- word32 idx;
- der->subjectSz = (int)min((word32)sizeof(der->subject),
- (word32)XSTRLEN((const char*)cert->sbjRaw));
- /* header */
- idx = SetSequence((word32)der->subjectSz, der->subject);
- if ((word32)der->subjectSz + idx > (word32)sizeof(der->subject)) {
- return SUBJECT_E;
- }
- XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
- (size_t)der->subjectSz);
- der->subjectSz += (int)idx;
- }
- else
- #endif
- {
- /* Use the name structure */
- der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
- &cert->subject, cert->heap);
- }
- if (der->subjectSz <= 0)
- return SUBJECT_E;
- /* issuer name */
- #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
- if (XSTRLEN((const char*)cert->issRaw) > 0) {
- /* Use the raw issuer */
- word32 idx;
- der->issuerSz = (int)min((word32)sizeof(der->issuer),
- (word32)XSTRLEN((const char*)cert->issRaw));
- /* header */
- idx = SetSequence((word32)der->issuerSz, der->issuer);
- if ((word32)der->issuerSz + idx > (word32)sizeof(der->issuer)) {
- return ISSUER_E;
- }
- XMEMCPY((char*)der->issuer + idx, (const char*)cert->issRaw,
- (size_t)der->issuerSz);
- der->issuerSz += (int)idx;
- }
- else
- #endif
- {
- /* Use the name structure */
- der->issuerSz = SetNameEx(der->issuer, sizeof(der->issuer),
- cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
- }
- if (der->issuerSz <= 0)
- return ISSUER_E;
- /* set the extensions */
- der->extensionsSz = 0;
- /* RFC 5280 : 4.2.1.9. Basic Constraints
- * The pathLenConstraint field is meaningful only if the CA boolean is
- * asserted and the key usage extension, if present, asserts the
- * keyCertSign bit */
- /* Set CA and path length */
- if ((cert->isCA) && (cert->pathLenSet)
- #ifdef WOLFSSL_CERT_EXT
- && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
- #endif
- ) {
- der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
- if (der->caSz <= 0)
- return CA_TRUE_E;
- der->extensionsSz += der->caSz;
- }
- /* Set CA */
- else if (cert->isCA) {
- der->caSz = SetCa(der->ca, sizeof(der->ca));
- if (der->caSz <= 0)
- return CA_TRUE_E;
- der->extensionsSz += der->caSz;
- }
- /* Set Basic Constraint */
- else if (cert->basicConstSet) {
- der->caSz = SetBC(der->ca, sizeof(der->ca));
- if (der->caSz <= 0)
- return EXTENSIONS_E;
- der->extensionsSz += der->caSz;
- }
- else
- der->caSz = 0;
- #ifdef WOLFSSL_ALT_NAMES
- /* Alternative Name */
- if (cert->altNamesSz) {
- der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
- cert->altNames, (word32)cert->altNamesSz,
- cert->altNamesCrit);
- if (der->altNamesSz <= 0)
- return ALT_NAME_E;
- der->extensionsSz += der->altNamesSz;
- }
- else
- der->altNamesSz = 0;
- #endif
- #ifdef WOLFSSL_CERT_EXT
- /* SKID */
- if (cert->skidSz) {
- /* check the provided SKID size */
- if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
- return SKID_E;
- /* Note: different skid buffers sizes for der (MAX_KID_SZ) and
- cert (CTC_MAX_SKID_SIZE). */
- der->skidSz = SetSKID(der->skid, sizeof(der->skid),
- cert->skid, (word32)cert->skidSz);
- if (der->skidSz <= 0)
- return SKID_E;
- der->extensionsSz += der->skidSz;
- }
- else
- der->skidSz = 0;
- /* AKID */
- if (cert->akidSz) {
- /* check the provided AKID size */
- if ((
- #ifdef WOLFSSL_AKID_NAME
- !cert->rawAkid &&
- #endif
- cert->akidSz > (int)min(CTC_MAX_AKID_SIZE, sizeof(der->akid)))
- #ifdef WOLFSSL_AKID_NAME
- || (cert->rawAkid && cert->akidSz > (int)sizeof(der->akid))
- #endif
- )
- return AKID_E;
- der->akidSz = SetAKID(der->akid, sizeof(der->akid), cert->akid,
- (word32)cert->akidSz,
- #ifdef WOLFSSL_AKID_NAME
- cert->rawAkid
- #else
- 0
- #endif
- );
- if (der->akidSz <= 0)
- return AKID_E;
- der->extensionsSz += der->akidSz;
- }
- else
- der->akidSz = 0;
- /* Key Usage */
- if (cert->keyUsage != 0){
- der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
- cert->keyUsage);
- if (der->keyUsageSz <= 0)
- return KEYUSAGE_E;
- der->extensionsSz += der->keyUsageSz;
- }
- else
- der->keyUsageSz = 0;
- /* Extended Key Usage */
- if (cert->extKeyUsage != 0){
- der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
- sizeof(der->extKeyUsage), cert->extKeyUsage);
- if (der->extKeyUsageSz <= 0)
- return EXTKEYUSAGE_E;
- der->extensionsSz += der->extKeyUsageSz;
- }
- else
- der->extKeyUsageSz = 0;
- #ifndef IGNORE_NETSCAPE_CERT_TYPE
- /* Netscape Certificate Type */
- if (cert->nsCertType != 0) {
- der->nsCertTypeSz = SetNsCertType(cert, der->nsCertType,
- sizeof(der->nsCertType), cert->nsCertType);
- if (der->nsCertTypeSz <= 0)
- return EXTENSIONS_E;
- der->extensionsSz += der->nsCertTypeSz;
- }
- else
- der->nsCertTypeSz = 0;
- #endif
- if (cert->crlInfoSz > 0) {
- der->crlInfoSz = SetCRLInfo(cert, der->crlInfo, sizeof(der->crlInfo),
- cert->crlInfo, cert->crlInfoSz);
- if (der->crlInfoSz <= 0)
- return EXTENSIONS_E;
- der->extensionsSz += der->crlInfoSz;
- }
- else
- der->crlInfoSz = 0;
- /* Certificate Policies */
- if (cert->certPoliciesNb != 0) {
- der->certPoliciesSz = SetCertificatePolicies(der->certPolicies,
- sizeof(der->certPolicies),
- cert->certPolicies,
- cert->certPoliciesNb,
- cert->heap);
- if (der->certPoliciesSz <= 0)
- return CERTPOLICIES_E;
- der->extensionsSz += der->certPoliciesSz;
- }
- else
- der->certPoliciesSz = 0;
- #endif /* WOLFSSL_CERT_EXT */
- /* put extensions */
- if (der->extensionsSz > 0) {
- /* put the start of extensions sequence (ID, Size) */
- der->extensionsSz = SetExtensionsHeader(der->extensions,
- sizeof(der->extensions),
- (word32)der->extensionsSz);
- if (der->extensionsSz <= 0)
- return EXTENSIONS_E;
- /* put CA */
- if (der->caSz) {
- ret = SetExtensions(der->extensions, sizeof(der->extensions),
- &der->extensionsSz,
- der->ca, der->caSz);
- if (ret == 0)
- return EXTENSIONS_E;
- }
- #ifdef WOLFSSL_ALT_NAMES
- /* put Alternative Names */
- if (der->altNamesSz) {
- ret = SetExtensions(der->extensions, sizeof(der->extensions),
- &der->extensionsSz,
- der->altNames, der->altNamesSz);
- if (ret <= 0)
- return EXTENSIONS_E;
- }
- #endif
- #ifdef WOLFSSL_CERT_EXT
- /* put SKID */
- if (der->skidSz) {
- ret = SetExtensions(der->extensions, sizeof(der->extensions),
- &der->extensionsSz,
- der->skid, der->skidSz);
- if (ret <= 0)
- return EXTENSIONS_E;
- }
- /* put AKID */
- if (der->akidSz) {
- ret = SetExtensions(der->extensions, sizeof(der->extensions),
- &der->extensionsSz,
- der->akid, der->akidSz);
- if (ret <= 0)
- return EXTENSIONS_E;
- }
- /* put CRL Distribution Points */
- if (der->crlInfoSz) {
- ret = SetExtensions(der->extensions, sizeof(der->extensions),
- &der->extensionsSz,
- der->crlInfo, der->crlInfoSz);
- if (ret <= 0)
- return EXTENSIONS_E;
- }
- /* put KeyUsage */
- if (der->keyUsageSz) {
- ret = SetExtensions(der->extensions, sizeof(der->extensions),
- &der->extensionsSz,
- der->keyUsage, der->keyUsageSz);
- if (ret <= 0)
- return EXTENSIONS_E;
- }
- /* put ExtendedKeyUsage */
- if (der->extKeyUsageSz) {
- ret = SetExtensions(der->extensions, sizeof(der->extensions),
- &der->extensionsSz,
- der->extKeyUsage, der->extKeyUsageSz);
- if (ret <= 0)
- return EXTENSIONS_E;
- }
- /* put Netscape Cert Type */
- #ifndef IGNORE_NETSCAPE_CERT_TYPE
- if (der->nsCertTypeSz) {
- ret = SetExtensions(der->extensions, sizeof(der->extensions),
- &der->extensionsSz,
- der->nsCertType, der->nsCertTypeSz);
- if (ret <= 0)
- return EXTENSIONS_E;
- }
- #endif
- /* put Certificate Policies */
- if (der->certPoliciesSz) {
- ret = SetExtensions(der->extensions, sizeof(der->extensions),
- &der->extensionsSz,
- der->certPolicies, der->certPoliciesSz);
- if (ret <= 0)
- return EXTENSIONS_E;
- }
- #endif /* WOLFSSL_CERT_EXT */
- }
- der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
- der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
- der->extensionsSz;
- return 0;
- }
- /* write DER encoded cert to buffer, size already checked */
- static int WriteCertBody(DerCert* der, byte* buf)
- {
- word32 idx;
- /* signed part header */
- idx = SetSequence((word32)der->total, buf);
- /* version */
- XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
- idx += (word32)der->versionSz;
- /* serial */
- XMEMCPY(buf + idx, der->serial, (size_t)der->serialSz);
- idx += (word32)der->serialSz;
- /* sig algo */
- XMEMCPY(buf + idx, der->sigAlgo, (size_t)der->sigAlgoSz);
- idx += (word32)der->sigAlgoSz;
- /* issuer */
- XMEMCPY(buf + idx, der->issuer, (size_t)der->issuerSz);
- idx += (word32)der->issuerSz;
- /* validity */
- XMEMCPY(buf + idx, der->validity, (size_t)der->validitySz);
- idx += (word32)der->validitySz;
- /* subject */
- XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
- idx += (word32)der->subjectSz;
- /* public key */
- XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
- idx += (word32)der->publicKeySz;
- if (der->extensionsSz) {
- /* extensions */
- XMEMCPY(buf + idx, der->extensions,
- min((word32)der->extensionsSz,
- (word32)sizeof(der->extensions)));
- idx += (word32)der->extensionsSz;
- }
- return (int)idx;
- }
- #endif /* !WOLFSSL_ASN_TEMPLATE */
- /* Make signature from buffer (sz), write to sig (sigSz) */
- static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz,
- byte* sig, word32 sigSz, RsaKey* rsaKey, ecc_key* eccKey,
- ed25519_key* ed25519Key, ed448_key* ed448Key, falcon_key* falconKey,
- dilithium_key* dilithiumKey, sphincs_key* sphincsKey, WC_RNG* rng,
- word32 sigAlgoType, void* heap)
- {
- int digestSz = 0, typeH = 0, ret = 0;
- (void)digestSz;
- (void)typeH;
- (void)buf;
- (void)sz;
- (void)sig;
- (void)sigSz;
- (void)rsaKey;
- (void)eccKey;
- (void)ed25519Key;
- (void)ed448Key;
- (void)falconKey;
- (void)dilithiumKey;
- (void)sphincsKey;
- (void)rng;
- (void)heap;
- switch (certSignCtx->state) {
- case CERTSIGN_STATE_BEGIN:
- case CERTSIGN_STATE_DIGEST:
- certSignCtx->state = CERTSIGN_STATE_DIGEST;
- certSignCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (certSignCtx->digest == NULL) {
- ret = MEMORY_E; goto exit_ms;
- }
- ret = HashForSignature(buf, sz, sigAlgoType, certSignCtx->digest,
- &typeH, &digestSz, 0);
- /* set next state, since WC_PENDING_E rentry for these are not "call again" */
- certSignCtx->state = CERTSIGN_STATE_ENCODE;
- if (ret != 0) {
- goto exit_ms;
- }
- FALL_THROUGH;
- case CERTSIGN_STATE_ENCODE:
- #ifndef NO_RSA
- if (rsaKey) {
- certSignCtx->encSig = (byte*)XMALLOC(MAX_DER_DIGEST_SZ, heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (certSignCtx->encSig == NULL) {
- ret = MEMORY_E; goto exit_ms;
- }
- /* signature */
- certSignCtx->encSigSz = (int)wc_EncodeSignature(certSignCtx->encSig,
- certSignCtx->digest, (word32)digestSz, typeH);
- }
- #endif /* !NO_RSA */
- FALL_THROUGH;
- case CERTSIGN_STATE_DO:
- certSignCtx->state = CERTSIGN_STATE_DO;
- ret = ALGO_ID_E; /* default to error */
- #ifndef NO_RSA
- if (rsaKey) {
- /* signature */
- ret = wc_RsaSSL_Sign(certSignCtx->encSig,
- (word32)certSignCtx->encSigSz,
- sig, sigSz, rsaKey, rng);
- }
- #endif /* !NO_RSA */
- #if defined(HAVE_ECC) && defined(HAVE_ECC_SIGN)
- if (!rsaKey && eccKey) {
- word32 outSz = sigSz;
- ret = wc_ecc_sign_hash(certSignCtx->digest, (word32)digestSz,
- sig, &outSz, rng, eccKey);
- if (ret == 0)
- ret = (int)outSz;
- }
- #endif /* HAVE_ECC && HAVE_ECC_SIGN */
- #if defined(HAVE_ED25519) && defined(HAVE_ED25519_SIGN)
- if (!rsaKey && !eccKey && ed25519Key) {
- word32 outSz = sigSz;
- ret = wc_ed25519_sign_msg(buf, sz, sig, &outSz, ed25519Key);
- if (ret == 0)
- ret = (int)outSz;
- }
- #endif /* HAVE_ED25519 && HAVE_ED25519_SIGN */
- #if defined(HAVE_ED448) && defined(HAVE_ED448_SIGN)
- if (!rsaKey && !eccKey && !ed25519Key && ed448Key) {
- word32 outSz = sigSz;
- ret = wc_ed448_sign_msg(buf, sz, sig, &outSz, ed448Key, NULL, 0);
- if (ret == 0)
- ret = (int)outSz;
- }
- #endif /* HAVE_ED448 && HAVE_ED448_SIGN */
- #if defined(HAVE_PQC)
- #if defined(HAVE_FALCON)
- if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && falconKey) {
- word32 outSz = sigSz;
- ret = wc_falcon_sign_msg(buf, sz, sig, &outSz, falconKey);
- if (ret == 0)
- ret = outSz;
- }
- #endif /* HAVE_FALCON */
- #if defined(HAVE_DILITHIUM)
- if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
- dilithiumKey) {
- word32 outSz = sigSz;
- ret = wc_dilithium_sign_msg(buf, sz, sig, &outSz, dilithiumKey);
- if (ret == 0)
- ret = outSz;
- }
- #endif /* HAVE_DILITHIUM */
- #if defined(HAVE_SPHINCS)
- if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
- !dilithiumKey && sphincsKey) {
- word32 outSz = sigSz;
- ret = wc_sphincs_sign_msg(buf, sz, sig, &outSz, sphincsKey);
- if (ret == 0)
- ret = outSz;
- }
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- break;
- }
- exit_ms:
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (ret == WC_PENDING_E) {
- return ret;
- }
- #endif
- #ifndef NO_RSA
- if (rsaKey) {
- XFREE(certSignCtx->encSig, heap, DYNAMIC_TYPE_TMP_BUFFER);
- }
- #endif /* !NO_RSA */
- XFREE(certSignCtx->digest, heap, DYNAMIC_TYPE_TMP_BUFFER);
- certSignCtx->digest = NULL;
- /* reset state */
- certSignCtx->state = CERTSIGN_STATE_BEGIN;
- if (ret < 0) {
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- return ret;
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* Generate a random integer value of at most len bytes.
- *
- * Most-significant bit will not be set when maximum size.
- * Random value may be smaller than maximum size in bytes.
- *
- * @param [in] rng Random number generator.
- * @param [out] out Buffer to hold integer value.
- * @param [in] len Maximum number of bytes of integer.
- * @return 0 on success.
- * @return -ve when random number generation failed.
- */
- static int GenerateInteger(WC_RNG* rng, byte* out, word32 len)
- {
- int ret;
- /* Generate random number. */
- ret = wc_RNG_GenerateBlock(rng, out, len);
- if (ret == 0) {
- int i;
- /* Clear the top bit to make positive. */
- out[0] &= 0x7f;
- /* Find first non-zero byte. One zero byte is valid though. */
- for (i = 0; i < (int)len - 1; i++) {
- if (out[i] != 0) {
- break;
- }
- }
- if (i != 0) {
- /* Remove leading zeros. */
- XMEMMOVE(out, out + i, (size_t)len - (size_t)i);
- }
- }
- return ret;
- }
- /* ASN.1 template for a Certificate.
- * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
- */
- static const ASNItem sigASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* tbsCertificate */
- /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
- /* signatureAlgorithm */
- /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
- /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
- /* signatureValue */
- /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
- };
- enum {
- SIGASN_IDX_SEQ = 0,
- SIGASN_IDX_TBS_SEQ,
- SIGASN_IDX_SIGALGO_SEQ,
- SIGASN_IDX_SIGALGO_OID,
- SIGASN_IDX_SIGALGO_NULL,
- SIGASN_IDX_SIGNATURE
- };
- /* Number of items in ASN.1 template for a Certificate. */
- #define sigASN_Length (sizeof(sigASN) / sizeof(ASNItem))
- #endif
- /* add signature to end of buffer, size of buffer assumed checked, return
- new length */
- int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz,
- int sigAlgoType)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- byte seq[MAX_SEQ_SZ];
- word32 idx, seqSz;
- if ((bodySz < 0) || (sigSz < 0))
- return BUFFER_E;
- idx = (word32)bodySz;
- /* algo */
- idx += SetAlgoID(sigAlgoType, buf ? buf + idx : NULL, oidSigType, 0);
- /* bit string */
- idx += SetBitString((word32)sigSz, 0, buf ? buf + idx : NULL);
- /* signature */
- if (buf)
- XMEMCPY(buf + idx, sig, (size_t)sigSz);
- idx += (word32)sigSz;
- /* make room for overall header */
- seqSz = SetSequence(idx, seq);
- if (buf) {
- XMEMMOVE(buf + seqSz, buf, idx);
- XMEMCPY(buf, seq, seqSz);
- }
- return (int)(idx + seqSz);
- #else
- DECL_ASNSETDATA(dataASN, sigASN_Length);
- word32 seqSz;
- int sz;
- int ret = 0;
- CALLOC_ASNSETDATA(dataASN, sigASN_Length, ret, NULL);
- /* In place, put body between SEQUENCE and signature. */
- if (ret == 0) {
- /* Set sigature OID and signature data. */
- SetASN_OID(&dataASN[SIGASN_IDX_SIGALGO_OID], (word32)sigAlgoType,
- oidSigType);
- if (IsSigAlgoECC((word32)sigAlgoType)) {
- /* ECDSA and EdDSA doesn't have NULL tagged item. */
- dataASN[SIGASN_IDX_SIGALGO_NULL].noOut = 1;
- }
- SetASN_Buffer(&dataASN[SIGASN_IDX_SIGNATURE], sig, (word32)sigSz);
- /* Calculate size of signature data. */
- ret = SizeASN_Items(&sigASN[SIGASN_IDX_SIGALGO_SEQ],
- &dataASN[SIGASN_IDX_SIGALGO_SEQ], sigASN_Length - 2, &sz);
- }
- if (ret == 0) {
- /* Calculate size of outer sequence by calculating size of the encoded
- * length and adding 1 for tag. */
- seqSz = SizeASNHeader((word32)bodySz + (word32)sz);
- if (buf != NULL) {
- /* Move body to after sequence. */
- XMEMMOVE(buf + seqSz, buf, (size_t)bodySz);
- }
- /* Leave space for body in encoding. */
- SetASN_ReplaceBuffer(&dataASN[SIGASN_IDX_TBS_SEQ], NULL,
- (word32)bodySz);
- /* Calculate overall size and put in offsets and lengths. */
- ret = SizeASN_Items(sigASN, dataASN, sigASN_Length, &sz);
- }
- if ((ret == 0) && (buf != NULL)) {
- /* Write SEQUENCE and signature around body. */
- SetASN_Items(sigASN, dataASN, sigASN_Length, buf);
- }
- if (ret == 0) {
- /* Return the encoding size. */
- ret = sz;
- }
- FREE_ASNSETDATA(dataASN, NULL);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
- static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
- RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng,
- DsaKey* dsaKey, ed25519_key* ed25519Key,
- ed448_key* ed448Key, falcon_key* falconKey,
- dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret;
- #ifdef WOLFSSL_SMALL_STACK
- DerCert* der;
- #else
- DerCert der[1];
- #endif
- if (derBuffer == NULL)
- return BAD_FUNC_ARG;
- if (eccKey)
- cert->keyType = ECC_KEY;
- else if (rsaKey)
- cert->keyType = RSA_KEY;
- else if (dsaKey)
- cert->keyType = DSA_KEY;
- else if (ed25519Key)
- cert->keyType = ED25519_KEY;
- else if (ed448Key)
- cert->keyType = ED448_KEY;
- #ifdef HAVE_PQC
- #ifdef HAVE_FALCON
- else if ((falconKey != NULL) && (falconKey->level == 1))
- cert->keyType = FALCON_LEVEL1_KEY;
- else if ((falconKey != NULL) && (falconKey->level == 5))
- cert->keyType = FALCON_LEVEL5_KEY;
- #endif /* HAVE_FALCON */
- #ifdef HAVE_DILITHIUM
- else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
- cert->keyType = DILITHIUM_LEVEL2_KEY;
- else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
- cert->keyType = DILITHIUM_LEVEL3_KEY;
- else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
- cert->keyType = DILITHIUM_LEVEL5_KEY;
- #endif /* HAVE_DILITHIUM */
- #ifdef HAVE_SPHINCS
- else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
- && (sphincsKey->optim == FAST_VARIANT))
- cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
- else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
- && (sphincsKey->optim == FAST_VARIANT))
- cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
- else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
- && (sphincsKey->optim == FAST_VARIANT))
- cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
- else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
- && (sphincsKey->optim == SMALL_VARIANT))
- cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
- else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
- && (sphincsKey->optim == SMALL_VARIANT))
- cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
- else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
- && (sphincsKey->optim == SMALL_VARIANT))
- cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- else
- return BAD_FUNC_ARG;
- #ifdef WOLFSSL_SMALL_STACK
- der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (der == NULL)
- return MEMORY_E;
- #endif
- ret = EncodeCert(cert, der, rsaKey, eccKey, rng, dsaKey, ed25519Key,
- ed448Key, falconKey, dilithiumKey, sphincsKey);
- if (ret == 0) {
- if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
- ret = BUFFER_E;
- else
- ret = cert->bodySz = WriteCertBody(der, derBuffer);
- }
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return ret;
- #else
- /* TODO: issRaw and sbjRaw should be NUL terminated. */
- DECL_ASNSETDATA(dataASN, x509CertASN_Length);
- word32 publicKeySz = 0;
- word32 issuerSz = 0;
- word32 subjectSz = 0;
- word32 extSz = 0;
- int sz = 0;
- int ret = 0;
- word32 issRawLen = 0;
- word32 sbjRawLen = 0;
- /* Unused without OQS */
- (void)falconKey;
- (void)dilithiumKey;
- (void)sphincsKey;
- CALLOC_ASNSETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
- if (ret == 0) {
- /* Set key type into certificate object based on key passed in. */
- if (rsaKey) {
- cert->keyType = RSA_KEY;
- }
- else if (eccKey) {
- cert->keyType = ECC_KEY;
- }
- else if (dsaKey) {
- cert->keyType = DSA_KEY;
- }
- else if (ed25519Key) {
- cert->keyType = ED25519_KEY;
- }
- else if (ed448Key) {
- cert->keyType = ED448_KEY;
- }
- #ifdef HAVE_PQC
- #ifdef HAVE_FALCON
- else if ((falconKey != NULL) && (falconKey->level == 1)) {
- cert->keyType = FALCON_LEVEL1_KEY;
- }
- else if ((falconKey != NULL) && (falconKey->level == 5)) {
- cert->keyType = FALCON_LEVEL5_KEY;
- }
- #endif /* HAVE_FALCON */
- #ifdef HAVE_DILITHIUM
- else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
- cert->keyType = DILITHIUM_LEVEL2_KEY;
- }
- else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
- cert->keyType = DILITHIUM_LEVEL3_KEY;
- }
- else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
- cert->keyType = DILITHIUM_LEVEL5_KEY;
- }
- #endif /* HAVE_DILITHIUM */
- #ifdef HAVE_SPHINCS
- else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
- && (sphincsKey->optim == FAST_VARIANT)) {
- cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
- }
- else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
- && (sphincsKey->optim == FAST_VARIANT)) {
- cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
- }
- else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
- && (sphincsKey->optim == FAST_VARIANT)) {
- cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
- }
- else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
- && (sphincsKey->optim == SMALL_VARIANT)) {
- cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
- }
- else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
- && (sphincsKey->optim == SMALL_VARIANT)) {
- cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
- }
- else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
- && (sphincsKey->optim == SMALL_VARIANT)) {
- cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
- }
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- else {
- ret = BAD_FUNC_ARG;
- }
- }
- if ((ret == 0) && (cert->serialSz == 0)) {
- /* Generate random serial number. */
- cert->serialSz = CTC_GEN_SERIAL_SZ;
- ret = GenerateInteger(rng, cert->serial, CTC_GEN_SERIAL_SZ);
- }
- if (ret == 0) {
- /* Determine issuer name size. */
- #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
- defined(WOLFSSL_CERT_REQ)
- issRawLen = (word32)XSTRLEN((const char*)cert->issRaw);
- if (issRawLen > 0) {
- issuerSz = min(sizeof(cert->issRaw), issRawLen);
- }
- else
- #endif
- {
- /* Calculate issuer name encoding size. If the cert is self-signed
- * use the subject instead of the issuer. */
- ret = SetNameEx(NULL, WC_ASN_NAME_MAX, cert->selfSigned ?
- &cert->subject : &cert->issuer, cert->heap);
- issuerSz = (word32)ret;
- }
- }
- if (ret >= 0) {
- /* Determine subject name size. */
- #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
- defined(WOLFSSL_CERT_REQ)
- sbjRawLen = (word32)XSTRLEN((const char*)cert->sbjRaw);
- if (sbjRawLen > 0) {
- subjectSz = min(sizeof(cert->sbjRaw), sbjRawLen);
- }
- else
- #endif
- {
- /* Calculate subject name encoding size. */
- ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject,
- cert->heap);
- subjectSz = (word32)ret;
- }
- }
- if (ret >= 0) {
- /* Calculate public key encoding size. */
- ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
- eccKey, ed25519Key, ed448Key, dsaKey);
- publicKeySz = (word32)ret;
- }
- if (ret >= 0) {
- /* Calculate extensions encoding size - may be 0. */
- ret = EncodeExtensions(cert, NULL, 0, 0);
- extSz = (word32)ret;
- }
- if (ret >= 0) {
- /* Don't write out outer sequence - only doing body. */
- dataASN[X509CERTASN_IDX_SEQ].noOut = 1;
- /* Set version, serial number and signature OID */
- SetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT],
- (byte)cert->version);
- SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
- (word32)cert->serialSz);
- SetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID],
- (word32)cert->sigType, oidSigType);
- if (IsSigAlgoECC((word32)cert->sigType)) {
- /* No NULL tagged item with ECDSA and EdDSA signature OIDs. */
- dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL].noOut = 1;
- }
- #ifdef WC_RSA_PSS
- /* TODO: Encode RSA PSS parameters. */
- dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].noOut = 1;
- #endif
- if (issRawLen > 0) {
- #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
- defined(WOLFSSL_CERT_REQ)
- /* Put in encoded issuer name. */
- SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
- cert->issRaw, issuerSz);
- #endif
- }
- else {
- /* Leave space for issuer name. */
- SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
- NULL, issuerSz);
- }
- if (cert->beforeDateSz && cert->afterDateSz) {
- if (cert->beforeDate[0] == ASN_UTC_TIME) {
- /* Make space for before date data. */
- SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC],
- cert->beforeDate + 2, ASN_UTC_TIME_SIZE - 1);
- /* Don't put out Generalized Time before data. */
- dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT].noOut = 1;
- }
- else {
- /* Don't put out UTC before data. */
- dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
- /* Make space for before date data. */
- SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
- cert->beforeDate + 2, ASN_GEN_TIME_SZ);
- }
- if (cert->afterDate[0] == ASN_UTC_TIME) {
- /* Make space for after date data. */
- SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC],
- cert->afterDate + 2, ASN_UTC_TIME_SIZE - 1);
- /* Don't put out UTC Generalized Time after data. */
- dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT].noOut = 1;
- }
- else {
- /* Don't put out UTC after data. */
- dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
- /* Make space for after date data. */
- SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
- cert->afterDate + 2, ASN_GEN_TIME_SZ);
- }
- }
- else
- {
- /* Don't put out UTC before data. */
- dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
- /* Make space for before date data. */
- SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
- NULL, ASN_GEN_TIME_SZ);
- /* Don't put out UTC after data. */
- dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
- /* Make space for after date data. */
- SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
- NULL, ASN_GEN_TIME_SZ);
- }
- if (sbjRawLen > 0) {
- /* Put in encoded subject name. */
- #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
- defined(WOLFSSL_CERT_REQ)
- SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
- cert->sbjRaw, subjectSz);
- #endif
- }
- else {
- /* Leave space for subject name. */
- SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
- NULL, subjectSz);
- }
- /* Leave space for public key. */
- SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ],
- NULL, publicKeySz);
- /* Replacement buffer instead of algorithm identifier items. */
- SetASNItem_NoOut(dataASN,
- X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
- X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY);
- /* issuerUniqueID and subjectUniqueID not supported. */
- dataASN[X509CERTASN_IDX_TBS_ISSUERUID].noOut = 1;
- dataASN[X509CERTASN_IDX_TBS_SUBJECTUID].noOut = 1;
- /* Leave space for extensions if any set into certificate object. */
- if (extSz > 0) {
- SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_EXT_SEQ], NULL, extSz);
- }
- else {
- SetASNItem_NoOutNode(dataASN, x509CertASN,
- X509CERTASN_IDX_TBS_EXT, x509CertASN_Length);
- }
- /* No signature - added later. */
- SetASNItem_NoOut(dataASN, X509CERTASN_IDX_SIGALGO_SEQ,
- X509CERTASN_IDX_SIGNATURE);
- /* Calculate encoded certificate body size. */
- ret = SizeASN_Items(x509CertASN, dataASN, x509CertASN_Length, &sz);
- }
- /* Check buffer is big enough for encoded data. */
- if ((ret == 0) && (sz > (int)derSz)) {
- ret = BUFFER_E;
- }
- if (ret == 0) {
- /* Encode certificate body into buffer. */
- SetASN_Items(x509CertASN, dataASN, x509CertASN_Length, derBuffer);
- if (issRawLen == 0) {
- /* Encode issuer name into buffer. Use the subject as the issuer
- * if it is self-signed. Size will be correct because we did the
- * same for size. */
- ret = SetNameEx(
- (byte*)dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.data,
- dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.length,
- cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
- }
- }
- if ((ret >= 0) && (sbjRawLen == 0)) {
- /* Encode subject name into buffer. */
- ret = SetNameEx(
- (byte*)dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.data,
- dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.length,
- &cert->subject, cert->heap);
- }
- if (ret >= 0) {
- if (cert->beforeDateSz == 0 || cert->afterDateSz == 0)
- {
- /* Encode validity into buffer. */
- ret = SetValidity(
- (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT]
- .data.buffer.data,
- (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT]
- .data.buffer.data, cert->daysValid);
- }
- }
- if (ret >= 0) {
- /* Encode public key into buffer. */
- ret = EncodePublicKey(cert->keyType,
- (byte*)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
- .data.buffer.data,
- (int)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
- .data.buffer.length,
- rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
- }
- if ((ret >= 0) && (!dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].noOut)) {
- /* Encode extensions into buffer. */
- ret = EncodeExtensions(cert,
- (byte*)dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.data,
- dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.length, 0);
- }
- if (ret >= 0) {
- /* Store encoded certifcate body size. */
- cert->bodySz = sz;
- /* Return the encoding size. */
- ret = sz;
- }
- FREE_ASNSETDATA(dataASN, cert->heap);
- return ret;
- #endif
- }
- /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
- int wc_MakeCert_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
- void* key, WC_RNG* rng)
- {
- RsaKey* rsaKey = NULL;
- DsaKey* dsaKey = NULL;
- ecc_key* eccKey = NULL;
- ed25519_key* ed25519Key = NULL;
- ed448_key* ed448Key = NULL;
- falcon_key* falconKey = NULL;
- dilithium_key* dilithiumKey = NULL;
- sphincs_key* sphincsKey = NULL;
- if (keyType == RSA_TYPE)
- rsaKey = (RsaKey*)key;
- else if (keyType == DSA_TYPE)
- dsaKey = (DsaKey*)key;
- else if (keyType == ECC_TYPE)
- eccKey = (ecc_key*)key;
- else if (keyType == ED25519_TYPE)
- ed25519Key = (ed25519_key*)key;
- else if (keyType == ED448_TYPE)
- ed448Key = (ed448_key*)key;
- else if (keyType == FALCON_LEVEL1_TYPE)
- falconKey = (falcon_key*)key;
- else if (keyType == FALCON_LEVEL5_TYPE)
- falconKey = (falcon_key*)key;
- else if (keyType == DILITHIUM_LEVEL2_TYPE)
- dilithiumKey = (dilithium_key*)key;
- else if (keyType == DILITHIUM_LEVEL3_TYPE)
- dilithiumKey = (dilithium_key*)key;
- else if (keyType == DILITHIUM_LEVEL5_TYPE)
- dilithiumKey = (dilithium_key*)key;
- else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
- sphincsKey = (sphincs_key*)key;
- return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, dsaKey,
- ed25519Key, ed448Key, falconKey, dilithiumKey,
- sphincsKey);
- }
- /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
- WOLFSSL_ABI
- int wc_MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,
- ecc_key* eccKey, WC_RNG* rng)
- {
- return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, NULL,
- NULL, NULL, NULL, NULL);
- }
- #ifdef WOLFSSL_CERT_REQ
- #ifndef WOLFSSL_ASN_TEMPLATE
- /* return size of data set on success
- * if getting size only then attr and oid should be NULL
- */
- static word32 SetReqAttribSingle(byte* output, word32* idx, char* attr,
- word32 attrSz, const byte* oid, word32 oidSz, byte printable,
- word32 extSz)
- {
- word32 totalSz = 0;
- word32 seqSz = 0;
- word32 setSz = 0;
- word32 strSz = 0;
- byte seq[MAX_SEQ_SZ];
- byte set[MAX_SET_SZ];
- byte str[MAX_PRSTR_SZ];
- totalSz = (word32)SetObjectId((int)oidSz, NULL);
- totalSz += oidSz;
- if (extSz > 0) {
- totalSz += setSz = SetSet(extSz, set);
- totalSz += seqSz = SetSequence(totalSz + extSz, seq);
- totalSz += extSz;
- }
- else {
- if (printable) {
- strSz = SetPrintableString(attrSz, str);
- totalSz += strSz;
- }
- else {
- totalSz += strSz = SetUTF8String(attrSz, str);
- }
- totalSz += setSz = SetSet(strSz + attrSz, set);
- totalSz += seqSz = SetSequence(totalSz + attrSz, seq);
- totalSz += attrSz;
- }
- if (oid) {
- XMEMCPY(&output[*idx], seq, seqSz);
- *idx += seqSz;
- *idx += (word32)SetObjectId((int)oidSz, output + *idx);
- XMEMCPY(&output[*idx], oid, oidSz);
- *idx += oidSz;
- XMEMCPY(&output[*idx], set, setSz);
- *idx += setSz;
- if (strSz > 0) {
- XMEMCPY(&output[*idx], str, strSz);
- *idx += strSz;
- if (attrSz > 0) {
- XMEMCPY(&output[*idx], attr, attrSz);
- *idx += attrSz;
- }
- }
- }
- return totalSz;
- }
- static int SetReqAttrib(byte* output, Cert* cert, word32 extSz)
- {
- word32 sz = 0; /* overall size */
- word32 setSz = 0;
- output[0] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
- sz++;
- if (cert->challengePw[0]) {
- setSz += SetReqAttribSingle(output, &sz, NULL,
- (word32)XSTRLEN(cert->challengePw), NULL,
- sizeof(attrChallengePasswordOid),
- (byte)cert->challengePwPrintableString, 0);
- }
- if (cert->unstructuredName[0]) {
- setSz += SetReqAttribSingle(output, &sz, NULL,
- (word32)XSTRLEN(cert->unstructuredName), NULL,
- sizeof(attrUnstructuredNameOid), 1, 0);
- }
- if (extSz) {
- setSz += SetReqAttribSingle(output, &sz, NULL, 0, NULL,
- sizeof(attrExtensionRequestOid), 1, extSz);
- }
- /* Put the pieces together. */
- sz += SetLength(setSz, &output[sz]);
- if (sz + setSz - extSz > MAX_ATTRIB_SZ) {
- WOLFSSL_MSG("Attribute Buffer is not big enough!");
- return REQ_ATTRIBUTE_E;
- }
- if (cert->challengePw[0]) {
- SetReqAttribSingle(output, &sz, cert->challengePw,
- (word32)XSTRLEN(cert->challengePw),
- &attrChallengePasswordOid[0],
- sizeof(attrChallengePasswordOid),
- (byte)cert->challengePwPrintableString, 0);
- }
- if (cert->unstructuredName[0]) {
- SetReqAttribSingle(output, &sz, cert->unstructuredName,
- (word32)XSTRLEN(cert->unstructuredName),
- &attrUnstructuredNameOid[0],
- sizeof(attrUnstructuredNameOid), 1, 0);
- }
- if (extSz) {
- SetReqAttribSingle(output, &sz, NULL, 0, &attrExtensionRequestOid[0],
- sizeof(attrExtensionRequestOid), 1, extSz);
- /* The actual extension data will be tacked onto the output later. */
- }
- return (int)sz;
- }
- #ifdef WOLFSSL_CUSTOM_OID
- /* encode a custom oid and value */
- static int SetCustomObjectId(Cert* cert, byte* output, word32 outSz,
- CertOidField* custom)
- {
- int idx = 0, cust_lenSz, cust_oidSz;
- if (cert == NULL || output == NULL || custom == NULL) {
- return BAD_FUNC_ARG;
- }
- if (custom->oid == NULL || custom->oidSz <= 0) {
- return 0; /* none set */
- }
- /* Octet String header */
- cust_lenSz = SetOctetString(custom->valSz, NULL);
- cust_oidSz = SetObjectId(custom->oidSz, NULL);
- /* check for output buffer room */
- if ((word32)(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz) >
- outSz) {
- return BUFFER_E;
- }
- /* put sequence with total */
- idx = SetSequence(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz,
- output);
- /* put oid header */
- idx += SetObjectId(custom->oidSz, output+idx);
- XMEMCPY(output+idx, custom->oid, custom->oidSz);
- idx += custom->oidSz;
- /* put value */
- idx += SetOctetString(custom->valSz, output+idx);
- XMEMCPY(output+idx, custom->val, custom->valSz);
- idx += custom->valSz;
- return idx;
- }
- #endif /* WOLFSSL_CUSTOM_OID */
- /* encode info from cert into DER encoded format */
- static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey,
- DsaKey* dsaKey, ecc_key* eccKey,
- ed25519_key* ed25519Key, ed448_key* ed448Key,
- falcon_key* falconKey, dilithium_key* dilithiumKey,
- sphincs_key* sphincsKey)
- {
- int ret;
- (void)eccKey;
- (void)ed25519Key;
- (void)ed448Key;
- (void)falconKey;
- (void)dilithiumKey;
- (void)sphincsKey;
- if (cert == NULL || der == NULL)
- return BAD_FUNC_ARG;
- if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
- dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
- falconKey == NULL) {
- return PUBLIC_KEY_E;
- }
- /* init */
- XMEMSET(der, 0, sizeof(DerCert));
- /* version */
- der->versionSz = SetMyVersion((word32)cert->version, der->version, FALSE);
- /* subject name */
- #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
- if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
- /* Use the raw subject */
- int idx;
- der->subjectSz = (int)min(sizeof(der->subject),
- (word32)XSTRLEN((const char*)cert->sbjRaw));
- /* header */
- idx = (int)SetSequence((word32)der->subjectSz, der->subject);
- if (der->subjectSz + idx > (int)sizeof(der->subject)) {
- return SUBJECT_E;
- }
- XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
- (size_t)der->subjectSz);
- der->subjectSz += idx;
- }
- else
- #endif
- {
- der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
- &cert->subject, cert->heap);
- }
- if (der->subjectSz <= 0)
- return SUBJECT_E;
- /* public key */
- #ifndef NO_RSA
- if (cert->keyType == RSA_KEY) {
- if (rsaKey == NULL)
- return PUBLIC_KEY_E;
- der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
- sizeof(der->publicKey), 1);
- }
- #endif
- #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
- if (cert->keyType == DSA_KEY) {
- if (dsaKey == NULL)
- return PUBLIC_KEY_E;
- der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
- sizeof(der->publicKey), 1);
- }
- #endif
- #ifdef HAVE_ECC
- if (cert->keyType == ECC_KEY) {
- if (eccKey == NULL)
- return PUBLIC_KEY_E;
- der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
- sizeof(der->publicKey), 1, 0);
- }
- #endif
- #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
- if (cert->keyType == ED25519_KEY) {
- if (ed25519Key == NULL)
- return PUBLIC_KEY_E;
- der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
- (word32)sizeof(der->publicKey), 1);
- }
- #endif
- #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
- if (cert->keyType == ED448_KEY) {
- if (ed448Key == NULL)
- return PUBLIC_KEY_E;
- der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
- (word32)sizeof(der->publicKey), 1);
- }
- #endif
- #if defined(HAVE_PQC)
- #if defined(HAVE_FALCON)
- if ((cert->keyType == FALCON_LEVEL1_KEY) ||
- (cert->keyType == FALCON_LEVEL5_KEY)) {
- if (falconKey == NULL)
- return PUBLIC_KEY_E;
- der->publicKeySz = wc_Falcon_PublicKeyToDer(falconKey,
- der->publicKey, (word32)sizeof(der->publicKey), 1);
- }
- #endif
- #if defined(HAVE_DILITHIUM)
- if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
- (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
- (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
- if (dilithiumKey == NULL)
- return PUBLIC_KEY_E;
- der->publicKeySz = wc_Dilithium_PublicKeyToDer(dilithiumKey,
- der->publicKey, (word32)sizeof(der->publicKey), 1);
- }
- #endif
- #if defined(HAVE_SPHINCS)
- if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
- (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
- (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
- (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
- (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
- (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
- if (sphincsKey == NULL)
- return PUBLIC_KEY_E;
- der->publicKeySz = wc_Sphincs_PublicKeyToDer(sphincsKey,
- der->publicKey, (word32)sizeof(der->publicKey), 1);
- }
- #endif
- #endif /* HAVE_PQC */
- if (der->publicKeySz <= 0)
- return PUBLIC_KEY_E;
- /* set the extensions */
- der->extensionsSz = 0;
- /* RFC 5280 : 4.2.1.9. Basic Constraints
- * The pathLenConstraint field is meaningful only if the CA boolean is
- * asserted and the key usage extension, if present, asserts the
- * keyCertSign bit */
- /* Set CA and path length */
- if ((cert->isCA) && (cert->pathLenSet)
- #ifdef WOLFSSL_CERT_EXT
- && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
- #endif
- ) {
- der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
- if (der->caSz <= 0)
- return CA_TRUE_E;
- der->extensionsSz += der->caSz;
- }
- /* Set CA */
- else if (cert->isCA) {
- der->caSz = SetCa(der->ca, sizeof(der->ca));
- if (der->caSz <= 0)
- return CA_TRUE_E;
- der->extensionsSz += der->caSz;
- }
- /* Set Basic Constraint */
- else if (cert->basicConstSet) {
- der->caSz = SetBC(der->ca, sizeof(der->ca));
- if (der->caSz <= 0)
- return EXTENSIONS_E;
- der->extensionsSz += der->caSz;
- }
- else
- der->caSz = 0;
- #ifdef WOLFSSL_ALT_NAMES
- /* Alternative Name */
- if (cert->altNamesSz) {
- der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
- cert->altNames, (word32)cert->altNamesSz,
- cert->altNamesCrit);
- if (der->altNamesSz <= 0)
- return ALT_NAME_E;
- der->extensionsSz += der->altNamesSz;
- }
- else
- der->altNamesSz = 0;
- #endif
- #ifdef WOLFSSL_CERT_EXT
- /* SKID */
- if (cert->skidSz) {
- /* check the provided SKID size */
- if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
- return SKID_E;
- der->skidSz = SetSKID(der->skid, sizeof(der->skid),
- cert->skid, (word32)cert->skidSz);
- if (der->skidSz <= 0)
- return SKID_E;
- der->extensionsSz += der->skidSz;
- }
- else
- der->skidSz = 0;
- /* Key Usage */
- if (cert->keyUsage != 0) {
- der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
- cert->keyUsage);
- if (der->keyUsageSz <= 0)
- return KEYUSAGE_E;
- der->extensionsSz += der->keyUsageSz;
- }
- else
- der->keyUsageSz = 0;
- /* Extended Key Usage */
- if (cert->extKeyUsage != 0) {
- der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
- sizeof(der->extKeyUsage), cert->extKeyUsage);
- if (der->extKeyUsageSz <= 0)
- return EXTKEYUSAGE_E;
- der->extensionsSz += der->extKeyUsageSz;
- }
- else
- der->extKeyUsageSz = 0;
- #endif /* WOLFSSL_CERT_EXT */
- #ifdef WOLFSSL_CUSTOM_OID
- /* encode a custom oid and value */
- /* zero returns, means none set */
- ret = SetCustomObjectId(cert, der->extCustom,
- sizeof(der->extCustom), &cert->extCustom);
- if (ret < 0)
- return ret;
- der->extCustomSz = ret;
- der->extensionsSz += der->extCustomSz;
- #endif
- /* put extensions */
- if (der->extensionsSz > 0) {
- /* put the start of sequence (ID, Size) */
- der->extensionsSz = (int)SetSequence((word32)der->extensionsSz,
- der->extensions);
- if (der->extensionsSz <= 0)
- return EXTENSIONS_E;
- /* put CA */
- if (der->caSz) {
- ret = SetExtensions(der->extensions, sizeof(der->extensions),
- &der->extensionsSz,
- der->ca, der->caSz);
- if (ret <= 0)
- return EXTENSIONS_E;
- }
- #ifdef WOLFSSL_ALT_NAMES
- /* put Alternative Names */
- if (der->altNamesSz) {
- ret = SetExtensions(der->extensions, sizeof(der->extensions),
- &der->extensionsSz,
- der->altNames, der->altNamesSz);
- if (ret <= 0)
- return EXTENSIONS_E;
- }
- #endif
- #ifdef WOLFSSL_CERT_EXT
- /* put SKID */
- if (der->skidSz) {
- ret = SetExtensions(der->extensions, sizeof(der->extensions),
- &der->extensionsSz,
- der->skid, der->skidSz);
- if (ret <= 0)
- return EXTENSIONS_E;
- }
- /* put AKID */
- if (der->akidSz) {
- ret = SetExtensions(der->extensions, sizeof(der->extensions),
- &der->extensionsSz,
- der->akid, der->akidSz);
- if (ret <= 0)
- return EXTENSIONS_E;
- }
- /* put KeyUsage */
- if (der->keyUsageSz) {
- ret = SetExtensions(der->extensions, sizeof(der->extensions),
- &der->extensionsSz,
- der->keyUsage, der->keyUsageSz);
- if (ret <= 0)
- return EXTENSIONS_E;
- }
- /* put ExtendedKeyUsage */
- if (der->extKeyUsageSz) {
- ret = SetExtensions(der->extensions, sizeof(der->extensions),
- &der->extensionsSz,
- der->extKeyUsage, der->extKeyUsageSz);
- if (ret <= 0)
- return EXTENSIONS_E;
- }
- #ifdef WOLFSSL_CUSTOM_OID
- if (der->extCustomSz) {
- ret = SetExtensions(der->extensions, sizeof(der->extensions),
- &der->extensionsSz,
- der->extCustom, der->extCustomSz);
- if (ret <= 0)
- return EXTENSIONS_E;
- }
- #endif
- #endif /* WOLFSSL_CERT_EXT */
- }
- der->attribSz = SetReqAttrib(der->attrib, cert, (word32)der->extensionsSz);
- if (der->attribSz <= 0)
- return REQ_ATTRIBUTE_E;
- der->total = der->versionSz + der->subjectSz + der->publicKeySz +
- der->extensionsSz + der->attribSz;
- return 0;
- }
- /* write DER encoded cert req to buffer, size already checked */
- static int WriteCertReqBody(DerCert* der, byte* buf)
- {
- int idx;
- /* signed part header */
- idx = (int)SetSequence((word32)der->total, buf);
- /* version */
- if (buf)
- XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
- idx += der->versionSz;
- /* subject */
- if (buf)
- XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
- idx += der->subjectSz;
- /* public key */
- if (buf)
- XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
- idx += der->publicKeySz;
- /* attributes */
- if (buf)
- XMEMCPY(buf + idx, der->attrib, (size_t)der->attribSz);
- idx += der->attribSz;
- /* extensions */
- if (der->extensionsSz) {
- if (buf)
- XMEMCPY(buf + idx, der->extensions, min((word32)der->extensionsSz,
- sizeof(der->extensions)));
- idx += der->extensionsSz;
- }
- return idx;
- }
- #endif
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for Certificate Request body.
- * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
- */
- static const ASNItem certReqBodyASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* version */
- /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* subject */
- /* SUBJ_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
- /* subjectPKInfo */
- /* SPUBKEYINFO_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
- /* attributes*/
- /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
- /* Challenge Password Attribute */
- /* ATTRS_CPW_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
- /* ATTRS_CPW_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
- /* ATTRS_CPW_SET */ { 3, ASN_SET, 1, 1, 0 },
- /* ATTRS_CPW_PS */ { 4, ASN_PRINTABLE_STRING, 0, 0, 0 },
- /* ATTRS_CPW_UTF */ { 4, ASN_UTF8STRING, 0, 0, 0 },
- /* Extensions Attribute */
- /* EXT_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
- /* EXT_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
- /* EXT_SET */ { 3, ASN_SET, 1, 1, 0 },
- /* EXT_BODY */ { 4, ASN_SEQUENCE, 1, 0, 0 },
- };
- enum {
- CERTREQBODYASN_IDX_SEQ = 0,
- CERTREQBODYASN_IDX_VER,
- CERTREQBODYASN_IDX_SUBJ_SEQ,
- CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ,
- CERTREQBODYASN_IDX_ATTRS,
- CERTREQBODYASN_IDX_ATTRS_CPW_SEQ,
- CERTREQBODYASN_IDX_ATTRS_CPW_OID,
- CERTREQBODYASN_IDX_ATTRS_CPW_SET,
- CERTREQBODYASN_IDX_ATTRS_CPW_PS,
- CERTREQBODYASN_IDX_ATTRS_CPW_UTF,
- CERTREQBODYASN_IDX_EXT_SEQ,
- CERTREQBODYASN_IDX_EXT_OID,
- CERTREQBODYASN_IDX_EXT_SET,
- CERTREQBODYASN_IDX_EXT_BODY
- };
- /* Number of items in ASN.1 template for Certificate Request body. */
- #define certReqBodyASN_Length (sizeof(certReqBodyASN) / sizeof(ASNItem))
- #endif
- static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
- RsaKey* rsaKey, DsaKey* dsaKey, ecc_key* eccKey,
- ed25519_key* ed25519Key, ed448_key* ed448Key,
- falcon_key* falconKey, dilithium_key* dilithiumKey,
- sphincs_key* sphincsKey)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret;
- #ifdef WOLFSSL_SMALL_STACK
- DerCert* der;
- #else
- DerCert der[1];
- #endif
- if (eccKey)
- cert->keyType = ECC_KEY;
- else if (rsaKey)
- cert->keyType = RSA_KEY;
- else if (dsaKey)
- cert->keyType = DSA_KEY;
- else if (ed25519Key)
- cert->keyType = ED25519_KEY;
- else if (ed448Key)
- cert->keyType = ED448_KEY;
- #ifdef HAVE_PQC
- #ifdef HAVE_FALCON
- else if ((falconKey != NULL) && (falconKey->level == 1))
- cert->keyType = FALCON_LEVEL1_KEY;
- else if ((falconKey != NULL) && (falconKey->level == 5))
- cert->keyType = FALCON_LEVEL5_KEY;
- #endif /* HAVE_FALCON */
- #ifdef HAVE_DILITHIUM
- else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
- cert->keyType = DILITHIUM_LEVEL2_KEY;
- else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
- cert->keyType = DILITHIUM_LEVEL3_KEY;
- else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
- cert->keyType = DILITHIUM_LEVEL5_KEY;
- #endif /* HAVE_DILITHIUM */
- #ifdef HAVE_SPHINCS
- else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
- && (sphincsKey->optim == FAST_VARIANT))
- cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
- else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
- && (sphincsKey->optim == FAST_VARIANT))
- cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
- else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
- && (sphincsKey->optim == FAST_VARIANT))
- cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
- else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
- && (sphincsKey->optim == SMALL_VARIANT))
- cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
- else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
- && (sphincsKey->optim == SMALL_VARIANT))
- cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
- else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
- && (sphincsKey->optim == SMALL_VARIANT))
- cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- else
- return BAD_FUNC_ARG;
- #ifdef WOLFSSL_SMALL_STACK
- der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (der == NULL)
- return MEMORY_E;
- #endif
- ret = EncodeCertReq(cert, der, rsaKey, dsaKey, eccKey, ed25519Key, ed448Key,
- falconKey, dilithiumKey, sphincsKey);
- if (ret == 0) {
- if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
- ret = BUFFER_E;
- else
- ret = cert->bodySz = WriteCertReqBody(der, derBuffer);
- }
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return ret;
- #else
- DECL_ASNSETDATA(dataASN, certReqBodyASN_Length);
- word32 publicKeySz = 0;
- word32 subjectSz = 0;
- word32 extSz = 0;
- int sz = 0;
- int ret = 0;
- #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
- word32 sbjRawSz = 0;
- #endif
- /* Unused without OQS */
- (void)falconKey;
- (void)dilithiumKey;
- (void)sphincsKey;
- CALLOC_ASNSETDATA(dataASN, certReqBodyASN_Length, ret, cert->heap);
- if (ret == 0) {
- /* Set key type into certificate object based on key passed in. */
- if (rsaKey != NULL) {
- cert->keyType = RSA_KEY;
- }
- else if (eccKey != NULL) {
- cert->keyType = ECC_KEY;
- }
- else if (dsaKey != NULL) {
- cert->keyType = DSA_KEY;
- }
- else if (ed25519Key != NULL) {
- cert->keyType = ED25519_KEY;
- }
- else if (ed448Key != NULL) {
- cert->keyType = ED448_KEY;
- }
- #ifdef HAVE_PQC
- #ifdef HAVE_FALCON
- else if ((falconKey != NULL) && (falconKey->level == 1)) {
- cert->keyType = FALCON_LEVEL1_KEY;
- }
- else if ((falconKey != NULL) && (falconKey->level == 5)) {
- cert->keyType = FALCON_LEVEL5_KEY;
- }
- #endif /* HAVE_FALCON */
- #ifdef HAVE_DILITHIUM
- else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
- cert->keyType = DILITHIUM_LEVEL2_KEY;
- }
- else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
- cert->keyType = DILITHIUM_LEVEL3_KEY;
- }
- else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
- cert->keyType = DILITHIUM_LEVEL5_KEY;
- }
- #endif /* HAVE_DILITHIUM */
- #ifdef HAVE_SPHINCS
- else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
- && (sphincsKey->optim == FAST_VARIANT)) {
- cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
- }
- else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
- && (sphincsKey->optim == FAST_VARIANT)) {
- cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
- }
- else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
- && (sphincsKey->optim == FAST_VARIANT)) {
- cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
- }
- else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
- && (sphincsKey->optim == SMALL_VARIANT)) {
- cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
- }
- else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
- && (sphincsKey->optim == SMALL_VARIANT)) {
- cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
- }
- else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
- && (sphincsKey->optim == SMALL_VARIANT)) {
- cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
- }
- #endif /* HAVE_SPHINCS */
- #endif /* HAVE_PQC */
- else {
- ret = BAD_FUNC_ARG;
- }
- }
- if (ret == 0) {
- /* Determine subject name size. */
- #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
- sbjRawSz = (word32)XSTRLEN((const char*)cert->sbjRaw);
- if (sbjRawSz > 0) {
- subjectSz = min(sizeof(cert->sbjRaw), sbjRawSz);
- }
- else
- #endif
- {
- ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject, cert->heap);
- subjectSz = (word32)ret;
- }
- }
- if (ret >= 0) {
- /* Determine encode public key size. */
- ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
- eccKey, ed25519Key, ed448Key, dsaKey);
- publicKeySz = (word32)ret;
- }
- if (ret >= 0) {
- /* Determine encode extensions size. */
- ret = EncodeExtensions(cert, NULL, 0, 1);
- extSz = (word32)ret;
- }
- if (ret >= 0) {
- /* Set version. */
- SetASN_Int8Bit(&dataASN[CERTREQBODYASN_IDX_VER], (byte)cert->version);
- #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
- if (sbjRawSz > 0) {
- /* Put in encoded subject name. */
- SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], cert->sbjRaw,
- subjectSz);
- }
- else
- #endif
- {
- /* Leave space for subject name. */
- SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], NULL,
- subjectSz);
- }
- /* Leave space for public key. */
- SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ],
- NULL, publicKeySz);
- if (cert->challengePw[0] != '\0') {
- /* Add challenge password attribute. */
- /* Set challenge password OID. */
- SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_OID],
- attrChallengePasswordOid, sizeof(attrChallengePasswordOid));
- /* Enable the ASN template item with the appropriate tag. */
- if (cert->challengePwPrintableString) {
- /* PRINTABLE_STRING - set buffer */
- SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS],
- (byte*)cert->challengePw,
- (word32)XSTRLEN(cert->challengePw));
- /* UTF8STRING - don't encode */
- dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF].noOut = 1;
- }
- else {
- /* PRINTABLE_STRING - don't encode */
- dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS].noOut = 1;
- /* UTF8STRING - set buffer */
- SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF],
- (byte*)cert->challengePw,
- (word32)XSTRLEN(cert->challengePw));
- }
- }
- else {
- /* Leave out challenge password attribute items. */
- SetASNItem_NoOutNode(dataASN, certReqBodyASN,
- CERTREQBODYASN_IDX_ATTRS_CPW_SEQ, certReqBodyASN_Length);
- }
- if (extSz > 0) {
- /* Set extension attribute OID. */
- SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_OID], attrExtensionRequestOid,
- sizeof(attrExtensionRequestOid));
- /* Leave space for data. */
- SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_BODY], NULL, extSz);
- }
- else {
- /* Leave out extension attribute items. */
- SetASNItem_NoOutNode(dataASN, certReqBodyASN,
- CERTREQBODYASN_IDX_EXT_SEQ, certReqBodyASN_Length);
- }
- /* Calculate size of encoded certificate request body. */
- ret = SizeASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length,
- &sz);
- }
- /* Check buffer is big enough for encoded data. */
- if ((ret == 0) && (sz > (int)derSz)) {
- ret = BUFFER_E;
- }
- if (ret == 0 && derBuffer != NULL) {
- /* Encode certificate request body into buffer. */
- SetASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length, derBuffer);
- /* Put in generated data */
- #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
- if (sbjRawSz == 0)
- #endif
- {
- /* Encode subject name into space in buffer. */
- ret = SetNameEx(
- (byte*)dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.data,
- dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.length,
- &cert->subject, cert->heap);
- }
- }
- if (ret >= 0 && derBuffer != NULL) {
- /* Encode public key into space in buffer. */
- ret = EncodePublicKey(cert->keyType,
- (byte*)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.data,
- (int)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.length,
- rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
- }
- if ((ret >= 0 && derBuffer != NULL) &&
- (!dataASN[CERTREQBODYASN_IDX_EXT_BODY].noOut)) {
- /* Encode extensions into space in buffer. */
- ret = EncodeExtensions(cert,
- (byte*)dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.data,
- dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.length, 1);
- }
- if (ret >= 0) {
- /* Store encoded certifcate request body size. */
- cert->bodySz = sz;
- /* Return the encoding size. */
- ret = sz;
- }
- FREE_ASNSETDATA(dataASN, cert->heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- int wc_MakeCertReq_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
- void* key)
- {
- RsaKey* rsaKey = NULL;
- DsaKey* dsaKey = NULL;
- ecc_key* eccKey = NULL;
- ed25519_key* ed25519Key = NULL;
- ed448_key* ed448Key = NULL;
- falcon_key* falconKey = NULL;
- dilithium_key* dilithiumKey = NULL;
- sphincs_key* sphincsKey = NULL;
- if (keyType == RSA_TYPE)
- rsaKey = (RsaKey*)key;
- else if (keyType == DSA_TYPE)
- dsaKey = (DsaKey*)key;
- else if (keyType == ECC_TYPE)
- eccKey = (ecc_key*)key;
- else if (keyType == ED25519_TYPE)
- ed25519Key = (ed25519_key*)key;
- else if (keyType == ED448_TYPE)
- ed448Key = (ed448_key*)key;
- else if (keyType == FALCON_LEVEL1_TYPE)
- falconKey = (falcon_key*)key;
- else if (keyType == FALCON_LEVEL5_TYPE)
- falconKey = (falcon_key*)key;
- else if (keyType == DILITHIUM_LEVEL2_TYPE)
- dilithiumKey = (dilithium_key*)key;
- else if (keyType == DILITHIUM_LEVEL3_TYPE)
- dilithiumKey = (dilithium_key*)key;
- else if (keyType == DILITHIUM_LEVEL5_TYPE)
- dilithiumKey = (dilithium_key*)key;
- else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
- sphincsKey = (sphincs_key*)key;
- return MakeCertReq(cert, derBuffer, derSz, rsaKey, dsaKey, eccKey,
- ed25519Key, ed448Key, falconKey, dilithiumKey,
- sphincsKey);
- }
- WOLFSSL_ABI
- int wc_MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
- RsaKey* rsaKey, ecc_key* eccKey)
- {
- return MakeCertReq(cert, derBuffer, derSz, rsaKey, NULL, eccKey, NULL,
- NULL, NULL, NULL, NULL);
- }
- #endif /* WOLFSSL_CERT_REQ */
- static int SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
- RsaKey* rsaKey, ecc_key* eccKey, ed25519_key* ed25519Key,
- ed448_key* ed448Key, falcon_key* falconKey,
- dilithium_key* dilithiumKey, sphincs_key* sphincsKey,
- WC_RNG* rng)
- {
- int sigSz = 0;
- void* heap = NULL;
- CertSignCtx certSignCtx_lcl;
- CertSignCtx* certSignCtx = &certSignCtx_lcl;
- XMEMSET(certSignCtx, 0, sizeof(*certSignCtx));
- if (requestSz < 0)
- return requestSz;
- /* locate ctx */
- if (rsaKey) {
- #ifndef NO_RSA
- #ifdef WOLFSSL_ASYNC_CRYPT
- certSignCtx = &rsaKey->certSignCtx;
- #endif
- heap = rsaKey->heap;
- #else
- return NOT_COMPILED_IN;
- #endif /* NO_RSA */
- }
- else if (eccKey) {
- #ifdef HAVE_ECC
- #ifdef WOLFSSL_ASYNC_CRYPT
- certSignCtx = &eccKey->certSignCtx;
- #endif
- heap = eccKey->heap;
- #else
- return NOT_COMPILED_IN;
- #endif /* HAVE_ECC */
- }
- if (certSignCtx->sig == NULL) {
- certSignCtx->sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (certSignCtx->sig == NULL)
- return MEMORY_E;
- }
- sigSz = MakeSignature(certSignCtx, buf, (word32)requestSz, certSignCtx->sig,
- MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key,
- falconKey, dilithiumKey, sphincsKey, rng, (word32)sType, heap);
- #ifdef WOLFSSL_ASYNC_CRYPT
- if (sigSz == WC_PENDING_E) {
- /* Not free'ing certSignCtx->sig here because it could still be in use
- * with async operations. */
- return sigSz;
- }
- #endif
- if (sigSz >= 0) {
- if (requestSz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
- sigSz = BUFFER_E;
- else
- sigSz = AddSignature(buf, requestSz, certSignCtx->sig, sigSz,
- sType);
- }
- XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER);
- certSignCtx->sig = NULL;
- return sigSz;
- }
- int wc_SignCert_ex(int requestSz, int sType, byte* buf, word32 buffSz,
- int keyType, void* key, WC_RNG* rng)
- {
- RsaKey* rsaKey = NULL;
- ecc_key* eccKey = NULL;
- ed25519_key* ed25519Key = NULL;
- ed448_key* ed448Key = NULL;
- falcon_key* falconKey = NULL;
- dilithium_key* dilithiumKey = NULL;
- sphincs_key* sphincsKey = NULL;
- if (keyType == RSA_TYPE)
- rsaKey = (RsaKey*)key;
- else if (keyType == ECC_TYPE)
- eccKey = (ecc_key*)key;
- else if (keyType == ED25519_TYPE)
- ed25519Key = (ed25519_key*)key;
- else if (keyType == ED448_TYPE)
- ed448Key = (ed448_key*)key;
- else if (keyType == FALCON_LEVEL1_TYPE)
- falconKey = (falcon_key*)key;
- else if (keyType == FALCON_LEVEL5_TYPE)
- falconKey = (falcon_key*)key;
- else if (keyType == DILITHIUM_LEVEL2_TYPE)
- dilithiumKey = (dilithium_key*)key;
- else if (keyType == DILITHIUM_LEVEL3_TYPE)
- dilithiumKey = (dilithium_key*)key;
- else if (keyType == DILITHIUM_LEVEL5_TYPE)
- dilithiumKey = (dilithium_key*)key;
- else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
- sphincsKey = (sphincs_key*)key;
- return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, ed25519Key,
- ed448Key, falconKey, dilithiumKey, sphincsKey, rng);
- }
- int wc_SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
- RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng)
- {
- return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, NULL, NULL,
- NULL, NULL, NULL, rng);
- }
- WOLFSSL_ABI
- int wc_MakeSelfCert(Cert* cert, byte* buf, word32 buffSz,
- RsaKey* key, WC_RNG* rng)
- {
- int ret;
- ret = wc_MakeCert(cert, buf, buffSz, key, NULL, rng);
- if (ret < 0)
- return ret;
- return wc_SignCert(cert->bodySz, cert->sigType,
- buf, buffSz, key, NULL, rng);
- }
- #ifdef WOLFSSL_CERT_EXT
- /* Get raw subject from cert, which may contain OIDs not parsed by Decode.
- The raw subject pointer will only be valid while "cert" is valid. */
- WOLFSSL_ABI
- int wc_GetSubjectRaw(byte **subjectRaw, Cert *cert)
- {
- int rc = BAD_FUNC_ARG;
- if ((subjectRaw != NULL) && (cert != NULL)) {
- *subjectRaw = cert->sbjRaw;
- rc = 0;
- }
- return rc;
- }
- /* Set KID from public key */
- static int SetKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey,
- ed25519_key* ed25519Key, ed448_key* ed448Key,
- falcon_key* falconKey,
- dilithium_key* dilithiumKey,
- sphincs_key *sphincsKey, int kid_type)
- {
- byte *buf;
- int bufferSz, ret;
- if (cert == NULL ||
- (rsakey == NULL && eckey == NULL && ed25519Key == NULL &&
- ed448Key == NULL && falconKey == NULL && dilithiumKey == NULL &&
- sphincsKey == NULL) ||
- (kid_type != SKID_TYPE && kid_type != AKID_TYPE))
- return BAD_FUNC_ARG;
- buf = (byte *)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (buf == NULL)
- return MEMORY_E;
- /* Public Key */
- bufferSz = -1;
- #ifndef NO_RSA
- /* RSA public key */
- if (rsakey != NULL)
- bufferSz = SetRsaPublicKey(buf, rsakey, MAX_PUBLIC_KEY_SZ, 0);
- #endif
- #ifdef HAVE_ECC
- /* ECC public key */
- if (eckey != NULL)
- bufferSz = SetEccPublicKey(buf, eckey, MAX_PUBLIC_KEY_SZ, 0, 0);
- #endif
- #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
- /* ED25519 public key */
- if (ed25519Key != NULL) {
- bufferSz = wc_Ed25519PublicKeyToDer(ed25519Key, buf, MAX_PUBLIC_KEY_SZ, 0);
- }
- #endif
- #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
- /* ED448 public key */
- if (ed448Key != NULL) {
- bufferSz = wc_Ed448PublicKeyToDer(ed448Key, buf, MAX_PUBLIC_KEY_SZ, 0);
- }
- #endif
- #if defined(HAVE_PQC)
- #if defined(HAVE_FALCON)
- if (falconKey != NULL) {
- bufferSz = wc_Falcon_PublicKeyToDer(falconKey, buf, MAX_PUBLIC_KEY_SZ,
- 0);
- }
- #endif
- #if defined(HAVE_DILITHIUM)
- if (dilithiumKey != NULL) {
- bufferSz = wc_Dilithium_PublicKeyToDer(dilithiumKey, buf,
- MAX_PUBLIC_KEY_SZ, 0);
- }
- #endif
- #if defined(HAVE_SPHINCS)
- if (sphincsKey != NULL) {
- bufferSz = wc_Sphincs_PublicKeyToDer(sphincsKey, buf,
- MAX_PUBLIC_KEY_SZ, 0);
- }
- #endif
- #endif /* HAVE_PQC */
- if (bufferSz <= 0) {
- XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
- return PUBLIC_KEY_E;
- }
- /* Compute SKID by hashing public key */
- if (kid_type == SKID_TYPE) {
- int hashId = HashIdAlg(cert->sigType);
- ret = CalcHashId_ex(buf, (word32)bufferSz, cert->skid, hashId);
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- cert->skidSz = wc_HashGetDigestSize(wc_HashTypeConvert(hashId));
- #else
- cert->skidSz = KEYID_SIZE;
- #endif
- }
- else if (kid_type == AKID_TYPE) {
- int hashId = HashIdAlg(cert->sigType);
- ret = CalcHashId_ex(buf, (word32)bufferSz, cert->akid, hashId);
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- cert->akidSz = wc_HashGetDigestSize(wc_HashTypeConvert(hashId));
- #else
- cert->akidSz = KEYID_SIZE;
- #endif
- }
- else
- ret = BAD_FUNC_ARG;
- XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
- return ret;
- }
- int wc_SetSubjectKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
- {
- RsaKey* rsaKey = NULL;
- ecc_key* eccKey = NULL;
- ed25519_key* ed25519Key = NULL;
- ed448_key* ed448Key = NULL;
- falcon_key* falconKey = NULL;
- dilithium_key* dilithiumKey = NULL;
- sphincs_key* sphincsKey = NULL;
- if (keyType == RSA_TYPE)
- rsaKey = (RsaKey*)key;
- else if (keyType == ECC_TYPE)
- eccKey = (ecc_key*)key;
- else if (keyType == ED25519_TYPE)
- ed25519Key = (ed25519_key*)key;
- else if (keyType == ED448_TYPE)
- ed448Key = (ed448_key*)key;
- else if (keyType == FALCON_LEVEL1_TYPE)
- falconKey = (falcon_key*)key;
- else if (keyType == FALCON_LEVEL5_TYPE)
- falconKey = (falcon_key*)key;
- else if (keyType == DILITHIUM_LEVEL2_TYPE)
- dilithiumKey = (dilithium_key*)key;
- else if (keyType == DILITHIUM_LEVEL3_TYPE)
- dilithiumKey = (dilithium_key*)key;
- else if (keyType == DILITHIUM_LEVEL5_TYPE)
- dilithiumKey = (dilithium_key*)key;
- else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
- sphincsKey = (sphincs_key*)key;
- return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
- falconKey, dilithiumKey, sphincsKey,
- SKID_TYPE);
- }
- /* Set SKID from RSA or ECC public key */
- int wc_SetSubjectKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
- {
- return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
- NULL, SKID_TYPE);
- }
- int wc_SetAuthKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
- {
- RsaKey* rsaKey = NULL;
- ecc_key* eccKey = NULL;
- ed25519_key* ed25519Key = NULL;
- ed448_key* ed448Key = NULL;
- falcon_key* falconKey = NULL;
- dilithium_key* dilithiumKey = NULL;
- sphincs_key* sphincsKey = NULL;
- if (keyType == RSA_TYPE)
- rsaKey = (RsaKey*)key;
- else if (keyType == ECC_TYPE)
- eccKey = (ecc_key*)key;
- else if (keyType == ED25519_TYPE)
- ed25519Key = (ed25519_key*)key;
- else if (keyType == ED448_TYPE)
- ed448Key = (ed448_key*)key;
- else if (keyType == FALCON_LEVEL1_TYPE)
- falconKey = (falcon_key*)key;
- else if (keyType == FALCON_LEVEL5_TYPE)
- falconKey = (falcon_key*)key;
- else if (keyType == DILITHIUM_LEVEL2_TYPE)
- dilithiumKey = (dilithium_key*)key;
- else if (keyType == DILITHIUM_LEVEL3_TYPE)
- dilithiumKey = (dilithium_key*)key;
- else if (keyType == DILITHIUM_LEVEL5_TYPE)
- dilithiumKey = (dilithium_key*)key;
- else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
- sphincsKey = (sphincs_key*)key;
- else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
- sphincsKey = (sphincs_key*)key;
- return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
- falconKey, dilithiumKey, sphincsKey,
- AKID_TYPE);
- }
- /* Set SKID from RSA or ECC public key */
- int wc_SetAuthKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
- {
- return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
- NULL, AKID_TYPE);
- }
- #if !defined(NO_FILESYSTEM) && !defined(NO_ASN_CRYPT)
- /* Set SKID from public key file in PEM */
- int wc_SetSubjectKeyId(Cert *cert, const char* file)
- {
- int ret, derSz;
- byte* der;
- word32 idx;
- RsaKey *rsakey = NULL;
- ecc_key *eckey = NULL;
- if (cert == NULL || file == NULL)
- return BAD_FUNC_ARG;
- der = (byte*)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap, DYNAMIC_TYPE_CERT);
- if (der == NULL) {
- WOLFSSL_MSG("wc_SetSubjectKeyId memory Problem");
- return MEMORY_E;
- }
- derSz = MAX_PUBLIC_KEY_SZ;
- XMEMSET(der, 0, (size_t)derSz);
- derSz = wc_PemPubKeyToDer(file, der, derSz);
- if (derSz <= 0) {
- XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
- return derSz;
- }
- /* Load PubKey in internal structure */
- #ifndef NO_RSA
- rsakey = (RsaKey*) XMALLOC(sizeof(RsaKey), cert->heap, DYNAMIC_TYPE_RSA);
- if (rsakey == NULL) {
- XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
- return MEMORY_E;
- }
- if (wc_InitRsaKey(rsakey, cert->heap) != 0) {
- WOLFSSL_MSG("wc_InitRsaKey failure");
- XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
- XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
- return MEMORY_E;
- }
- idx = 0;
- ret = wc_RsaPublicKeyDecode(der, &idx, rsakey, (word32)derSz);
- if (ret != 0)
- #endif
- {
- #ifndef NO_RSA
- WOLFSSL_MSG("wc_RsaPublicKeyDecode failed");
- wc_FreeRsaKey(rsakey);
- XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
- rsakey = NULL;
- #endif
- #ifdef HAVE_ECC
- /* Check to load ecc public key */
- eckey = (ecc_key*) XMALLOC(sizeof(ecc_key), cert->heap,
- DYNAMIC_TYPE_ECC);
- if (eckey == NULL) {
- XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
- return MEMORY_E;
- }
- if (wc_ecc_init(eckey) != 0) {
- WOLFSSL_MSG("wc_ecc_init failure");
- wc_ecc_free(eckey);
- XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
- XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
- return MEMORY_E;
- }
- idx = 0;
- ret = wc_EccPublicKeyDecode(der, &idx, eckey, (word32)derSz);
- if (ret != 0) {
- WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
- XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
- wc_ecc_free(eckey);
- XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
- return PUBLIC_KEY_E;
- }
- #else
- XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
- return PUBLIC_KEY_E;
- #endif /* HAVE_ECC */
- }
- XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
- ret = wc_SetSubjectKeyIdFromPublicKey(cert, rsakey, eckey);
- #ifndef NO_RSA
- wc_FreeRsaKey(rsakey);
- XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
- #endif
- #ifdef HAVE_ECC
- wc_ecc_free(eckey);
- XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
- #endif
- return ret;
- }
- #endif /* !NO_FILESYSTEM && !NO_ASN_CRYPT */
- static int SetAuthKeyIdFromDcert(Cert* cert, DecodedCert* decoded)
- {
- int ret = 0;
- /* Subject Key Id not found !! */
- if (decoded->extSubjKeyIdSet == 0) {
- ret = ASN_NO_SKID;
- }
- /* SKID invalid size */
- else if (sizeof(cert->akid) < sizeof(decoded->extSubjKeyId)) {
- ret = MEMORY_E;
- }
- else {
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- cert->akidSz = wc_HashGetDigestSize(wc_HashTypeConvert(HashIdAlg(
- cert->sigType)));
- #else
- cert->akidSz = KEYID_SIZE;
- #endif
- /* Put the SKID of CA to AKID of certificate */
- XMEMCPY(cert->akid, decoded->extSubjKeyId, cert->akidSz);
- }
- return ret;
- }
- /* Set AKID from certificate contains in buffer (DER encoded) */
- int wc_SetAuthKeyIdFromCert(Cert *cert, const byte *der, int derSz)
- {
- int ret = 0;
- if (cert == NULL) {
- ret = BAD_FUNC_ARG;
- }
- else {
- /* Check if decodedCert is cached */
- if (cert->der != der) {
- /* Allocate cache for the decoded cert */
- ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
- }
- if (ret >= 0) {
- ret = SetAuthKeyIdFromDcert(cert, (DecodedCert*)cert->decodedCert);
- #ifndef WOLFSSL_CERT_GEN_CACHE
- wc_SetCert_Free(cert);
- #endif
- }
- }
- return ret;
- }
- #ifndef NO_FILESYSTEM
- /* Set AKID from certificate file in PEM */
- int wc_SetAuthKeyId(Cert *cert, const char* file)
- {
- int ret;
- DerBuffer* der = NULL;
- if (cert == NULL || file == NULL)
- return BAD_FUNC_ARG;
- ret = wc_PemCertToDer_ex(file, &der);
- if (ret == 0)
- {
- ret = wc_SetAuthKeyIdFromCert(cert, der->buffer, (int)der->length);
- FreeDer(&der);
- }
- return ret;
- }
- #endif /* !NO_FILESYSTEM */
- /* Set KeyUsage from human readable string */
- int wc_SetKeyUsage(Cert *cert, const char *value)
- {
- int ret = 0;
- char *token, *str, *ptr;
- word32 len;
- if (cert == NULL || value == NULL)
- return BAD_FUNC_ARG;
- cert->keyUsage = 0;
- /* duplicate string (including terminator) */
- len = (word32)XSTRLEN(value);
- str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (str == NULL)
- return MEMORY_E;
- XMEMCPY(str, value, len+1);
- /* parse value, and set corresponding Key Usage value */
- if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
- XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
- return KEYUSAGE_E;
- }
- while (token != NULL)
- {
- if (!XSTRCASECMP(token, "digitalSignature"))
- cert->keyUsage |= KEYUSE_DIGITAL_SIG;
- else if (!XSTRCASECMP(token, "nonRepudiation") ||
- !XSTRCASECMP(token, "contentCommitment"))
- cert->keyUsage |= KEYUSE_CONTENT_COMMIT;
- else if (!XSTRCASECMP(token, "keyEncipherment"))
- cert->keyUsage |= KEYUSE_KEY_ENCIPHER;
- else if (!XSTRCASECMP(token, "dataEncipherment"))
- cert->keyUsage |= KEYUSE_DATA_ENCIPHER;
- else if (!XSTRCASECMP(token, "keyAgreement"))
- cert->keyUsage |= KEYUSE_KEY_AGREE;
- else if (!XSTRCASECMP(token, "keyCertSign"))
- cert->keyUsage |= KEYUSE_KEY_CERT_SIGN;
- else if (!XSTRCASECMP(token, "cRLSign"))
- cert->keyUsage |= KEYUSE_CRL_SIGN;
- else if (!XSTRCASECMP(token, "encipherOnly"))
- cert->keyUsage |= KEYUSE_ENCIPHER_ONLY;
- else if (!XSTRCASECMP(token, "decipherOnly"))
- cert->keyUsage |= KEYUSE_DECIPHER_ONLY;
- else {
- ret = KEYUSAGE_E;
- break;
- }
- token = XSTRTOK(NULL, ",", &ptr);
- }
- XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
- return ret;
- }
- /* Set ExtendedKeyUsage from human readable string */
- int wc_SetExtKeyUsage(Cert *cert, const char *value)
- {
- int ret = 0;
- char *token, *str, *ptr;
- word32 len;
- if (cert == NULL || value == NULL)
- return BAD_FUNC_ARG;
- cert->extKeyUsage = 0;
- /* duplicate string (including terminator) */
- len = (word32)XSTRLEN(value);
- str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (str == NULL)
- return MEMORY_E;
- XMEMCPY(str, value, len+1);
- /* parse value, and set corresponding Key Usage value */
- if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
- XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
- return EXTKEYUSAGE_E;
- }
- while (token != NULL)
- {
- if (!XSTRCASECMP(token, "any"))
- cert->extKeyUsage |= EXTKEYUSE_ANY;
- else if (!XSTRCASECMP(token, "serverAuth"))
- cert->extKeyUsage |= EXTKEYUSE_SERVER_AUTH;
- else if (!XSTRCASECMP(token, "clientAuth"))
- cert->extKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
- else if (!XSTRCASECMP(token, "codeSigning"))
- cert->extKeyUsage |= EXTKEYUSE_CODESIGN;
- else if (!XSTRCASECMP(token, "emailProtection"))
- cert->extKeyUsage |= EXTKEYUSE_EMAILPROT;
- else if (!XSTRCASECMP(token, "timeStamping"))
- cert->extKeyUsage |= EXTKEYUSE_TIMESTAMP;
- else if (!XSTRCASECMP(token, "OCSPSigning"))
- cert->extKeyUsage |= EXTKEYUSE_OCSP_SIGN;
- else {
- ret = EXTKEYUSAGE_E;
- break;
- }
- token = XSTRTOK(NULL, ",", &ptr);
- }
- XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
- return ret;
- }
- #ifdef WOLFSSL_EKU_OID
- /*
- * cert structure to set EKU oid in
- * oid the oid in byte representation
- * sz size of oid buffer
- * idx index of array to place oid
- *
- * returns 0 on success
- */
- int wc_SetExtKeyUsageOID(Cert *cert, const char *in, word32 sz, byte idx,
- void* heap)
- {
- byte oid[MAX_OID_SZ];
- word32 oidSz = MAX_OID_SZ;
- if (idx >= CTC_MAX_EKU_NB || sz >= CTC_MAX_EKU_OID_SZ) {
- WOLFSSL_MSG("Either idx or sz was too large");
- return BAD_FUNC_ARG;
- }
- if (EncodePolicyOID(oid, &oidSz, in, heap) != 0) {
- return BUFFER_E;
- }
- XMEMCPY(cert->extKeyUsageOID[idx], oid, oidSz);
- cert->extKeyUsageOIDSz[idx] = oidSz;
- cert->extKeyUsage |= EXTKEYUSE_USER;
- return 0;
- }
- #endif /* WOLFSSL_EKU_OID */
- #if defined(WOLFSSL_ASN_TEMPLATE) && defined(WOLFSSL_CERT_GEN) && \
- defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_ENCODING) && \
- defined(WOLFSSL_CERT_EXT)
- int wc_SetCustomExtension(Cert *cert, int critical, const char *oid,
- const byte *der, word32 derSz) {
- CertExtension *ext;
- byte encodedOid[MAX_OID_SZ];
- word32 encodedOidSz = MAX_OID_SZ;
- int ret;
- if (cert == NULL || oid == NULL || der == NULL || derSz == 0) {
- return BAD_FUNC_ARG;
- }
- if (cert->customCertExtCount >= NUM_CUSTOM_EXT) {
- return MEMORY_E;
- }
- /* Make sure we can properly parse the OID. */
- ret = EncodePolicyOID(encodedOid, &encodedOidSz, oid, NULL);
- if (ret != 0) {
- return ret;
- }
- ext = &cert->customCertExt[cert->customCertExtCount];
- ext->oid = oid;
- ext->crit = (critical == 0) ? 0 : 1;
- ext->val = der;
- ext->valSz = derSz;
- cert->customCertExtCount++;
- return 0;
- }
- #endif
- #endif /* WOLFSSL_CERT_EXT */
- #ifdef WOLFSSL_ALT_NAMES
- static int SetAltNamesFromDcert(Cert* cert, DecodedCert* decoded)
- {
- int ret = 0;
- cert->altNamesSz = 0;
- if (decoded->altNames) {
- ret = FlattenAltNames(cert->altNames,
- sizeof(cert->altNames), decoded->altNames);
- if (ret >= 0) {
- cert->altNamesSz = ret;
- ret = 0;
- }
- }
- return ret;
- }
- #ifndef NO_FILESYSTEM
- /* Set Alt Names from der cert, return 0 on success */
- static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz,
- int devId)
- {
- int ret;
- #ifdef WOLFSSL_SMALL_STACK
- DecodedCert* decoded;
- #else
- DecodedCert decoded[1];
- #endif
- if (derSz < 0)
- return derSz;
- #ifdef WOLFSSL_SMALL_STACK
- decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), cert->heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (decoded == NULL)
- return MEMORY_E;
- #endif
- InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
- ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
- if (ret < 0) {
- WOLFSSL_MSG("ParseCertRelative error");
- }
- else {
- ret = SetAltNamesFromDcert(cert, decoded);
- }
- FreeDecodedCert(decoded);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(decoded, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return ret < 0 ? ret : 0;
- }
- #endif
- static int SetDatesFromDcert(Cert* cert, DecodedCert* decoded)
- {
- int ret = 0;
- if (decoded->beforeDate == NULL || decoded->afterDate == NULL) {
- WOLFSSL_MSG("Couldn't extract dates");
- ret = -1;
- }
- else if (decoded->beforeDateLen > MAX_DATE_SIZE ||
- decoded->afterDateLen > MAX_DATE_SIZE) {
- WOLFSSL_MSG("Bad date size");
- ret = -1;
- }
- else {
- XMEMCPY(cert->beforeDate, decoded->beforeDate,
- (size_t)decoded->beforeDateLen);
- XMEMCPY(cert->afterDate, decoded->afterDate,
- (size_t)decoded->afterDateLen);
- cert->beforeDateSz = decoded->beforeDateLen;
- cert->afterDateSz = decoded->afterDateLen;
- }
- return ret;
- }
- #endif /* WOLFSSL_ALT_NAMES */
- static void SetNameFromDcert(CertName* cn, DecodedCert* decoded)
- {
- int sz;
- if (decoded->subjectCN) {
- sz = (decoded->subjectCNLen < CTC_NAME_SIZE) ? decoded->subjectCNLen
- : CTC_NAME_SIZE - 1;
- XSTRNCPY(cn->commonName, decoded->subjectCN, (size_t)sz);
- cn->commonName[sz] = '\0';
- cn->commonNameEnc = decoded->subjectCNEnc;
- }
- if (decoded->subjectC) {
- sz = (decoded->subjectCLen < CTC_NAME_SIZE) ? decoded->subjectCLen
- : CTC_NAME_SIZE - 1;
- XSTRNCPY(cn->country, decoded->subjectC, (size_t)sz);
- cn->country[sz] = '\0';
- cn->countryEnc = decoded->subjectCEnc;
- }
- if (decoded->subjectST) {
- sz = (decoded->subjectSTLen < CTC_NAME_SIZE) ? decoded->subjectSTLen
- : CTC_NAME_SIZE - 1;
- XSTRNCPY(cn->state, decoded->subjectST, (size_t)sz);
- cn->state[sz] = '\0';
- cn->stateEnc = decoded->subjectSTEnc;
- }
- if (decoded->subjectL) {
- sz = (decoded->subjectLLen < CTC_NAME_SIZE) ? decoded->subjectLLen
- : CTC_NAME_SIZE - 1;
- XSTRNCPY(cn->locality, decoded->subjectL, (size_t)sz);
- cn->locality[sz] = '\0';
- cn->localityEnc = decoded->subjectLEnc;
- }
- if (decoded->subjectO) {
- sz = (decoded->subjectOLen < CTC_NAME_SIZE) ? decoded->subjectOLen
- : CTC_NAME_SIZE - 1;
- XSTRNCPY(cn->org, decoded->subjectO, (size_t)sz);
- cn->org[sz] = '\0';
- cn->orgEnc = decoded->subjectOEnc;
- }
- if (decoded->subjectOU) {
- sz = (decoded->subjectOULen < CTC_NAME_SIZE) ? decoded->subjectOULen
- : CTC_NAME_SIZE - 1;
- XSTRNCPY(cn->unit, decoded->subjectOU, (size_t)sz);
- cn->unit[sz] = '\0';
- cn->unitEnc = decoded->subjectOUEnc;
- }
- if (decoded->subjectSN) {
- sz = (decoded->subjectSNLen < CTC_NAME_SIZE) ? decoded->subjectSNLen
- : CTC_NAME_SIZE - 1;
- XSTRNCPY(cn->sur, decoded->subjectSN, (size_t)sz);
- cn->sur[sz] = '\0';
- cn->surEnc = decoded->subjectSNEnc;
- }
- if (decoded->subjectSND) {
- sz = (decoded->subjectSNDLen < CTC_NAME_SIZE) ? decoded->subjectSNDLen
- : CTC_NAME_SIZE - 1;
- XSTRNCPY(cn->serialDev, decoded->subjectSND, (size_t)sz);
- cn->serialDev[sz] = '\0';
- cn->serialDevEnc = decoded->subjectSNDEnc;
- }
- if (decoded->subjectUID) {
- sz = (decoded->subjectUIDLen < CTC_NAME_SIZE) ? decoded->subjectUIDLen
- : CTC_NAME_SIZE - 1;
- XSTRNCPY(cn->userId, decoded->subjectUID, (size_t)sz);
- cn->userId[sz] = '\0';
- cn->userIdEnc = decoded->subjectUIDEnc;
- }
- #ifdef WOLFSSL_CERT_EXT
- if (decoded->subjectBC) {
- sz = (decoded->subjectBCLen < CTC_NAME_SIZE) ? decoded->subjectBCLen
- : CTC_NAME_SIZE - 1;
- XSTRNCPY(cn->busCat, decoded->subjectBC, (size_t)sz);
- cn->busCat[sz] = '\0';
- cn->busCatEnc = decoded->subjectBCEnc;
- }
- if (decoded->subjectJC) {
- sz = (decoded->subjectJCLen < CTC_NAME_SIZE) ? decoded->subjectJCLen
- : CTC_NAME_SIZE - 1;
- XSTRNCPY(cn->joiC, decoded->subjectJC, (size_t)sz);
- cn->joiC[sz] = '\0';
- cn->joiCEnc = decoded->subjectJCEnc;
- }
- if (decoded->subjectJS) {
- sz = (decoded->subjectJSLen < CTC_NAME_SIZE) ? decoded->subjectJSLen
- : CTC_NAME_SIZE - 1;
- XSTRNCPY(cn->joiSt, decoded->subjectJS, (size_t)sz);
- cn->joiSt[sz] = '\0';
- cn->joiStEnc = decoded->subjectJSEnc;
- }
- #endif
- if (decoded->subjectEmail) {
- sz = (decoded->subjectEmailLen < CTC_NAME_SIZE)
- ? decoded->subjectEmailLen : CTC_NAME_SIZE - 1;
- XSTRNCPY(cn->email, decoded->subjectEmail, (size_t)sz);
- cn->email[sz] = '\0';
- }
- #if defined(WOLFSSL_CERT_NAME_ALL) && \
- (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
- if (decoded->subjectN) {
- sz = (decoded->subjectNLen < CTC_NAME_SIZE) ? decoded->subjectNLen
- : CTC_NAME_SIZE - 1;
- XSTRNCPY(cn->dnName, decoded->subjectN, (size_t)sz);
- cn->dnName[sz] = '\0';
- cn->dnNameEnc = decoded->subjectNEnc;
- }
- if (decoded->subjectI) {
- sz = (decoded->subjectILen < CTC_NAME_SIZE) ? decoded->subjectILen
- : CTC_NAME_SIZE - 1;
- XSTRNCPY(cn->initials, decoded->subjectI, (size_t)sz);
- cn->initials[sz] = '\0';
- cn->initialsEnc = decoded->subjectIEnc;
- }
- if (decoded->subjectGN) {
- sz = (decoded->subjectGNLen < CTC_NAME_SIZE) ? decoded->subjectGNLen
- : CTC_NAME_SIZE - 1;
- XSTRNCPY(cn->givenName, decoded->subjectGN, (size_t)sz);
- cn->givenName[sz] = '\0';
- cn->givenNameEnc = decoded->subjectGNEnc;
- }
- if (decoded->subjectDNQ) {
- sz = (decoded->subjectDNQLen < CTC_NAME_SIZE) ? decoded->subjectDNQLen
- : CTC_NAME_SIZE - 1;
- XSTRNCPY(cn->dnQualifier, decoded->subjectDNQ, (size_t)sz);
- cn->dnQualifier[sz] = '\0';
- cn->dnQualifierEnc = decoded->subjectDNQEnc;
- }
- #endif /* WOLFSSL_CERT_NAME_ALL */
- }
- #ifndef NO_FILESYSTEM
- /* Set cn name from der buffer, return 0 on success */
- static int SetNameFromCert(CertName* cn, const byte* der, int derSz, int devId)
- {
- int ret;
- #ifdef WOLFSSL_SMALL_STACK
- DecodedCert* decoded;
- #else
- DecodedCert decoded[1];
- #endif
- if (derSz < 0)
- return derSz;
- #ifdef WOLFSSL_SMALL_STACK
- decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (decoded == NULL)
- return MEMORY_E;
- #endif
- InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
- ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
- if (ret < 0) {
- WOLFSSL_MSG("ParseCertRelative error");
- }
- else {
- SetNameFromDcert(cn, decoded);
- }
- FreeDecodedCert(decoded);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return ret < 0 ? ret : 0;
- }
- /* Set cert issuer from issuerFile in PEM */
- WOLFSSL_ABI
- int wc_SetIssuer(Cert* cert, const char* issuerFile)
- {
- int ret;
- DerBuffer* der = NULL;
- if (cert == NULL || issuerFile == NULL)
- return BAD_FUNC_ARG;
- ret = wc_PemCertToDer_ex(issuerFile, &der);
- if (ret == 0) {
- cert->selfSigned = 0;
- ret = SetNameFromCert(&cert->issuer, der->buffer, (int)der->length,
- INVALID_DEVID);
- FreeDer(&der);
- }
- return ret;
- }
- /* Set cert subject from subjectFile in PEM */
- WOLFSSL_ABI
- int wc_SetSubject(Cert* cert, const char* subjectFile)
- {
- int ret;
- DerBuffer* der = NULL;
- if (cert == NULL || subjectFile == NULL)
- return BAD_FUNC_ARG;
- ret = wc_PemCertToDer_ex(subjectFile, &der);
- if (ret == 0) {
- ret = SetNameFromCert(&cert->subject, der->buffer, (int)der->length,
- INVALID_DEVID);
- FreeDer(&der);
- }
- return ret;
- }
- #ifdef WOLFSSL_ALT_NAMES
- /* Set alt names from file in PEM */
- WOLFSSL_ABI
- int wc_SetAltNames(Cert* cert, const char* file)
- {
- int ret;
- DerBuffer* der = NULL;
- if (cert == NULL) {
- return BAD_FUNC_ARG;
- }
- ret = wc_PemCertToDer_ex(file, &der);
- if (ret == 0) {
- ret = SetAltNamesFromCert(cert, der->buffer, (int)der->length,
- INVALID_DEVID);
- FreeDer(&der);
- }
- return ret;
- }
- #endif /* WOLFSSL_ALT_NAMES */
- #endif /* !NO_FILESYSTEM */
- /* Set cert issuer from DER buffer */
- WOLFSSL_ABI
- int wc_SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
- {
- int ret = 0;
- if (cert == NULL) {
- ret = BAD_FUNC_ARG;
- }
- else {
- cert->selfSigned = 0;
- /* Check if decodedCert is cached */
- if (cert->der != der) {
- /* Allocate cache for the decoded cert */
- ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
- }
- if (ret >= 0) {
- SetNameFromDcert(&cert->issuer, (DecodedCert*)cert->decodedCert);
- #ifndef WOLFSSL_CERT_GEN_CACHE
- wc_SetCert_Free(cert);
- #endif
- }
- }
- return ret;
- }
- /* Set cert subject from DER buffer */
- WOLFSSL_ABI
- int wc_SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
- {
- int ret = 0;
- if (cert == NULL) {
- ret = BAD_FUNC_ARG;
- }
- else {
- /* Check if decodedCert is cached */
- if (cert->der != der) {
- /* Allocate cache for the decoded cert */
- ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
- }
- if (ret >= 0) {
- SetNameFromDcert(&cert->subject, (DecodedCert*)cert->decodedCert);
- #ifndef WOLFSSL_CERT_GEN_CACHE
- wc_SetCert_Free(cert);
- #endif
- }
- }
- return ret;
- }
- #ifdef WOLFSSL_CERT_EXT
- /* Set cert raw subject from DER buffer */
- WOLFSSL_ABI
- int wc_SetSubjectRaw(Cert* cert, const byte* der, int derSz)
- {
- int ret = 0;
- if (cert == NULL) {
- ret = BAD_FUNC_ARG;
- }
- else {
- /* Check if decodedCert is cached */
- if (cert->der != der) {
- /* Allocate cache for the decoded cert */
- ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
- }
- if (ret >= 0) {
- if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
- (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
- (int)sizeof(CertName))) {
- XMEMCPY(cert->sbjRaw,
- ((DecodedCert*)cert->decodedCert)->subjectRaw,
- (size_t)((DecodedCert*)cert->decodedCert)->
- subjectRawLen);
- }
- #ifndef WOLFSSL_CERT_GEN_CACHE
- wc_SetCert_Free(cert);
- #endif
- }
- }
- return ret;
- }
- /* Set cert raw issuer from DER buffer */
- WOLFSSL_ABI
- int wc_SetIssuerRaw(Cert* cert, const byte* der, int derSz)
- {
- int ret = 0;
- if (cert == NULL) {
- ret = BAD_FUNC_ARG;
- }
- else {
- /* Check if decodedCert is cached */
- if (cert->der != der) {
- /* Allocate cache for the decoded cert */
- ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
- }
- if (ret >= 0) {
- if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
- (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
- (int)sizeof(CertName))) {
- /* Copy the subject to the issuer field */
- XMEMCPY(cert->issRaw,
- ((DecodedCert*)cert->decodedCert)->subjectRaw,
- (size_t)((DecodedCert*)cert->decodedCert)->
- subjectRawLen);
- }
- #ifndef WOLFSSL_CERT_GEN_CACHE
- wc_SetCert_Free(cert);
- #endif
- }
- }
- return ret;
- }
- #endif
- #ifdef WOLFSSL_ALT_NAMES
- /* Set cert alt names from DER buffer */
- WOLFSSL_ABI
- int wc_SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
- {
- int ret = 0;
- if (cert == NULL) {
- ret = BAD_FUNC_ARG;
- }
- else {
- /* Check if decodedCert is cached */
- if (cert->der != der) {
- /* Allocate cache for the decoded cert */
- ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
- }
- if (ret >= 0) {
- ret = SetAltNamesFromDcert(cert, (DecodedCert*)cert->decodedCert);
- #ifndef WOLFSSL_CERT_GEN_CACHE
- wc_SetCert_Free(cert);
- #endif
- }
- }
- return(ret);
- }
- /* Set cert dates from DER buffer */
- WOLFSSL_ABI
- int wc_SetDatesBuffer(Cert* cert, const byte* der, int derSz)
- {
- int ret = 0;
- if (cert == NULL) {
- ret = BAD_FUNC_ARG;
- }
- else {
- /* Check if decodedCert is cached */
- if (cert->der != der) {
- /* Allocate cache for the decoded cert */
- ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
- }
- if (ret >= 0) {
- ret = SetDatesFromDcert(cert, (DecodedCert*)cert->decodedCert);
- #ifndef WOLFSSL_CERT_GEN_CACHE
- wc_SetCert_Free(cert);
- #endif
- }
- }
- return(ret);
- }
- #endif /* WOLFSSL_ALT_NAMES */
- #endif /* WOLFSSL_CERT_GEN */
- #if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) \
- || defined(OPENSSL_EXTRA)
- /* Encode OID string representation to ITU-T X.690 format */
- int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap)
- {
- word32 idx = 0, nb_val;
- char *token, *str, *ptr;
- word32 len;
- (void)heap;
- if (out == NULL || outSz == NULL || *outSz < 2 || in == NULL)
- return BAD_FUNC_ARG;
- /* duplicate string (including terminator) */
- len = (word32)XSTRLEN(in);
- str = (char *)XMALLOC(len+1, heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (str == NULL)
- return MEMORY_E;
- XMEMCPY(str, in, len+1);
- nb_val = 0;
- /* parse value, and set corresponding Policy OID value */
- token = XSTRTOK(str, ".", &ptr);
- while (token != NULL)
- {
- word32 val = (word32)XATOI(token);
- if (nb_val == 0) {
- if (val > 2) {
- XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
- return ASN_OBJECT_ID_E;
- }
- out[idx] = (byte)(40 * val);
- }
- else if (nb_val == 1) {
- if (val > 127) {
- XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
- return ASN_OBJECT_ID_E;
- }
- if (idx > *outSz) {
- XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
- return BUFFER_E;
- }
- out[idx++] += (byte)val;
- }
- else {
- word32 tb = 0;
- int i = 0;
- byte oid[MAX_OID_SZ];
- while (val >= 128) {
- word32 x = val % 128;
- val /= 128;
- oid[i++] = (byte) (((tb++) ? 0x80 : 0) | x);
- }
- if ((idx+(word32)i) >= *outSz) {
- XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
- return BUFFER_E;
- }
- oid[i] = (byte) (((tb++) ? 0x80 : 0) | val);
- /* push value in the right order */
- while (i >= 0)
- out[idx++] = oid[i--];
- }
- token = XSTRTOK(NULL, ".", &ptr);
- nb_val++;
- }
- *outSz = idx;
- XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
- return 0;
- }
- #endif /* WOLFSSL_CERT_EXT || OPENSSL_EXTRA */
- #endif /* !NO_CERTS */
- #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
- /* Helper function for wolfSSL_i2d_DHparams */
- int StoreDHparams(byte* out, word32* outLen, mp_int* p, mp_int* g)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0;
- word32 total;
- WOLFSSL_ENTER("StoreDHparams");
- if (out == NULL) {
- WOLFSSL_MSG("Null buffer error");
- return BUFFER_E;
- }
- /* determine size */
- /* integer - g */
- idx = SetASNIntMP(g, -1, NULL);
- /* integer - p */
- idx += SetASNIntMP(p, -1, NULL);
- total = idx;
- /* sequence */
- idx += SetSequence(idx, NULL);
- /* make sure output fits in buffer */
- if (idx > *outLen) {
- return BUFFER_E;
- }
- /* write DH parameters */
- /* sequence - for P and G only */
- idx = SetSequence(total, out);
- /* integer - p */
- idx += SetASNIntMP(p, -1, out + idx);
- /* integer - g */
- idx += SetASNIntMP(g, -1, out + idx);
- *outLen = idx;
- return 0;
- #else
- ASNSetData dataASN[dhParamASN_Length];
- int ret = 0;
- int sz = 0;
- WOLFSSL_ENTER("StoreDHparams");
- if (out == NULL) {
- ret = BUFFER_E;
- }
- if (ret == 0) {
- XMEMSET(dataASN, 0, sizeof(dataASN));
- /* Set mp_int containing p and g. */
- SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], p);
- SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], g);
- /* privateValueLength not encoded. */
- dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
- /* Calculate the size of the DH parameters. */
- ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
- }
- /* Check buffer is big enough for encoding. */
- if ((ret == 0) && ((int)*outLen < sz)) {
- ret = BUFFER_E;
- }
- if (ret == 0) {
- /* Encode the DH parameters into buffer. */
- SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, out);
- /* Set the actual encoding size. */
- *outLen = sz;
- }
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
- #if defined(HAVE_ECC) || !defined(NO_DSA)
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for DSA signature.
- * RFC 5912, 6 - DSA-Sig-Value
- */
- static const ASNItem dsaSigASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* r */
- /* R */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* s */
- /* S */ { 1, ASN_INTEGER, 0, 0, 0 },
- };
- enum {
- DSASIGASN_IDX_SEQ = 0,
- DSASIGASN_IDX_R,
- DSASIGASN_IDX_S
- };
- #define dsaSigASN_Length (sizeof(dsaSigASN) / sizeof(ASNItem))
- #endif
- /* Der Encode r & s ints into out, outLen is (in/out) size */
- int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0;
- int rSz; /* encoding size */
- int sSz;
- int headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
- /* If the leading bit on the INTEGER is a 1, add a leading zero */
- int rLeadingZero = mp_leading_bit(r);
- int sLeadingZero = mp_leading_bit(s);
- int rLen = mp_unsigned_bin_size(r); /* big int size */
- int sLen = mp_unsigned_bin_size(s);
- if (*outLen < (word32)((rLen + rLeadingZero + sLen + sLeadingZero +
- headerSz + 2))) /* SEQ_TAG + LEN(ENUM) */
- return BUFFER_E;
- idx = SetSequence((word32)(rLen + rLeadingZero + sLen + sLeadingZero +
- headerSz), out);
- /* store r */
- rSz = SetASNIntMP(r, (int)(*outLen - idx), &out[idx]);
- if (rSz < 0)
- return rSz;
- idx += (word32)rSz;
- /* store s */
- sSz = SetASNIntMP(s, (int)(*outLen - idx), &out[idx]);
- if (sSz < 0)
- return sSz;
- idx += (word32)sSz;
- *outLen = idx;
- return 0;
- #else
- ASNSetData dataASN[dsaSigASN_Length];
- int ret;
- int sz;
- /* Clear dynamic data and set mp_ints r and s */
- XMEMSET(dataASN, 0, sizeof(dataASN));
- SetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
- SetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
- /* Calculate size of encoding. */
- ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
- /* Check buffer is big enough for encoding. */
- if ((ret == 0) && ((int)*outLen < sz)) {
- ret = BUFFER_E;
- }
- if (ret == 0) {
- /* Encode DSA signature into buffer. */
- SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
- /* Set the actual encoding size. */
- *outLen = (word32)sz;
- }
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #ifndef WOLFSSL_ASN_TEMPLATE
- /* determine if leading bit is set */
- static word32 is_leading_bit_set(const byte* input, word32 sz)
- {
- byte c = 0;
- if (sz > 0)
- c = input[0];
- return (c & 0x80) != 0;
- }
- static word32 trim_leading_zeros(const byte** input, word32 sz)
- {
- int i;
- word32 leadingZeroCount = 0;
- const byte* tmp = *input;
- for (i=0; i<(int)sz; i++) {
- if (tmp[i] != 0)
- break;
- leadingZeroCount++;
- }
- /* catch all zero case */
- if (sz > 0 && leadingZeroCount == sz) {
- leadingZeroCount--;
- }
- *input += leadingZeroCount;
- sz -= leadingZeroCount;
- return sz;
- }
- #endif
- /* Der Encode r & s ints into out, outLen is (in/out) size */
- /* All input/outputs are assumed to be big-endian */
- int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen,
- const byte* s, word32 sLen)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret;
- word32 idx;
- word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
- word32 rAddLeadZero, sAddLeadZero;
- if ((out == NULL) || (outLen == NULL) || (r == NULL) || (s == NULL))
- return BAD_FUNC_ARG;
- /* Trim leading zeros */
- rLen = trim_leading_zeros(&r, rLen);
- sLen = trim_leading_zeros(&s, sLen);
- /* If the leading bit on the INTEGER is a 1, add a leading zero */
- /* Add leading zero if MSB is set */
- rAddLeadZero = is_leading_bit_set(r, rLen);
- sAddLeadZero = is_leading_bit_set(s, sLen);
- if (*outLen < (rLen + rAddLeadZero + sLen + sAddLeadZero +
- headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
- return BUFFER_E;
- idx = SetSequence(rLen+rAddLeadZero + sLen+sAddLeadZero + headerSz, out);
- /* store r */
- ret = SetASNInt((int)rLen, (byte)(rAddLeadZero ? 0x80U : 0x00U), &out[idx]);
- if (ret < 0)
- return ret;
- idx += (word32)ret;
- XMEMCPY(&out[idx], r, rLen);
- idx += rLen;
- /* store s */
- ret = SetASNInt((int)sLen, (byte)(sAddLeadZero ? 0x80U : 0x00U), &out[idx]);
- if (ret < 0)
- return ret;
- idx += (word32)ret;
- XMEMCPY(&out[idx], s, sLen);
- idx += sLen;
- *outLen = idx;
- return 0;
- #else
- ASNSetData dataASN[dsaSigASN_Length];
- int ret;
- int sz;
- /* Clear dynamic data and set buffers for r and s */
- XMEMSET(dataASN, 0, sizeof(dataASN));
- SetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
- SetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
- /* Calculate size of encoding. */
- ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
- /* Check buffer is big enough for encoding. */
- if ((ret == 0) && ((int)*outLen < sz)) {
- ret = BUFFER_E;
- }
- if (ret == 0) {
- /* Encode DSA signature into buffer. */
- SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
- /* Set the actual encoding size. */
- *outLen = (word32)sz;
- }
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- /* Der Decode ECC-DSA Signature with R/S as unsigned bin */
- /* All input/outputs are assumed to be big-endian */
- int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen,
- byte* s, word32* sLen)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret;
- word32 idx = 0;
- int len = 0;
- if (GetSequence(sig, &idx, &len, sigLen) < 0) {
- return ASN_ECC_KEY_E;
- }
- #ifndef NO_STRICT_ECDSA_LEN
- /* enable strict length checking for signature */
- if (sigLen != idx + (word32)len) {
- return ASN_ECC_KEY_E;
- }
- #else
- /* allow extra signature bytes at end */
- if ((word32)len > (sigLen - idx)) {
- return ASN_ECC_KEY_E;
- }
- #endif
- ret = GetASNInt(sig, &idx, &len, sigLen);
- if (ret != 0)
- return ret;
- if (rLen)
- *rLen = (word32)len;
- if (r)
- XMEMCPY(r, (byte*)sig + idx, (size_t)len);
- idx += (word32)len;
- ret = GetASNInt(sig, &idx, &len, sigLen);
- if (ret != 0)
- return ret;
- if (sLen)
- *sLen = (word32)len;
- if (s)
- XMEMCPY(s, (byte*)sig + idx, (size_t)len);
- #ifndef NO_STRICT_ECDSA_LEN
- /* sanity check that the index has been advanced all the way to the end of
- * the buffer */
- if (idx + (word32)len != sigLen) {
- ret = ASN_ECC_KEY_E;
- }
- #endif
- return ret;
- #else
- ASNGetData dataASN[dsaSigASN_Length];
- word32 idx = 0;
- /* Clear dynamic data and set buffers to put r and s into. */
- XMEMSET(dataASN, 0, sizeof(dataASN));
- GetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
- GetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
- /* Decode the DSA signature. */
- return GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 1, sig, &idx,
- sigLen);
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
- {
- return DecodeECC_DSA_Sig_Ex(sig, sigLen, r, s, 1);
- }
- int DecodeECC_DSA_Sig_Ex(const byte* sig, word32 sigLen, mp_int* r, mp_int* s,
- int init)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0;
- int len = 0;
- if (GetSequence(sig, &idx, &len, sigLen) < 0) {
- return ASN_ECC_KEY_E;
- }
- #ifndef NO_STRICT_ECDSA_LEN
- /* enable strict length checking for signature */
- if (sigLen != idx + (word32)len) {
- return ASN_ECC_KEY_E;
- }
- #else
- /* allow extra signature bytes at end */
- if ((word32)len > (sigLen - idx)) {
- return ASN_ECC_KEY_E;
- }
- #endif
- if (GetIntPositive(r, sig, &idx, sigLen, init) < 0) {
- return ASN_ECC_KEY_E;
- }
- if (GetIntPositive(s, sig, &idx, sigLen, init) < 0) {
- mp_clear(r);
- return ASN_ECC_KEY_E;
- }
- #ifndef NO_STRICT_ECDSA_LEN
- /* sanity check that the index has been advanced all the way to the end of
- * the buffer */
- if (idx != sigLen) {
- mp_clear(r);
- mp_clear(s);
- return ASN_ECC_KEY_E;
- }
- #endif
- return 0;
- #else
- ASNGetData dataASN[dsaSigASN_Length];
- word32 idx = 0;
- int ret;
- /* Clear dynamic data and set mp_ints to put r and s into. */
- XMEMSET(dataASN, 0, sizeof(dataASN));
- if (init) {
- GetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
- GetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
- }
- else {
- GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_R], r);
- GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_S], s);
- }
- /* Decode the DSA signature. */
- ret = GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 0, sig, &idx,
- sigLen);
- #ifndef NO_STRICT_ECDSA_LEN
- /* sanity check that the index has been advanced all the way to the end of
- * the buffer */
- if ((ret == 0) && (idx != sigLen)) {
- ret = ASN_ECC_KEY_E;
- }
- #endif
- if (ret != 0) {
- mp_clear(r);
- mp_clear(s);
- }
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #endif
- #ifdef WOLFSSL_ASN_TEMPLATE
- #ifdef WOLFSSL_CUSTOM_CURVES
- /* Convert data to hex string.
- *
- * Big-endian byte array is converted to big-endian hexadecimal string.
- *
- * @param [in] input Buffer containing data.
- * @param [in] inSz Size of data in buffer.
- * @param [out] out Buffer to hold hex string.
- */
- static void DataToHexString(const byte* input, word32 inSz, char* out)
- {
- static const char hexChar[] = { '0', '1', '2', '3', '4', '5', '6', '7',
- '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
- word32 i;
- /* Converting a byte of data at a time to two hex characters. */
- for (i = 0; i < inSz; i++) {
- out[i*2 + 0] = hexChar[input[i] >> 4];
- out[i*2 + 1] = hexChar[input[i] & 0xf];
- }
- /* NUL terminate string. */
- out[i * 2] = '\0';
- }
- #ifndef WOLFSSL_ECC_CURVE_STATIC
- /* Convert data to hex string and place in allocated buffer.
- *
- * Big-endian byte array is converted to big-endian hexadecimal string.
- *
- * @param [in] input Buffer containing data.
- * @param [in] inSz Size of data in buffer.
- * @param [out] out Allocated buffer holding hex string.
- * @param [in] heap Dynamic memory allocation hint.
- * @param [in] heapType Type of heap to use.
- * @return 0 on succcess.
- * @return MEMORY_E when dynamic memory allocation fails.
- */
- static int DataToHexStringAlloc(const byte* input, word32 inSz, char** out,
- void* heap, int heapType)
- {
- int ret = 0;
- char* str;
- /* Allocate for 2 string characters ber byte plus NUL. */
- str = (char*)XMALLOC(inSz * 2 + 1, heap, heapType);
- if (str == NULL) {
- ret = MEMORY_E;
- }
- else {
- /* Convert to hex string. */
- DataToHexString(input, inSz, str);
- *out = str;
- }
- (void)heap;
- (void)heapType;
- return ret;
- }
- #endif /* WOLFSSL_ECC_CURVE_STATIC */
- /* ASN.1 template for SpecifiedECDomain.
- * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
- * NOTE: characteristic-two-field not supported. */
- static const ASNItem eccSpecifiedASN[] = {
- /* version */
- /* VER */ { 0, ASN_INTEGER, 0, 0, 0 },
- /* fieldID */
- /* PRIME_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* prime-field or characteristic-two-field */
- /* PRIME_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
- /* Prime-p */
- /* PRIME_P */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* fieldID */
- /* PARAM_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* a */
- /* PARAM_A */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
- /* b */
- /* PARAM_B */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
- /* seed */
- /* PARAM_SEED */ { 1, ASN_BIT_STRING, 0, 0, 1 },
- /* base */
- /* BASE */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
- /* order */
- /* ORDER */ { 0, ASN_INTEGER, 0, 0, 0 },
- /* cofactor */
- /* COFACTOR */ { 0, ASN_INTEGER, 0, 0, 1 },
- /* hash */
- /* HASH_SEQ */ { 0, ASN_SEQUENCE, 0, 0, 1 },
- };
- enum {
- ECCSPECIFIEDASN_IDX_VER = 0,
- ECCSPECIFIEDASN_IDX_PRIME_SEQ,
- ECCSPECIFIEDASN_IDX_PRIME_OID,
- ECCSPECIFIEDASN_IDX_PRIME_P,
- ECCSPECIFIEDASN_IDX_PARAM_SEQ,
- ECCSPECIFIEDASN_IDX_PARAM_A,
- ECCSPECIFIEDASN_IDX_PARAM_B,
- ECCSPECIFIEDASN_IDX_PARAM_SEED,
- ECCSPECIFIEDASN_IDX_BASE,
- ECCSPECIFIEDASN_IDX_ORDER,
- ECCSPECIFIEDASN_IDX_COFACTOR,
- ECCSPECIFIEDASN_IDX_HASH_SEQ
- };
- /* Number of items in ASN.1 template for SpecifiedECDomain. */
- #define eccSpecifiedASN_Length (sizeof(eccSpecifiedASN) / sizeof(ASNItem))
- /* OID indicating the prime field is explicity defined. */
- static const byte primeFieldOID[] = {
- 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01
- };
- static const char ecSetCustomName[] = "Custom";
- /* Explicit EC parameter values. */
- static int EccSpecifiedECDomainDecode(const byte* input, word32 inSz,
- ecc_key* key)
- {
- DECL_ASNGETDATA(dataASN, eccSpecifiedASN_Length);
- int ret = 0;
- ecc_set_type* curve;
- word32 idx = 0;
- byte version;
- byte cofactor;
- const byte *base;
- word32 baseLen;
- /* Allocate a new parameter set. */
- curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
- DYNAMIC_TYPE_ECC_BUFFER);
- if (curve == NULL) {
- ret = MEMORY_E;
- }
- else {
- /* Clear out parameters and set fields to indicate it is custom. */
- XMEMSET(curve, 0, sizeof(*curve));
- }
- CALLOC_ASNGETDATA(dataASN, eccSpecifiedASN_Length, ret, key->heap);
- if (ret == 0) {
- /* Set name to be: "Custom" */
- #ifndef WOLFSSL_ECC_CURVE_STATIC
- curve->name = ecSetCustomName;
- #else
- XMEMCPY((void*)curve->name, ecSetCustomName, sizeof(ecSetCustomName));
- #endif
- curve->id = ECC_CURVE_CUSTOM;
- /* Get version, must have prime field OID and get co-factor. */
- GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_VER], &version);
- GetASN_ExpBuffer(&dataASN[ECCSPECIFIEDASN_IDX_PRIME_OID],
- primeFieldOID, sizeof(primeFieldOID));
- GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_COFACTOR], &cofactor);
- /* Decode the explicit parameters. */
- ret = GetASN_Items(eccSpecifiedASN, dataASN, eccSpecifiedASN_Length, 1,
- input, &idx, inSz);
- }
- /* Version must be 1 or 2 for supporting explicit parameters. */
- if ((ret == 0) && (version < 1 || version > 3)) {
- ret = ASN_PARSE_E;
- }
- #ifndef WOLFSSL_NO_ASN_STRICT
- /* Only version 2 and above can have a seed. */
- if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_PARAM_SEED].tag != 0) &&
- (version < 2)) {
- ret = ASN_PARSE_E;
- }
- #endif
- /* Only version 2 and above can have a hash algorithm. */
- if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_HASH_SEQ].tag != 0) &&
- (version < 2)) {
- ret = ASN_PARSE_E;
- }
- if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_COFACTOR].tag != 0)) {
- /* Store optional co-factor. */
- curve->cofactor = cofactor;
- }
- if (ret == 0) {
- /* Length of the prime in bytes is the curve size. */
- curve->size =
- (int)dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length;
- /* Base point: 0x04 <x> <y> (must be uncompressed). */
- GetASN_GetConstRef(&dataASN[ECCSPECIFIEDASN_IDX_BASE], &base,
- &baseLen);
- if ((baseLen < (word32)curve->size * 2 + 1) || (base[0] != 0x4)) {
- ret = ASN_PARSE_E;
- }
- }
- /* Put the curve parameters into the set.
- * Convert the big-endian number byte array to a big-endian string.
- */
- #ifndef WOLFSSL_ECC_CURVE_STATIC
- /* Allocate buffer to put hex strings into. */
- if (ret == 0) {
- /* Base X-ordinate */
- ret = DataToHexStringAlloc(base + 1, (word32)curve->size,
- (char**)&curve->Gx, key->heap,
- DYNAMIC_TYPE_ECC_BUFFER);
- }
- if (ret == 0) {
- /* Base Y-ordinate */
- ret = DataToHexStringAlloc(base + 1 + curve->size, (word32)curve->size,
- (char**)&curve->Gy, key->heap,
- DYNAMIC_TYPE_ECC_BUFFER);
- }
- if (ret == 0) {
- /* Prime */
- ret = DataToHexStringAlloc(
- dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
- dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
- (char**)&curve->prime, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
- }
- if (ret == 0) {
- /* Parameter A */
- ret = DataToHexStringAlloc(
- dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
- dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
- (char**)&curve->Af, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
- }
- if (ret == 0) {
- /* Parameter B */
- ret = DataToHexStringAlloc(
- dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
- dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
- (char**)&curve->Bf, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
- }
- if (ret == 0) {
- /* Order of curve */
- ret = DataToHexStringAlloc(
- dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
- dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
- (char**)&curve->order, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
- }
- #else
- if (ret == 0) {
- /* Base X-ordinate */
- DataToHexString(base + 1, curve->size, curve->Gx);
- /* Base Y-ordinate */
- DataToHexString(base + 1 + curve->size, curve->size, curve->Gy);
- /* Prime */
- DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
- dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
- curve->prime);
- /* Parameter A */
- DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
- dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
- curve->Af);
- /* Parameter B */
- DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
- dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
- curve->Bf);
- /* Order of curve */
- DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
- dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
- curve->order);
- }
- #endif /* WOLFSSL_ECC_CURVE_STATIC */
- /* Store parameter set in key. */
- if ((ret == 0) && (wc_ecc_set_custom_curve(key, curve) < 0)) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- /* The parameter set was allocated.. */
- key->deallocSet = 1;
- }
- if ((ret != 0) && (curve != NULL)) {
- /* Failed to set parameters so free paramter set. */
- wc_ecc_free_curve(curve, key->heap);
- }
- FREE_ASNGETDATA(dataASN, key->heap);
- return ret;
- }
- #endif /* WOLFSSL_CUSTOM_CURVES */
- #endif /* WOLFSSL_ASN_TEMPLATE */
- #ifdef HAVE_ECC
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for ECC private key.
- * SEC.1 Ver 2.0, C.4 - Syntax for Elliptic Curve Private Keys
- */
- static const ASNItem eccKeyASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* version */
- /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* privateKey */
- /* PKEY */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
- /* parameters */
- /* PARAMS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PARAMS, 1, 1, 1 },
- /* named */
- /* CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
- /* specified */
- /* CURVEPARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
- /* publicKey */
- /* PUBKEY */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PUBKEY, 1, 1, 1 },
- /* Uncompressed point - X9.62. */
- /* PUBKEY_VAL, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
- };
- enum {
- ECCKEYASN_IDX_SEQ = 0,
- ECCKEYASN_IDX_VER,
- ECCKEYASN_IDX_PKEY,
- ECCKEYASN_IDX_PARAMS,
- ECCKEYASN_IDX_CURVEID,
- ECCKEYASN_IDX_CURVEPARAMS,
- ECCKEYASN_IDX_PUBKEY,
- ECCKEYASN_IDX_PUBKEY_VAL
- };
- /* Number of items in ASN.1 template for ECC private key. */
- #define eccKeyASN_Length (sizeof(eccKeyASN) / sizeof(ASNItem))
- #endif
- WOLFSSL_ABI
- int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
- word32 inSz)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 oidSum;
- int version, length;
- int privSz, pubSz = 0;
- byte b;
- int ret = 0;
- int curve_id = ECC_CURVE_DEF;
- #ifdef WOLFSSL_SMALL_STACK
- byte* priv;
- byte* pub = NULL;
- #else
- byte priv[ECC_MAXSIZE+1];
- byte pub[2*(ECC_MAXSIZE+1)]; /* public key has two parts plus header */
- #endif
- word32 algId = 0;
- byte* pubData = NULL;
- if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
- return BAD_FUNC_ARG;
- /* if has pkcs8 header skip it */
- if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
- /* ignore error, did not have pkcs8 header */
- }
- else {
- curve_id = wc_ecc_get_oid(algId, NULL, NULL);
- }
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
- return ASN_PARSE_E;
- if (*inOutIdx >= inSz)
- return ASN_PARSE_E;
- b = input[*inOutIdx];
- *inOutIdx += 1;
- /* priv type */
- if (b != 4 && b != 6 && b != 7)
- return ASN_PARSE_E;
- if (GetLength(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- privSz = length;
- if (privSz > ECC_MAXSIZE)
- return BUFFER_E;
- #ifdef WOLFSSL_SMALL_STACK
- priv = (byte*)XMALLOC(privSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (priv == NULL)
- return MEMORY_E;
- #endif
- /* priv key */
- XMEMCPY(priv, &input[*inOutIdx], (size_t)privSz);
- *inOutIdx += (word32)length;
- if ((*inOutIdx + 1) < inSz) {
- /* prefix 0, may have */
- b = input[*inOutIdx];
- if (b == ECC_PREFIX_0) {
- *inOutIdx += 1;
- if (GetLength(input, inOutIdx, &length, inSz) <= 0)
- ret = ASN_PARSE_E;
- else {
- ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType,
- inSz);
- if (ret == 0) {
- if ((ret = CheckCurve(oidSum)) < 0)
- ret = ECC_CURVE_OID_E;
- else {
- curve_id = ret;
- ret = 0;
- }
- }
- }
- }
- }
- if (ret == 0 && (*inOutIdx + 1) < inSz) {
- /* prefix 1 */
- b = input[*inOutIdx];
- *inOutIdx += 1;
- if (b != ECC_PREFIX_1) {
- ret = ASN_ECC_KEY_E;
- }
- else if (GetLength(input, inOutIdx, &length, inSz) <= 0) {
- ret = ASN_PARSE_E;
- }
- else {
- /* key header */
- ret = CheckBitString(input, inOutIdx, &length, inSz, 0, NULL);
- if (ret == 0) {
- /* pub key */
- pubSz = length;
- if (pubSz > 2*(ECC_MAXSIZE+1))
- ret = BUFFER_E;
- else {
- #ifdef WOLFSSL_SMALL_STACK
- pub = (byte*)XMALLOC(pubSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (pub == NULL)
- ret = MEMORY_E;
- else
- #endif
- {
- XMEMCPY(pub, &input[*inOutIdx], (size_t)pubSz);
- *inOutIdx += (word32)length;
- pubData = pub;
- }
- }
- }
- }
- }
- if (ret == 0) {
- ret = wc_ecc_import_private_key_ex(priv, (word32)privSz, pubData,
- (word32)pubSz, key, curve_id);
- }
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(priv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return ret;
- #else
- DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
- byte version;
- int ret = 0;
- int curve_id = ECC_CURVE_DEF;
- #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) || defined(SM2)
- word32 algId = 0;
- #endif
- /* Validate parameters. */
- if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
- ret = BAD_FUNC_ARG;
- }
- #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) || defined(SM2)
- /* if has pkcs8 header skip it */
- if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
- /* ignore error, did not have pkcs8 header */
- }
- else {
- curve_id = wc_ecc_get_oid(algId, NULL, NULL);
- }
- #endif
- CALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
- if (ret == 0) {
- /* Get the version and set the expected OID type. */
- GetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], &version);
- GetASN_OID(&dataASN[ECCKEYASN_IDX_CURVEID], oidCurveType);
- /* Decode the private ECC key. */
- ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
- inOutIdx, inSz);
- }
- /* Only version 1 supported. */
- if ((ret == 0) && (version != 1)) {
- ret = ASN_PARSE_E;
- }
- /* Curve Parameters are optional. */
- if ((ret == 0) && (dataASN[ECCKEYASN_IDX_PARAMS].tag != 0)) {
- if (dataASN[ECCKEYASN_IDX_CURVEID].tag != 0) {
- /* Named curve - check and get id. */
- curve_id = CheckCurve(dataASN[ECCKEYASN_IDX_CURVEID].data.oid.sum);
- if (curve_id < 0) {
- ret = ECC_CURVE_OID_E;
- }
- }
- else {
- #ifdef WOLFSSL_CUSTOM_CURVES
- /* Parse explicit parameters. */
- ret = EccSpecifiedECDomainDecode(
- dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.data,
- dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.length, key);
- #else
- /* Explicit parameters not supported in build configuration. */
- ret = ASN_PARSE_E;
- #endif
- }
- }
- if (ret == 0) {
- /* Import private key value and public point (may be NULL). */
- ret = wc_ecc_import_private_key_ex(
- dataASN[ECCKEYASN_IDX_PKEY].data.ref.data,
- dataASN[ECCKEYASN_IDX_PKEY].data.ref.length,
- dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.data,
- dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.length,
- key, curve_id);
- }
- FREE_ASNGETDATA(dataASN, key->heap);
- return ret;
- #endif
- }
- #ifdef WOLFSSL_CUSTOM_CURVES
- #ifndef WOLFSSL_ASN_TEMPLATE
- /* returns 0 on success */
- static int ASNToHexString(const byte* input, word32* inOutIdx, char** out,
- word32 inSz, void* heap, int heapType)
- {
- int len;
- int i;
- char* str;
- word32 localIdx;
- byte tag;
- if (*inOutIdx >= inSz) {
- return BUFFER_E;
- }
- localIdx = *inOutIdx;
- if (GetASNTag(input, &localIdx, &tag, inSz) == 0 && tag == ASN_INTEGER) {
- if (GetASNInt(input, inOutIdx, &len, inSz) < 0)
- return ASN_PARSE_E;
- }
- else {
- if (GetOctetString(input, inOutIdx, &len, inSz) < 0)
- return ASN_PARSE_E;
- }
- str = (char*)XMALLOC((size_t)len * 2 + 1, heap, heapType);
- if (str == NULL) {
- return MEMORY_E;
- }
- for (i=0; i<len; i++)
- ByteToHexStr(input[*inOutIdx + (word32)i], str + i*2);
- str[len*2] = '\0';
- *inOutIdx += (word32)len;
- *out = str;
- (void)heap;
- (void)heapType;
- return 0;
- }
- static int EccKeyParamCopy(char** dst, char* src)
- {
- int ret = 0;
- #ifdef WOLFSSL_ECC_CURVE_STATIC
- word32 length;
- #endif
- if (dst == NULL || src == NULL)
- return BAD_FUNC_ARG;
- #ifndef WOLFSSL_ECC_CURVE_STATIC
- *dst = src;
- #else
- length = (int)XSTRLEN(src) + 1;
- if (length > MAX_ECC_STRING) {
- WOLFSSL_MSG("ECC Param too large for buffer");
- ret = BUFFER_E;
- }
- else {
- XSTRNCPY(*dst, src, MAX_ECC_STRING);
- }
- XFREE(src, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
- #endif
- return ret;
- }
- #endif /* !WOLFSSL_ASN_TEMPLATE */
- #endif /* WOLFSSL_CUSTOM_CURVES */
- WOLFSSL_ABI
- int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx,
- ecc_key* key, word32 inSz)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret;
- int version, length;
- int curve_id = ECC_CURVE_DEF;
- word32 oidSum, localIdx;
- byte tag, isPrivFormat = 0;
- if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
- return BAD_FUNC_ARG;
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- /* Check if ECC private key is being used and skip private portion */
- if (GetMyVersion(input, inOutIdx, &version, inSz) >= 0) {
- isPrivFormat = 1;
- /* Type private key */
- if (*inOutIdx >= inSz)
- return ASN_PARSE_E;
- tag = input[*inOutIdx];
- *inOutIdx += 1;
- if (tag != 4 && tag != 6 && tag != 7)
- return ASN_PARSE_E;
- /* Skip Private Key */
- if (GetLength(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- if (length > ECC_MAXSIZE)
- return BUFFER_E;
- *inOutIdx += (word32)length;
- /* Private Curve Header */
- if (*inOutIdx >= inSz)
- return ASN_PARSE_E;
- tag = input[*inOutIdx];
- *inOutIdx += 1;
- if (tag != ECC_PREFIX_0)
- return ASN_ECC_KEY_E;
- if (GetLength(input, inOutIdx, &length, inSz) <= 0)
- return ASN_PARSE_E;
- }
- /* Standard ECC public key */
- else {
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- ret = SkipObjectId(input, inOutIdx, inSz);
- if (ret != 0)
- return ret;
- }
- if (*inOutIdx >= inSz) {
- return BUFFER_E;
- }
- localIdx = *inOutIdx;
- if (GetASNTag(input, &localIdx, &tag, inSz) == 0 &&
- tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
- #ifdef WOLFSSL_CUSTOM_CURVES
- ecc_set_type* curve;
- int len;
- char* point = NULL;
- ret = 0;
- curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
- DYNAMIC_TYPE_ECC_BUFFER);
- if (curve == NULL)
- ret = MEMORY_E;
- if (ret == 0) {
- static const char customName[] = "Custom";
- XMEMSET(curve, 0, sizeof(*curve));
- #ifndef WOLFSSL_ECC_CURVE_STATIC
- curve->name = customName;
- #else
- XMEMCPY((void*)curve->name, customName, sizeof(customName));
- #endif
- curve->id = ECC_CURVE_CUSTOM;
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- GetInteger7Bit(input, inOutIdx, inSz);
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- char* p = NULL;
- SkipObjectId(input, inOutIdx, inSz);
- ret = ASNToHexString(input, inOutIdx, &p, inSz,
- key->heap, DYNAMIC_TYPE_ECC_BUFFER);
- if (ret == 0) {
- #ifndef WOLFSSL_ECC_CURVE_STATIC
- ret = EccKeyParamCopy((char**)&curve->prime, p);
- #else
- const char *_tmp_ptr = &curve->prime[0];
- ret = EccKeyParamCopy((char**)&_tmp_ptr, p);
- #endif
- }
- }
- if (ret == 0) {
- curve->size = (int)XSTRLEN(curve->prime) / 2;
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- char* af = NULL;
- ret = ASNToHexString(input, inOutIdx, &af, inSz,
- key->heap, DYNAMIC_TYPE_ECC_BUFFER);
- if (ret == 0) {
- #ifndef WOLFSSL_ECC_CURVE_STATIC
- ret = EccKeyParamCopy((char**)&curve->Af, af);
- #else
- const char *_tmp_ptr = &curve->Af[0];
- ret = EccKeyParamCopy((char**)&_tmp_ptr, af);
- #endif
- }
- }
- if (ret == 0) {
- char* bf = NULL;
- ret = ASNToHexString(input, inOutIdx, &bf, inSz,
- key->heap, DYNAMIC_TYPE_ECC_BUFFER);
- if (ret == 0) {
- #ifndef WOLFSSL_ECC_CURVE_STATIC
- ret = EccKeyParamCopy((char**)&curve->Bf, bf);
- #else
- const char *_tmp_ptr = &curve->Bf[0];
- ret = EccKeyParamCopy((char**)&_tmp_ptr, bf);
- #endif
- }
- }
- if (ret == 0) {
- localIdx = *inOutIdx;
- if (*inOutIdx < inSz && GetASNTag(input, &localIdx, &tag, inSz)
- == 0 && tag == ASN_BIT_STRING) {
- len = 0;
- ret = GetASNHeader(input, ASN_BIT_STRING, inOutIdx, &len, inSz);
- if (ret > 0)
- ret = 0; /* reset on success */
- *inOutIdx += (word32)len;
- }
- }
- if (ret == 0) {
- ret = ASNToHexString(input, inOutIdx, (char**)&point, inSz,
- key->heap, DYNAMIC_TYPE_ECC_BUFFER);
- /* sanity check that point buffer is not smaller than the expected
- * size to hold ( 0 4 || Gx || Gy )
- * where Gx and Gy are each the size of curve->size * 2 */
- if (ret == 0 && (int)XSTRLEN(point) < (curve->size * 4) + 2) {
- XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
- ret = BUFFER_E;
- }
- }
- if (ret == 0) {
- #ifndef WOLFSSL_ECC_CURVE_STATIC
- curve->Gx = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
- key->heap, DYNAMIC_TYPE_ECC_BUFFER);
- curve->Gy = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
- key->heap, DYNAMIC_TYPE_ECC_BUFFER);
- if (curve->Gx == NULL || curve->Gy == NULL) {
- XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
- ret = MEMORY_E;
- }
- #else
- if (curve->size * 2 + 2 > MAX_ECC_STRING) {
- WOLFSSL_MSG("curve size is too large to fit in buffer");
- ret = BUFFER_E;
- }
- #endif
- }
- if (ret == 0) {
- char* o = NULL;
- XMEMCPY((char*)curve->Gx, point + 2, (size_t)curve->size * 2);
- XMEMCPY((char*)curve->Gy, point + curve->size * 2 + 2,
- (size_t)curve->size * 2);
- ((char*)curve->Gx)[curve->size * 2] = '\0';
- ((char*)curve->Gy)[curve->size * 2] = '\0';
- XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
- ret = ASNToHexString(input, inOutIdx, &o, inSz,
- key->heap, DYNAMIC_TYPE_ECC_BUFFER);
- if (ret == 0) {
- #ifndef WOLFSSL_ECC_CURVE_STATIC
- ret = EccKeyParamCopy((char**)&curve->order, o);
- #else
- const char *_tmp_ptr = &curve->order[0];
- ret = EccKeyParamCopy((char**)&_tmp_ptr, o);
- #endif
- }
- }
- if (ret == 0) {
- curve->cofactor = GetInteger7Bit(input, inOutIdx, inSz);
- #ifndef WOLFSSL_ECC_CURVE_STATIC
- curve->oid = NULL;
- #else
- XMEMSET((void*)curve->oid, 0, sizeof(curve->oid));
- #endif
- curve->oidSz = 0;
- curve->oidSum = 0;
- if (wc_ecc_set_custom_curve(key, curve) < 0) {
- ret = ASN_PARSE_E;
- }
- key->deallocSet = 1;
- curve = NULL;
- }
- if (curve != NULL)
- wc_ecc_free_curve(curve, key->heap);
- if (ret < 0)
- return ret;
- #else
- return ASN_PARSE_E;
- #endif /* WOLFSSL_CUSTOM_CURVES */
- }
- else {
- /* ecc params information */
- ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType, inSz);
- if (ret != 0)
- return ret;
- /* get curve id */
- if ((ret = CheckCurve(oidSum)) < 0)
- return ECC_CURVE_OID_E;
- else {
- curve_id = ret;
- }
- }
- if (isPrivFormat) {
- /* Public Curve Header - skip */
- if (*inOutIdx >= inSz)
- return ASN_PARSE_E;
- tag = input[*inOutIdx];
- *inOutIdx += 1;
- if (tag != ECC_PREFIX_1)
- return ASN_ECC_KEY_E;
- if (GetLength(input, inOutIdx, &length, inSz) <= 0)
- return ASN_PARSE_E;
- }
- /* key header */
- ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
- if (ret != 0)
- return ret;
- /* This is the raw point data compressed or uncompressed. */
- if (wc_ecc_import_x963_ex(input + *inOutIdx, (word32)length, key,
- curve_id) != 0) {
- return ASN_ECC_KEY_E;
- }
- *inOutIdx += (word32)length;
- return 0;
- #else
- /* eccKeyASN is longer than eccPublicKeyASN. */
- DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
- int ret = 0;
- int curve_id = ECC_CURVE_DEF;
- int oidIdx = ECCPUBLICKEYASN_IDX_ALGOID_CURVEID;
- #ifdef WOLFSSL_CUSTOM_CURVES
- int specIdx = ECCPUBLICKEYASN_IDX_ALGOID_PARAMS;
- #endif
- int pubIdx = ECCPUBLICKEYASN_IDX_PUBKEY;
- if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
- ret = BAD_FUNC_ARG;
- }
- ALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
- if (ret == 0) {
- /* Clear dynamic data for ECC public key. */
- XMEMSET(dataASN, 0, sizeof(*dataASN) * eccPublicKeyASN_Length);
- #if !defined(WOLFSSL_SM2) || !defined(WOLFSSL_SM3)
- /* Set required ECDSA OID and ignore the curve OID type. */
- GetASN_ExpBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], keyEcdsaOid,
- sizeof(keyEcdsaOid));
- #else
- GetASN_OID(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], oidKeyType);
- #endif
- GetASN_OID(&dataASN[oidIdx], oidCurveType);
- /* Decode the public ECC key. */
- ret = GetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length, 1,
- input, inOutIdx, inSz);
- if (ret != 0) {
- oidIdx = ECCKEYASN_IDX_CURVEID;
- #ifdef WOLFSSL_CUSTOM_CURVES
- specIdx = ECCKEYASN_IDX_CURVEPARAMS;
- #endif
- pubIdx = ECCKEYASN_IDX_PUBKEY_VAL;
- /* Clear dynamic data for ECC private key. */
- XMEMSET(dataASN, 0, sizeof(*dataASN) * eccKeyASN_Length);
- /* Check named curve OID type. */
- GetASN_OID(&dataASN[oidIdx], oidCurveType);
- /* Try private key format .*/
- ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
- inOutIdx, inSz);
- if (ret != 0) {
- ret = ASN_PARSE_E;
- }
- }
- }
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- if ((ret == 0) && (oidIdx == ECCPUBLICKEYASN_IDX_ALGOID_CURVEID)) {
- int oidSum = dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID].data.oid.sum;
- if ((oidSum != ECDSAk) && (oidSum != SM2k)) {
- ret = ASN_PARSE_E;
- }
- }
- #endif
- if (ret == 0) {
- if (dataASN[oidIdx].tag != 0) {
- /* Named curve - check and get id. */
- curve_id = CheckCurve(dataASN[oidIdx].data.oid.sum);
- if (curve_id < 0) {
- ret = ASN_OBJECT_ID_E;
- }
- }
- else {
- #ifdef WOLFSSL_CUSTOM_CURVES
- /* Parse explicit parameters. */
- ret = EccSpecifiedECDomainDecode(dataASN[specIdx].data.ref.data,
- dataASN[specIdx].data.ref.length, key);
- #else
- /* Explicit parameters not supported in build configuration. */
- ret = ASN_PARSE_E;
- #endif
- }
- }
- if (ret == 0) {
- /* Import public point. */
- ret = wc_ecc_import_x963_ex(dataASN[pubIdx].data.ref.data,
- dataASN[pubIdx].data.ref.length, key, curve_id);
- if (ret != 0) {
- ret = ASN_ECC_KEY_E;
- }
- }
- FREE_ASNGETDATA(dataASN, key->heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #if defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
- /* build DER formatted ECC key, include optional public key if requested,
- * return length on success, negative on error */
- static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen,
- int pubIn, int curveIn)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- byte curve[MAX_ALGO_SZ+2];
- byte ver[MAX_VERSION_SZ];
- byte seq[MAX_SEQ_SZ];
- int ret, curveSz, verSz;
- word32 totalSz;
- int privHdrSz = ASN_ECC_HEADER_SZ;
- int pubHdrSz = ASN_ECC_CONTEXT_SZ + ASN_ECC_HEADER_SZ;
- #ifdef WOLFSSL_NO_MALLOC
- byte prv[MAX_ECC_BYTES + ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
- byte pub[(MAX_ECC_BYTES * 2) + 1 + ASN_ECC_CONTEXT_SZ +
- ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
- #else
- byte *prv = NULL, *pub = NULL;
- #endif
- word32 idx = 0, prvidx = 0, pubidx = 0, curveidx = 0;
- word32 seqSz, privSz, pubSz = ECC_BUFSIZE;
- if (key == NULL || (output == NULL && inLen == NULL))
- return BAD_FUNC_ARG;
- if (curveIn) {
- /* curve */
- curve[curveidx++] = ECC_PREFIX_0;
- curveidx++ /* to put the size after computation */;
- curveSz = SetCurve(key, curve+curveidx, MAX_ALGO_SZ);
- if (curveSz < 0)
- return curveSz;
- /* set computed size */
- curve[1] = (byte)curveSz;
- curveidx += (word32)curveSz;
- }
- /* private */
- privSz = (word32)key->dp->size;
- #ifdef WOLFSSL_QNX_CAAM
- /* check if is a black key, and add MAC size if needed */
- if (key->blackKey > 0 && key->blackKey != CAAM_BLACK_KEY_ECB) {
- privSz = privSz + WC_CAAM_MAC_SZ;
- }
- #endif
- #ifndef WOLFSSL_NO_MALLOC
- prv = (byte*)XMALLOC(privSz + (word32)privHdrSz + MAX_SEQ_SZ,
- key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (prv == NULL) {
- return MEMORY_E;
- }
- #else
- if (sizeof(prv) < privSz + privHdrSz + MAX_SEQ_SZ) {
- return BUFFER_E;
- }
- #endif
- if (privSz < ASN_LONG_LENGTH) {
- prvidx += SetOctetString8Bit(privSz, &prv[prvidx]);
- }
- else {
- prvidx += SetOctetString(privSz, &prv[prvidx]);
- }
- ret = wc_ecc_export_private_only(key, prv + prvidx, &privSz);
- if (ret < 0) {
- #ifndef WOLFSSL_NO_MALLOC
- XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return ret;
- }
- prvidx += privSz;
- /* pubIn */
- if (pubIn) {
- PRIVATE_KEY_UNLOCK();
- ret = wc_ecc_export_x963(key, NULL, &pubSz);
- PRIVATE_KEY_LOCK();
- if (ret != LENGTH_ONLY_E) {
- #ifndef WOLFSSL_NO_MALLOC
- XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return ret;
- }
- #ifndef WOLFSSL_NO_MALLOC
- pub = (byte*)XMALLOC(pubSz + (word32)pubHdrSz + MAX_SEQ_SZ,
- key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (pub == NULL) {
- XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- return MEMORY_E;
- }
- #else
- if (sizeof(pub) < pubSz + pubHdrSz + MAX_SEQ_SZ) {
- return BUFFER_E;
- }
- #endif
- pub[pubidx++] = ECC_PREFIX_1;
- if (pubSz > 128) /* leading zero + extra size byte */
- pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 2, pub+pubidx);
- else /* leading zero */
- pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 1, pub+pubidx);
- /* SetBitString adds leading zero */
- pubidx += SetBitString(pubSz, 0, pub + pubidx);
- PRIVATE_KEY_UNLOCK();
- ret = wc_ecc_export_x963(key, pub + pubidx, &pubSz);
- PRIVATE_KEY_LOCK();
- if (ret != 0) {
- #ifndef WOLFSSL_NO_MALLOC
- XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return ret;
- }
- pubidx += pubSz;
- }
- /* make headers */
- verSz = SetMyVersion(1, ver, FALSE);
- seqSz = SetSequence((word32)verSz + prvidx + pubidx + curveidx, seq);
- totalSz = prvidx + pubidx + curveidx + (word32)verSz + seqSz;
- if (output == NULL) {
- *inLen = totalSz;
- #ifndef WOLFSSL_NO_MALLOC
- XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (pubIn) {
- XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- }
- #endif
- return LENGTH_ONLY_E;
- }
- if (inLen != NULL && totalSz > *inLen) {
- #ifndef WOLFSSL_NO_MALLOC
- XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (pubIn) {
- XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- }
- #endif
- return BAD_FUNC_ARG;
- }
- /* write out */
- /* seq */
- XMEMCPY(output + idx, seq, seqSz);
- idx = seqSz;
- /* ver */
- XMEMCPY(output + idx, ver, (size_t)verSz);
- idx += (word32)verSz;
- /* private */
- XMEMCPY(output + idx, prv, prvidx);
- idx += prvidx;
- #ifndef WOLFSSL_NO_MALLOC
- XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- /* curve */
- XMEMCPY(output + idx, curve, curveidx);
- idx += curveidx;
- /* pubIn */
- if (pubIn) {
- XMEMCPY(output + idx, pub, pubidx);
- /* idx += pubidx; not used after write, if more data remove comment */
- #ifndef WOLFSSL_NO_MALLOC
- XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- }
- return (int)totalSz;
- #else
- DECL_ASNSETDATA(dataASN, eccKeyASN_Length);
- word32 privSz, pubSz;
- int sz = 0;
- int ret = 0;
- int curveIdSz = 0;
- /* Check validity of parameters. */
- if ((key == NULL) || ((output == NULL) && (inLen == NULL))) {
- ret = BAD_FUNC_ARG;
- }
- /* Check key has parameters when encoding curve. */
- if ((ret == 0) && curveIn && (key->dp == NULL)) {
- ret = BAD_FUNC_ARG;
- }
- CALLOC_ASNSETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
- if (ret == 0) {
- /* Private key size is the curve size. */
- privSz = (word32)key->dp->size;
- if (pubIn) {
- /* Get the length of the public key. */
- PRIVATE_KEY_UNLOCK();
- ret = wc_ecc_export_x963(key, NULL, &pubSz);
- PRIVATE_KEY_LOCK();
- if (ret == LENGTH_ONLY_E)
- ret = 0;
- }
- }
- if (ret == 0) {
- /* Version: 1 */
- SetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], 1);
- /* Leave space for private key. */
- SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PKEY], NULL, privSz);
- if (curveIn) {
- /* Get length of the named curve OID to put into the encoding. */
- curveIdSz = SetCurve(key, NULL, 0);
- if (curveIdSz < 0) {
- ret = curveIdSz;
- }
- /* Curve OID */
- SetASN_ReplaceBuffer(&dataASN[ECCKEYASN_IDX_CURVEID], NULL,
- (word32)curveIdSz);
- /* TODO: add support for SpecifiedECDomain curve. */
- dataASN[ECCKEYASN_IDX_CURVEPARAMS].noOut = 1;
- }
- else {
- SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PARAMS,
- eccKeyASN_Length);
- }
- if (ret == 0) {
- if (pubIn) {
- /* Leave space for public key. */
- SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PUBKEY_VAL], NULL, pubSz);
- }
- else {
- /* Don't write out public key. */
- SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PUBKEY,
- eccKeyASN_Length);
- }
- /* Calculate size of the private key encoding. */
- ret = SizeASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, &sz);
- }
- }
- /* Return the size if no buffer. */
- if ((ret == 0) && (output == NULL)) {
- *inLen = (word32)sz;
- ret = LENGTH_ONLY_E;
- }
- /* Check the buffer is big enough. */
- if ((ret == 0) && (inLen != NULL) && (sz > (int)*inLen)) {
- ret = BAD_FUNC_ARG;
- }
- if ((ret == 0) && (output != NULL)) {
- /* Encode the private key. */
- SetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, output);
- if (curveIn) {
- /* Put named curve OID data into encoding. */
- curveIdSz = SetCurve(key,
- (byte*)dataASN[ECCKEYASN_IDX_CURVEID].data.buffer.data,
- (size_t)curveIdSz);
- if (curveIdSz < 0) {
- ret = curveIdSz;
- }
- }
- if (ret == 0) {
- /* Export the private value into the buffer. */
- ret = wc_ecc_export_private_only(key,
- (byte*)dataASN[ECCKEYASN_IDX_PKEY].data.buffer.data, &privSz);
- }
- if ((ret == 0) && pubIn) {
- /* Export the public point into the buffer. */
- PRIVATE_KEY_UNLOCK();
- ret = wc_ecc_export_x963(key,
- (byte*)dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.buffer.data,
- &pubSz);
- PRIVATE_KEY_LOCK();
- }
- }
- if (ret == 0) {
- /* Return the encoding size. */
- ret = sz;
- }
- FREE_ASNSETDATA(dataASN, key->heap);
- return ret;
- #endif
- }
- /* Write a Private ecc key, including public to DER format,
- * length on success else < 0 */
- WOLFSSL_ABI
- int wc_EccKeyToDer(ecc_key* key, byte* output, word32 inLen)
- {
- return wc_BuildEccKeyDer(key, output, &inLen, 1, 1);
- }
- /* Write only private ecc key to DER format,
- * length on success else < 0 */
- int wc_EccKeyDerSize(ecc_key* key, int pub)
- {
- word32 sz = 0;
- int ret;
- ret = wc_BuildEccKeyDer(key, NULL, &sz, pub, 1);
- if (ret != LENGTH_ONLY_E) {
- return ret;
- }
- return (int)sz;
- }
- /* Write only private ecc key to DER format,
- * length on success else < 0 */
- int wc_EccPrivateKeyToDer(ecc_key* key, byte* output, word32 inLen)
- {
- return wc_BuildEccKeyDer(key, output, &inLen, 0, 1);
- }
- #ifdef HAVE_PKCS8
- /* Write only private ecc key or both private and public parts to unencrypted
- * PKCS#8 format.
- *
- * If output is NULL, places required PKCS#8 buffer size in outLen and
- * returns LENGTH_ONLY_E.
- *
- * return length on success else < 0 */
- static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen,
- int includePublic)
- {
- int ret;
- word32 tmpDerSz;
- int algoID = 0;
- word32 oidSz = 0;
- word32 pkcs8Sz = 0;
- const byte* curveOID = NULL;
- #ifdef WOLFSSL_NO_MALLOC
- byte tmpDer[ECC_BUFSIZE];
- #else
- byte* tmpDer = NULL;
- #endif
- word32 sz = ECC_BUFSIZE;
- if (key == NULL || key->dp == NULL || outLen == NULL)
- return BAD_FUNC_ARG;
- /* set algoID, get curve OID */
- algoID = ECDSAk;
- ret = wc_ecc_get_oid(key->dp->oidSum, &curveOID, &oidSz);
- if (ret < 0)
- return ret;
- #ifndef WOLFSSL_NO_MALLOC
- /* temp buffer for plain DER key */
- tmpDer = (byte*)XMALLOC(ECC_BUFSIZE, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- if (tmpDer == NULL)
- return MEMORY_E;
- #endif
- XMEMSET(tmpDer, 0, ECC_BUFSIZE);
- ret = wc_BuildEccKeyDer(key, tmpDer, &sz, includePublic, 0);
- if (ret < 0) {
- #ifndef WOLFSSL_NO_MALLOC
- XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return ret;
- }
- tmpDerSz = (word32)ret;
- /* get pkcs8 expected output size */
- ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, tmpDer, tmpDerSz, algoID,
- curveOID, oidSz);
- if (ret != LENGTH_ONLY_E) {
- #ifndef WOLFSSL_NO_MALLOC
- XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return ret;
- }
- if (output == NULL) {
- #ifndef WOLFSSL_NO_MALLOC
- XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- *outLen = pkcs8Sz;
- return LENGTH_ONLY_E;
- }
- else if (*outLen < pkcs8Sz) {
- #ifndef WOLFSSL_NO_MALLOC
- XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- WOLFSSL_MSG("Input buffer too small for ECC PKCS#8 key");
- return BUFFER_E;
- }
- ret = wc_CreatePKCS8Key(output, &pkcs8Sz, tmpDer, tmpDerSz,
- algoID, curveOID, oidSz);
- if (ret < 0) {
- #ifndef WOLFSSL_NO_MALLOC
- XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- return ret;
- }
- #ifndef WOLFSSL_NO_MALLOC
- XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- *outLen = (word32)ret;
- return ret;
- }
- /* Write only private ecc key to unencrypted PKCS#8 format.
- *
- * return length on success else < 0 */
- int wc_EccPrivateKeyToPKCS8(ecc_key* key, byte* output, word32* outLen)
- {
- return eccToPKCS8(key, output, outLen, 0);
- }
- /* Write both private and public ecc keys to unencrypted PKCS#8 format.
- *
- * return length on success else < 0 */
- int wc_EccKeyToPKCS8(ecc_key* key, byte* output,
- word32* outLen)
- {
- return eccToPKCS8(key, output, outLen, 1);
- }
- #endif /* HAVE_PKCS8 */
- #endif /* HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
- #endif /* HAVE_ECC */
- #ifdef WC_ENABLE_ASYM_KEY_IMPORT
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for Ed25519 and Ed448 private key.
- * RFC 8410, 7 - Private Key Format (but public value is EXPLICIT OCTET_STRING)
- */
- static const ASNItem edKeyASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* Version */
- /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* privateKeyAlgorithm */
- /* PKEYALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* PKEYALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
- /* privateKey */
- /* PKEY */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
- /* CurvePrivateKey */
- /* PKEY_CURVEPKEY */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
- /* attributes */
- /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_ATTRS, 1, 1, 1 },
- /* publicKey */
- /* PUBKEY */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY, 0, 0, 1 },
- };
- enum {
- EDKEYASN_IDX_SEQ = 0,
- EDKEYASN_IDX_VER,
- EDKEYASN_IDX_PKEYALGO_SEQ,
- EDKEYASN_IDX_PKEYALGO_OID,
- EDKEYASN_IDX_PKEY,
- EDKEYASN_IDX_PKEY_CURVEPKEY,
- EDKEYASN_IDX_ATTRS,
- EDKEYASN_IDX_PUBKEY
- };
- /* Number of items in ASN.1 template for Ed25519 and Ed448 private key. */
- #define edKeyASN_Length (sizeof(edKeyASN) / sizeof(ASNItem))
- #endif
- #if ((defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)) \
- || (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)) \
- || (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)) \
- || (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)) \
- || (defined(HAVE_PQC) && defined(HAVE_FALCON)) \
- || (defined(HAVE_PQC) && defined(HAVE_DILITHIUM)) \
- || (defined(HAVE_PQC) && defined(HAVE_SPHINCS)))
- int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz,
- byte* privKey, word32* privKeyLen,
- byte* pubKey, word32* pubKeyLen, int keyType)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 oid;
- int version, length, endKeyIdx, privSz, pubSz;
- const byte* priv;
- const byte* pub;
- #else
- int ret = 0;
- DECL_ASNGETDATA(dataASN, edKeyASN_Length);
- CALLOC_ASNGETDATA(dataASN, edKeyASN_Length, ret, NULL);
- #endif
- if (input == NULL || inOutIdx == NULL || inSz == 0 ||
- privKey == NULL || privKeyLen == NULL) {
- return BAD_FUNC_ARG;
- }
- #ifndef WOLFSSL_ASN_TEMPLATE
- if (GetSequence(input, inOutIdx, &length, inSz) >= 0) {
- endKeyIdx = (int)*inOutIdx + length;
- if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
- return ASN_PARSE_E;
- if (version != 0) {
- WOLFSSL_MSG("Unrecognized version of ED25519 private key");
- return ASN_PARSE_E;
- }
- if (GetAlgoId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
- return ASN_PARSE_E;
- if (oid != (word32)keyType)
- return ASN_PARSE_E;
- if (GetOctetString(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
- return ASN_PARSE_E;
- priv = input + *inOutIdx;
- *inOutIdx += (word32)privSz;
- }
- else {
- if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
- return ASN_PARSE_E;
- priv = input + *inOutIdx;
- *inOutIdx += (word32)privSz;
- endKeyIdx = (int)*inOutIdx;
- }
- if ((word32)privSz > *privKeyLen)
- return BUFFER_E;
- if (endKeyIdx == (int)*inOutIdx) {
- *privKeyLen = (word32)privSz;
- XMEMCPY(privKey, priv, *privKeyLen);
- if (pubKeyLen != NULL)
- *pubKeyLen = 0;
- }
- else {
- if (pubKeyLen == NULL) {
- return BAD_FUNC_ARG;
- }
- if (GetASNHeader(input, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY | 1,
- inOutIdx, &pubSz, inSz) < 0) {
- return ASN_PARSE_E;
- }
- if ((word32)pubSz > *pubKeyLen)
- return BUFFER_E;
- pub = input + *inOutIdx;
- *inOutIdx += (word32)pubSz;
- *privKeyLen = (word32)privSz;
- XMEMCPY(privKey, priv, *privKeyLen);
- *pubKeyLen = (word32)pubSz;
- if (pubKey != NULL)
- XMEMCPY(pubKey, pub, *pubKeyLen);
- }
- if (endKeyIdx != (int)*inOutIdx)
- return ASN_PARSE_E;
- return 0;
- #else
- if (ret == 0) {
- /* Require OID. */
- word32 oidSz;
- const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz);
- GetASN_ExpBuffer(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], oid, oidSz);
- /* Parse full private key. */
- ret = GetASN_Items(edKeyASN, dataASN, edKeyASN_Length, 1, input,
- inOutIdx, inSz);
- if (ret != 0) {
- /* Parse just the OCTET_STRING. */
- ret = GetASN_Items(&edKeyASN[EDKEYASN_IDX_PKEY_CURVEPKEY],
- &dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], 1, 0, input,
- inOutIdx, inSz);
- if (ret != 0) {
- ret = ASN_PARSE_E;
- }
- }
- }
- /* Check the private value length is correct. */
- if ((ret == 0) && dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length
- > *privKeyLen) {
- ret = ASN_PARSE_E;
- }
- if ((ret == 0) && dataASN[EDKEYASN_IDX_PUBKEY].tag == 0) {
- *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
- XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
- *privKeyLen);
- if (pubKeyLen != NULL)
- *pubKeyLen = 0;
- }
- else if ((ret == 0) &&
- (pubKeyLen != NULL) &&
- (dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
- ret = ASN_PARSE_E;
- }
- else if (ret == 0) {
- /* Import private and public value. */
- *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
- XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
- *privKeyLen);
- if (pubKeyLen != NULL)
- *pubKeyLen = dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length;
- if (pubKey != NULL && pubKeyLen != NULL)
- XMEMCPY(pubKey, dataASN[EDKEYASN_IDX_PUBKEY].data.ref.data,
- *pubKeyLen);
- }
- FREE_ASNGETDATA(dataASN, NULL);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz,
- byte* pubKey, word32* pubKeyLen, int keyType)
- {
- int ret = 0;
- #ifndef WOLFSSL_ASN_TEMPLATE
- int length;
- word32 oid;
- #else
- word32 len;
- DECL_ASNGETDATA(dataASN, edPubKeyASN_Length);
- #endif
- if (input == NULL || inSz == 0 || inOutIdx == NULL ||
- pubKey == NULL || pubKeyLen == NULL) {
- return BAD_FUNC_ARG;
- }
- #ifndef WOLFSSL_ASN_TEMPLATE
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- if (GetSequence(input, inOutIdx, &length, inSz) < 0)
- return ASN_PARSE_E;
- if (GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
- return ASN_PARSE_E;
- if (oid != (word32)keyType)
- return ASN_PARSE_E;
- /* key header */
- ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
- if (ret != 0)
- return ret;
- /* check that the value found is not too large for pubKey buffer */
- if ((word32)length > *pubKeyLen)
- return ASN_PARSE_E;
- /* check that input buffer is exhausted */
- if (*inOutIdx + (word32)length != inSz)
- return ASN_PARSE_E;
- /* This is the raw point data compressed or uncompressed. */
- *pubKeyLen = (word32)length;
- XMEMCPY(pubKey, input + *inOutIdx, *pubKeyLen);
- #else
- len = inSz - *inOutIdx;
- CALLOC_ASNGETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
- if (ret == 0) {
- /* Require OID. */
- word32 oidSz;
- const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz);
- GetASN_ExpBuffer(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], oid, oidSz);
- /* Decode Ed25519 private key. */
- ret = GetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, 1, input,
- inOutIdx, inSz);
- if (ret != 0)
- ret = ASN_PARSE_E;
- /* check that input buffer is exhausted */
- if (*inOutIdx != inSz)
- ret = ASN_PARSE_E;
- }
- /* Check the public value length is correct. */
- if ((ret == 0) &&
- (dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
- ret = ASN_PARSE_E;
- }
- /* Check that the all the buffer was used. */
- if ((ret == 0) &&
- (GetASNItem_Length(dataASN[EDPUBKEYASN_IDX_SEQ], input) != len)) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- *pubKeyLen = dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length;
- XMEMCPY(pubKey, dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.data,
- *pubKeyLen);
- }
- FREE_ASNGETDATA(dataASN, NULL);
- #endif /* WOLFSSL_ASN_TEMPLATE */
- return ret;
- }
- #endif
- #endif /* WC_ENABLE_ASYM_KEY_IMPORT */
- #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
- int wc_Ed25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
- ed25519_key* key, word32 inSz)
- {
- int ret;
- byte privKey[ED25519_KEY_SIZE], pubKey[ED25519_PUB_KEY_SIZE];
- word32 privKeyLen = (word32)sizeof(privKey);
- word32 pubKeyLen = (word32)sizeof(pubKey);
- if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
- return BAD_FUNC_ARG;
- }
- ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
- pubKey, &pubKeyLen, ED25519k);
- if (ret == 0) {
- if (pubKeyLen == 0) {
- ret = wc_ed25519_import_private_only(privKey, privKeyLen, key);
- }
- else {
- ret = wc_ed25519_import_private_key(privKey, privKeyLen,
- pubKey, pubKeyLen, key);
- }
- }
- return ret;
- }
- int wc_Ed25519PublicKeyDecode(const byte* input, word32* inOutIdx,
- ed25519_key* key, word32 inSz)
- {
- int ret;
- byte pubKey[ED25519_PUB_KEY_SIZE];
- word32 pubKeyLen = (word32)sizeof(pubKey);
- if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
- return BAD_FUNC_ARG;
- }
- ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
- pubKey, &pubKeyLen, ED25519k);
- if (ret == 0) {
- ret = wc_ed25519_import_public(pubKey, pubKeyLen, key);
- }
- return ret;
- }
- #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */
- #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)
- int wc_Curve25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
- curve25519_key* key, word32 inSz)
- {
- int ret;
- byte privKey[CURVE25519_KEYSIZE];
- word32 privKeyLen = CURVE25519_KEYSIZE;
- if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
- return BAD_FUNC_ARG;
- }
- ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
- NULL, NULL, X25519k);
- if (ret == 0) {
- ret = wc_curve25519_import_private(privKey, privKeyLen, key);
- }
- return ret;
- }
- int wc_Curve25519PublicKeyDecode(const byte* input, word32* inOutIdx,
- curve25519_key* key, word32 inSz)
- {
- int ret;
- byte pubKey[CURVE25519_KEYSIZE];
- word32 pubKeyLen = (word32)sizeof(pubKey);
- if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
- return BAD_FUNC_ARG;
- }
- ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
- pubKey, &pubKeyLen, X25519k);
- if (ret == 0) {
- ret = wc_curve25519_import_public(pubKey, pubKeyLen, key);
- }
- return ret;
- }
- #endif /* HAVE_CURVE25519 && HAVE_ED25519_KEY_IMPORT */
- #ifdef WC_ENABLE_ASYM_KEY_EXPORT
- /* Build ASN.1 formatted key based on RFC 5958 (Asymmetric Key Packages)
- *
- * Pass NULL for output to get the size of the encoding.
- *
- * @param [in] privKey private key buffer
- * @param [in] privKeyLen private ket buffer length
- * @param [in] pubKey public key buffer (optional)
- * @param [in] pubKeyLen public ket buffer length
- * @param [out] output Buffer to put encoded data in (optional)
- * @param [in] outLen Size of buffer in bytes
- * @param [in] keyType is "enum Key_Sum" like ED25519k
- * @return Size of encoded data in bytes on success
- * @return BAD_FUNC_ARG when key is NULL.
- * @return MEMORY_E when dynamic memory allocation failed.
- */
- int SetAsymKeyDer(const byte* privKey, word32 privKeyLen,
- const byte* pubKey, word32 pubKeyLen,
- byte* output, word32 outLen, int keyType)
- {
- int ret = 0;
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0, seqSz, verSz, algoSz, privSz, pubSz = 0, sz;
- #else
- DECL_ASNSETDATA(dataASN, edKeyASN_Length);
- int sz;
- #endif
- /* Validate parameters. */
- if (privKey == NULL || outLen == 0) {
- return BAD_FUNC_ARG;
- }
- #ifndef WOLFSSL_ASN_TEMPLATE
- /* calculate size */
- if (pubKey) {
- pubSz = 2 + pubKeyLen;
- }
- privSz = 2 + 2 + privKeyLen;
- algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
- verSz = 3; /* version is 3 bytes (enum + id + version(byte)) */
- seqSz = SetSequence(verSz + algoSz + privSz + pubSz, NULL);
- sz = seqSz + verSz + algoSz + privSz + pubSz;
- /* checkout output size */
- if (output != NULL && sz > outLen) {
- ret = BAD_FUNC_ARG;
- }
- if (ret == 0 && output != NULL) {
- /* write out */
- /* seq */
- seqSz = SetSequence(verSz + algoSz + privSz + pubSz, output);
- idx = seqSz;
- /* ver */
- SetMyVersion(0, output + idx, FALSE);
- idx += verSz;
- /* algo */
- algoSz = SetAlgoID(keyType, output + idx, oidKeyType, 0);
- idx += algoSz;
- /* privKey */
- idx += SetOctetString(2 + privKeyLen, output + idx);
- idx += SetOctetString(privKeyLen, output + idx);
- XMEMCPY(output + idx, privKey, privKeyLen);
- idx += privKeyLen;
- /* pubKey */
- if (pubKey) {
- idx += SetHeader(ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY |
- 1, pubKeyLen, output + idx);
- XMEMCPY(output + idx, pubKey, pubKeyLen);
- idx += pubKeyLen;
- }
- sz = idx;
- }
- if (ret == 0) {
- /* Return size of encoding. */
- ret = (int)sz;
- }
- #else
- CALLOC_ASNSETDATA(dataASN, edKeyASN_Length, ret, NULL);
- if (ret == 0) {
- /* Set version = 0 */
- SetASN_Int8Bit(&dataASN[EDKEYASN_IDX_VER], 0);
- /* Set OID. */
- SetASN_OID(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], (word32)keyType,
- oidKeyType);
- /* Leave space for private key. */
- SetASN_Buffer(&dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], NULL, privKeyLen);
- /* Don't write out attributes. */
- dataASN[EDKEYASN_IDX_ATTRS].noOut = 1;
- if (pubKey) {
- /* Leave space for public key. */
- SetASN_Buffer(&dataASN[EDKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
- }
- else {
- /* Don't put out public part. */
- SetASNItem_NoOutNode(dataASN, edKeyASN, EDKEYASN_IDX_PUBKEY,
- edKeyASN_Length);
- }
- /* Calculate the size of encoding. */
- ret = SizeASN_Items(edKeyASN, dataASN, edKeyASN_Length, &sz);
- }
- /* Check buffer is big enough. */
- if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
- ret = BAD_FUNC_ARG;
- }
- if ((ret == 0) && (output != NULL)) {
- /* Encode private key. */
- SetASN_Items(edKeyASN, dataASN, edKeyASN_Length, output);
- /* Put private value into space provided. */
- XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.buffer.data,
- privKey, privKeyLen);
- if (pubKey != NULL) {
- /* Put public value into space provided. */
- XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PUBKEY].data.buffer.data,
- pubKey, pubKeyLen);
- }
- }
- if (ret == 0) {
- /* Return size of encoding. */
- ret = sz;
- }
- FREE_ASNSETDATA(dataASN, NULL);
- #endif
- return ret;
- }
- #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
- #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
- /* Write a Private ED25519 key, including public to DER format,
- * length on success else < 0 */
- int wc_Ed25519KeyToDer(ed25519_key* key, byte* output, word32 inLen)
- {
- if (key == NULL) {
- return BAD_FUNC_ARG;
- }
- return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
- key->p, ED25519_PUB_KEY_SIZE, output, inLen, ED25519k);
- }
- /* Write only private ED25519 key to DER format,
- * length on success else < 0 */
- int wc_Ed25519PrivateKeyToDer(ed25519_key* key, byte* output, word32 inLen)
- {
- if (key == NULL) {
- return BAD_FUNC_ARG;
- }
- return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
- NULL, 0, output, inLen, ED25519k);
- }
- #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
- #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_EXPORT)
- /* Write only private Curve25519 key to DER format,
- * length on success else < 0 */
- int wc_Curve25519PrivateKeyToDer(curve25519_key* key, byte* output, word32 inLen)
- {
- int ret;
- byte privKey[CURVE25519_KEYSIZE];
- word32 privKeyLen = CURVE25519_KEYSIZE;
- if (key == NULL) {
- return BAD_FUNC_ARG;
- }
- ret = wc_curve25519_export_private_raw(key, privKey, &privKeyLen);
- if (ret == 0) {
- ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
- X25519k);
- }
- return ret;
- }
- /* Write a public Curve25519 key to DER format,
- * length on success else < 0 */
- int wc_Curve25519PublicKeyToDer(curve25519_key* key, byte* output, word32 inLen,
- int withAlg)
- {
- int ret;
- byte pubKey[CURVE25519_PUB_KEY_SIZE];
- word32 pubKeyLen = (word32)sizeof(pubKey);
- if (key == NULL || output == NULL) {
- return BAD_FUNC_ARG;
- }
- ret = wc_curve25519_export_public(key, pubKey, &pubKeyLen);
- if (ret == 0) {
- ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
- X25519k, withAlg);
- }
- return ret;
- }
- #endif /* HAVE_CURVE25519 && HAVE_CURVE25519_KEY_EXPORT */
- #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
- int wc_Ed448PrivateKeyDecode(const byte* input, word32* inOutIdx,
- ed448_key* key, word32 inSz)
- {
- int ret;
- byte privKey[ED448_KEY_SIZE], pubKey[ED448_PUB_KEY_SIZE];
- word32 privKeyLen = (word32)sizeof(privKey);
- word32 pubKeyLen = (word32)sizeof(pubKey);
- if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
- return BAD_FUNC_ARG;
- }
- ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
- pubKey, &pubKeyLen, ED448k);
- if (ret == 0) {
- if (pubKeyLen == 0) {
- ret = wc_ed448_import_private_only(privKey, privKeyLen, key);
- }
- else {
- ret = wc_ed448_import_private_key(privKey, privKeyLen,
- pubKey, pubKeyLen, key);
- }
- }
- return ret;
- }
- int wc_Ed448PublicKeyDecode(const byte* input, word32* inOutIdx,
- ed448_key* key, word32 inSz)
- {
- int ret;
- byte pubKey[ED448_PUB_KEY_SIZE];
- word32 pubKeyLen = (word32)sizeof(pubKey);
- if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
- return BAD_FUNC_ARG;
- }
- ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
- pubKey, &pubKeyLen, ED448k);
- if (ret == 0) {
- ret = wc_ed448_import_public(pubKey, pubKeyLen, key);
- }
- return ret;
- }
- #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */
- #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)
- int wc_Curve448PrivateKeyDecode(const byte* input, word32* inOutIdx,
- curve448_key* key, word32 inSz)
- {
- int ret;
- byte privKey[CURVE448_KEY_SIZE];
- word32 privKeyLen = CURVE448_KEY_SIZE;
- if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
- return BAD_FUNC_ARG;
- }
- ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
- NULL, NULL, X448k);
- if (ret == 0) {
- ret = wc_curve448_import_private(privKey, privKeyLen, key);
- }
- return ret;
- }
- int wc_Curve448PublicKeyDecode(const byte* input, word32* inOutIdx,
- curve448_key* key, word32 inSz)
- {
- int ret;
- byte pubKey[CURVE448_PUB_KEY_SIZE];
- word32 pubKeyLen = (word32)sizeof(pubKey);
- if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
- return BAD_FUNC_ARG;
- }
- ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
- pubKey, &pubKeyLen, X448k);
- if (ret == 0) {
- ret = wc_curve448_import_public(pubKey, pubKeyLen, key);
- }
- return ret;
- }
- #endif /* HAVE_CURVE448 && HAVE_ED448_KEY_IMPORT */
- #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
- /* Write a Private ecc key, including public to DER format,
- * length on success else < 0 */
- int wc_Ed448KeyToDer(ed448_key* key, byte* output, word32 inLen)
- {
- if (key == NULL) {
- return BAD_FUNC_ARG;
- }
- return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
- key->p, ED448_KEY_SIZE, output, inLen, ED448k);
- }
- /* Write only private ecc key to DER format,
- * length on success else < 0 */
- int wc_Ed448PrivateKeyToDer(ed448_key* key, byte* output, word32 inLen)
- {
- if (key == NULL) {
- return BAD_FUNC_ARG;
- }
- return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
- NULL, 0, output, inLen, ED448k);
- }
- #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
- #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_EXPORT)
- /* Write private Curve448 key to DER format,
- * length on success else < 0 */
- int wc_Curve448PrivateKeyToDer(curve448_key* key, byte* output, word32 inLen)
- {
- int ret;
- byte privKey[CURVE448_KEY_SIZE];
- word32 privKeyLen = CURVE448_KEY_SIZE;
- if (key == NULL) {
- return BAD_FUNC_ARG;
- }
- ret = wc_curve448_export_private_raw(key, privKey, &privKeyLen);
- if (ret == 0) {
- ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
- X448k);
- }
- return ret;
- }
- /* Write a public Curve448 key to DER format,
- * length on success else < 0 */
- int wc_Curve448PublicKeyToDer(curve448_key* key, byte* output, word32 inLen,
- int withAlg)
- {
- int ret;
- byte pubKey[CURVE448_PUB_KEY_SIZE];
- word32 pubKeyLen = (word32)sizeof(pubKey);
- if (key == NULL || output == NULL) {
- return BAD_FUNC_ARG;
- }
- ret = wc_curve448_export_public(key, pubKey, &pubKeyLen);
- if (ret == 0) {
- ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
- X448k, withAlg);
- }
- return ret;
- }
- #endif /* HAVE_CURVE448 && HAVE_CURVE448_KEY_EXPORT */
- #ifndef WOLFSSL_ASN_TEMPLATE
- #if (defined(HAVE_OCSP) || defined(HAVE_CRL)) && !defined(WOLFCRYPT_ONLY)
- /* Get raw Date only, no processing, 0 on success */
- static int GetBasicDate(const byte* source, word32* idx, byte* date,
- byte* format, int maxIdx)
- {
- int ret, length;
- const byte *datePtr = NULL;
- WOLFSSL_ENTER("GetBasicDate");
- ret = GetDateInfo(source, idx, &datePtr, format, &length, maxIdx);
- if (ret < 0)
- return ret;
- XMEMCPY(date, datePtr, length);
- return 0;
- }
- #endif /* HAVE_OCSP || HAVE_CRL */
- #endif /* WOLFSSL_ASN_TEMPLATE */
- #if defined(HAVE_OCSP) && !defined(WOLFCRYPT_ONLY)
- #ifndef WOLFSSL_ASN_TEMPLATE
- static int GetEnumerated(const byte* input, word32* inOutIdx, int *value,
- int sz)
- {
- word32 idx = *inOutIdx;
- word32 len;
- byte tag;
- WOLFSSL_ENTER("GetEnumerated");
- *value = 0;
- if (GetASNTag(input, &idx, &tag, sz) < 0)
- return ASN_PARSE_E;
- if (tag != ASN_ENUMERATED)
- return ASN_PARSE_E;
- if ((int)idx >= sz)
- return BUFFER_E;
- len = input[idx++];
- if (len > 4 || (int)(len + idx) > sz)
- return ASN_PARSE_E;
- while (len--) {
- *value = *value << 8 | input[idx++];
- }
- *inOutIdx = idx;
- return *value;
- }
- #endif /* !WOLFSSL_ASN_TEMPLATE */
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for OCSP single response.
- * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
- */
- static const ASNItem singleResponseASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* certId */
- /* CID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* hashAlgorithm */
- /* CID_HASHALGO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
- /* CID_HASHALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
- /* CID_HASHALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
- /* issuerNameHash */
- /* CID_ISSUERHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
- /* issuerKeyHash */
- /* CID_ISSUERKEYHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
- /* serialNumber */
- /* CID_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
- /* certStatus - CHOICE */
- /* good [0] IMPLICIT NULL */
- /* CS_GOOD */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 2 },
- /* revoked [1] IMPLICIT RevokedInfo */
- /* CS_REVOKED */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 2 },
- /* revocationTime */
- /* CS_REVOKED_TIME */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
- /* revocationReason [0] EXPLICIT CRLReason OPTIONAL */
- /* CS_REVOKED_REASON */ { 2, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 1 },
- /* crlReason */
- /* CS_REVOKED_REASON_VAL */ { 3, ASN_ENUMERATED, 0, 0, 0 },
- /* unknown [2] IMPLICIT UnknownInfo ::= NULL */
- /* UNKNOWN */ { 1, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 2 },
- /* thisUpdate */
- /* THISUPDATE_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0 },
- /* nextUpdate */
- /* NEXTUPDATE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
- /* NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
- /* singleExtensions */
- /* EXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
- };
- enum {
- SINGLERESPONSEASN_IDX_SEQ = 0,
- SINGLERESPONSEASN_IDX_CID_SEQ,
- SINGLERESPONSEASN_IDX_CID_HASHALGO_SEQ,
- SINGLERESPONSEASN_IDX_CID_HASHALGO_OID,
- SINGLERESPONSEASN_IDX_CID_HASHALGO_NULL,
- SINGLERESPONSEASN_IDX_CID_ISSUERHASH,
- SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH,
- SINGLERESPONSEASN_IDX_CID_SERIAL,
- SINGLERESPONSEASN_IDX_CS_GOOD,
- SINGLERESPONSEASN_IDX_CS_REVOKED,
- SINGLERESPONSEASN_IDX_CS_REVOKED_TIME,
- SINGLERESPONSEASN_IDX_CS_REVOKED_REASON,
- SINGLERESPONSEASN_IDX_CS_REVOKED_REASON_VAL,
- SINGLERESPONSEASN_IDX_UNKNOWN,
- SINGLERESPONSEASN_IDX_THISUPDATE_GT,
- SINGLERESPONSEASN_IDX_NEXTUPDATE,
- SINGLERESPONSEASN_IDX_NEXTUPDATE_GT,
- SINGLERESPONSEASN_IDX_EXT,
- };
- /* Number of items in ASN.1 template for OCSP single response. */
- #define singleResponseASN_Length (sizeof(singleResponseASN) / sizeof(ASNItem))
- #endif
- static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size,
- int wrapperSz, OcspEntry* single)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = *ioIndex, prevIndex, oid, localIdx, certIdIdx;
- int length;
- int ret;
- byte tag;
- WOLFSSL_ENTER("DecodeSingleResponse");
- prevIndex = idx;
- /* Wrapper around the Single Response */
- if (GetSequence(source, &idx, &length, size) < 0)
- return ASN_PARSE_E;
- /* Wrapper around the CertID */
- certIdIdx = idx;
- if (GetSequence(source, &idx, &length, size) < 0)
- return ASN_PARSE_E;
- single->rawCertId = source + certIdIdx;
- /* Hash algorithm */
- ret = GetAlgoId(source, &idx, &oid, oidIgnoreType, size);
- if (ret < 0)
- return ret;
- single->hashAlgoOID = oid;
- /* Save reference to the hash of CN */
- ret = GetOctetString(source, &idx, &length, size);
- if (ret < 0)
- return ret;
- if (length > (int)sizeof(single->issuerHash))
- return BUFFER_E;
- XMEMCPY(single->issuerHash, source + idx, length);
- idx += length;
- /* Save reference to the hash of the issuer public key */
- ret = GetOctetString(source, &idx, &length, size);
- if (ret < 0)
- return ret;
- if (length > (int)sizeof(single->issuerKeyHash))
- return BUFFER_E;
- XMEMCPY(single->issuerKeyHash, source + idx, length);
- idx += length;
- /* Get serial number */
- if (wc_GetSerialNumber(source, &idx, single->status->serial,
- &single->status->serialSz, size) < 0)
- return ASN_PARSE_E;
- single->rawCertIdSize = idx - certIdIdx;
- if (idx >= size)
- return BUFFER_E;
- /* CertStatus */
- switch (source[idx++])
- {
- case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
- single->status->status = CERT_GOOD;
- idx++;
- break;
- case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
- single->status->status = CERT_REVOKED;
- if (GetLength(source, &idx, &length, size) < 0)
- return ASN_PARSE_E;
- idx += length;
- break;
- case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
- single->status->status = CERT_UNKNOWN;
- idx++;
- break;
- default:
- return ASN_PARSE_E;
- }
- if (idx >= size)
- return BUFFER_E;
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
- single->status->thisDateAsn = source + idx;
- localIdx = 0;
- if (GetDateInfo(single->status->thisDateAsn, &localIdx, NULL,
- (byte*)&single->status->thisDateParsed.type,
- &single->status->thisDateParsed.length, size - idx) < 0)
- return ASN_PARSE_E;
- if (idx + localIdx >= size)
- return BUFFER_E;
- XMEMCPY(single->status->thisDateParsed.data,
- single->status->thisDateAsn + localIdx - single->status->thisDateParsed.length,
- single->status->thisDateParsed.length);
- #endif
- if (GetBasicDate(source, &idx, single->status->thisDate,
- &single->status->thisDateFormat, size) < 0)
- return ASN_PARSE_E;
- #ifndef NO_ASN_TIME_CHECK
- #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
- if (!XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, BEFORE))
- return ASN_BEFORE_DATE_E;
- #endif
- #endif
- /* The following items are optional. Only check for them if there is more
- * unprocessed data in the singleResponse wrapper. */
- localIdx = idx;
- if (((int)(idx - prevIndex) < wrapperSz) &&
- GetASNTag(source, &localIdx, &tag, size) == 0 &&
- tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
- {
- idx++;
- if (GetLength(source, &idx, &length, size) < 0)
- return ASN_PARSE_E;
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
- single->status->nextDateAsn = source + idx;
- localIdx = 0;
- if (GetDateInfo(single->status->nextDateAsn, &localIdx, NULL,
- (byte*)&single->status->nextDateParsed.type,
- &single->status->nextDateParsed.length, size - idx) < 0)
- return ASN_PARSE_E;
- if (idx + localIdx >= size)
- return BUFFER_E;
- XMEMCPY(single->status->nextDateParsed.data,
- single->status->nextDateAsn + localIdx - single->status->nextDateParsed.length,
- single->status->nextDateParsed.length);
- #endif
- if (GetBasicDate(source, &idx, single->status->nextDate,
- &single->status->nextDateFormat, size) < 0)
- return ASN_PARSE_E;
- #ifndef NO_ASN_TIME_CHECK
- #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
- if (!XVALIDATE_DATE(single->status->nextDate, single->status->nextDateFormat, AFTER))
- return ASN_AFTER_DATE_E;
- #endif
- #endif
- }
- /* Skip the optional extensions in singleResponse. */
- localIdx = idx;
- if (((int)(idx - prevIndex) < wrapperSz) &&
- GetASNTag(source, &localIdx, &tag, size) == 0 &&
- tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
- {
- idx++;
- if (GetLength(source, &idx, &length, size) < 0)
- return ASN_PARSE_E;
- idx += length;
- }
- *ioIndex = idx;
- return 0;
- #else
- DECL_ASNGETDATA(dataASN, singleResponseASN_Length);
- int ret = 0;
- word32 ocspDigestSize = OCSP_DIGEST_SIZE;
- CertStatus* cs = NULL;
- word32 serialSz;
- word32 issuerHashLen;
- word32 issuerKeyHashLen;
- word32 thisDateLen;
- word32 nextDateLen;
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
- defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
- WOLFSSL_ASN1_TIME *at;
- #endif
- (void)wrapperSz;
- WOLFSSL_ENTER("DecodeSingleResponse");
- CALLOC_ASNGETDATA(dataASN, singleResponseASN_Length, ret, NULL);
- if (ret == 0) {
- /* Certificate Status field. */
- cs = single->status;
- /* Set maximum lengths for data. */
- issuerHashLen = OCSP_DIGEST_SIZE;
- issuerKeyHashLen = OCSP_DIGEST_SIZE;
- serialSz = EXTERNAL_SERIAL_SIZE;
- thisDateLen = MAX_DATE_SIZE;
- nextDateLen = MAX_DATE_SIZE;
- /* Set OID type, buffers to hold data and variables to hold size. */
- GetASN_OID(&dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID],
- oidHashType);
- GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERHASH],
- single->issuerHash, &issuerHashLen);
- GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH],
- single->issuerKeyHash, &issuerKeyHashLen);
- GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_SERIAL], cs->serial,
- &serialSz);
- GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT],
- cs->thisDate, &thisDateLen);
- GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT],
- cs->nextDate, &nextDateLen);
- /* TODO: decode revoked time and reason. */
- /* Decode OCSP single response. */
- ret = GetASN_Items(singleResponseASN, dataASN, singleResponseASN_Length,
- 1, source, ioIndex, size);
- }
- if (ret == 0) {
- single->hashAlgoOID =
- dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID].data.oid.sum;
- ocspDigestSize = wc_HashGetDigestSize(
- wc_OidGetHash(single->hashAlgoOID));
- }
- /* Validate the issuer hash length is the size required. */
- if ((ret == 0) && (issuerHashLen != ocspDigestSize)) {
- ret = ASN_PARSE_E;
- }
- /* Validate the issuer key hash length is the size required. */
- if ((ret == 0) && (issuerKeyHashLen != ocspDigestSize)) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- /* Store serial size. */
- cs->serialSz = serialSz;
- /* Determine status by which item was found. */
- if (dataASN[SINGLERESPONSEASN_IDX_CS_GOOD].tag != 0) {
- cs->status = CERT_GOOD;
- }
- if (dataASN[SINGLERESPONSEASN_IDX_CS_REVOKED].tag != 0) {
- cs->status = CERT_REVOKED;
- }
- if (dataASN[SINGLERESPONSEASN_IDX_UNKNOWN].tag != 0) {
- cs->status = CERT_UNKNOWN;
- }
- /* Store the thisDate format - only one possible. */
- cs->thisDateFormat = ASN_GENERALIZED_TIME;
- #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
- /* Check date is a valid string and BEFORE now. */
- if (!XVALIDATE_DATE(cs->thisDate, ASN_GENERALIZED_TIME, BEFORE)) {
- ret = ASN_BEFORE_DATE_E;
- }
- }
- if (ret == 0) {
- #endif
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
- defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
- /* Store ASN.1 version of thisDate. */
- cs->thisDateAsn = GetASNItem_Addr(
- dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT], source);
- at = &cs->thisDateParsed;
- at->type = ASN_GENERALIZED_TIME;
- XMEMCPY(at->data, cs->thisDate, thisDateLen);
- at->length = thisDateLen;
- #endif
- }
- if ((ret == 0) &&
- (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
- /* Store the nextDate format - only one possible. */
- cs->nextDateFormat = ASN_GENERALIZED_TIME;
- #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
- /* Check date is a valid string and AFTER now. */
- if (!XVALIDATE_DATE(cs->nextDate, ASN_GENERALIZED_TIME, AFTER)) {
- ret = ASN_AFTER_DATE_E;
- }
- }
- if ((ret == 0) &&
- (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
- #endif
- #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
- defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
- /* Store ASN.1 version of thisDate. */
- cs->nextDateAsn = GetASNItem_Addr(
- dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT], source);
- at = &cs->nextDateParsed;
- at->type = ASN_GENERALIZED_TIME;
- XMEMCPY(at->data, cs->nextDate, nextDateLen);
- at->length = nextDateLen;
- #endif
- }
- if (ret == 0) {
- /* OcspEntry now used. */
- single->used = 1;
- }
- FREE_ASNGETDATA(dataASN, NULL);
- return ret;
- #endif
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for OCSP response extension header.
- * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
- */
- static const ASNItem respExtHdrASN[] = {
- /* responseExtensions */
- /* EXT */ { 0, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 0 },
- /* extensions */
- /* EXT_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- };
- enum {
- RESPEXTHDRASN_IDX_EXT = 0,
- RESPEXTHDRASN_IDX_EXT_SEQ,
- };
- /* Number of items in ASN.1 template for OCSP response extension header. */
- #define respExtHdrASN_Length (sizeof(respExtHdrASN) / sizeof(ASNItem))
- #endif
- static int DecodeOcspRespExtensions(byte* source, word32* ioIndex,
- OcspResponse* resp, word32 sz)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = *ioIndex;
- int length;
- int ext_bound; /* boundary index for the sequence of extensions */
- word32 oid;
- int ret;
- byte tag;
- WOLFSSL_ENTER("DecodeOcspRespExtensions");
- if ((idx + 1) > sz)
- return BUFFER_E;
- if (GetASNTag(source, &idx, &tag, sz) < 0)
- return ASN_PARSE_E;
- if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
- return ASN_PARSE_E;
- if (GetLength(source, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- if (GetSequence(source, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- ext_bound = idx + length;
- while (idx < (word32)ext_bound) {
- word32 localIdx;
- if (GetSequence(source, &idx, &length, sz) < 0) {
- WOLFSSL_MSG("\tfail: should be a SEQUENCE");
- return ASN_PARSE_E;
- }
- oid = 0;
- if (GetObjectId(source, &idx, &oid, oidOcspType, sz) < 0) {
- WOLFSSL_MSG("\tfail: OBJECT ID");
- return ASN_PARSE_E;
- }
- /* check for critical flag */
- if ((idx + 1) > (word32)sz) {
- WOLFSSL_MSG("\tfail: malformed buffer");
- return BUFFER_E;
- }
- localIdx = idx;
- if (GetASNTag(source, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
- WOLFSSL_MSG("\tfound optional critical flag, moving past");
- ret = GetBoolean(source, &idx, sz);
- if (ret < 0)
- return ret;
- }
- ret = GetOctetString(source, &idx, &length, sz);
- if (ret < 0)
- return ret;
- if (oid == OCSP_NONCE_OID) {
- /* get data inside extra OCTET_STRING */
- ret = GetOctetString(source, &idx, &length, sz);
- if (ret < 0)
- return ret;
- resp->nonce = source + idx;
- resp->nonceSz = length;
- }
- idx += length;
- }
- *ioIndex = idx;
- return 0;
- #else
- /* certExtASN_Length is greater than respExtHdrASN_Length */
- DECL_ASNGETDATA(dataASN, certExtASN_Length);
- int ret = 0;
- word32 idx = *ioIndex;
- word32 maxIdx = 0;
- WOLFSSL_ENTER("DecodeOcspRespExtensions");
- CALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, resp->heap);
- if (ret == 0) {
- /* Check for header and move past. */
- ret = GetASN_Items(respExtHdrASN, dataASN, respExtHdrASN_Length, 0,
- source, &idx, sz);
- }
- if (ret == 0) {
- /* Keep end extensions index for total length check. */
- maxIdx = idx + dataASN[RESPEXTHDRASN_IDX_EXT_SEQ].length;
- }
- /* Step through all extensions. */
- while ((ret == 0) && (idx < maxIdx)) {
- /* Clear dynamic data, set OID type to expect. */
- XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
- GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidOcspType);
- /* TODO: check criticality. */
- /* Decode OCSP response extension. */
- ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0,
- source, &idx, sz);
- if (ret == 0) {
- word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
- int length = dataASN[CERTEXTASN_IDX_VAL].length;
- if (oid == OCSP_NONCE_OID) {
- /* Extract nonce data. */
- ret = GetOctetString(source, &idx, &length, sz);
- if (ret >= 0) {
- ret = 0;
- /* get data inside extra OCTET_STRING */
- resp->nonce = source + idx;
- resp->nonceSz = length;
- }
- }
- /* Ignore all other extension types. */
- /* Skip over rest of extension. */
- idx += length;
- }
- }
- /* Return index after extensions. */
- *ioIndex = idx;
- FREE_ASNGETDATA(dataASN, resp->heap);
- return ret;
- #endif
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for OCSP ResponseData.
- * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
- */
- static const ASNItem ocspRespDataASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* version DEFAULT v1 */
- /* VER_PRESENT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
- /* VER */ { 2, ASN_INTEGER, 1, 0, 0 },
- /* byName */
- /* BYNAME */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
- /* byKey */
- /* BYKEY */ { 1, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 2 },
- /* producedAt */
- /* PA */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0, },
- /* responses */
- /* RESP */ { 1, ASN_SEQUENCE, 1, 0, 0 },
- /* responseExtensions */
- /* RESPEXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 }
- };
- enum {
- OCSPRESPDATAASN_IDX_SEQ = 0,
- OCSPRESPDATAASN_IDX_VER_PRESENT,
- OCSPRESPDATAASN_IDX_VER,
- OCSPRESPDATAASN_IDX_BYNAME,
- OCSPRESPDATAASN_IDX_BYKEY,
- OCSPRESPDATAASN_IDX_PA,
- OCSPRESPDATAASN_IDX_RESP,
- OCSPRESPDATAASN_IDX_RESPEXT,
- };
- /* Number of items in ASN.1 template for OCSP ResponseData. */
- #define ocspRespDataASN_Length (sizeof(ocspRespDataASN) / sizeof(ASNItem))
- #endif
- static int DecodeResponseData(byte* source, word32* ioIndex,
- OcspResponse* resp, word32 size)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = *ioIndex, prev_idx, localIdx;
- int length;
- int version;
- int ret;
- byte tag;
- int wrapperSz;
- OcspEntry* single;
- WOLFSSL_ENTER("DecodeResponseData");
- resp->response = source + idx;
- prev_idx = idx;
- if (GetSequence(source, &idx, &length, size) < 0)
- return ASN_PARSE_E;
- resp->responseSz = length + idx - prev_idx;
- /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
- * item isn't an EXPLICIT[0], then set version to zero and move
- * onto the next item.
- */
- localIdx = idx;
- if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
- tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
- {
- idx += 2; /* Eat the value and length */
- if (GetMyVersion(source, &idx, &version, size) < 0)
- return ASN_PARSE_E;
- } else
- version = 0;
- localIdx = idx;
- if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
- ( tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1) ||
- tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2) ))
- {
- idx++; /* advance past ASN tag */
- if (GetLength(source, &idx, &length, size) < 0)
- return ASN_PARSE_E;
- idx += length;
- }
- else
- return ASN_PARSE_E;
- /* save pointer to the producedAt time */
- if (GetBasicDate(source, &idx, resp->producedDate,
- &resp->producedDateFormat, size) < 0)
- return ASN_PARSE_E;
- /* Outer wrapper of the SEQUENCE OF Single Responses. */
- if (GetSequence(source, &idx, &wrapperSz, size) < 0)
- return ASN_PARSE_E;
- localIdx = idx;
- single = resp->single;
- while (idx - localIdx < (word32)wrapperSz) {
- ret = DecodeSingleResponse(source, &idx, size, wrapperSz, single);
- if (ret < 0)
- return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
- if (idx - localIdx < (word32)wrapperSz) {
- single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
- DYNAMIC_TYPE_OCSP_ENTRY);
- if (single->next == NULL) {
- return MEMORY_E;
- }
- XMEMSET(single->next, 0, sizeof(OcspEntry));
- single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
- resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
- if (single->next->status == NULL) {
- XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
- single->next = NULL;
- return MEMORY_E;
- }
- XMEMSET(single->next->status, 0, sizeof(CertStatus));
- single->next->isDynamic = 1;
- single = single->next;
- }
- }
- /*
- * Check the length of the ResponseData against the current index to
- * see if there are extensions, they are optional.
- */
- if (idx - prev_idx < resp->responseSz)
- if (DecodeOcspRespExtensions(source, &idx, resp, size) < 0)
- return ASN_PARSE_E;
- *ioIndex = idx;
- return 0;
- #else
- DECL_ASNGETDATA(dataASN, ocspRespDataASN_Length);
- int ret = 0;
- byte version;
- word32 dateSz, idx = *ioIndex;
- OcspEntry* single = NULL;
- WOLFSSL_ENTER("DecodeResponseData");
- CALLOC_ASNGETDATA(dataASN, ocspRespDataASN_Length, ret, resp->heap);
- if (ret == 0) {
- resp->response = source + idx;
- /* Default, not present, is v1 = 0. */
- version = 0;
- /* Max size of date supported. */
- dateSz = MAX_DATE_SIZE;
- /* Set the where to put version an produced date. */
- GetASN_Int8Bit(&dataASN[OCSPRESPDATAASN_IDX_VER], &version);
- GetASN_Buffer(&dataASN[OCSPRESPDATAASN_IDX_PA], resp->producedDate,
- &dateSz);
- /* Decode the ResponseData. */
- ret = GetASN_Items(ocspRespDataASN, dataASN, ocspRespDataASN_Length,
- 1, source, ioIndex, size);
- }
- /* Only support v1 == 0 */
- if ((ret == 0) && (version != 0)) {
- ret = ASN_PARSE_E;
- }
- /* Ensure date is a minimal size. */
- if ((ret == 0) && (dateSz < MIN_DATE_SIZE)) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- /* TODO: use byName/byKey fields. */
- /* Store size of response. */
- resp->responseSz = *ioIndex - idx;
- /* Store date format/tag. */
- resp->producedDateFormat = dataASN[OCSPRESPDATAASN_IDX_PA].tag;
- /* Get the index of the responses SEQUENCE. */
- idx = GetASNItem_DataIdx(dataASN[OCSPRESPDATAASN_IDX_RESP], source);
- /* Start with the pre-existing OcspEntry. */
- single = resp->single;
- }
- while ((ret == 0) && (idx < dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset)) {
- /* Allocate and use a new OCSP entry if this is used. */
- if (single->used) {
- single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
- DYNAMIC_TYPE_OCSP_ENTRY);
- if (single->next == NULL) {
- ret = MEMORY_E;
- }
- else {
- XMEMSET(single->next, 0, sizeof(OcspEntry));
- single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
- resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
- if (single->next->status == NULL) {
- XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
- single->next = NULL;
- ret = MEMORY_E;
- }
- else {
- XMEMSET(single->next->status, 0, sizeof(CertStatus));
- /* Entry to be freed. */
- single->next->isDynamic = 1;
- /* used will be 0 (false) */
- single = single->next;
- }
- }
- }
- if (ret == 0) {
- /* Decode SingleResponse into OcspEntry. */
- ret = DecodeSingleResponse(source, &idx,
- dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset,
- dataASN[OCSPRESPDATAASN_IDX_RESP].length, single);
- /* single->used set on successful decode. */
- }
- }
- /* Check if there were extensions. */
- if ((ret == 0) &&
- (dataASN[OCSPRESPDATAASN_IDX_RESPEXT].data.buffer.data != NULL)) {
- /* Get index of [1] */
- idx = dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset;
- /* Decode the response extensions. */
- if (DecodeOcspRespExtensions(source, &idx, resp, *ioIndex) < 0) {
- ret = ASN_PARSE_E;
- }
- }
- FREE_ASNGETDATA(dataASN, resp->heap);
- return ret;
- #endif
- }
- #ifndef WOLFSSL_ASN_TEMPLATE
- #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
- static int DecodeCerts(byte* source,
- word32* ioIndex, OcspResponse* resp, word32 size)
- {
- word32 idx = *ioIndex;
- byte tag;
- WOLFSSL_ENTER("DecodeCerts");
- if (GetASNTag(source, &idx, &tag, size) < 0)
- return ASN_PARSE_E;
- if (tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
- {
- int length;
- if (GetLength(source, &idx, &length, size) < 0)
- return ASN_PARSE_E;
- if (GetSequence(source, &idx, &length, size) < 0)
- return ASN_PARSE_E;
- resp->cert = source + idx;
- resp->certSz = length;
- idx += length;
- }
- *ioIndex = idx;
- return 0;
- }
- #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
- #endif /* !WOLFSSL_ASN_TEMPLATE */
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for BasicOCSPResponse.
- * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
- */
- static const ASNItem ocspBasicRespASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* tbsResponseData */
- /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0, },
- /* signatureAlgorithm */
- /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0, },
- /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
- /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
- /* parameters */
- #ifdef WC_RSA_PSS
- /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
- #endif
- /* signature */
- /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
- /* certs */
- /* CERTS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
- /* CERTS_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0, },
- };
- enum {
- OCSPBASICRESPASN_IDX_SEQ = 0,
- OCSPBASICRESPASN_IDX_TBS_SEQ,
- OCSPBASICRESPASN_IDX_SIGALGO,
- OCSPBASICRESPASN_IDX_SIGALGO_OID,
- OCSPBASICRESPASN_IDX_SIGALGO_NULL,
- #ifdef WC_RSA_PSS
- OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS,
- #endif
- OCSPBASICRESPASN_IDX_SIGNATURE,
- OCSPBASICRESPASN_IDX_CERTS,
- OCSPBASICRESPASN_IDX_CERTS_SEQ,
- };
- /* Number of items in ASN.1 template for BasicOCSPResponse. */
- #define ocspBasicRespASN_Length (sizeof(ocspBasicRespASN) / sizeof(ASNItem))
- #endif /* WOLFSSL_ASN_TEMPLATE */
- static int DecodeBasicOcspResponse(byte* source, word32* ioIndex,
- OcspResponse* resp, word32 size, void* cm, void* heap, int noVerify)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int length;
- word32 idx = *ioIndex;
- #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
- word32 end_index;
- #endif
- int ret;
- int sigLength;
- const byte* sigParams = NULL;
- word32 sigParamsSz = 0;
- WOLFSSL_ENTER("DecodeBasicOcspResponse");
- (void)heap;
- if (GetSequence(source, &idx, &length, size) < 0)
- return ASN_PARSE_E;
- if (idx + length > size)
- return ASN_INPUT_E;
- #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
- end_index = idx + length;
- #endif
- if ((ret = DecodeResponseData(source, &idx, resp, size)) < 0)
- return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
- /* Get the signature algorithm */
- if (GetAlgoId(source, &idx, &resp->sigOID, oidSigType, size) < 0) {
- return ASN_PARSE_E;
- }
- #ifdef WC_RSA_PSS
- else if (resp->sigOID == CTC_RSASSAPSS) {
- word32 sz;
- int len;
- const byte* params;
- sz = idx;
- params = source + idx;
- if (GetSequence(source, &idx, &len, size) < 0)
- ret = ASN_PARSE_E;
- if (ret == 0) {
- idx += len;
- sigParams = params;
- sigParamsSz = idx - sz;
- }
- }
- #endif
- ret = CheckBitString(source, &idx, &sigLength, size, 1, NULL);
- if (ret != 0)
- return ret;
- resp->sigSz = sigLength;
- resp->sig = source + idx;
- idx += sigLength;
- /*
- * Check the length of the BasicOcspResponse against the current index to
- * see if there are certificates, they are optional.
- */
- #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
- if (idx < end_index)
- {
- int cert_inited = 0;
- #ifdef WOLFSSL_SMALL_STACK
- DecodedCert *cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (cert == NULL)
- return MEMORY_E;
- #else
- DecodedCert cert[1];
- #endif
- do {
- if (DecodeCerts(source, &idx, resp, size) < 0) {
- ret = ASN_PARSE_E;
- break;
- }
- InitDecodedCert(cert, resp->cert, resp->certSz, heap);
- cert_inited = 1;
- /* Don't verify if we don't have access to Cert Manager. */
- ret = ParseCertRelative(cert, CERT_TYPE,
- noVerify ? NO_VERIFY : VERIFY_OCSP_CERT,
- cm);
- if (ret < 0) {
- WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
- break;
- }
- #ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK
- if ((cert->extExtKeyUsage & EXTKEYUSE_OCSP_SIGN) == 0) {
- if (XMEMCMP(cert->subjectHash,
- resp->single->issuerHash, OCSP_DIGEST_SIZE) == 0) {
- WOLFSSL_MSG("\tOCSP Response signed by issuer");
- }
- else {
- WOLFSSL_MSG("\tOCSP Responder key usage check failed");
- #ifdef OPENSSL_EXTRA
- resp->verifyError = OCSP_BAD_ISSUER;
- #else
- ret = BAD_OCSP_RESPONDER;
- break;
- #endif
- }
- }
- #endif
- /* ConfirmSignature is blocking here */
- ret = ConfirmSignature(
- &cert->sigCtx,
- resp->response, resp->responseSz,
- cert->publicKey, cert->pubKeySize, cert->keyOID,
- resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
- NULL);
- if (ret != 0) {
- WOLFSSL_MSG("\tOCSP Confirm signature failed");
- ret = ASN_OCSP_CONFIRM_E;
- break;
- }
- } while(0);
- if (cert_inited)
- FreeDecodedCert(cert);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(cert, NULL, DYNAMIC_TYPE_TMP_BUFFER);
- #endif
- if (ret != 0)
- return ret;
- }
- else
- #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
- {
- Signer* ca;
- int sigValid = -1;
- #ifndef NO_SKID
- ca = GetCA(cm, resp->single->issuerKeyHash);
- #else
- ca = GetCA(cm, resp->single->issuerHash);
- #endif
- if (ca) {
- SignatureCtx sigCtx;
- InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
- /* ConfirmSignature is blocking here */
- sigValid = ConfirmSignature(&sigCtx, resp->response,
- resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
- resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
- NULL);
- }
- if (ca == NULL || sigValid != 0) {
- WOLFSSL_MSG("\tOCSP Confirm signature failed");
- return ASN_OCSP_CONFIRM_E;
- }
- (void)noVerify;
- }
- *ioIndex = idx;
- return 0;
- #else
- DECL_ASNGETDATA(dataASN, ocspBasicRespASN_Length);
- int ret = 0;
- word32 idx = *ioIndex;
- const byte* sigParams = NULL;
- word32 sigParamsSz = 0;
- #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
- #ifdef WOLFSSL_SMALL_STACK
- DecodedCert* cert = NULL;
- #else
- DecodedCert cert[1];
- #endif
- int certInit = 0;
- #endif
- WOLFSSL_ENTER("DecodeBasicOcspResponse");
- (void)heap;
- CALLOC_ASNGETDATA(dataASN, ocspBasicRespASN_Length, ret, heap);
- if (ret == 0) {
- /* Set expecting signature OID. */
- GetASN_OID(&dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID], oidSigType);
- /* Decode BasicOCSPResponse. */
- ret = GetASN_Items(ocspBasicRespASN, dataASN, ocspBasicRespASN_Length,
- 1, source, &idx, size);
- }
- if (ret == 0) {
- word32 dataIdx = 0;
- /* Decode the response data. */
- if (DecodeResponseData(
- GetASNItem_Addr(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source),
- &dataIdx, resp,
- GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source)
- ) < 0) {
- ret = ASN_PARSE_E;
- }
- }
- #ifdef WC_RSA_PSS
- if (ret == 0 && (dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS].tag != 0)) {
- sigParams = GetASNItem_Addr(
- dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
- source);
- sigParamsSz =
- GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
- source);
- }
- #endif
- if (ret == 0) {
- /* Get the signature OID and signature. */
- resp->sigOID = dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID].data.oid.sum;
- GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_SIGNATURE], &resp->sig,
- &resp->sigSz);
- }
- #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
- if ((ret == 0) &&
- (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
- /* TODO: support more than one certificate. */
- /* Store reference to certificate BER data. */
- GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ], &resp->cert,
- &resp->certSz);
- /* Allocate a certificate object to decode cert into. */
- #ifdef WOLFSSL_SMALL_STACK
- cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), heap,
- DYNAMIC_TYPE_TMP_BUFFER);
- if (cert == NULL) {
- ret = MEMORY_E;
- }
- }
- if ((ret == 0) &&
- (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
- #endif
- /* Initialize the crtificate object. */
- InitDecodedCert(cert, resp->cert, resp->certSz, heap);
- certInit = 1;
- /* Parse the certificate and don't verify if we don't have access to
- * Cert Manager. */
- ret = ParseCertRelative(cert, CERT_TYPE, noVerify ? NO_VERIFY : VERIFY,
- cm);
- if (ret < 0) {
- WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
- }
- }
- if ((ret == 0) &&
- (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
- /* TODO: ConfirmSignature is blocking here */
- /* Check the signature of the response. */
- ret = ConfirmSignature(&cert->sigCtx, resp->response, resp->responseSz,
- cert->publicKey, cert->pubKeySize, cert->keyOID, resp->sig,
- resp->sigSz, resp->sigOID, NULL, 0, NULL);
- if (ret != 0) {
- WOLFSSL_MSG("\tOCSP Confirm signature failed");
- ret = ASN_OCSP_CONFIRM_E;
- }
- }
- if ((ret == 0) &&
- (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data == NULL))
- #else
- if (ret == 0)
- #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
- {
- Signer* ca;
- int sigValid = -1;
- /* Resonse didn't have a certificate - lookup CA. */
- #ifndef NO_SKID
- ca = GetCA(cm, resp->single->issuerKeyHash);
- #else
- ca = GetCA(cm, resp->single->issuerHash);
- #endif
- if (ca) {
- SignatureCtx sigCtx;
- /* Initialize he signature context. */
- InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
- /* TODO: ConfirmSignature is blocking here */
- /* Check the signature of the response CA public key. */
- sigValid = ConfirmSignature(&sigCtx, resp->response,
- resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
- resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
- NULL);
- }
- if ((ca == NULL) || (sigValid != 0)) {
- /* Didn't find certificate or signature verificate failed. */
- WOLFSSL_MSG("\tOCSP Confirm signature failed");
- ret = ASN_OCSP_CONFIRM_E;
- }
- }
- if (ret == 0) {
- /* Update the position to after response data. */
- *ioIndex = idx;
- }
- #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
- if (certInit) {
- FreeDecodedCert(cert);
- }
- #ifdef WOLFSSL_SMALL_STACK
- if (cert != NULL) {
- /* Dispose of certificate object. */
- XFREE(cert, heap, DYNAMIC_TYPE_TMP_BUFFER);
- }
- #endif
- #endif
- FREE_ASNGETDATA(dataASN, heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- void InitOcspResponse(OcspResponse* resp, OcspEntry* single, CertStatus* status,
- byte* source, word32 inSz, void* heap)
- {
- WOLFSSL_ENTER("InitOcspResponse");
- XMEMSET(status, 0, sizeof(CertStatus));
- XMEMSET(single, 0, sizeof(OcspEntry));
- XMEMSET(resp, 0, sizeof(OcspResponse));
- single->status = status;
- resp->responseStatus = -1;
- resp->single = single;
- resp->source = source;
- resp->maxIdx = inSz;
- resp->heap = heap;
- }
- void FreeOcspResponse(OcspResponse* resp)
- {
- OcspEntry *single, *next;
- if (resp != NULL) {
- for (single = resp->single; single; single = next) {
- next = single->next;
- if (single->isDynamic) {
- XFREE(single->status, resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
- XFREE(single, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
- }
- }
- }
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for OCSPResponse.
- * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
- */
- static const ASNItem ocspResponseASN[] = {
- /* OCSPResponse ::= SEQUENCE */
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* responseStatus OCSPResponseStatus */
- /* STATUS */ { 1, ASN_ENUMERATED, 0, 0, 0, },
- /* responseBytes [0] EXPLICIT ResponseBytes OPTIONAL */
- /* BYTES */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
- /* ResponseBytes ::= SEQUENCE */
- /* BYTES_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
- /* responseType OBJECT IDENTIFIER */
- /* BYTES_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
- /* response OCTET STRING */
- /* BYTES_VAL */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
- };
- enum {
- OCSPRESPONSEASN_IDX_SEQ = 0,
- OCSPRESPONSEASN_IDX_STATUS,
- OCSPRESPONSEASN_IDX_BYTES,
- OCSPRESPONSEASN_IDX_BYTES_SEQ,
- OCSPRESPONSEASN_IDX_BYTES_TYPE,
- OCSPRESPONSEASN_IDX_BYTES_VAL,
- };
- /* Number of items in ASN.1 template for OCSPResponse. */
- #define ocspResponseASN_Length (sizeof(ocspResponseASN) / sizeof(ASNItem))
- #endif /* WOLFSSL_ASN_TEMPLATE */
- int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, int noVerify)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret;
- int length = 0;
- word32 idx = 0;
- byte* source = resp->source;
- word32 size = resp->maxIdx;
- word32 oid;
- byte tag;
- WOLFSSL_ENTER("OcspResponseDecode");
- /* peel the outer SEQUENCE wrapper */
- if (GetSequence(source, &idx, &length, size) < 0) {
- WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
- return ASN_PARSE_E;
- }
- /* First get the responseStatus, an ENUMERATED */
- if (GetEnumerated(source, &idx, &resp->responseStatus, size) < 0) {
- WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
- return ASN_PARSE_E;
- }
- if (resp->responseStatus != OCSP_SUCCESSFUL) {
- WOLFSSL_LEAVE("OcspResponseDecode", 0);
- return 0;
- }
- /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
- if (idx >= size) {
- WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
- return ASN_PARSE_E;
- }
- if (GetASNTag(source, &idx, &tag, size) < 0) {
- WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
- return ASN_PARSE_E;
- }
- if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC)) {
- WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
- return ASN_PARSE_E;
- }
- if (GetLength(source, &idx, &length, size) < 0) {
- WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
- return ASN_PARSE_E;
- }
- /* Get the responseBytes SEQUENCE */
- if (GetSequence(source, &idx, &length, size) < 0) {
- WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
- return ASN_PARSE_E;
- }
- /* Check ObjectID for the resposeBytes */
- if (GetObjectId(source, &idx, &oid, oidOcspType, size) < 0) {
- WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
- return ASN_PARSE_E;
- }
- if (oid != OCSP_BASIC_OID) {
- WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
- return ASN_PARSE_E;
- }
- ret = GetOctetString(source, &idx, &length, size);
- if (ret < 0) {
- WOLFSSL_LEAVE("OcspResponseDecode", ret);
- return ret;
- }
- ret = DecodeBasicOcspResponse(source, &idx, resp, size, cm, heap, noVerify);
- if (ret < 0) {
- WOLFSSL_LEAVE("OcspResponseDecode", ret);
- return ret;
- }
- WOLFSSL_LEAVE("OcspResponseDecode", 0);
- return 0;
- #else
- DECL_ASNGETDATA(dataASN, ocspResponseASN_Length);
- int ret = 0;
- word32 idx = 0, size = resp->maxIdx;
- byte* source = resp->source;
- byte status;
- byte* basic;
- word32 basicSz;
- WOLFSSL_ENTER("OcspResponseDecode");
- CALLOC_ASNGETDATA(dataASN, ocspResponseASN_Length, ret, resp->heap);
- if (ret == 0) {
- /* Set variable to put status in and expect OCSP OID. */
- GetASN_Int8Bit(&dataASN[OCSPRESPONSEASN_IDX_STATUS], &status);
- GetASN_OID(&dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE], oidOcspType);
- /* Decode OCSPResponse (and ResponseBytes). */
- ret = GetASN_Items(ocspResponseASN, dataASN, ocspResponseASN_Length, 1,
- source, &idx, size);
- }
- if (ret == 0) {
- /* Get response. */
- resp->responseStatus = status;
- if (dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE].data.oid.sum
- == OCSP_BASIC_OID) {
- /* Get reference to BasicOCSPResponse. */
- GetASN_GetRef(&dataASN[OCSPRESPONSEASN_IDX_BYTES_VAL], &basic,
- &basicSz);
- idx = 0;
- /* Decode BasicOCSPResponse. */
- ret = DecodeBasicOcspResponse(basic, &idx, resp, basicSz, cm, heap,
- noVerify);
- }
- /* Only support BasicOCSPResponse. */
- else {
- ret = ASN_PARSE_E;
- }
- }
- FREE_ASNGETDATA(dataASN, resp->heap);
- WOLFSSL_LEAVE("OcspResponseDecode", ret);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for OCSP nonce extension.
- * RFC 6960, 4.4.1 - Nonce
- * X.509: RFC 5280, 4.1 - Basic Certificate Fields. (Extension)
- */
- static const ASNItem ocspNonceExtASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* Extension */
- /* EXT */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* extnId */
- /* EXT_OID */ {2, ASN_OBJECT_ID, 0, 0, 0 },
- /* critcal not encoded. */
- /* extnValue */
- /* EXT_VAL */ {2, ASN_OCTET_STRING, 0, 1, 0 },
- /* nonce */
- /* EXT_NONCE */ {3, ASN_OCTET_STRING, 0, 0, 0 },
- };
- enum {
- OCSPNONCEEXTASN_IDX_SEQ = 0,
- OCSPNONCEEXTASN_IDX_EXT,
- OCSPNONCEEXTASN_IDX_EXT_OID,
- OCSPNONCEEXTASN_IDX_EXT_VAL,
- OCSPNONCEEXTASN_IDX_EXT_NONCE,
- };
- /* Number of items in ASN.1 template for OCSP nonce extension. */
- #define ocspNonceExtASN_Length (sizeof(ocspNonceExtASN) / sizeof(ASNItem))
- #endif /* WOLFSSL_ASN_TEMPLATE */
- word32 EncodeOcspRequestExtensions(OcspRequest* req, byte* output, word32 size)
- {
- const byte NonceObjId[] = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07,
- 0x30, 0x01, 0x02 };
- #ifndef WOLFSSL_ASN_TEMPLATE
- byte seqArray[5][MAX_SEQ_SZ];
- word32 seqSz[5], totalSz = (word32)sizeof(NonceObjId);
- WOLFSSL_ENTER("SetOcspReqExtensions");
- if (!req || !output || !req->nonceSz)
- return 0;
- totalSz += req->nonceSz;
- totalSz += seqSz[0] = SetOctetString(req->nonceSz, seqArray[0]);
- totalSz += seqSz[1] = SetOctetString(req->nonceSz + seqSz[0], seqArray[1]);
- totalSz += seqSz[2] = SetObjectId(sizeof(NonceObjId), seqArray[2]);
- totalSz += seqSz[3] = SetSequence(totalSz, seqArray[3]);
- totalSz += seqSz[4] = SetSequence(totalSz, seqArray[4]);
- if (totalSz > size)
- return 0;
- totalSz = 0;
- XMEMCPY(output + totalSz, seqArray[4], seqSz[4]);
- totalSz += seqSz[4];
- XMEMCPY(output + totalSz, seqArray[3], seqSz[3]);
- totalSz += seqSz[3];
- XMEMCPY(output + totalSz, seqArray[2], seqSz[2]);
- totalSz += seqSz[2];
- XMEMCPY(output + totalSz, NonceObjId, sizeof(NonceObjId));
- totalSz += (word32)sizeof(NonceObjId);
- XMEMCPY(output + totalSz, seqArray[1], seqSz[1]);
- totalSz += seqSz[1];
- XMEMCPY(output + totalSz, seqArray[0], seqSz[0]);
- totalSz += seqSz[0];
- XMEMCPY(output + totalSz, req->nonce, req->nonceSz);
- totalSz += req->nonceSz;
- return totalSz;
- #else
- int ret = 0;
- WOLFSSL_ENTER("SetOcspReqExtensions");
- /* Check request has nonce to write in extension. */
- if (req != NULL && req->nonceSz != 0) {
- DECL_ASNSETDATA(dataASN, ocspNonceExtASN_Length);
- int sz;
- CALLOC_ASNSETDATA(dataASN, ocspNonceExtASN_Length, ret, req->heap);
- /* Set nonce extension OID and nonce. */
- SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_OID], NonceObjId,
- sizeof(NonceObjId));
- SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_NONCE], req->nonce,
- req->nonceSz);
- /* Calculate size of nonce extension. */
- ret = SizeASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
- &sz);
- /* Check buffer big enough for encoding if supplied. */
- if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
- ret = BUFFER_E;
- }
- if ((ret == 0) && (output != NULL)) {
- /* Encode nonce extension. */
- SetASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
- output);
- }
- if (ret == 0) {
- /* Return size of encoding. */
- ret = sz;
- }
- FREE_ASNSETDATA(dataASN, req->heap);
- }
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for OCSPRequest.
- * RFC 6960, 4.1.1 - ASN.1 Specification of the OCSP Request
- */
- static const ASNItem ocspRequestASN[] = {
- /* OCSPRequest */
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* tbsRequest */
- /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* version not written - v1 */
- /* requestorName not written */
- /* requestList */
- /* TBS_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
- /* Request */
- /* TBS_LIST */ { 3, ASN_SEQUENCE, 1, 1, 0 },
- /* reqCert */
- /* TBS_REQ_CID */ { 4, ASN_SEQUENCE, 1, 1, 0 },
- /* hashAlgorithm */
- /* TBS_REQ_HASH */ { 5, ASN_SEQUENCE, 1, 1, 0 },
- /* TBS_REQ_HASH_OID */ { 6, ASN_OBJECT_ID, 0, 0, 0 },
- /* issuerNameHash */
- /* TBS_REQ_ISSUER */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
- /* issuerKeyHash */
- /* TBS_REQ_ISSUERKEY */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
- /* serialNumber */
- /* TBS_REQ_SERIAL */ { 5, ASN_INTEGER, 0, 0, 0 },
- /* requestExtensions */
- /* TBS_REQEXT */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 0 },
- /* optionalSignature not written. */
- };
- enum {
- OCSPREQUESTASN_IDX_SEQ = 0,
- OCSPREQUESTASN_IDX_TBS,
- OCSPREQUESTASN_IDX_TBS_SEQ,
- OCSPREQUESTASN_IDX_TBS_LIST,
- OCSPREQUESTASN_IDX_TBS_REQ_CID,
- OCSPREQUESTASN_IDX_TBS_REQ_HASH,
- OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID,
- OCSPREQUESTASN_IDX_TBS_REQ_ISSUER,
- OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY,
- OCSPREQUESTASN_IDX_TBS_REQ_SERIAL,
- OCSPREQUESTASN_IDX_TBS_REQEXT,
- };
- /* Number of items in ASN.1 template for OCSPRequest. */
- #define ocspRequestASN_Length (sizeof(ocspRequestASN) / sizeof(ASNItem))
- #endif
- int EncodeOcspRequest(OcspRequest* req, byte* output, word32 size)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- byte seqArray[5][MAX_SEQ_SZ];
- /* The ASN.1 of the OCSP Request is an onion of sequences */
- byte algoArray[MAX_ALGO_SZ];
- byte issuerArray[MAX_ENCODED_DIG_SZ];
- byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
- byte snArray[MAX_SN_SZ];
- byte extArray[MAX_OCSP_EXT_SZ];
- word32 seqSz[5], algoSz, issuerSz, issuerKeySz, extSz, totalSz;
- int i, snSz;
- int keyIdSz;
- WOLFSSL_ENTER("EncodeOcspRequest");
- #ifdef NO_SHA
- algoSz = SetAlgoID(SHA256h, algoArray, oidHashType, 0);
- keyIdSz = WC_SHA256_DIGEST_SIZE;
- #else
- algoSz = SetAlgoID(SHAh, algoArray, oidHashType, 0);
- keyIdSz = WC_SHA_DIGEST_SIZE;
- #endif
- issuerSz = SetDigest(req->issuerHash, keyIdSz, issuerArray);
- issuerKeySz = SetDigest(req->issuerKeyHash, keyIdSz, issuerKeyArray);
- snSz = SetSerialNumber(req->serial, req->serialSz, snArray,
- MAX_SN_SZ, MAX_SN_SZ);
- extSz = 0;
- if (snSz < 0)
- return snSz;
- if (req->nonceSz) {
- /* TLS Extensions use this function too - put extensions after
- * ASN.1: Context Specific [2].
- */
- extSz = EncodeOcspRequestExtensions(req, extArray + 2,
- OCSP_NONCE_EXT_SZ);
- extSz += SetExplicit(2, extSz, extArray);
- }
- totalSz = algoSz + issuerSz + issuerKeySz + snSz;
- for (i = 4; i >= 0; i--) {
- seqSz[i] = SetSequence(totalSz, seqArray[i]);
- totalSz += seqSz[i];
- if (i == 2) totalSz += extSz;
- }
- if (output == NULL)
- return totalSz;
- if (totalSz > size)
- return BUFFER_E;
- totalSz = 0;
- for (i = 0; i < 5; i++) {
- XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
- totalSz += seqSz[i];
- }
- XMEMCPY(output + totalSz, algoArray, algoSz);
- totalSz += algoSz;
- XMEMCPY(output + totalSz, issuerArray, issuerSz);
- totalSz += issuerSz;
- XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
- totalSz += issuerKeySz;
- XMEMCPY(output + totalSz, snArray, snSz);
- totalSz += snSz;
- if (extSz != 0) {
- XMEMCPY(output + totalSz, extArray, extSz);
- totalSz += extSz;
- }
- return totalSz;
- #else
- DECL_ASNSETDATA(dataASN, ocspRequestASN_Length);
- word32 extSz = 0;
- int sz = 0;
- int ret = 0;
- int keyIdSz;
- WOLFSSL_ENTER("EncodeOcspRequest");
- CALLOC_ASNSETDATA(dataASN, ocspRequestASN_Length, ret, req->heap);
- if (ret == 0) {
- /* Set OID of hash algorithm use on issuer and key. */
- #ifdef NO_SHA
- SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHA256h,
- oidHashType);
- keyIdSz = WC_SHA256_DIGEST_SIZE;
- #else
- SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHAh,
- oidHashType);
- keyIdSz = WC_SHA_DIGEST_SIZE;
- #endif
- /* Set issuer, issuer key hash and serial number of certificate being
- * checked. */
- SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUER],
- req->issuerHash, keyIdSz);
- SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY],
- req->issuerKeyHash, keyIdSz);
- SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_SERIAL],
- req->serial, req->serialSz);
- /* Only extension to write is nonce - check if one to encode. */
- if (req->nonceSz) {
- /* Get size of extensions and leave space for them in encoding. */
- ret = extSz = EncodeOcspRequestExtensions(req, NULL, 0);
- SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT], NULL, extSz);
- if (ret > 0) {
- ret = 0;
- }
- }
- else {
- /* Don't write out extensions. */
- dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].noOut = 1;
- }
- }
- if (ret == 0) {
- /* Calculate size of encoding. */
- ret = SizeASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length,
- &sz);
- }
- /* Check buffer big enough for encoding if supplied. */
- if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
- ret = BUFFER_E;
- }
- if ((ret == 0) && (output != NULL)) {
- /* Encode OCSPRequest. */
- SetASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length, output);
- if (req->nonceSz) {
- /* Encode extensions into space provided. */
- ret = EncodeOcspRequestExtensions(req,
- (byte*)dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].data.buffer.data,
- extSz);
- if (ret > 0) {
- ret = 0;
- }
- }
- }
- if (ret == 0) {
- /* Return size of encoding. */
- ret = sz;
- }
- FREE_ASNSETDATA(dataASN, req->heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- int InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce,
- void* heap)
- {
- int ret;
- WOLFSSL_ENTER("InitOcspRequest");
- if (req == NULL)
- return BAD_FUNC_ARG;
- XMEMSET(req, 0, sizeof(OcspRequest));
- req->heap = heap;
- if (cert) {
- XMEMCPY(req->issuerHash, cert->issuerHash, KEYID_SIZE);
- XMEMCPY(req->issuerKeyHash, cert->issuerKeyHash, KEYID_SIZE);
- req->serial = (byte*)XMALLOC(cert->serialSz, req->heap,
- DYNAMIC_TYPE_OCSP_REQUEST);
- if (req->serial == NULL)
- return MEMORY_E;
- XMEMCPY(req->serial, cert->serial, cert->serialSz);
- req->serialSz = cert->serialSz;
- if (cert->extAuthInfoSz != 0 && cert->extAuthInfo != NULL) {
- req->url = (byte*)XMALLOC(cert->extAuthInfoSz + 1, req->heap,
- DYNAMIC_TYPE_OCSP_REQUEST);
- if (req->url == NULL) {
- XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP);
- req->serial = NULL;
- return MEMORY_E;
- }
- XMEMCPY(req->url, cert->extAuthInfo, cert->extAuthInfoSz);
- req->urlSz = cert->extAuthInfoSz;
- req->url[req->urlSz] = 0;
- }
- }
- if (useNonce) {
- WC_RNG rng;
- #ifndef HAVE_FIPS
- ret = wc_InitRng_ex(&rng, req->heap, INVALID_DEVID);
- #else
- ret = wc_InitRng(&rng);
- #endif
- if (ret != 0) {
- WOLFSSL_MSG("\tCannot initialize RNG. Skipping the OCSP Nonce.");
- } else {
- if (wc_RNG_GenerateBlock(&rng, req->nonce, MAX_OCSP_NONCE_SZ) != 0)
- WOLFSSL_MSG("\tCannot run RNG. Skipping the OCSP Nonce.");
- else
- req->nonceSz = MAX_OCSP_NONCE_SZ;
- wc_FreeRng(&rng);
- }
- }
- return 0;
- }
- void FreeOcspRequest(OcspRequest* req)
- {
- WOLFSSL_ENTER("FreeOcspRequest");
- if (req) {
- if (req->serial)
- XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
- req->serial = NULL;
- #ifdef OPENSSL_EXTRA
- if (req->serialInt) {
- if (req->serialInt->isDynamic) {
- XFREE(req->serialInt->data, NULL, DYNAMIC_TYPE_OPENSSL);
- }
- XFREE(req->serialInt, NULL, DYNAMIC_TYPE_OPENSSL);
- }
- req->serialInt = NULL;
- #endif
- if (req->url)
- XFREE(req->url, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
- req->url = NULL;
- }
- }
- int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
- {
- int cmp = -1; /* default as not matching, cmp gets set on each check */
- int ocspDigestSize;
- OcspEntry *single, *next, *prev = NULL, *top;
- WOLFSSL_ENTER("CompareOcspReqResp");
- if (req == NULL) {
- WOLFSSL_MSG("\tReq missing");
- return -1;
- }
- if (resp == NULL || resp->single == NULL) {
- WOLFSSL_MSG("\tResp missing");
- return 1;
- }
- /* Nonces are not critical. The responder may not necessarily add
- * the nonce to the response. */
- if (req->nonceSz && resp->nonce != NULL
- #ifndef WOLFSSL_FORCE_OCSP_NONCE_CHECK
- && resp->nonceSz != 0
- #endif
- ) {
- cmp = req->nonceSz - resp->nonceSz;
- if (cmp != 0) {
- WOLFSSL_MSG("\tnonceSz mismatch");
- return cmp;
- }
- cmp = XMEMCMP(req->nonce, resp->nonce, req->nonceSz);
- if (cmp != 0) {
- WOLFSSL_MSG("\tnonce mismatch");
- return cmp;
- }
- }
- /* match based on found status and return */
- for (single = resp->single; single; single = next) {
- #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
- ocspDigestSize = wc_HashGetDigestSize(
- wc_OidGetHash(single->hashAlgoOID));
- #else
- ocspDigestSize = OCSP_DIGEST_SIZE;
- #endif
- cmp = req->serialSz - single->status->serialSz;
- if (cmp == 0) {
- cmp = XMEMCMP(req->serial, single->status->serial, req->serialSz)
- || XMEMCMP(req->issuerHash, single->issuerHash, ocspDigestSize)
- || XMEMCMP(req->issuerKeyHash, single->issuerKeyHash, ocspDigestSize);
- if (cmp == 0) {
- /* match found */
- if (resp->single != single && prev) {
- /* move to top of list */
- top = resp->single;
- resp->single = single;
- prev->next = single->next;
- single->next = top;
- }
- break;
- }
- }
- next = single->next;
- prev = single;
- }
- if (cmp != 0) {
- WOLFSSL_MSG("\trequest and response mismatch");
- return cmp;
- }
- return 0;
- }
- #endif /* HAVE_OCSP */
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for certificate name hash. */
- static const ASNItem nameHashASN[] = {
- /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
- /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
- };
- enum {
- NAMEHASHASN_IDX_OID = 0,
- NAMEHASHASN_IDX_NAME
- };
- /* Number of items in ASN.1 template for certificate name hash. */
- #define nameHashASN_Length (sizeof(nameHashASN) / sizeof(ASNItem))
- #endif /* WOLFSSL_ASN_TEMPLATE */
- /* store WC_SHA hash of NAME */
- int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx)
- {
- /* Use summy signature OID. */
- return GetNameHash_ex(source, idx, hash, maxIdx, 0);
- }
- /* store WC_SHA hash of NAME */
- int GetNameHash_ex(const byte* source, word32* idx, byte* hash, int maxIdx,
- int sigOID)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int length; /* length of all distinguished names */
- int ret;
- word32 dummy;
- byte tag;
- WOLFSSL_ENTER("GetNameHash");
- dummy = *idx;
- if (GetASNTag(source, &dummy, &tag, (word32)maxIdx) == 0 &&
- tag == ASN_OBJECT_ID) {
- WOLFSSL_MSG("Trying optional prefix...");
- if (GetLength(source, idx, &length, (word32)maxIdx) < 0)
- return ASN_PARSE_E;
- *idx += (word32)length;
- WOLFSSL_MSG("Got optional prefix");
- }
- /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
- * calculated over the entire DER encoding of the Name field, including
- * the tag and length. */
- dummy = *idx;
- if (GetSequence(source, idx, &length, (word32)maxIdx) < 0)
- return ASN_PARSE_E;
- ret = CalcHashId_ex(source + dummy, (word32)length + *idx - dummy, hash,
- HashIdAlg(sigOID));
- *idx += (word32)length;
- return ret;
- #else
- ASNGetData dataASN[nameHashASN_Length];
- int ret;
- XMEMSET(dataASN, 0, sizeof(dataASN));
- /* Ignore the OID even when present. */
- GetASN_OID(&dataASN[NAMEHASHASN_IDX_OID], oidIgnoreType);
- /* Decode certificate name. */
- ret = GetASN_Items(nameHashASN, dataASN, nameHashASN_Length, 0, source, idx,
- (word32)maxIdx);
- if (ret == 0) {
- /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
- * calculated over the entire DER encoding of the Name field, including
- * the tag and length. */
- /* Calculate hash of complete name including SEQUENCE. */
- ret = CalcHashId_ex(
- GetASNItem_Addr(dataASN[NAMEHASHASN_IDX_NAME], source),
- GetASNItem_Length(dataASN[NAMEHASHASN_IDX_NAME], source),
- hash, HashIdAlg(sigOID));
- }
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #if defined(HAVE_CRL) && !defined(WOLFCRYPT_ONLY)
- #ifdef OPENSSL_EXTRA
- static char* GetNameFromDer(const byte* source, int sz)
- {
- char* out;
- out = (char*)XMALLOC(sz, NULL, DYNAMIC_TYPE_OPENSSL);
- if (out == NULL) {
- WOLFSSL_MSG("Name malloc failed");
- return NULL;
- }
- XMEMCPY(out, source, sz);
- return out;
- }
- #endif
- /* initialize decoded CRL */
- void InitDecodedCRL(DecodedCRL* dcrl, void* heap)
- {
- WOLFSSL_MSG("InitDecodedCRL");
- XMEMSET(dcrl, 0, sizeof(DecodedCRL));
- dcrl->heap = heap;
- #ifdef WOLFSSL_HEAP_TEST
- dcrl->heap = (void*)WOLFSSL_HEAP_TEST;
- #endif
- }
- /* free decoded CRL resources */
- void FreeDecodedCRL(DecodedCRL* dcrl)
- {
- RevokedCert* tmp = dcrl->certs;
- WOLFSSL_MSG("FreeDecodedCRL");
- while(tmp) {
- RevokedCert* next = tmp->next;
- XFREE(tmp, dcrl->heap, DYNAMIC_TYPE_REVOKED);
- tmp = next;
- }
- #ifdef OPENSSL_EXTRA
- if (dcrl->issuer != NULL)
- XFREE(dcrl->issuer, NULL, DYNAMIC_TYPE_OPENSSL);
- #endif
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for revoked certificates.
- * X.509: RFC 5280, 5.1 - CRL Fields
- */
- static const ASNItem revokedASN[] = {
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* userCertificate CertificateSerialNumber */
- /* CERT */ { 1, ASN_INTEGER, 0, 0, 0 },
- /* revocationDate Time */
- /* TIME_UTC */ { 1, ASN_UTC_TIME, 0, 0, 2 },
- /* TIME_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 2 },
- /* crlEntryExensions Extensions */
- /* TIME_EXT */ { 1, ASN_SEQUENCE, 1, 0, 1 },
- };
- enum {
- REVOKEDASN_IDX_SEQ = 0,
- REVOKEDASN_IDX_CERT,
- REVOKEDASN_IDX_TIME_UTC,
- REVOKEDASN_IDX_TIME_GT,
- REVOKEDASN_IDX_TIME_EXT,
- };
- /* Number of items in ASN.1 template for revoked certificates. */
- #define revokedASN_Length (sizeof(revokedASN) / sizeof(ASNItem))
- #endif
- /* Get Revoked Cert list, 0 on success */
- static int GetRevoked(RevokedCert* rcert, const byte* buff, word32* idx,
- DecodedCRL* dcrl, int maxIdx)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int ret;
- int len;
- word32 end;
- RevokedCert* rc;
- #ifdef CRL_STATIC_REVOKED_LIST
- int totalCerts = 0;
- #endif
- WOLFSSL_ENTER("GetRevoked");
- if (GetSequence(buff, idx, &len, maxIdx) < 0)
- return ASN_PARSE_E;
- end = *idx + len;
- #ifdef CRL_STATIC_REVOKED_LIST
- totalCerts = dcrl->totalCerts;
- if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
- return MEMORY_E;
- }
- rc = &rcert[totalCerts];
- ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
- if (ret < 0) {
- WOLFSSL_MSG("wc_GetSerialNumber error");
- return ret;
- }
- #else
- rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
- DYNAMIC_TYPE_REVOKED);
- if (rc == NULL) {
- WOLFSSL_MSG("Alloc Revoked Cert failed");
- return MEMORY_E;
- }
- ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
- if (ret < 0) {
- WOLFSSL_MSG("wc_GetSerialNumber error");
- XFREE(rc, dcrl->heap, DYNAMIC_TYPE_REVOKED);
- return ret;
- }
- /* add to list */
- rc->next = dcrl->certs;
- dcrl->certs = rc;
- (void)rcert;
- #endif /* CRL_STATIC_REVOKED_LIST */
- dcrl->totalCerts++;
- /* get date */
- #ifndef NO_ASN_TIME
- ret = GetBasicDate(buff, idx, rc->revDate, &rc->revDateFormat, maxIdx);
- if (ret < 0) {
- WOLFSSL_MSG("Expecting Date");
- return ret;
- }
- #endif
- /* skip extensions */
- *idx = end;
- return 0;
- #else
- DECL_ASNGETDATA(dataASN, revokedASN_Length);
- int ret = 0;
- word32 serialSz = EXTERNAL_SERIAL_SIZE;
- word32 revDateSz = MAX_DATE_SIZE;
- RevokedCert* rc;
- #ifdef CRL_STATIC_REVOKED_LIST
- int totalCerts = dcrl->totalCerts;
- if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
- return MEMORY_E;
- }
- rc = &rcert[totalCerts];
- #else
- /* Allocate a new revoked certificate object. */
- rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
- DYNAMIC_TYPE_CRL);
- if (rc == NULL) {
- ret = MEMORY_E;
- }
- #endif /* CRL_STATIC_REVOKED_LIST */
- CALLOC_ASNGETDATA(dataASN, revokedASN_Length, ret, dcrl->heap);
- if (ret == 0) {
- /* Set buffer to place serial number into. */
- GetASN_Buffer(&dataASN[REVOKEDASN_IDX_CERT], rc->serialNumber,
- &serialSz);
- /* Set buffer to store revocation date. */
- GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_UTC], rc->revDate,
- &revDateSz);
- GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_GT], rc->revDate,
- &revDateSz);
- /* Decode the Revoked */
- ret = GetASN_Items(revokedASN, dataASN, revokedASN_Length, 1, buff, idx,
- maxIdx);
- }
- if (ret == 0) {
- /* Store size of serial number. */
- rc->serialSz = serialSz;
- rc->revDateFormat = (dataASN[REVOKEDASN_IDX_TIME_UTC].tag != 0)
- ? dataASN[REVOKEDASN_IDX_TIME_UTC].tag
- : dataASN[REVOKEDASN_IDX_TIME_GT].tag;
- /* TODO: use extensions, only v2 */
- /* Add revoked certificate to chain. */
- #ifndef CRL_STATIC_REVOKED_LIST
- rc->next = dcrl->certs;
- dcrl->certs = rc;
- #endif
- dcrl->totalCerts++;
- }
- FREE_ASNGETDATA(dataASN, dcrl->heap);
- #ifndef CRL_STATIC_REVOKED_LIST
- if ((ret != 0) && (rc != NULL)) {
- XFREE(rc, dcrl->heap, DYNAMIC_TYPE_CRL);
- }
- (void)rcert;
- #endif
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* Parse the revoked certificates of a CRL.
- *
- * @param [in] dcrl Decoded CRL object.
- * @param [in] buff Buffer holding CRL.
- * @param [in] idx Index into buffer of revoked certificates.
- * @param [in] maxIdx Maximum index of revoked cartificates data.
- * @return 0 on success.
- * @return ASN_PARSE_E on failure.
- */
- static int ParseCRL_RevokedCerts(RevokedCert* rcert, DecodedCRL* dcrl,
- const byte* buff, word32 idx, word32 maxIdx)
- {
- int ret = 0;
- /* Parse each revoked cerificate. */
- while ((ret == 0) && (idx < maxIdx)) {
- /* Parse a revoked certificate. */
- if (GetRevoked(rcert, buff, &idx, dcrl, maxIdx) < 0) {
- ret = ASN_PARSE_E;
- }
- }
- return ret;
- }
- #endif /* WOLFSSL_ASN_TEMPLATE */
- #ifndef WOLFSSL_ASN_TEMPLATE
- /* Get CRL Signature, 0 on success */
- static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
- int maxIdx)
- {
- int length;
- int ret;
- WOLFSSL_ENTER("GetCRL_Signature");
- ret = CheckBitString(source, idx, &length, maxIdx, 1, NULL);
- if (ret != 0)
- return ret;
- dcrl->sigLength = length;
- dcrl->signature = (byte*)&source[*idx];
- *idx += dcrl->sigLength;
- return 0;
- }
- #endif /* !WOLFSSL_ASN_TEMPLATE */
- int VerifyCRL_Signature(SignatureCtx* sigCtx, const byte* toBeSigned,
- word32 tbsSz, const byte* signature, word32 sigSz,
- word32 signatureOID, Signer *ca, void* heap)
- {
- /* try to confirm/verify signature */
- #ifndef IGNORE_KEY_EXTENSIONS
- if ((ca->keyUsage & KEYUSE_CRL_SIGN) == 0) {
- WOLFSSL_MSG("CA cannot sign CRLs");
- WOLFSSL_ERROR_VERBOSE(ASN_CRL_NO_SIGNER_E);
- return ASN_CRL_NO_SIGNER_E;
- }
- #endif /* IGNORE_KEY_EXTENSIONS */
- InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
- if (ConfirmSignature(sigCtx, toBeSigned, tbsSz, ca->publicKey,
- ca->pubKeySize, ca->keyOID, signature, sigSz,
- signatureOID, NULL, 0, NULL) != 0) {
- WOLFSSL_MSG("CRL Confirm signature failed");
- WOLFSSL_ERROR_VERBOSE(ASN_CRL_CONFIRM_E);
- return ASN_CRL_CONFIRM_E;
- }
- return 0;
- }
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* Find the signer for the CRL and verify the signature.
- *
- * @param [in] dcrl Decoded CRL object.
- * @param [in] buff Buffer holding CRL.
- * @param [in] cm Certificate manager object.
- * @return 0 on success.
- * @return ASN_CRL_NO_SIGNER_E when no signer found.
- * @return ASN_CRL_CONFIRM_E when signature did not verify.
- */
- static int PaseCRL_CheckSignature(DecodedCRL* dcrl, const byte* buff, void* cm)
- {
- int ret = 0;
- Signer* ca = NULL;
- SignatureCtx sigCtx;
- /* OpenSSL doesn't add skid by default for CRLs cause firefox chokes.
- * If experiencing issues uncomment NO_SKID define in CRL section of
- * wolfssl/wolfcrypt/settings.h */
- #ifndef NO_SKID
- if (dcrl->extAuthKeyIdSet) {
- /* more unique than issuerHash */
- ca = GetCA(cm, dcrl->extAuthKeyId);
- }
- /* Check issuerHash matched CA's subjectNameHash. */
- if ((ca != NULL) && (XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
- KEYID_SIZE) != 0)) {
- ca = NULL;
- }
- if (ca == NULL) {
- ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
- /* If AKID is available then this CA doesn't have the public
- * key required */
- if (ca && dcrl->extAuthKeyIdSet) {
- WOLFSSL_MSG("CA SKID doesn't match AKID");
- ca = NULL;
- }
- }
- #else
- ca = GetCA(cm, dcrl->issuerHash);
- #endif /* !NO_SKID */
- WOLFSSL_MSG("About to verify CRL signature");
- if (ca == NULL) {
- WOLFSSL_MSG("Did NOT find CRL issuer CA");
- ret = ASN_CRL_NO_SIGNER_E;
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- if (ret == 0) {
- WOLFSSL_MSG("Found CRL issuer CA");
- /* Verify CRL signature with CA. */
- ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
- dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
- dcrl->signatureOID, ca, dcrl->heap);
- }
- return ret;
- }
- #endif
- #ifndef WOLFSSL_ASN_TEMPLATE
- static int ParseCRL_CertList(RevokedCert* rcert, DecodedCRL* dcrl,
- const byte* buf,word32* inOutIdx, int sz, int verify)
- {
- word32 oid, dateIdx, idx, checkIdx;
- int length;
- #ifdef WOLFSSL_NO_CRL_NEXT_DATE
- int doNextDate = 1;
- #endif
- byte tag;
- if (dcrl == NULL || inOutIdx == NULL || buf == NULL) {
- return BAD_FUNC_ARG;
- }
- /* may have version */
- idx = *inOutIdx;
- checkIdx = idx;
- if (GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag == ASN_INTEGER) {
- if (GetMyVersion(buf, &idx, &dcrl->version, sz) < 0)
- return ASN_PARSE_E;
- dcrl->version++;
- }
- if (GetAlgoId(buf, &idx, &oid, oidIgnoreType, sz) < 0)
- return ASN_PARSE_E;
- checkIdx = idx;
- if (GetSequence(buf, &checkIdx, &length, sz) < 0) {
- return ASN_PARSE_E;
- }
- #ifdef OPENSSL_EXTRA
- dcrl->issuerSz = length + (checkIdx - idx);
- dcrl->issuer = (byte*)GetNameFromDer(buf + idx, (int)dcrl->issuerSz);
- #endif
- if (GetNameHash_ex(buf, &idx, dcrl->issuerHash, sz, oid) < 0)
- return ASN_PARSE_E;
- if (GetBasicDate(buf, &idx, dcrl->lastDate, &dcrl->lastDateFormat, sz) < 0)
- return ASN_PARSE_E;
- dateIdx = idx;
- if (GetBasicDate(buf, &idx, dcrl->nextDate, &dcrl->nextDateFormat, sz) < 0)
- {
- #ifndef WOLFSSL_NO_CRL_NEXT_DATE
- (void)dateIdx;
- return ASN_PARSE_E;
- #else
- dcrl->nextDateFormat = ASN_OTHER_TYPE; /* skip flag */
- doNextDate = 0;
- idx = dateIdx;
- #endif
- }
- #ifdef WOLFSSL_NO_CRL_NEXT_DATE
- if (doNextDate)
- #endif
- {
- #ifndef NO_ASN_TIME
- if (verify != NO_VERIFY &&
- !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
- WOLFSSL_MSG("CRL after date is no longer valid");
- WOLFSSL_ERROR_VERBOSE(CRL_CERT_DATE_ERR);
- return CRL_CERT_DATE_ERR;
- }
- #else
- (void)verify;
- #endif
- }
- checkIdx = idx;
- if (idx != dcrl->sigIndex &&
- GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag != CRL_EXTENSIONS) {
- int len;
- if (GetSequence(buf, &idx, &len, sz) < 0)
- return ASN_PARSE_E;
- len += idx;
- while (idx < (word32)len) {
- if (GetRevoked(rcert, buf, &idx, dcrl, len) < 0)
- return ASN_PARSE_E;
- }
- }
- *inOutIdx = idx;
- return 0;
- }
- #endif /* !WOLFSSL_ASN_TEMPLATE */
- #ifndef NO_SKID
- static int ParseCRL_AuthKeyIdExt(const byte* input, int sz, DecodedCRL* dcrl)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- word32 idx = 0;
- int length = 0, ret = 0;
- byte tag;
- WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
- if (GetSequence(input, &idx, &length, sz) < 0) {
- WOLFSSL_MSG("\tfail: should be a SEQUENCE");
- return ASN_PARSE_E;
- }
- if (GetASNTag(input, &idx, &tag, sz) < 0) {
- return ASN_PARSE_E;
- }
- if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
- WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
- return 0;
- }
- if (GetLength(input, &idx, &length, sz) <= 0) {
- WOLFSSL_MSG("\tfail: extension data length");
- return ASN_PARSE_E;
- }
- dcrl->extAuthKeyIdSet = 1;
- /* Get the hash or hash of the hash if wrong size. */
- ret = GetHashId(input + idx, length, dcrl->extAuthKeyId,
- HashIdAlg(dcrl->signatureOID));
- return ret;
- #else
- DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
- int ret = 0;
- word32 idx = 0;
- WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
- CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, dcrl->heap);
- if (ret == 0) {
- /* Parse an authority key identifier. */
- ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
- &idx, sz);
- }
- if (ret == 0) {
- /* Key id is optional. */
- if (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data == NULL) {
- WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
- }
- else {
- /* Get the hash or hash of the hash if wrong size. */
- ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
- dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
- dcrl->extAuthKeyId, HashIdAlg(dcrl->signatureOID));
- }
- }
- FREE_ASNGETDATA(dataASN, dcrl->heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #endif
- #ifndef WOLFSSL_ASN_TEMPLATE
- static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf,
- word32* inOutIdx, word32 sz)
- {
- int length;
- word32 idx;
- word32 ext_bound; /* boundary index for the sequence of extensions */
- word32 oid;
- byte tag;
- WOLFSSL_ENTER("ParseCRL_Extensions");
- (void)dcrl;
- if (inOutIdx == NULL)
- return BAD_FUNC_ARG;
- idx = *inOutIdx;
- /* CRL Extensions are optional */
- if ((idx + 1) > sz)
- return 0;
- /* CRL Extensions are optional */
- if (GetASNTag(buf, &idx, &tag, sz) < 0)
- return 0;
- /* CRL Extensions are optional */
- if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
- return 0;
- if (GetLength(buf, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- if (GetSequence(buf, &idx, &length, sz) < 0)
- return ASN_PARSE_E;
- ext_bound = idx + length;
- while (idx < (word32)ext_bound) {
- word32 localIdx;
- int ret;
- if (GetSequence(buf, &idx, &length, sz) < 0) {
- WOLFSSL_MSG("\tfail: should be a SEQUENCE");
- return ASN_PARSE_E;
- }
- oid = 0;
- if (GetObjectId(buf, &idx, &oid, oidCrlExtType, sz) < 0) {
- WOLFSSL_MSG("\tfail: OBJECT ID");
- return ASN_PARSE_E;
- }
- /* check for critical flag */
- if ((idx + 1) > (word32)sz) {
- WOLFSSL_MSG("\tfail: malformed buffer");
- return BUFFER_E;
- }
- localIdx = idx;
- if (GetASNTag(buf, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
- WOLFSSL_MSG("\tfound optional critical flag, moving past");
- ret = GetBoolean(buf, &idx, sz);
- if (ret < 0)
- return ret;
- }
- ret = GetOctetString(buf, &idx, &length, sz);
- if (ret < 0)
- return ret;
- if (oid == AUTH_KEY_OID) {
- #ifndef NO_SKID
- ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
- if (ret < 0) {
- WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
- return ret;
- }
- #endif
- }
- else if (oid == CRL_NUMBER_OID) {
- localIdx = idx;
- if (GetASNTag(buf, &localIdx, &tag, sz) == 0 &&
- tag == ASN_INTEGER) {
- ret = GetASNInt(buf, &idx, &length, sz);
- if (ret < 0) {
- WOLFSSL_MSG("\tcouldn't parse CRL number extension");
- return ret;
- }
- else {
- if (length > 1) {
- int i;
- #ifdef WOLFSSL_SMALL_STACK
- mp_int* m = (mp_int*)XMALLOC(sizeof(*m), NULL,
- DYNAMIC_TYPE_BIGINT);
- if (m == NULL) {
- return MEMORY_E;
- }
- #else
- mp_int m[1];
- #endif
- if (mp_init(m) != MP_OKAY) {
- ret = MP_INIT_E;
- }
- if (ret == 0)
- ret = mp_read_unsigned_bin(m, buf + idx, length);
- if (ret != MP_OKAY)
- ret = BUFFER_E;
- if (ret == 0) {
- dcrl->crlNumber = 0;
- for (i = 0; i < (int)(*m).used; ++i) {
- if (i > (CHAR_BIT *
- (int)sizeof(word32) / DIGIT_BIT)) {
- break;
- }
- dcrl->crlNumber |= ((word32)(*m).dp[i]) <<
- (DIGIT_BIT * i);
- }
- }
- mp_free(m);
- #ifdef WOLFSSL_SMALL_STACK
- XFREE(m, NULL, DYNAMIC_TYPE_BIGINT);
- #endif
- if (ret != 0)
- return ret;
- }
- else if (length == 1) {
- dcrl->crlNumber = buf[idx];
- }
- }
- }
- }
- idx += length;
- }
- *inOutIdx = idx;
- return 0;
- }
- #else
- /* Parse the extensions of a CRL.
- *
- * @param [in] dcrl Decoded CRL object.
- * @param [in] buff Buffer holding CRL.
- * @param [in] idx Index into buffer of extensions.
- * @param [in] maxIdx Maximum index of extension data.
- * @return 0 on success.
- * @return ASN_PARSE_E on failure.
- */
- static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf, word32 idx,
- word32 maxIdx)
- {
- DECL_ASNGETDATA(dataASN, certExtASN_Length);
- int ret = 0;
- ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, dcrl->heap);
- while ((ret == 0) && (idx < maxIdx)) {
- byte critical = 0;
- /* Clear dynamic data. */
- XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
- /* Ensure OID is an extention type. */
- GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
- /* Set criticality variable. */
- GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
- /* Parse extension wrapper. */
- ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, buf, &idx,
- maxIdx);
- if (ret == 0) {
- /* OID in extension. */
- word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
- /* Length of extension data. */
- int length = dataASN[CERTEXTASN_IDX_VAL].length;
- if (oid == AUTH_KEY_OID) {
- #ifndef NO_SKID
- /* Parse Authority Key Id extesion.
- * idx is at start of OCTET_STRING data. */
- ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
- if (ret != 0) {
- WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
- }
- #endif
- }
- /* TODO: Parse CRL Number extension */
- /* TODO: check criticality */
- /* Move index on to next extension. */
- idx += length;
- }
- }
- if (ret < 0) {
- ret = ASN_PARSE_E;
- }
- FREE_ASNGETDATA(dataASN, dcrl->heap);
- return ret;
- }
- #endif /* !WOLFSSL_ASN_TEMPLATE */
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* ASN.1 template for a CRL- CertificateList.
- * X.509: RFC 5280, 5.1 - CRL Fields
- */
- static const ASNItem crlASN[] = {
- /* CertificateList */
- /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
- /* tbsCertList */
- /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* version Version OPTIONAL if present must be v2 */
- /* TBS_VER */ { 2, ASN_INTEGER, 0, 0, 1 },
- /* signature */
- /* TBS_SIGALGO */ { 2, ASN_SEQUENCE, 1, 1, 0 },
- /* TBS_SIGALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
- /* TBS_SIGALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
- /* issuer */
- /* TBS_ISSUER */ { 2, ASN_SEQUENCE, 1, 0, 0 },
- /* thisUpdate */
- /* TBS_THISUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 2 },
- /* TBS_THISUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 2 },
- /* nextUpdate */
- /* TBS_NEXTUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 3 },
- /* TBS_NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 3 },
- /* revokedCertificates */
- /* TBS_REVOKEDCERTS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
- /* crlExtensions */
- /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
- /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
- /* signatureAlgorithm */
- /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0 },
- /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
- /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
- /* signatureValue */
- /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
- };
- enum {
- CRLASN_IDX_SEQ = 0,
- CRLASN_IDX_TBS,
- CRLASN_IDX_TBS_VER,
- CRLASN_IDX_TBS_SIGALGO,
- CRLASN_IDX_TBS_SIGALGO_OID,
- CRLASN_IDX_TBS_SIGALGO_NULL,
- CRLASN_IDX_TBS_ISSUER,
- CRLASN_IDX_TBS_THISUPDATE_UTC,
- CRLASN_IDX_TBS_THISUPDATE_GT,
- CRLASN_IDX_TBS_NEXTUPDATE_UTC,
- CRLASN_IDX_TBS_NEXTUPDATE_GT,
- CRLASN_IDX_TBS_REVOKEDCERTS,
- CRLASN_IDX_TBS_EXT,
- CRLASN_IDX_TBS_EXT_SEQ,
- CRLASN_IDX_SIGALGO,
- CRLASN_IDX_SIGALGO_OID,
- CRLASN_IDX_SIGALGO_NULL,
- CRLASN_IDX_SIGNATURE,
- };
- /* Number of items in ASN.1 template for a CRL- CertificateList. */
- #define crlASN_Length (sizeof(crlASN) / sizeof(ASNItem))
- #endif
- /* parse crl buffer into decoded state, 0 on success */
- int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz,
- int verify, void* cm)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- Signer* ca = NULL;
- SignatureCtx sigCtx;
- int ret = 0;
- int len;
- word32 idx = 0;
- WOLFSSL_MSG("ParseCRL");
- /* raw crl hash */
- /* hash here if needed for optimized comparisons
- * wc_Sha sha;
- * wc_InitSha(&sha);
- * wc_ShaUpdate(&sha, buff, sz);
- * wc_ShaFinal(&sha, dcrl->crlHash); */
- if (GetSequence(buff, &idx, &len, sz) < 0)
- return ASN_PARSE_E;
- dcrl->certBegin = idx;
- /* Normalize sz for the length inside the outer sequence. */
- sz = len + idx;
- if (GetSequence(buff, &idx, &len, sz) < 0)
- return ASN_PARSE_E;
- dcrl->sigIndex = len + idx;
- if (ParseCRL_CertList(rcert, dcrl, buff, &idx, dcrl->sigIndex, verify) < 0)
- return ASN_PARSE_E;
- if (ParseCRL_Extensions(dcrl, buff, &idx, dcrl->sigIndex) < 0)
- return ASN_PARSE_E;
- idx = dcrl->sigIndex;
- if (GetAlgoId(buff, &idx, &dcrl->signatureOID, oidSigType, sz) < 0)
- return ASN_PARSE_E;
- if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
- return ASN_PARSE_E;
- /* openssl doesn't add skid by default for CRLs cause firefox chokes
- if experiencing issues uncomment NO_SKID define in CRL section of
- wolfssl/wolfcrypt/settings.h */
- #ifndef NO_SKID
- if (dcrl->extAuthKeyIdSet) {
- ca = GetCA(cm, dcrl->extAuthKeyId); /* more unique than issuerHash */
- }
- if (ca != NULL && XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
- KEYID_SIZE) != 0) {
- ca = NULL;
- }
- if (ca == NULL) {
- ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
- /* If AKID is available then this CA doesn't have the public
- * key required */
- if (ca && dcrl->extAuthKeyIdSet) {
- WOLFSSL_MSG("CA SKID doesn't match AKID");
- ca = NULL;
- }
- }
- #else
- ca = GetCA(cm, dcrl->issuerHash);
- #endif /* !NO_SKID */
- WOLFSSL_MSG("About to verify CRL signature");
- if (ca == NULL) {
- WOLFSSL_MSG("Did NOT find CRL issuer CA");
- ret = ASN_CRL_NO_SIGNER_E;
- WOLFSSL_ERROR_VERBOSE(ret);
- goto end;
- }
- WOLFSSL_MSG("Found CRL issuer CA");
- ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
- dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
- dcrl->signatureOID, ca, dcrl->heap);
- end:
- return ret;
- #else
- DECL_ASNGETDATA(dataASN, crlASN_Length);
- int ret = 0;
- /* Default version - v1 = 0 */
- byte version = 0;
- word32 idx = 0;
- /* Size of buffer for date. */
- word32 lastDateSz = MAX_DATE_SIZE;
- word32 nextDateSz = MAX_DATE_SIZE;
- /* When NO_ASN_TIME is defined, verify not used. */
- (void)verify;
- WOLFSSL_MSG("ParseCRL");
- CALLOC_ASNGETDATA(dataASN, crlASN_Length, ret, dcrl->heap);
- if (ret == 0) {
- /* Set variable to store version. */
- GetASN_Int8Bit(&dataASN[CRLASN_IDX_TBS_VER], &version);
- /* Set expecting signature OID. */
- GetASN_OID(&dataASN[CRLASN_IDX_TBS_SIGALGO_OID], oidSigType);
- /* Set buffer to put last and next date into. */
- GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC], dcrl->lastDate,
- &lastDateSz);
- GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_GT], dcrl->lastDate,
- &lastDateSz);
- GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC], dcrl->nextDate,
- &nextDateSz);
- GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT], dcrl->nextDate,
- &nextDateSz);
- /* Set expecting signature OID. */
- GetASN_OID(&dataASN[CRLASN_IDX_SIGALGO_OID], oidSigType);
- /* Decode the CRL. */
- ret = GetASN_Items(crlASN, dataASN, crlASN_Length, 1, buff, &idx, sz);
- }
- /* Version must be v2 = 1 if present. */
- if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_VER].tag != 0) &&
- (version != 1)) {
- ret = ASN_PARSE_E;
- }
- /* Check minimum size of last date. */
- if ((ret == 0) && (lastDateSz < MIN_DATE_SIZE)) {
- ret = ASN_PARSE_E;
- }
- /* Check minimum size of next date. */
- if ((ret == 0) && (nextDateSz < MIN_DATE_SIZE)) {
- ret = ASN_PARSE_E;
- }
- /* 'signatureAlgorithm' OID must be the same as 'signature' OID. */
- if ((ret == 0) && (dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum !=
- dataASN[CRLASN_IDX_TBS_SIGALGO_OID].data.oid.sum)) {
- ret = ASN_PARSE_E;
- }
- if (ret == 0) {
- /* Store version */
- dcrl->version = ++version;
- /* Store offset of to be signed part. */
- dcrl->certBegin = dataASN[CRLASN_IDX_TBS].offset;
- /* Store index of signature. */
- dcrl->sigIndex = dataASN[CRLASN_IDX_SIGALGO].offset;
- /* Store address and length of signature data. */
- GetASN_GetRef(&dataASN[CRLASN_IDX_SIGNATURE], &dcrl->signature,
- &dcrl->sigLength);
- /* Get the signature OID. */
- dcrl->signatureOID = dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum;
- /* Get the format/tag of the last and next date. */
- dcrl->lastDateFormat = (dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag != 0)
- ? dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag
- : dataASN[CRLASN_IDX_TBS_THISUPDATE_GT].tag;
- dcrl->nextDateFormat = (dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag != 0)
- ? dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag
- : dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT].tag;
- #ifndef NO_ASN_TIME
- if (dcrl->nextDateFormat != 0) {
- /* Next date was set, so validate it. */
- if (verify != NO_VERIFY &&
- !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
- WOLFSSL_MSG("CRL after date is no longer valid");
- ret = CRL_CERT_DATE_ERR;
- WOLFSSL_ERROR_VERBOSE(ret);
- }
- }
- }
- if (ret == 0) {
- #endif
- #ifdef OPENSSL_EXTRA
- /* Parse and store the issuer name. */
- dcrl->issuerSz = GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER],
- buff);
- dcrl->issuer = (byte*)GetNameFromDer((byte*)GetASNItem_Addr(
- dataASN[CRLASN_IDX_TBS_ISSUER], buff),
- (int)dcrl->issuerSz);
- #endif
- /* Calculate the Hash id from the issuer name. */
- ret = CalcHashId_ex(
- GetASNItem_Addr(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
- GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
- dcrl->issuerHash, HashIdAlg(dcrl->signatureOID));
- if (ret < 0) {
- ret = ASN_PARSE_E;
- }
- }
- if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_REVOKEDCERTS].tag != 0)) {
- /* Parse revoked cerificates - starting after SEQUENCE OF. */
- ret = ParseCRL_RevokedCerts(rcert, dcrl, buff,
- GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff),
- GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff));
- }
- if (ret == 0) {
- /* Parse the extensions - starting after SEQUENCE OF. */
- ret = ParseCRL_Extensions(dcrl, buff,
- GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff),
- GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff));
- }
- if (ret == 0) {
- /* Find signer and verify signature. */
- ret = PaseCRL_CheckSignature(dcrl, buff, cm);
- }
- FREE_ASNGETDATA(dataASN, dcrl->heap);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #endif /* HAVE_CRL */
- #ifdef WOLFSSL_CERT_PIV
- #ifdef WOLFSSL_ASN_TEMPLATE
- /* Template for PIV. */
- static const ASNItem pivASN[] = {
- /* CERT */ { 0, ASN_PIV_CERT, 0, 0, 0 },
- /* NONCE */ { 0, ASN_PIV_NONCE, 0, 0, 1 },
- /* SIGNEDNONCE */ { 0, ASN_PIV_SIGNED_NONCE, 0, 0, 1 },
- };
- enum {
- PIVASN_IDX_CERT = 0,
- PIVASN_IDX_NONCE,
- PIVASN_IDX_SIGNEDNONCE,
- };
- #define pivASN_Length (sizeof(pivASN) / sizeof(ASNItem))
- static const ASNItem pivCertASN[] = {
- /* 0x53 = 0x40 | 0x13 */
- /* CERT */ { 1, ASN_APPLICATION | 0x13, 0, 1, 0 },
- /* 0x70 = 0x40 | 0x10 + 0x20 (CONSTRUCTED) */
- /* X509 */ { 2, ASN_APPLICATION | 0x10, 1, 0, 0 },
- /* 0x71 = 0x40 | 0x11 + 0x20 (CONSTRUCTED) */
- /* INFO */ { 2, ASN_APPLICATION | 0x11, 1, 0, 1 },
- /* 0xFE = 0xC0 | 0x1E + 0x20 (CONSTRUCTED) */
- /* ERR */ { 2, ASN_PRIVATE | 0x1e, 1, 0, 1 },
- };
- enum {
- PIVCERTASN_IDX_CERT,
- PIVCERTASN_IDX_X509,
- PIVCERTASN_IDX_INFO,
- PIVCERTASN_IDX_ERR,
- };
- #define pivCertASN_Length (sizeof(pivCertASN) / sizeof(ASNItem))
- #endif
- int wc_ParseCertPIV(wc_CertPIV* piv, const byte* buf, word32 totalSz)
- {
- #ifndef WOLFSSL_ASN_TEMPLATE
- int length = 0;
- word32 idx = 0;
- WOLFSSL_ENTER("wc_ParseCertPIV");
- if (piv == NULL || buf == NULL || totalSz == 0)
- return BAD_FUNC_ARG;
- XMEMSET(piv, 0, sizeof(wc_CertPIV));
- /* Detect Identiv PIV (with 0x0A, 0x0B and 0x0C sections) */
- /* Certificate (0A 82 05FA) */
- if (GetASNHeader(buf, ASN_PIV_CERT, &idx, &length, totalSz) >= 0) {
- /* Identiv Type PIV card */
- piv->isIdentiv = 1;
- piv->cert = &buf[idx];
- piv->certSz = length;
- idx += length;
- /* Nonce (0B 14) */
- if (GetASNHeader(buf, ASN_PIV_NONCE, &idx, &length, totalSz) >= 0) {
- piv->nonce = &buf[idx];
- piv->nonceSz = length;
- idx += length;
- }
- /* Signed Nonce (0C 82 0100) */
- if (GetASNHeader(buf, ASN_PIV_SIGNED_NONCE, &idx, &length, totalSz) >= 0) {
- piv->signedNonce = &buf[idx];
- piv->signedNonceSz = length;
- }
- idx = 0;
- buf = piv->cert;
- totalSz = piv->certSz;
- }
- /* Certificate Buffer Total Size (53 82 05F6) */
- if (GetASNHeader(buf, ASN_APPLICATION | ASN_PRINTABLE_STRING, &idx,
- &length, totalSz) < 0) {
- return ASN_PARSE_E;
- }
- /* PIV Certificate (70 82 05ED) */
- if (GetASNHeader(buf, ASN_PIV_TAG_CERT, &idx, &length,
- totalSz) < 0) {
- return ASN_PARSE_E;
- }
- /* Capture certificate buffer pointer and length */
- piv->cert = &buf[idx];
- piv->certSz = length;
- idx += length;
- /* PIV Certificate Info (71 01 00) */
- if (GetASNHeader(buf, ASN_PIV_TAG_CERT_INFO, &idx, &length,
- totalSz) >= 0) {
- if (length >= 1) {
- piv->compression = (buf[idx] & ASN_PIV_CERT_INFO_COMPRESSED);
- piv->isX509 = ((buf[idx] & ASN_PIV_CERT_INFO_ISX509) != 0);
- }
- idx += length;
- }
- /* PIV Error Detection (FE 00) */
- if (GetASNHeader(buf, ASN_PIV_TAG_ERR_DET, &idx, &length,
- totalSz) >= 0) {
- piv->certErrDet = &buf[idx];
- piv->certErrDetSz = length;
- idx += length;
- }
- return 0;
- #else
- /* pivCertASN_Length is longer than pivASN_Length */
- DECL_ASNGETDATA(dataASN, pivCertASN_Length);
- int ret = 0;
- word32 idx;
- byte info;
- WOLFSSL_ENTER("wc_ParseCertPIV");
- ALLOC_ASNGETDATA(dataASN, pivCertASN_Length, ret, NULL);
- if (ret == 0) {
- /* Clear dynamic data. */
- XMEMSET(dataASN, 0, sizeof(*dataASN) * pivASN_Length);
- /* Start parsing from start of buffer. */
- idx = 0;
- /* Parse Identiv wrapper. */
- ret = GetASN_Items(pivASN, dataASN, pivASN_Length, 1, buf, &idx,
- totalSz);
- if (ret == 0) {
- /* Identiv wrapper found. */
- piv->isIdentiv = 1;
- /* Get nonce reference. */
- if (dataASN[PIVASN_IDX_NONCE].tag != 0) {
- GetASN_GetConstRef(&dataASN[PIVASN_IDX_NONCE], &piv->nonce,
- &piv->nonceSz);
- }
- /* Get signedNonce reference. */
- if (dataASN[PIVASN_IDX_SIGNEDNONCE].tag != 0) {
- GetASN_GetConstRef(&dataASN[PIVASN_IDX_SIGNEDNONCE],
- &piv->signedNonce, &piv->signedNonceSz);
- }
- /* Get the certificate data for parsing. */
- GetASN_GetConstRef(&dataASN[PIVASN_IDX_CERT], &buf, &totalSz);
- }
- ret = 0;
- }
- if (ret == 0) {
- /* Clear dynamic data and set variable to put cert info into. */
- XMEMSET(dataASN, 0, sizeof(*dataASN) * pivCertASN_Length);
- GetASN_Int8Bit(&dataASN[PIVCERTASN_IDX_INFO], &info);
- /* Start parsing from start of buffer. */
- idx = 0;
- /* Parse PIV cetificate data. */
- ret = GetASN_Items(pivCertASN, dataASN, pivCertASN_Length, 1, buf, &idx,
- totalSz);
- if (ret == 0) {
- /* Get X.509 certificate reference. */
- GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_X509], &piv->cert,
- &piv->certSz);
- /* Set the certificate info if available. */
- if (dataASN[PIVCERTASN_IDX_INFO].tag != 0) {
- /* Bits 1 and 2 are compression. */
- piv->compression = info & ASN_PIV_CERT_INFO_COMPRESSED;
- /* Bits 3 is X509 flag. */
- piv->isX509 = ((info & ASN_PIV_CERT_INFO_ISX509) != 0);
- }
- /* Get X.509 certificate error detection reference. */
- GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_ERR], &piv->certErrDet,
- &piv->certErrDetSz);
- }
- ret = 0;
- }
- FREE_ASNGETDATA(dataASN, NULL);
- return ret;
- #endif /* WOLFSSL_ASN_TEMPLATE */
- }
- #endif /* WOLFSSL_CERT_PIV */
- #ifdef HAVE_SMIME
- /*****************************************************************************
- * wc_MIME_parse_headers - Reads the char array in and parses out MIME headers
- * and parameters into headers. Will continue until in has no more content.
- *
- * RETURNS:
- * returns zero on success, non-zero on error.
- */
- int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers)
- {
- MimeHdr* nextHdr = NULL;
- MimeHdr* curHdr = NULL;
- MimeParam* nextParam = NULL;
- size_t start = 0;
- size_t end = 0;
- char* nameAttr = NULL;
- char* bodyVal = NULL;
- MimeTypes mimeType = MIME_HDR;
- MimeStatus mimeStatus = MIME_NAMEATTR;
- int ret = -1;
- size_t pos = 0;
- size_t lineLen = 0;
- char* curLine = NULL;
- char* ptr = NULL;
- if (in == NULL || inLen <= 0 || in[inLen] != '\0' || headers == NULL) {
- ret = BAD_FUNC_ARG;
- goto error;
- }
- nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL, DYNAMIC_TYPE_PKCS7);
- if (nextHdr == NULL) {
- ret = MEMORY_E;
- goto error;
- }
- XMEMSET(nextHdr, 0, sizeof(MimeHdr));
- nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
- DYNAMIC_TYPE_PKCS7);
- if (nextParam == NULL) {
- ret = MEMORY_E;
- goto error;
- }
- XMEMSET(nextParam, 0, sizeof(MimeParam));
- curLine = XSTRTOK(in, "\r\n", &ptr);
- if (curLine == NULL) {
- ret = ASN_PARSE_E;
- goto error;
- }
- while (curLine != NULL) {
- /* Leftover from previous line, add params to previous header. */
- if (curLine[0] == ' ' && curHdr) {
- mimeType = MIME_PARAM;
- }
- else {
- mimeType = MIME_HDR;
- }
- start = 0;
- lineLen = XSTRLEN(curLine);
- if (lineLen == 0) {
- ret = BAD_FUNC_ARG;
- goto error;
- }
- for (pos = 0; pos < lineLen; pos++) {
- char cur = curLine[pos];
- if (mimeStatus == MIME_NAMEATTR && ((cur == ':' &&
- mimeType == MIME_HDR) || (cur == '=' &&
- mimeType == MIME_PARAM)) && pos >= 1) {
- mimeStatus = MIME_BODYVAL;
- end = pos-1;
- if (nameAttr != NULL)
- XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
- ret = wc_MIME_header_strip(curLine, &nameAttr, start, end);
- if (ret) {
- goto error;
- }
- start = pos+1;
- }
- else if (mimeStatus == MIME_BODYVAL && cur == ';' && pos >= 1) {
- end = pos-1;
- if (bodyVal != NULL)
- XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
- ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
- if (ret) {
- goto error;
- }
- if (mimeType == MIME_HDR) {
- nextHdr->name = nameAttr;
- nameAttr = NULL;
- nextHdr->body = bodyVal;
- bodyVal = NULL;
- nextHdr->next = curHdr;
- curHdr = nextHdr;
- nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
- DYNAMIC_TYPE_PKCS7);
- if (nextHdr == NULL) {
- ret = MEMORY_E;
- goto error;
- }
- XMEMSET(nextHdr, 0, sizeof(MimeHdr));
- }
- else {
- nextParam->attribute = nameAttr;
- nameAttr = NULL;
- nextParam->value = bodyVal;
- bodyVal = NULL;
- nextParam->next = curHdr->params;
- curHdr->params = nextParam;
- nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
- DYNAMIC_TYPE_PKCS7);
- if (nextParam == NULL) {
- ret = MEMORY_E;
- goto error;
- }
- XMEMSET(nextParam, 0, sizeof(MimeParam));
- }
- mimeType = MIME_PARAM;
- mimeStatus = MIME_NAMEATTR;
- start = pos+1;
- }
- }
- end = lineLen-1;
- /* Omit newline characters. */
- while ((curLine[end] == '\r' || curLine[end] == '\n') && end > 0) {
- end--;
- }
- if (end >= start && mimeStatus == MIME_BODYVAL) {
- ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
- if (ret) {
- goto error;
- }
- if (mimeType == MIME_HDR) {
- nextHdr->name = nameAttr;
- nameAttr = NULL;
- nextHdr->body = bodyVal;
- bodyVal = NULL;
- nextHdr->next = curHdr;
- curHdr = nextHdr;
- nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
- DYNAMIC_TYPE_PKCS7);
- if (nextHdr == NULL) {
- ret = MEMORY_E;
- goto error;
- }
- XMEMSET(nextHdr, 0, sizeof(MimeHdr));
- } else {
- nextParam->attribute = nameAttr;
- nameAttr = NULL;
- nextParam->value = bodyVal;
- bodyVal = NULL;
- nextParam->next = curHdr->params;
- curHdr->params = nextParam;
- nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
- DYNAMIC_TYPE_PKCS7);
- if (nextParam == NULL) {
- ret = MEMORY_E;
- goto error;
- }
- XMEMSET(nextParam, 0, sizeof(MimeParam));
- }
- }
- curLine = XSTRTOK(NULL, "\r\n", &ptr);
- mimeStatus = MIME_NAMEATTR;
- }
- *headers = curHdr;
- ret = 0; /* success if at this point */
- error:
- if (ret != 0)
- wc_MIME_free_hdrs(curHdr);
- wc_MIME_free_hdrs(nextHdr);
- XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
- XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
- XFREE(nextParam, NULL, DYNAMIC_TYPE_PKCS7);
- return ret;
- }
- /*****************************************************************************
- * wc_MIME_header_strip - Reads the string in from indices start to end, strips
- * out disallowed/separator characters and places the rest into *out.
- *
- * RETURNS:
- * returns zero on success, non-zero on error.
- */
- int wc_MIME_header_strip(char* in, char** out, size_t start, size_t end)
- {
- size_t inPos = start;
- size_t outPos = 0;
- size_t inLen = 0;
- if (end < start || in == NULL || out == NULL) {
- return BAD_FUNC_ARG;
- }
- inLen = XSTRLEN(in);
- if (start > inLen || end > inLen) {
- return BAD_FUNC_ARG;
- }
- *out = (char*)XMALLOC(((end-start)+2)*sizeof(char), NULL,
- DYNAMIC_TYPE_PKCS7);
- if (*out == NULL) {
- return MEMORY_E;
- }
- while (inPos <= end) {
- if (in[inPos] >= MIME_HEADER_ASCII_MIN && in[inPos] <=
- MIME_HEADER_ASCII_MAX && in[inPos] != ';' && in[inPos] != '\"') {
- (*out)[outPos] = in[inPos];
- outPos++;
- }
- inPos++;
- }
- (*out)[outPos] = '\0';
- return 0;
- }
- /*****************************************************************************
- * wc_MIME_find_header_name - Searches through all given headers until a header with
- * a name matching the provided name is found.
- *
- * RETURNS:
- * returns a pointer to the found header, if no match was found, returns NULL.
- */
- MimeHdr* wc_MIME_find_header_name(const char* name, MimeHdr* header)
- {
- while (header) {
- if (!XSTRCMP(name, header->name)) {
- return header;
- }
- header = header->next;
- }
- return header;
- }
- /*****************************************************************************
- * wc_MIME_find_param_attr - Searches through all parameters until a parameter
- * with a attribute matching the provided attribute is found.
- *
- * RETURNS:
- * returns a pointer to the found parameter, if no match was found,
- * returns NULL.
- */
- MimeParam* wc_MIME_find_param_attr(const char* attribute,
- MimeParam* param)
- {
- while (param) {
- if (!XSTRCMP(attribute, param->attribute)) {
- return param;
- }
- param = param->next;
- }
- return param;
- }
- /*****************************************************************************
- * wc_MIME_single_canonicalize - Canonicalize a line by converting the trailing
- * line ending to CRLF.
- *
- * line - input line to canonicalize
- * len - length of line in chars on input, length of output array on return
- *
- * RETURNS:
- * returns a pointer to a canonicalized line on success, NULL on error.
- */
- char* wc_MIME_single_canonicalize(const char* line, word32* len)
- {
- size_t end = 0;
- char* canonLine = NULL;
- if (line == NULL || len == NULL || *len == 0) {
- return NULL;
- }
- end = *len;
- while (end >= 1 && ((line[end-1] == '\r') || (line[end-1] == '\n'))) {
- end--;
- }
- /* Need 2 chars for \r\n and 1 for EOL */
- canonLine = (char*)XMALLOC((end+3)*sizeof(char), NULL, DYNAMIC_TYPE_PKCS7);
- if (canonLine == NULL) {
- return NULL;
- }
- XMEMCPY(canonLine, line, end);
- canonLine[end] = '\r';
- canonLine[end+1] = '\n';
- canonLine[end+2] = '\0';
- *len = (word32)(end + 3);
- return canonLine;
- }
- /*****************************************************************************
- * wc_MIME_free_hdrs - Frees all MIME headers, parameters and strings starting from
- * the provided header pointer.
- *
- * RETURNS:
- * returns zero on success, non-zero on error.
- */
- int wc_MIME_free_hdrs(MimeHdr* head)
- {
- MimeHdr* curHdr = NULL;
- MimeParam* curParam = NULL;
- while (head) {
- while (head->params) {
- curParam = head->params;
- head->params = head->params->next;
- XFREE(curParam->attribute, NULL, DYNAMIC_TYPE_PKCS7);
- XFREE(curParam->value, NULL, DYNAMIC_TYPE_PKCS7);
- XFREE(curParam, NULL, DYNAMIC_TYPE_PKCS7);
- }
- curHdr = head;
- head = head->next;
- XFREE(curHdr->name, NULL, DYNAMIC_TYPE_PKCS7);
- XFREE(curHdr->body, NULL, DYNAMIC_TYPE_PKCS7);
- XFREE(curHdr, NULL, DYNAMIC_TYPE_PKCS7);
- }
- return 0;
- }
- #endif /* HAVE_SMIME */
- #undef ERROR_OUT
- #ifdef WOLFSSL_ASN_PRINT
- /*******************************************************************************
- * ASN.1 Parsing and Printing Implemenation
- ******************************************************************************/
- /* Initialize ASN.1 print options.
- *
- * @param [in, out] opts ASN.1 options for printing.
- * @return 0 on success.
- * @return BAD_FUNC_ARG when asn1 is NULL.
- */
- int wc_Asn1PrintOptions_Init(Asn1PrintOptions* opts)
- {
- int ret = 0;
- if (opts == NULL) {
- ret = BAD_FUNC_ARG;
- }
- else {
- XMEMSET(opts, 0, sizeof(*opts));
- }
- return ret;
- }
- /* Set a print option into Asn1PrintOptions object.
- *
- * @param [in, out] opts ASN.1 options for printing.
- * @param [in] opt Option to set value of.
- * @param [in] val Value to set for option.
- * @return 0 on success.
- * @return BAD_FUNC_ARG when asn1 is NULL.
- * @return BAD_FUNC_ARG when val is out of range for option.
- */
- int wc_Asn1PrintOptions_Set(Asn1PrintOptions* opts, enum Asn1PrintOpt opt,
- word32 val)
- {
- int ret = 0;
- /* Validate parameters. */
- if (opts == NULL) {
- ret = BAD_FUNC_ARG;
- }
- if (ret == 0) {
- switch (opt) {
- /* Offset into DER/BER data to start decoding from. */
- case ASN1_PRINT_OPT_OFFSET:
- opts->offset = val;
- break;
- /* Length of DER/BER encoding to parse. */
- case ASN1_PRINT_OPT_LENGTH:
- opts->length = val;
- break;
- /* Number of spaces to indent for each change in depth. */
- case ASN1_PRINT_OPT_INDENT:
- /* Only 4 bits allowed for value. */
- if (val >= (1 << 4)) {
- ret = BAD_FUNC_ARG;
- }
- else {
- opts->indent = (word8)val;
- }
- break;
- /* Draw branches instead of indenting. */
- case ASN1_PRINT_OPT_DRAW_BRANCH:
- /* Boolean value. */
- opts->draw_branch = (val > 0);
- break;
- /* Show raw data of primitive types as octets. */
- case ASN1_PRINT_OPT_SHOW_DATA:
- /* Boolean value. */
- opts->show_data = (val > 0);
- break;
- /* Show header data as octets. */
- case ASN1_PRINT_OPT_SHOW_HEADER_DATA:
- /* Boolean value. */
- opts->show_header_data = (val > 0);
- break;
- /* Show the wolfSSL OID value for OBJECT_ID. */
- case ASN1_PRINT_OPT_SHOW_OID:
- /* Boolean value. */
- opts->show_oid = (val > 0);
- break;
- /* Don't show text representations of primitive types. */
- case ASN1_PRINT_OPT_SHOW_NO_TEXT:
- /* Boolean value. */
- opts->show_no_text = (val > 0);
- break;
- /* Don't show dump text representations of primitive types. */
- case ASN1_PRINT_OPT_SHOW_NO_DUMP_TEXT:
- /* Boolean value. */
- opts->show_no_dump_text = (val > 0);
- break;
- }
- }
- return ret;
- }
- /* Initialize an ASN.1 parse object.
- *
- * @param [in, out] asn1 ASN.1 parse object.
- * @return 0 on success.
- * @return BAD_FUNC_ARG when asn1 is NULL.
- */
- int wc_Asn1_Init(Asn1* asn1)
- {
- int ret = 0;
- if (asn1 == NULL) {
- ret = BAD_FUNC_ARG;
- }
- else {
- XMEMSET(asn1, 0, sizeof(*asn1));
- asn1->file = XBADFILE;
- }
- return ret;
- }
- /* Set the file to use when printing.
- *
- * @param [in, out] asn1 ASN.1 parse object.
- * @param [in] file File to print to.
- * @return 0 on success.
- * @return BAD_FUNC_ARG when asn1 is NULL.
- * @return BAD_FUNC_ARG when file is XBADFILE.
- */
- int wc_Asn1_SetFile(Asn1* asn1, XFILE file)
- {
- int ret = 0;
- if ((asn1 == NULL) || (file == XBADFILE)) {
- ret = BAD_FUNC_ARG;
- }
- else {
- asn1->file = file;
- }
- return ret;
- }
- /* Maximum OID dotted form size. */
- #define ASN1_OID_DOTTED_MAX_SZ 16
- /* Print OID in dotted form or as hex bytes.
- *
- * @param [in] file File pointer to write to.
- * @param [in] oid OBJECT_ID data.
- * @param [in] oid_len Length of OBJECT_ID data.
- */
- static void PrintObjectIdNum(XFILE file, unsigned char* oid, word32 len)
- {
- word16 dotted_nums[ASN1_OID_DOTTED_MAX_SZ];
- word32 num = ASN1_OID_DOTTED_MAX_SZ;
- word32 i;
- /* Decode OBJECT_ID into dotted form array. */
- if (DecodeObjectId(oid, len, dotted_nums, &num) == 0) {
- /* Print out each number of dotted form. */
- for (i = 0; i < num; i++) {
- XFPRINTF(file, "%d", dotted_nums[i]);
- /* Add separetor. */
- if (i < num - 1) {
- XFPRINTF(file, ".");
- }
- }
- }
- else {
- /* Print out bytes as we couldn't decode. */
- for (i = 0; i < len; i++) {
- XFPRINTF(file, "%02x", oid[i]);
- /* Add separetor. */
- if (i < len - 1) {
- XFPRINTF(file, ":");
- }
- }
- }
- }
- /* OID value to name mapping. */
- typedef struct OidName {
- /* wolfSSL OID value. */
- word32 oid;
- /* Long name to print when OID seen. */
- const char* name;
- } OidName;
- /* Extra OID to name mappings. */
- static const OidName extraOids[] = {
- { 0x005c, "commonName" },
- { 0x005d, "surname" },
- { 0x005e, "serialNumber" },
- { 0x005f, "countryName" },
- { 0x0060, "localityName" },
- { 0x0061, "stateOrProvinceName" },
- { 0x0062, "streetAddress" },
- { 0x0063, "organizationName" },
- { 0x0064, "organizationUnitName" },
- { 0x0065, "title" },
- { 0x0086, "certificateExtension" },
- { 0x028d, "emailAddress" },
- { 0x0293, "challengePassword" },
- { 0x029a, "extensionReq" },
- };
- /* Length of table of extra OID to name mappings. */
- #define EXTRA_OIDS_LEN ((int)(sizeof(extraOids) / sizeof(*extraOids)))
- /* Convert OID value to long name.
- *
- * @param [in] oid OID value.
- * @param [out] name Long name for OID when known.
- * @return 1 when OID known.
- * @return 0 when OID not known.
- */
- static int Oid2LongName(word32 oid, const char** name)
- {
- int ret = 0;
- int i;
- /* Step through each entry in table. */
- for (i = 0; i < EXTRA_OIDS_LEN; i++) {
- if (extraOids[i].oid == oid) {
- /* Return the name associated with the OID value. */
- *name = extraOids[i].name;
- ret = 1;
- break;
- }
- }
- return ret;
- }
- /* Print the text version of the OBJECT_ID.
- *
- * @param [in] asn1 ASN.1 parse object.
- * @param [in] opts ASN.1 options for printing.
- */
- static void PrintObjectIdText(Asn1* asn1, Asn1PrintOptions* opts)
- {
- word32 oid = (word32)-1;
- #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
- int nid;
- #endif
- const char* ln = NULL;
- word32 i = 0;
- int known = 1;
- /* Get the OID value for the OBJECT_ID. */
- if (GetObjectId(asn1->data + asn1->offset, &i, &oid, oidIgnoreType,
- asn1->item.len + 2) == ASN_PARSE_E) {
- known = 0;
- }
- else
- #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
- /* Lookup NID for OID value. */
- if ((nid = oid2nid(oid, oidIgnoreType)) != -1) {
- /* Lookup long name for NID. */
- ln = wolfSSL_OBJ_nid2ln(nid);
- }
- else
- #endif
- /* Lookup long name for extra known OID values. */
- if (!Oid2LongName(oid, &ln)) {
- /* Unknown OID value. */
- ln = NULL;
- known = 0;
- }
- XFPRINTF(asn1->file, ":");
- /* Show OID value if not known or asked to. */
- if ((!known) || opts->show_oid) {
- XFPRINTF(asn1->file, "(0x%x) ", oid);
- }
- if (ln != NULL) {
- /* Print long name. */
- XFPRINTF(asn1->file, "%s", ln);
- }
- else {
- /* Print out as numbers - either dotted or hex values. */
- PrintObjectIdNum(asn1->file, asn1->data + asn1->item.data_idx,
- asn1->item.len);
- }
- }
- /* Print ASN.1 data as a character string.
- *
- * @param [in] asn1 ASN.1 parse object.
- */
- static void PrintText(Asn1* asn1)
- {
- word32 i;
- XFPRINTF(asn1->file, ":");
- /* Print all data bytes as characters. */
- for (i = 0; i < asn1->item.len; i++) {
- XFPRINTF(asn1->file, "%c", asn1->data[asn1->item.data_idx + i]);
- }
- }
- /* Print data as a hex bytes.
- *
- * @param [in] file File pointer to write to.
- * @param [in] data Data to print.
- * @param [in] len Number of bytes to print.
- */
- static void PrintHex(XFILE file, unsigned char* data, word32 len)
- {
- word32 i;
- /* Print data bytes as hex numbers. */
- for (i = 0; i < len; i++) {
- XFPRINTF(file, "%02x", data[i]);
- }
- }
- /* Print ASN.1 data as a hex bytes.
- *
- * @param [in] asn1 ASN.1 parse object.
- */
- static void PrintHexText(Asn1* asn1)
- {
- XFPRINTF(asn1->file, ":");
- PrintHex(asn1->file, asn1->data + asn1->item.data_idx, asn1->item.len);
- }
- /* Print ASN.1 BIT_STRING data as hex bytes noting special first byte.
- *
- * @param [in] asn1 ASN.1 parse object.
- */
- static void PrintBitStringText(Asn1* asn1)
- {
- if (asn1->item.len > 0) {
- XFPRINTF(asn1->file, ":[%02x]", asn1->data[asn1->item.data_idx]);
- PrintHex(asn1->file, asn1->data + asn1->item.data_idx + 1,
- asn1->item.len - 1);
- }
- }
- /* Print ASN.1 BOOLEAN data as text with value.
- *
- * @param [in] asn1 ASN.1 parse object.
- */
- static void PrintBooleanText(Asn1* asn1)
- {
- /* Booleans should be 1 byte of data. */
- if (asn1->item.len == 1) {
- XFPRINTF(asn1->file, ":%s (%d)",
- (asn1->data[asn1->item.data_idx] == 0) ? "FALSE" : "TRUE",
- asn1->data[asn1->item.data_idx]);
- }
- }
- /* Print ASN.1 data as single byte +/- number.
- *
- * @param [in] asn1 ASN.1 parse object.
- */
- static void PrintNumberText(Asn1* asn1)
- {
- /* Only supporting 1 byte of data for now. */
- if (asn1->item.len == 1) {
- int num = asn1->data[asn1->item.data_idx];
- XFPRINTF(asn1->file, ":%d", num >= 0x80 ? num - 0x100 : num);
- }
- }
- /* Print ASN.1 data as a text based on the tag.
- *
- * TODO: handle more tags.
- *
- * @param [in] asn1 ASN.1 parse object.
- * @param [in] opts ASN.1 options for printing.
- */
- static void PrintAsn1Text(Asn1* asn1, Asn1PrintOptions* opts)
- {
- /* Get the long name for OBJECT_ID where possible. */
- if (asn1->item.tag == ASN_OBJECT_ID) {
- PrintObjectIdText(asn1, opts);
- }
- /* Data is an array of printable characters. */
- else if ((asn1->item.tag == ASN_UTF8STRING) ||
- (asn1->item.tag == ASN_IA5_STRING) ||
- (asn1->item.tag == ASN_PRINTABLE_STRING) ||
- (asn1->item.tag == ASN_T61STRING) ||
- (asn1->item.tag == ASN_BMPSTRING) ||
- (asn1->item.tag == ASN_UTC_TIME) ||
- (asn1->item.tag == ASN_GENERALIZED_TIME) ||
- (asn1->item.tag == ASN_UNIVERSALSTRING) ||
- (asn1->item.tag == ASN_OBJECT_DESC) ||
- (asn1->item.tag == ASN_CHARACTER_STRING)) {
- PrintText(asn1);
- }
- /* Show TRUE and FALSE with number. */
- else if (asn1->item.tag == ASN_BOOLEAN) {
- PrintBooleanText(asn1);
- }
- /* Show number. */
- else if (asn1->item.tag == ASN_ENUMERATED) {
- PrintNumberText(asn1);
- }
- /* Dumping potentially long string of hex digites. */
- else if (!opts->show_no_dump_text) {
- /* Dump all bytes. */
- if ((asn1->item.tag == ASN_INTEGER) ||
- (asn1->item.tag == ASN_OCTET_STRING) ||
- ((asn1->item.tag > ASN_APPLICATION) && (asn1->item.cons))) {
- PrintHexText(asn1);
- }
- /* First byte is number of unused bits in last byte.
- * Print first specially and dump rest of the bytes. */
- else if (asn1->item.tag == ASN_BIT_STRING) {
- PrintBitStringText(asn1);
- }
- }
- }
- #define HexToChar(n) ((((n) >= 32) && ((n) < 127)) ? (n) : '.')
- /* Dump data as hex bytes.
- *
- * @param [in] file File pointer to write to.
- * @param [in] data Data to print.
- * @param [in] len Number of bytes to print.
- */
- static void DumpData(XFILE file, unsigned char* data, word32 len)
- {
- word32 i;
- word32 j;
- for (i = 0; i < len; i += j) {
- /* Print offset. */
- XFPRINTF(file, " %04x:", i);
- for (j = 0; (j < 16) && (i + j < len); j++) {
- /* Print byte as hex number. */
- XFPRINTF(file, "%s%02x", (j == 8) ? " " : " ", data[i + j]);
- }
- /* Print spaces between hex and characters. */
- XFPRINTF(file, " %*s", (16 - j) * 3 + ((j < 8) ? 1 : 0), "");
- for (j = 0; (j < 16) && (i + j < len); j++) {
- /* Print byte as hex number. */
- XFPRINTF(file, "%c", HexToChar(data[i + j]));
- }
- XFPRINTF(file, "\n");
- }
- }
- /* Update current depth based on the current position.
- *
- * @param [in, out] asn1 ASN.1 parse object.
- */
- static void UpdateDepth(Asn1* asn1)
- {
- /* If current index is greater than or equal end index then it is done. */
- while ((asn1->depth > 0) &&
- (asn1->end_idx[asn1->depth-1] <= asn1->curr)) {
- /* Move up a depth. */
- asn1->depth--;
- }
- }
- /* Check validity of end index of constructed ASN.1 items.
- *
- * @param [in, out] asn1 ASN.1 parse object.
- * @return 0 on success.
- * @return ASN_DEPTH_E when end offset invalid.
- */
- static int CheckDepth(Asn1* asn1)
- {
- int ret = 0;
- int i;
- word32 curr_end = asn1->curr + asn1->item.len;
- for (i = 0; (ret == 0) && (i < asn1->depth); i++) {
- /* Each end index must be at least as large as the current one. */
- if (asn1->end_idx[i] < asn1->end_idx[asn1->depth]) {
- ret = ASN_DEPTH_E;
- }
- /* Each end index must be at least as large as current index. */
- if (asn1->end_idx[i] < curr_end) {
- ret = ASN_DEPTH_E;
- }
- }
- return ret;
- }
- /* Draw branching based on depth for an ASN.1 item.
- *
- * @param [in] asn1 ASN.1 parse object.
- */
- static void DrawBranch(Asn1* asn1)
- {
- int i;
- word32 end = asn1->curr + asn1->item.len;
- /* Write out the character for all depths but current. */
- for (i = 0; i < asn1->depth; i++) {
- if (asn1->item.cons || (end < asn1->end_idx[i])) {
- if (i < asn1->depth - 1) {
- /* Constructed or not end index and not current depth: | */
- XFPRINTF(asn1->file, "\xe2\x94\x82");
- }
- else {
- /* Constructed or not end index and current depth: |- */
- XFPRINTF(asn1->file, "\xe2\x94\x9c");
- }
- }
- else if ((i > 1) && (end >= asn1->end_idx[i-1])) {
- /* End index for previous: _|_ (in top half) */
- XFPRINTF(asn1->file, "\xe2\x94\xb4");
- }
- else {
- /* End index but not for previous: L (in top half) */
- XFPRINTF(asn1->file, "\xe2\x94\x94");
- }
- }
- /* Prefix to tag name. */
- if (asn1->item.cons) {
- if (asn1->depth > 0) {
- /* Have other line to connect to: T (in bottom half) */
- XFPRINTF(asn1->file, "\xe2\x94\xac");
- }
- else {
- /* Have no other line to connect to: r */
- XFPRINTF(asn1->file, "\xe2\x94\x8c");
- }
- }
- else {
- /* In a sequence: - */
- XFPRINTF(asn1->file, "\xe2\x94\x80");
- }
- }
- /* Print data as hex bytes separated by space.
- *
- * @param [in] file File pointer to write to.
- * @param [in] data Data to print.
- * @param [in] len Number of bytes to print.
- */
- static void PrintHexBytes(XFILE file, unsigned char* data, word32 len)
- {
- word32 i;
- for (i = 0; i < len; i++) {
- XFPRINTF(file, " %02x", data[i]);
- }
- }
- /* Dump header data.
- *
- * @param [in] asn1 ASN.1 parse object.
- * @param [in] opts ASN.1 options for printing.
- */
- static void DumpHeader(Asn1* asn1, Asn1PrintOptions* opts)
- {
- /* Put on same line when not showing data too and not showing text data. */
- if ((!opts->show_data) && opts->show_no_text) {
- XFPRINTF(asn1->file, "%10s", "");
- }
- else {
- /* Align with start of data. */
- XFPRINTF(asn1->file, "\n%12s", "");
- }
- XFPRINTF(asn1->file, " %02x", asn1->item.tag);
- if (asn1->curr >= asn1->offset + 1) {
- /* Print the header bytes as hex bytes separated by a space. */
- PrintHexBytes(asn1->file, asn1->data + asn1->offset + 1,
- asn1->curr - (asn1->offset + 1));
- }
- }
- /* Print ASN.1 item info based on header and indeces.
- *
- * @param [in] asn1 ASN.1 parse object.
- * @param [in] opts ASN.1 options for printing.
- */
- static void PrintInfo(Asn1* asn1, Asn1PrintOptions* opts)
- {
- /* Print offset of this ASN.1 item. */
- XFPRINTF(asn1->file, "%4d: ", asn1->offset);
- /* Print length of header. */
- XFPRINTF(asn1->file, "%1d ", asn1->curr - asn1->offset);
- /* Print data length. */
- XFPRINTF(asn1->file, "%c%4d%c", asn1->item.cons ? '[' : '+', asn1->item.len,
- asn1->item.cons ? ']' : ' ');
- /* Print depth. */
- XFPRINTF(asn1->file, " %s(%d)", (asn1->depth < 10) ? " " : "", asn1->depth);
- if (!opts->draw_branch) {
- /* Indent to depth as required. */
- XFPRINTF(asn1->file, "%*s ", asn1->depth * opts->indent, "");
- if (!opts->indent) {
- /* Indicate constructed if no indent. */
- XFPRINTF(asn1->file, "%c", asn1->item.cons ? '+' : ' ');
- }
- }
- else {
- /* Draw branch structure for ASN.1 item. */
- XFPRINTF(asn1->file, " ");
- DrawBranch(asn1);
- }
- /* Print tag name. */
- XFPRINTF(asn1->file, "%-16s", TagString(asn1->item.tag));
- }
- /* Expecting tag part of ASN.1 item. */
- #define ASN_PART_TAG 0
- /* Expecting length part of ASN.1 item. */
- #define ASN_PART_LENGTH 1
- /* Expecting data part of ASN.1 item. */
- #define ASN_PART_DATA 2
- /* Print next ASN.1 item.
- *
- * @param [in, out] asn1 ASN.1 parse object.
- * @param [in] opts ASN.1 print options.
- * @return 0 on success.
- * @return BAD_FUNC_ARG when asn1 or opts is NULL.
- * @return ASN_LEN_E when ASN.1 item's length too long.
- * @return ASN_DEPTH_E when end offset invalid.
- */
- static int wc_Asn1_Print(Asn1* asn1, Asn1PrintOptions* opts)
- {
- int ret = 0;
- /* Process tag. */
- if (asn1->part == ASN_PART_TAG) {
- /* Recalculate which depth we are at. */
- UpdateDepth(asn1);
- /* Get tag. */
- asn1->item.tag = asn1->data[asn1->curr] & (byte)~ASN_CONSTRUCTED;
- /* Store whether tag indicates constructed. */
- asn1->item.cons = (asn1->data[asn1->curr] & ASN_CONSTRUCTED) ==
- ASN_CONSTRUCTED;
- /* Start of ASN.1 item is current index. */
- asn1->offset = asn1->curr;
- /* Step over tag. */
- asn1->curr++;
- /* Next part is length. */
- asn1->part = ASN_PART_LENGTH;
- }
- /* Process length. */
- if (asn1->part == ASN_PART_LENGTH) {
- int len;
- /* Decode length and step over it. */
- if (GetLength(asn1->data, &asn1->curr, &len, asn1->max) < 0) {
- ret = ASN_LEN_E;
- }
- else {
- /* Store ASN.1 item data offset. */
- asn1->item.data_idx = asn1->curr;
- /* Store ASN.1 item data length. */
- asn1->item.len = (word32)len;
- /* Print info about ASN.1 item. */
- PrintInfo(asn1, opts);
- if (!asn1->item.cons) {
- /* Move on to print data. */
- asn1->part = ASN_PART_DATA;
- }
- else {
- /* Print header now if not printing data. */
- if (opts->show_header_data) {
- DumpHeader(asn1, opts);
- }
- XFPRINTF(asn1->file, "\n");
- /* Record end offset for this depth. */
- asn1->end_idx[asn1->depth++] = asn1->curr + asn1->item.len;
- /* Done with this ASN.1 item. */
- asn1->part = ASN_PART_TAG;
- }
- /* Check end indeces are valid. */
- ret = CheckDepth(asn1);
- }
- }
- /* Process data. */
- if ((ret == 0) && (asn1->part == ASN_PART_DATA)) {
- if (!opts->show_no_text) {
- /* Print text representation of data. */
- PrintAsn1Text(asn1, opts);
- }
- if (opts->show_header_data) {
- /* Dump header bytes. */
- DumpHeader(asn1, opts);
- }
- XFPRINTF(asn1->file, "\n");
- if (opts->show_data) {
- /* Dump data bytes. */
- DumpData(asn1->file, asn1->data + asn1->item.data_idx,
- asn1->item.len);
- }
- /* Step past data to next ASN.1 item. */
- asn1->curr += asn1->item.len;
- /* Update the depth based on end indeces. */
- UpdateDepth(asn1);
- /* Done with this ASN.1 item. */
- asn1->part = ASN_PART_TAG;
- }
- /* Make ASN.1 item printing go out. */
- fflush(asn1->file);
- return ret;
- }
- /* Print all ASN.1 items.
- *
- * @param [in, out] asn1 ASN.1 parse object.
- * @param [in] opts ASN.1 print options.
- * @param [in] data BER/DER data to print.
- * @param [in] len Length of data to print in bytes.
- * @return 0 on success.
- * @return BAD_FUNC_ARG when asn1, opts or data is NULL.
- * @return ASN_LEN_E when ASN.1 item's length too long.
- * @return ASN_DEPTH_E when end offset invalid.
- * @return ASN_PARSE_E when not all of an ASN.1 item parsed.
- */
- int wc_Asn1_PrintAll(Asn1* asn1, Asn1PrintOptions* opts, unsigned char* data,
- word32 len)
- {
- int ret = 0;
- if ((asn1 == NULL) || (opts == NULL) || (data == NULL)) {
- ret = BAD_FUNC_ARG;
- }
- if (ret == 0) {
- /* Initialize start position. */
- asn1->curr = 0;
- /* Start parsing at tag. */
- asn1->part = ASN_PART_TAG;
- /* Start depth at 0. */
- asn1->depth = 0;
- /* Store the starting point of the data to parse. */
- asn1->data = data + opts->offset;
- if (opts->length > 0) {
- /* Use user specified maximum length. */
- asn1->max = opts->length;
- }
- else {
- /* Maximum length is up to end from offset. */
- asn1->max = len - opts->offset;
- }
- /* Keep going while no error and have data to parse. */
- while ((ret == 0) && (asn1->curr < asn1->max)) {
- /* Print an ASN.1 item. */
- ret = wc_Asn1_Print(asn1, opts);
- }
- }
- if ((ret == 0) && (asn1->part != ASN_PART_TAG)) {
- /* Stopped before finishing ASN.1 item. */
- ret = ASN_PARSE_E;
- }
- if ((ret == 0) && (asn1->depth != 0)) {
- /* Stopped without seeing all items in a constructed item. */
- ret = ASN_DEPTH_E;
- }
- return ret;
- }
- #endif /* WOLFSSL_ASN_PRINT */
- #endif /* !NO_ASN */
- /* Functions that parse, but are not using ASN.1 */
- #if !defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
- (!defined(NO_BIG_INT) || defined(WOLFSSL_SP_MATH))
- /* import RSA public key elements (n, e) into RsaKey structure (key) */
- /* this function does not use any ASN.1 parsing */
- int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e,
- word32 eSz, RsaKey* key)
- {
- if (n == NULL || e == NULL || key == NULL)
- return BAD_FUNC_ARG;
- key->type = RSA_PUBLIC;
- if (mp_init(&key->n) != MP_OKAY)
- return MP_INIT_E;
- if (mp_read_unsigned_bin(&key->n, n, nSz) != 0) {
- mp_clear(&key->n);
- return ASN_GETINT_E;
- }
- #ifdef HAVE_WOLF_BIGINT
- if ((int)nSz > 0 && wc_bigint_from_unsigned_bin(&key->n.raw, n, nSz) != 0) {
- mp_clear(&key->n);
- return ASN_GETINT_E;
- }
- #endif /* HAVE_WOLF_BIGINT */
- if (mp_init(&key->e) != MP_OKAY) {
- mp_clear(&key->n);
- return MP_INIT_E;
- }
- if (mp_read_unsigned_bin(&key->e, e, eSz) != 0) {
- mp_clear(&key->n);
- mp_clear(&key->e);
- return ASN_GETINT_E;
- }
- #ifdef HAVE_WOLF_BIGINT
- if ((int)eSz > 0 && wc_bigint_from_unsigned_bin(&key->e.raw, e, eSz) != 0) {
- mp_clear(&key->n);
- mp_clear(&key->e);
- return ASN_GETINT_E;
- }
- #endif /* HAVE_WOLF_BIGINT */
- #ifdef WOLFSSL_XILINX_CRYPT
- if (wc_InitRsaHw(key) != 0) {
- return BAD_STATE_E;
- }
- #endif
- return 0;
- }
- #endif /* !NO_RSA && !HAVE_USER_RSA && (!NO_BIG_INT || WOLFSSL_SP_MATH) */
- #ifdef WOLFSSL_SEP
- #endif /* WOLFSSL_SEP */
|