asn.c 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866
  1. /* asn.c
  2. *
  3. * Copyright (C) 2006-2023 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. /*
  22. * DESCRIPTION
  23. * This library provides the interface to Abstract Syntax Notation One (ASN.1)
  24. * objects.
  25. * ASN.1 is a standard interface description language for defining data
  26. * structures that can be serialized and deserialized in a cross-platform way.
  27. *
  28. * Encoding of ASN.1 is either using Basic Encoding Rules (BER) or
  29. * Distinguished Encoding Rules (DER). DER has only one possible encoding for a
  30. * ASN.1 description and the data.
  31. * Encode using DER and decode BER or DER.
  32. *
  33. * Provides routines to convert BER into DER. Replaces indefinite length
  34. * encoded items with explicit lengths.
  35. */
  36. #ifdef HAVE_CONFIG_H
  37. #include <config.h>
  38. #endif
  39. #include <wolfssl/wolfcrypt/settings.h>
  40. /*
  41. ASN Options:
  42. * NO_ASN_TIME_CHECK: Disables ASN time checks (avoiding the ASN_BEFORE_DATE_E
  43. * and ASN_AFTER_DATE_E errors). Safer ways to avoid date errors would be to
  44. * set the WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY flag when calling the _ex versions of
  45. * cert loading functions or to define the WOLFSSL_NO_OCSP_DATE_CHECK macro to
  46. * skip OCSP date errors. Defining NO_ASN_TIME_CHECK will skip ALL date checks
  47. * and could pose a security risk.
  48. * NO_ASN_TIME: Disables time parts of the ASN code for systems without an RTC
  49. or wishing to save space.
  50. * IGNORE_NAME_CONSTRAINTS: Skip ASN name checks.
  51. * ASN_DUMP_OID: Allows dump of OID information for debugging.
  52. * RSA_DECODE_EXTRA: Decodes extra information in RSA public key.
  53. * WOLFSSL_CERT_GEN: Cert generation. Saves extra certificate info in GetName.
  54. * WOLFSSL_NO_ASN_STRICT: Disable strict RFC compliance checks to
  55. restore 3.13.0 behavior.
  56. * WOLFSSL_NO_OCSP_OPTIONAL_CERTS: Skip optional OCSP certs (responder issuer
  57. must still be trusted)
  58. * WOLFSSL_NO_TRUSTED_CERTS_VERIFY: Workaround for situation where entire cert
  59. chain is not loaded. This only matches on subject and public key and
  60. does not perform a PKI validation, so it is not a secure solution.
  61. Only enabled for OCSP.
  62. * WOLFSSL_NO_OCSP_ISSUER_CHECK: Can be defined for backwards compatibility to
  63. disable checking of OCSP subject hash with issuer hash.
  64. * WOLFSSL_SMALL_CERT_VERIFY: Verify the certificate signature without using
  65. DecodedCert. Doubles up on some code but allows smaller dynamic memory
  66. usage.
  67. * WOLFSSL_NO_OCSP_DATE_CHECK: Disable date checks for OCSP responses. This
  68. may be required when the system's real-time clock is not very accurate.
  69. It is recommended to enforce the nonce check instead if possible.
  70. * WOLFSSL_FORCE_OCSP_NONCE_CHECK: Require nonces to be available in OCSP
  71. responses. The nonces are optional and may not be supported by all
  72. responders. If it can be ensured that the used responder sends nonces this
  73. option may improve security.
  74. * WOLFSSL_ASN_TEMPLATE: Encoding and decoding using a template.
  75. * WOLFSSL_DEBUG_ASN_TEMPLATE: Enables debugging output when using ASN.1
  76. templates.
  77. * WOLFSSL_ASN_TEMPLATE_TYPE_CHECK: Use ASN functions to better test compiler
  78. type issues for testing
  79. * CRLDP_VALIDATE_DATA: For ASN template only, validates the reason data
  80. * WOLFSSL_AKID_NAME: Enable support for full AuthorityKeyIdentifier extension.
  81. Only supports copying full AKID from an existing certificate.
  82. * WOLFSSL_CUSTOM_OID: Enable custom OID support for subject and request
  83. extensions
  84. * WOLFSSL_HAVE_ISSUER_NAMES: Store pointers to issuer name components and their
  85. lengths and encodings.
  86. * WOLFSSL_SUBJ_DIR_ATTR: Enable support for SubjectDirectoryAttributes
  87. extension.
  88. * WOLFSSL_SUBJ_INFO_ACC: Enable support for SubjectInfoAccess extension.
  89. * WOLFSSL_FPKI: Enable support for FPKI (Federal PKI) extensions.
  90. * WOLFSSL_CERT_NAME_ALL: Adds more certificate name capability at the
  91. cost of taking up more memory. Adds initials, givenname, dnQualifer for
  92. example.
  93. * WC_ASN_HASH_SHA256: Force use of SHA2-256 for the internal hash ID calcs.
  94. */
  95. #include <wolfssl/wolfcrypt/error-crypt.h>
  96. #ifndef NO_RSA
  97. #include <wolfssl/wolfcrypt/rsa.h>
  98. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  99. extern int wc_InitRsaHw(RsaKey* key);
  100. #endif
  101. #endif
  102. #ifndef NO_ASN
  103. #include <wolfssl/wolfcrypt/asn.h>
  104. #include <wolfssl/wolfcrypt/coding.h>
  105. #include <wolfssl/wolfcrypt/md2.h>
  106. #include <wolfssl/wolfcrypt/hmac.h>
  107. #include <wolfssl/wolfcrypt/pwdbased.h>
  108. #include <wolfssl/wolfcrypt/des3.h>
  109. #include <wolfssl/wolfcrypt/aes.h>
  110. #include <wolfssl/wolfcrypt/rc2.h>
  111. #include <wolfssl/wolfcrypt/wc_encrypt.h>
  112. #include <wolfssl/wolfcrypt/logging.h>
  113. #include <wolfssl/wolfcrypt/random.h>
  114. #include <wolfssl/wolfcrypt/hash.h>
  115. #ifdef NO_INLINE
  116. #include <wolfssl/wolfcrypt/misc.h>
  117. #else
  118. #define WOLFSSL_MISC_INCLUDED
  119. #include <wolfcrypt/src/misc.c>
  120. #endif
  121. #ifndef NO_RC4
  122. #include <wolfssl/wolfcrypt/arc4.h>
  123. #endif
  124. #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
  125. #include <wolfssl/wolfcrypt/sha512.h>
  126. #endif
  127. #ifndef NO_SHA256
  128. #include <wolfssl/wolfcrypt/sha256.h>
  129. #endif
  130. #ifdef HAVE_ECC
  131. #include <wolfssl/wolfcrypt/ecc.h>
  132. #endif
  133. #ifdef HAVE_ED25519
  134. #include <wolfssl/wolfcrypt/ed25519.h>
  135. #endif
  136. #ifdef HAVE_CURVE25519
  137. #include <wolfssl/wolfcrypt/curve25519.h>
  138. #endif
  139. #ifdef HAVE_ED448
  140. #include <wolfssl/wolfcrypt/ed448.h>
  141. #endif
  142. #ifdef HAVE_CURVE448
  143. #include <wolfssl/wolfcrypt/curve448.h>
  144. #endif
  145. #ifdef HAVE_PQC
  146. #if defined(HAVE_FALCON)
  147. #include <wolfssl/wolfcrypt/falcon.h>
  148. #endif
  149. #if defined(HAVE_DILITHIUM)
  150. #include <wolfssl/wolfcrypt/dilithium.h>
  151. #endif
  152. #if defined(HAVE_SPHINCS)
  153. #include <wolfssl/wolfcrypt/sphincs.h>
  154. #endif
  155. #endif
  156. #ifdef WOLFSSL_QNX_CAAM
  157. #include <wolfssl/wolfcrypt/port/caam/wolfcaam.h>
  158. #endif
  159. #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  160. #include <wolfssl/wolfcrypt/port/Renesas/renesas_cmn.h>
  161. #endif
  162. #ifndef NO_DSA
  163. #include <wolfssl/wolfcrypt/dsa.h>
  164. #else
  165. typedef void* DsaKey;
  166. #endif
  167. #ifdef WOLF_CRYPTO_CB
  168. #include <wolfssl/wolfcrypt/cryptocb.h>
  169. #endif
  170. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  171. #include <wolfssl/internal.h>
  172. #include <wolfssl/openssl/objects.h>
  173. #endif
  174. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  175. !defined(WOLFCRYPT_ONLY)
  176. #define WOLFSSL_X509_NAME_AVAILABLE
  177. #endif
  178. #ifdef _MSC_VER
  179. /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
  180. #pragma warning(disable: 4996)
  181. #endif
  182. #define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
  183. #if !defined(NO_SKID) && (!defined(HAVE_FIPS) || !defined(HAVE_FIPS_VERSION))
  184. #if !defined(HAVE_SELFTEST) || (defined(HAVE_SELFTEST) && \
  185. (!defined(HAVE_SELFTEST_VERSION) || \
  186. HAVE_SELFTEST_VERSION < 2))
  187. #ifndef WOLFSSL_AES_KEY_SIZE_ENUM
  188. #define WOLFSSL_AES_KEY_SIZE_ENUM
  189. enum Asn_Misc {
  190. AES_IV_SIZE = 16,
  191. AES_128_KEY_SIZE = 16,
  192. AES_192_KEY_SIZE = 24,
  193. AES_256_KEY_SIZE = 32
  194. };
  195. #endif
  196. #endif /* HAVE_SELFTEST */
  197. #endif
  198. #if defined(WOLFSSL_ASN_PRINT) || defined(WOLFSSL_DEBUG_ASN_TEMPLATE)
  199. /* String representations of tags. */
  200. static const char* tagString[4][32] = {
  201. /* Universal */
  202. {
  203. "EOC",
  204. "BOOLEAN",
  205. "INTEGER",
  206. "BIT STRING",
  207. "OCTET STRING",
  208. "NULL",
  209. "OBJECT ID",
  210. "ObjectDescriptor",
  211. "INSTANCE OF",
  212. "REAL",
  213. "ENUMERATED",
  214. "EMBEDDED PDV",
  215. "UT8String",
  216. "RELATIVE-OID",
  217. "(0x0e) 14",
  218. "(0x0f) 15",
  219. "SEQUENCE",
  220. "SET",
  221. "NumericString",
  222. "PrintableString",
  223. "T61String",
  224. "VideotexString",
  225. "IA5String",
  226. "UTCTime",
  227. "GeneralizedTime",
  228. "GraphicString",
  229. "ISO646String",
  230. "GeneralString",
  231. "UniversalString",
  232. "CHARACTER STRING",
  233. "BMPString",
  234. "(0x1f) 31",
  235. },
  236. /* Application */
  237. {
  238. "[A 0]", "[A 1]", "[A 2]", "[A 3]",
  239. "[A 4]", "[A 5]", "[A 6]", "[A 7]",
  240. "[A 8]", "[A 9]", "[A 10]", "[A 11]",
  241. "[A 12]", "[A 13]", "[A 14]", "[A 15]",
  242. "[A 16]", "[A 17]", "[A 18]", "[A 19]",
  243. "[A 20]", "[A 21]", "[A 22]", "[A 23]",
  244. "[A 24]", "[A 25]", "[A 26]", "[A 27]",
  245. "[A 28]", "[A 20]", "[A 30]", "[A 31]"
  246. },
  247. /* Context-Specific */
  248. {
  249. "[0]", "[1]", "[2]", "[3]", "[4]", "[5]", "[6]", "[7]",
  250. "[8]", "[9]", "[10]", "[11]", "[12]", "[13]", "[14]", "[15]",
  251. "[16]", "[17]", "[18]", "[19]", "[20]", "[21]", "[22]", "[23]",
  252. "[24]", "[25]", "[26]", "[27]", "[28]", "[20]", "[30]", "[31]"
  253. },
  254. /* Private */
  255. {
  256. "[P 0]", "[P 1]", "[P 2]", "[P 3]",
  257. "[P 4]", "[P 5]", "[P 6]", "[P 7]",
  258. "[P 8]", "[P 9]", "[P 10]", "[P 11]",
  259. "[P 12]", "[P 13]", "[P 14]", "[P 15]",
  260. "[P 16]", "[P 17]", "[P 18]", "[P 19]",
  261. "[P 20]", "[P 21]", "[P 22]", "[P 23]",
  262. "[P 24]", "[P 25]", "[P 26]", "[P 27]",
  263. "[P 28]", "[P 20]", "[P 30]", "[P 31]"
  264. }
  265. };
  266. /* Converts a tag byte to string.
  267. *
  268. * @param [in] tag BER tag value to interpret.
  269. * @return String corresponding to tag.
  270. */
  271. static const char* TagString(byte tag)
  272. {
  273. return tagString[tag >> 6][tag & ASN_TYPE_MASK];
  274. }
  275. #endif
  276. /* Calculates the minimum number of bytes required to encode the value.
  277. *
  278. * Only support up to 2^24-1.
  279. *
  280. * @param [in] value Value to be encoded.
  281. * @return Number of bytes to encode value.
  282. */
  283. static word32 BytePrecision(word32 value)
  284. {
  285. word32 i;
  286. for (i = (word32)sizeof(value) - 1; i; --i)
  287. if (value >> ((i - 1) * WOLFSSL_BIT_SIZE))
  288. break;
  289. return i;
  290. }
  291. /* DER encodes the length value in output buffer.
  292. *
  293. * 0 -> 2^7-1: <len byte>.
  294. * 2^7 -> : <0x80 + #bytes> <len big-endian bytes>
  295. *
  296. * @param [in] length Value to encode.
  297. * @param [in, out] output Buffer to encode into.
  298. * @return Number of bytes used in encoding.
  299. */
  300. WOLFSSL_LOCAL word32 SetASNLength(word32 length, byte* output)
  301. {
  302. word32 i = 0;
  303. if (length < ASN_LONG_LENGTH)
  304. output[i++] = (byte)length;
  305. else {
  306. word32 j;
  307. output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);
  308. for (j = BytePrecision(length); j; --j) {
  309. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  310. i++;
  311. }
  312. }
  313. return i;
  314. }
  315. #ifdef WOLFSSL_ASN_TEMPLATE
  316. /* Calculate the size of a DER encoded length value.
  317. *
  318. * 0 -> 2^7-1: <length byte>.
  319. * 2^7 -> : <0x80 + #bytes> <big-endian length bytes>
  320. *
  321. * @param [in] length Value to encode.
  322. * @return Number of bytes required to encode.
  323. */
  324. static word32 SizeASNLength(word32 length)
  325. {
  326. return 1 + ((length >= ASN_LONG_LENGTH) ? BytePrecision(length) : 0);
  327. }
  328. /* Calculate the size of a DER encoded header.
  329. *
  330. * Header = Tag | Encoded length
  331. *
  332. * @param [in] length Length value to encode.
  333. * @return Number of bytes required to encode a DER header.
  334. */
  335. #define SizeASNHeader(length) \
  336. (1 + SizeASNLength(length))
  337. #endif
  338. #ifdef WOLFSSL_ASN_TEMPLATE
  339. #ifdef WOLFSSL_SMALL_STACK
  340. /* Declare the variable that is the dynamic data for decoding BER data.
  341. *
  342. * @param [in] name Variable name to declare.
  343. * @param [in] cnt Number of elements required.
  344. */
  345. #define DECL_ASNGETDATA(name, cnt) \
  346. ASNGetData* name = NULL
  347. /* Allocates the dynamic BER decoding data.
  348. *
  349. * @param [in] name Variable name to declare.
  350. * @param [in] cnt Number of elements required.
  351. * @param [in, out] err Error variable.
  352. * @param [in] heap Dynamic memory allocation hint.
  353. */
  354. #define ALLOC_ASNGETDATA(name, cnt, err, heap) \
  355. do { \
  356. if ((err) == 0) { \
  357. (name) = (ASNGetData*)XMALLOC(sizeof(ASNGetData) * (cnt), (heap), \
  358. DYNAMIC_TYPE_TMP_BUFFER); \
  359. if ((name) == NULL) { \
  360. (err) = MEMORY_E; \
  361. } \
  362. } \
  363. } \
  364. while (0)
  365. /* Allocates the dynamic BER decoding data and clears the memory.
  366. *
  367. * @param [in] name Variable name to declare.
  368. * @param [in] cnt Number of elements required.
  369. * @param [in, out] err Error variable.
  370. * @param [in] heap Dynamic memory allocation hint.
  371. */
  372. #define CALLOC_ASNGETDATA(name, cnt, err, heap) \
  373. do { \
  374. ALLOC_ASNGETDATA(name, cnt, err, heap); \
  375. if ((err) == 0) { \
  376. XMEMSET((name), 0, sizeof(ASNGetData) * (cnt)); \
  377. } \
  378. } \
  379. while (0)
  380. /* Disposes of the dynamic BER decoding data.
  381. *
  382. * @param [in] name Variable name to declare.
  383. * @param [in] heap Dynamic memory allocation hint.
  384. */
  385. #define FREE_ASNGETDATA(name, heap) \
  386. do { \
  387. if ((name) != NULL) { \
  388. XFREE((name), (heap), DYNAMIC_TYPE_TMP_BUFFER); \
  389. } \
  390. } \
  391. while (0)
  392. /* Declare the variable that is the dynamic data for encoding DER data.
  393. *
  394. * @param [in] name Variable name to declare.
  395. * @param [in] cnt Number of elements required.
  396. */
  397. #define DECL_ASNSETDATA(name, cnt) \
  398. ASNSetData* name = NULL
  399. /* Allocates the dynamic DER encoding data.
  400. *
  401. * @param [in] name Variable name to declare.
  402. * @param [in] cnt Number of elements required.
  403. * @param [in, out] err Error variable.
  404. * @param [in] heap Dynamic memory allocation hint.
  405. */
  406. #define ALLOC_ASNSETDATA(name, cnt, err, heap) \
  407. do { \
  408. if ((err) == 0) { \
  409. (name) = (ASNSetData*)XMALLOC(sizeof(ASNGetData) * (cnt), (heap), \
  410. DYNAMIC_TYPE_TMP_BUFFER); \
  411. if ((name) == NULL) { \
  412. (err) = MEMORY_E; \
  413. } \
  414. } \
  415. } \
  416. while (0)
  417. /* Allocates the dynamic DER encoding data and clears the memory.
  418. *
  419. * @param [in] name Variable name to declare.
  420. * @param [in] cnt Number of elements required.
  421. * @param [in, out] err Error variable.
  422. * @param [in] heap Dynamic memory allocation hint.
  423. */
  424. #define CALLOC_ASNSETDATA(name, cnt, err, heap) \
  425. do { \
  426. ALLOC_ASNSETDATA(name, cnt, err, heap); \
  427. if ((err) == 0) { \
  428. XMEMSET(name, 0, sizeof(ASNSetData) * (cnt)); \
  429. } \
  430. } \
  431. while (0)
  432. /* Disposes of the dynamic DER encoding data.
  433. *
  434. * @param [in] name Variable name to declare.
  435. * @param [in] heap Dynamic memory allocation hint.
  436. */
  437. #define FREE_ASNSETDATA(name, heap) \
  438. do { \
  439. if ((name) != NULL) { \
  440. XFREE(name, heap, DYNAMIC_TYPE_TMP_BUFFER); \
  441. } \
  442. } \
  443. while (0)
  444. #else
  445. /* Declare the variable that is the dynamic data for decoding BER data.
  446. *
  447. * @param [in] name Variable name to declare.
  448. * @param [in] cnt Number of elements required.
  449. */
  450. #define DECL_ASNGETDATA(name, cnt) \
  451. ASNGetData name[cnt]
  452. /* No implementation as declaration is static.
  453. *
  454. * @param [in] name Variable name to declare.
  455. * @param [in] cnt Number of elements required.
  456. * @param [in, out] err Error variable.
  457. * @param [in] heap Dynamic memory allocation hint.
  458. */
  459. #define ALLOC_ASNGETDATA(name, cnt, err, heap)
  460. /* Clears the memory of the dynamic BER encoding data.
  461. *
  462. * @param [in] name Variable name to declare.
  463. * @param [in] cnt Number of elements required.
  464. * @param [in, out] err Error variable.
  465. * @param [in] heap Dynamic memory allocation hint.
  466. */
  467. #define CALLOC_ASNGETDATA(name, cnt, err, heap) \
  468. XMEMSET(name, 0, sizeof(name))
  469. /* No implementation as declaration is static.
  470. *
  471. * @param [in] name Variable name to declare.
  472. * @param [in] heap Dynamic memory allocation hint.
  473. */
  474. #define FREE_ASNGETDATA(name, heap)
  475. /* Declare the variable that is the dynamic data for encoding DER data.
  476. *
  477. * @param [in] name Variable name to declare.
  478. * @param [in] cnt Number of elements required.
  479. */
  480. #define DECL_ASNSETDATA(name, cnt) \
  481. ASNSetData name[cnt]
  482. /* No implementation as declaration is static.
  483. *
  484. * @param [in] name Variable name to declare.
  485. * @param [in] cnt Number of elements required.
  486. * @param [in, out] err Error variable.
  487. * @param [in] heap Dynamic memory allocation hint.
  488. */
  489. #define ALLOC_ASNSETDATA(name, cnt, err, heap)
  490. /* Clears the memory of the dynamic BER encoding data.
  491. *
  492. * @param [in] name Variable name to declare.
  493. * @param [in] cnt Number of elements required.
  494. * @param [in, out] err Error variable.
  495. * @param [in] heap Dynamic memory allocation hint.
  496. */
  497. #define CALLOC_ASNSETDATA(name, cnt, err, heap) \
  498. XMEMSET(name, 0, sizeof(name))
  499. /* No implementation as declaration is static.
  500. *
  501. * @param [in] name Variable name to declare.
  502. * @param [in] heap Dynamic memory allocation hint.
  503. */
  504. #define FREE_ASNSETDATA(name, heap)
  505. #endif
  506. #ifdef DEBUG_WOLFSSL
  507. /* Enable this when debugging the parsing or creation of ASN.1 data. */
  508. #if 0
  509. #define WOLFSSL_DEBUG_ASN_TEMPLATE
  510. #endif
  511. #endif
  512. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  513. #include <stdarg.h>
  514. /* Log a message that has the printf format string.
  515. *
  516. * @param [in] <va_args> printf style arguments.
  517. */
  518. #define WOLFSSL_MSG_VSNPRINTF(...) \
  519. do { \
  520. char line[81]; \
  521. snprintf(line, sizeof(line) - 1, __VA_ARGS__); \
  522. line[sizeof(line) - 1] = '\0'; \
  523. WOLFSSL_MSG(line); \
  524. } \
  525. while (0)
  526. #endif
  527. /* Returns whether ASN.1 item is an integer and the Most-Significant Bit is set.
  528. *
  529. * @param [in] asn ASN.1 items to encode.
  530. * @param [in] data_a Data to place in each item. Lengths set were not known.
  531. * @param [in] i Index of item to check.
  532. * @return 1 when ASN.1 item is an integer and MSB is 1.
  533. * @return 0 otherwise.
  534. */
  535. #define ASNIntMSBSet(asn, data_a, i) \
  536. (((asn)[i].tag == ASN_INTEGER) && \
  537. ((data_a)[i].data.buffer.data != NULL && \
  538. ((data_a)[i].data.buffer.data[0] & 0x80) == 0x80))
  539. /* Calculate the size of a DER encoded number.
  540. *
  541. * @param [in] n Number to be encoded.
  542. * @param [in] bits Maximum number of bits to encode.
  543. * @param [in] tag BER tag e.g. INTEGER, BIT_STRING, etc.
  544. * @return Number of bytes to the ASN.1 item.
  545. */
  546. static word32 SizeASN_Num(word32 n, int bits, byte tag)
  547. {
  548. int j;
  549. word32 len;
  550. len = 1 + 1 + (word32)bits / 8;
  551. /* Discover actual size by checking for high zeros. */
  552. for (j = bits - 8; j > 0; j -= 8) {
  553. if (n >> j)
  554. break;
  555. len--;
  556. }
  557. if (tag == ASN_BIT_STRING)
  558. len++;
  559. else if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80))
  560. len++;
  561. return len;
  562. }
  563. /* Calculate the size of the data in the constructed item based on the
  564. * length of the ASN.1 items below.
  565. *
  566. * @param [in] asn ASN.1 items to encode.
  567. * @param [in, out] data Data to place in each item. Lengths set were not
  568. * known.
  569. * @param [in] idx Index of item working on.
  570. */
  571. static void SizeASN_CalcDataLength(const ASNItem* asn, ASNSetData *data,
  572. int idx, int max)
  573. {
  574. int j;
  575. data[idx].data.buffer.length = 0;
  576. /* Sum the item length of all items underneath. */
  577. for (j = idx + 1; j < max; j++) {
  578. /* Stop looking if the next ASN.1 is same level or higher. */
  579. if (asn[j].depth <= asn[idx].depth)
  580. break;
  581. /* Only add in length if it is one level below. */
  582. if (asn[j].depth - 1 == asn[idx].depth) {
  583. data[idx].data.buffer.length += data[j].length;
  584. /* The length of a header only item doesn't include the data unless
  585. * a replacement buffer is supplied.
  586. */
  587. if (asn[j].headerOnly && data[j].data.buffer.data == NULL &&
  588. data[j].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
  589. data[idx].data.buffer.length += data[j].data.buffer.length;
  590. }
  591. }
  592. }
  593. }
  594. /* Calculate the size of the DER encoding.
  595. *
  596. * Call SetASN_Items() to write encoding to a buffer.
  597. *
  598. * @param [in] asn ASN.1 items to encode.
  599. * @param [in, out] data Data to place in each item. Lengths set where not
  600. * known.
  601. * @param [in] count Count of items to encode.
  602. * @param [out] encSz Length of the DER encoding.
  603. * @return 0 on success.
  604. * @return BAD_STATE_E when the data type is not supported.
  605. */
  606. int SizeASN_Items(const ASNItem* asn, ASNSetData *data, int count, int* encSz)
  607. {
  608. int i;
  609. word32 sz = 0;
  610. word32 len;
  611. word32 dataLen;
  612. int length;
  613. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  614. WOLFSSL_ENTER("SizeASN_Items");
  615. #endif
  616. for (i = count - 1; i >= 0; i--) {
  617. /* Skip this ASN.1 item when encoding. */
  618. if (data[i].noOut) {
  619. /* Set the offset to the current size - used in writing DER. */
  620. data[i].offset = sz;
  621. continue;
  622. }
  623. len = 0;
  624. switch (data[i].dataType) {
  625. /* Calculate the size of the number of different sizes. */
  626. case ASN_DATA_TYPE_WORD8:
  627. len = SizeASN_Num(data[i].data.u8, 8, asn[i].tag);
  628. break;
  629. case ASN_DATA_TYPE_WORD16:
  630. len = SizeASN_Num(data[i].data.u16, 16, asn[i].tag);
  631. break;
  632. #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
  633. /* Not used yet! */
  634. case ASN_DATA_TYPE_WORD32:
  635. len = SizeASN_Num(data[i].data.u32, 32, asn[i].tag);
  636. break;
  637. #endif
  638. case ASN_DATA_TYPE_MP:
  639. /* Calculate the size of the MP integer data. */
  640. length = mp_unsigned_bin_size(data[i].data.mp);
  641. length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
  642. len = (word32)SizeASNHeader((word32)length) + (word32)length;
  643. break;
  644. case ASN_DATA_TYPE_REPLACE_BUFFER:
  645. /* Buffer is put in directly - use the length. */
  646. len = data[i].data.buffer.length;
  647. break;
  648. case ASN_DATA_TYPE_NONE:
  649. /* Calculate the size based on the data to be included.
  650. * Mostly used for constructed items.
  651. */
  652. if (asn[i].headerOnly) {
  653. if (data[i].data.buffer.data != NULL) {
  654. /* Force all child nodes to be ignored. Buffer
  655. * overwrites children. */
  656. {
  657. int ii;
  658. for (ii = i + 1; ii < count; ii++) {
  659. if (asn[ii].depth <= asn[i].depth)
  660. break;
  661. sz -= data[ii].length;
  662. data[ii].noOut = 1;
  663. }
  664. }
  665. }
  666. else {
  667. /* Calculate data length from items below if no buffer
  668. * supplied. */
  669. SizeASN_CalcDataLength(asn, data, i, count);
  670. }
  671. }
  672. if (asn[i].tag == ASN_BOOLEAN) {
  673. dataLen = 1;
  674. }
  675. else {
  676. dataLen = data[i].data.buffer.length;
  677. }
  678. /* BIT_STRING and INTEGER have one byte prepended. */
  679. if ((asn[i].tag == ASN_BIT_STRING) ||
  680. ASNIntMSBSet(asn, data, i)) {
  681. dataLen++;
  682. /* ASN.1 items are below and cannot include extra byte. */
  683. if (asn[i].headerOnly) {
  684. len++;
  685. }
  686. }
  687. /* Add in the size of tag and length. */
  688. len += SizeASNHeader(dataLen);
  689. /* Include data in length if not header only or if
  690. * buffer supplied. */
  691. if (!asn[i].headerOnly || data[i].data.buffer.data != NULL) {
  692. len += dataLen;
  693. }
  694. break;
  695. #ifdef DEBUG_WOLFSSL
  696. default:
  697. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  698. WOLFSSL_MSG_VSNPRINTF("%2d: %d", i, data[i].dataType);
  699. WOLFSSL_MSG("Bad data type");
  700. #endif
  701. return BAD_STATE_E;
  702. #endif
  703. }
  704. /* Set the total length of the item. */
  705. data[i].length = len;
  706. /* Add length to total size. */
  707. sz += len;
  708. /* Set the offset to the current size - used in writing DER. */
  709. data[i].offset = sz;
  710. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  711. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  712. data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
  713. asn[i].depth, "", TagString(asn[i].tag));
  714. #endif
  715. }
  716. *encSz = (int)sz;
  717. return 0;
  718. }
  719. /* Create the DER encoding of a number.
  720. *
  721. * Assumes that the out buffer is large enough for encoding.
  722. *
  723. * @param [in] n Number to be encoded.
  724. * @param [in] bits Maximum number of bits to encode.
  725. * @param [in] tag DER tag e.g. INTEGER, BIT_STRING, etc.
  726. */
  727. static void SetASN_Num(word32 n, int bits, byte* out, byte tag)
  728. {
  729. int j;
  730. word32 idx;
  731. byte len;
  732. /* Encoding: Tag (1 byte) | Length (1 byte) | Data (number) */
  733. /* Data will start at index 2 unless BIT_STRING or INTEGER */
  734. idx = 2;
  735. /* Set the length of the number based on maximum bit length. */
  736. len = (byte)(bits / 8);
  737. /* Discover actual size by checking for leading zero bytes. */
  738. for (j = bits - 8; j > 0; j -= 8) {
  739. if ((n >> j) != 0) {
  740. break;
  741. }
  742. len--;
  743. }
  744. /* Keep j, index of first non-zero byte, for writing out. */
  745. /* A BIT_STRING has the number of unused bits in last byte prepended to
  746. * data.
  747. */
  748. if (tag == ASN_BIT_STRING) {
  749. byte unusedBits = 0;
  750. byte lastByte = (byte)(n >> j);
  751. /* Quick check last bit. */
  752. if ((lastByte & 0x01) == 0x00) {
  753. unusedBits++;
  754. /* Check each bit for first least significant bit set. */
  755. while (((lastByte >> unusedBits) & 0x01) == 0x00)
  756. unusedBits++;
  757. }
  758. /* Add unused bits byte. */
  759. len++;
  760. out[idx++] = unusedBits;
  761. }
  762. /* An INTEGER has a prepended byte if MSB of number is 1 - makes encoded
  763. * value positive. */
  764. if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80)) {
  765. len++;
  766. out[idx++] = 0;
  767. }
  768. /* Go back and put in length. */
  769. out[1] = len;
  770. /* Place in the required bytes of the number. */
  771. for (; j >= 0; j -= 8)
  772. out[idx++] = (byte)(n >> j);
  773. }
  774. /* Creates the DER encoding of the ASN.1 items.
  775. *
  776. * Assumes the output buffer is large enough to hold encoding.
  777. * Must call SizeASN_Items() to determine size of encoding and offsets.
  778. *
  779. * @param [in] asn ASN.1 items to encode.
  780. * @param [in] data Data to place in each item.
  781. * @param [in] count Count of items to encode.
  782. * @param [in, out] output Buffer to write encoding into.
  783. * @return Size of the DER encoding in bytes.
  784. */
  785. int SetASN_Items(const ASNItem* asn, ASNSetData *data, int count, byte* output)
  786. {
  787. int i;
  788. int length;
  789. int err;
  790. word32 sz;
  791. word32 idx;
  792. byte* out;
  793. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  794. WOLFSSL_ENTER("SetASN_Items");
  795. #endif
  796. /* Offset of first item is the total length.
  797. * SizeASN_Items() calculated this. */
  798. sz = data[0].offset;
  799. /* Write out each item. */
  800. for (i = 0; i < count; i++) {
  801. /* Skip items not writing out. */
  802. if (data[i].noOut)
  803. continue;
  804. /* Start position to write item based on reverse offsets. */
  805. out = output + sz - data[i].offset;
  806. /* Index from start of item out. */
  807. idx = 0;
  808. if (data[i].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
  809. /* Put in the tag - not dumping in DER from buffer. */
  810. out[idx++] = asn[i].tag |
  811. (asn[i].constructed ? ASN_CONSTRUCTED : 0);
  812. }
  813. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  814. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  815. sz - data[i].offset,
  816. data[i].length, asn[i].constructed ? '+' : ' ', asn[i].depth,
  817. "", TagString(asn[i].tag));
  818. #endif
  819. switch (data[i].dataType) {
  820. /* Write out the length and data of a number. */
  821. case ASN_DATA_TYPE_WORD8:
  822. SetASN_Num(data[i].data.u8, 8, out, asn[i].tag);
  823. break;
  824. case ASN_DATA_TYPE_WORD16:
  825. SetASN_Num(data[i].data.u16, 16, out, asn[i].tag);
  826. break;
  827. #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
  828. /* Not used yet! */
  829. case ASN_DATA_TYPE_WORD32:
  830. SetASN_Num(data[i].data.u32, 32, out, asn[i].tag);
  831. break;
  832. #endif
  833. /* Write out the length and data of a multi-precision number. */
  834. case ASN_DATA_TYPE_MP:
  835. /* Get length in bytes. */
  836. length = mp_unsigned_bin_size(data[i].data.mp);
  837. /* Add one for leading zero to make encoding a positive num. */
  838. length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
  839. /* Write out length. */
  840. idx += SetASNLength((word32)length, out + idx);
  841. /* Write out leading zero to make positive. */
  842. if (mp_leading_bit(data[i].data.mp)) {
  843. out[idx++] = 0;
  844. }
  845. /* Encode number in big-endian byte array. */
  846. err = mp_to_unsigned_bin(data[i].data.mp, out + idx);
  847. if (err != MP_OKAY) {
  848. WOLFSSL_MSG("SetASN_Items: Failed to write mp_int");
  849. return MP_TO_E;
  850. }
  851. break;
  852. case ASN_DATA_TYPE_REPLACE_BUFFER:
  853. if (data[i].data.buffer.data == NULL) {
  854. /* Return pointer for caller to use. */
  855. data[i].data.buffer.data = out + idx;
  856. }
  857. else {
  858. /* Dump in the DER encoded data. */
  859. XMEMCPY(out + idx, data[i].data.buffer.data,
  860. data[i].data.buffer.length);
  861. }
  862. break;
  863. case ASN_DATA_TYPE_NONE:
  864. if (asn[i].tag == ASN_BOOLEAN) {
  865. /* Always one byte of data. */
  866. out[idx++] = 1;
  867. /* TRUE = 0xff, FALSE = 0x00 */
  868. out[idx] = data[i].data.u8 ? 0xffU : 0x00U;
  869. }
  870. else if (asn[i].tag == ASN_TAG_NULL) {
  871. /* NULL tag is always a zero length item. */
  872. out[idx] = 0;
  873. }
  874. else {
  875. word32 dataLen = data[i].data.buffer.length;
  876. /* Add one to data length for BIT_STRING unused bits and
  877. * INTEGER leading zero to make positive.
  878. */
  879. if ((asn[i].tag == ASN_BIT_STRING) ||
  880. ASNIntMSBSet(asn, data, i)) {
  881. dataLen++;
  882. }
  883. /* Write out length. */
  884. idx += SetASNLength(dataLen, out + idx);
  885. if ((asn[i].tag == ASN_BIT_STRING) ||
  886. ASNIntMSBSet(asn, data, i)) {
  887. /* Write out leading byte. BIT_STRING has no unused bits
  888. * - use number data types if needed. */
  889. out[idx++] = 0x00;
  890. }
  891. /* Record pointer for caller if data not supplied. */
  892. if (data[i].data.buffer.data == NULL) {
  893. data[i].data.buffer.data = out + idx;
  894. }
  895. /* Copy supplied data if not putting out header only or
  896. * if buffer supplied. */
  897. else if (!asn[i].headerOnly ||
  898. data[i].data.buffer.data != NULL) {
  899. /* Allow data to come from output buffer. */
  900. XMEMMOVE(out + idx, data[i].data.buffer.data,
  901. data[i].data.buffer.length);
  902. }
  903. }
  904. break;
  905. #ifdef DEBUG_WOLFSSL
  906. default:
  907. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  908. WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data[i].dataType);
  909. #endif
  910. return BAD_STATE_E;
  911. #endif
  912. }
  913. }
  914. return (int)sz;
  915. }
  916. static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
  917. word32 oidType, int length);
  918. /* Maximum supported depth in ASN.1 description. */
  919. #define GET_ASN_MAX_DEPTH 7
  920. /* Maximum number of checked numbered choices. Only one of the items with the
  921. * number is allowed.
  922. */
  923. #define GET_ASN_MAX_CHOICES 2
  924. /* Use existing function to decode BER length encoding. */
  925. #define GetASN_Length GetLength_ex
  926. /* Check an INTEGER's first byte - must be a positive number.
  927. *
  928. * @param [in] input BER encoded data.
  929. * @param [in] idx Index of BIT_STRING data.
  930. * @param [in] length Length of input data.
  931. * @param [in] positive Indicates number must be positive.
  932. * @return 0 on success.
  933. * @return ASN_PARSE_E when 0 is not required but seen.
  934. * @return ASN_EXPECT_0_E when 0 is required and not seen.
  935. */
  936. static int GetASN_Integer(const byte* input, word32 idx, int length,
  937. int positive)
  938. {
  939. #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) || \
  940. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  941. /* Check contents consist of one or more octets. */
  942. if (length == 0) {
  943. WOLFSSL_MSG("Zero length INTEGER not allowed");
  944. return ASN_PARSE_E;
  945. }
  946. #endif
  947. if (input[idx] == 0) {
  948. /* Check leading zero byte required. */
  949. if ((length > 1) && ((input[idx + 1] & 0x80) == 0)) {
  950. WOLFSSL_MSG("Zero not required on INTEGER");
  951. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  952. return ASN_PARSE_E;
  953. #endif
  954. }
  955. }
  956. /* Check whether a leading zero byte was required. */
  957. else if (positive && (input[idx] & 0x80)) {
  958. WOLFSSL_MSG("INTEGER is negative");
  959. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  960. return ASN_EXPECT_0_E;
  961. #endif /* WOLFSSL_ASN_INT_LEAD_0_ANY */
  962. }
  963. return 0;
  964. }
  965. /* Check a BIT_STRING's first byte - unused bits.
  966. *
  967. * @param [in] input BER encoded data.
  968. * @param [in] idx Index of BIT_STRING data.
  969. * @param [in] length Length of input data.
  970. * @return 0 on success.
  971. * @return ASN_PARSE_E when unused bits is invalid.
  972. */
  973. static int GetASN_BitString(const byte* input, word32 idx, int length)
  974. {
  975. #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) || \
  976. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  977. /* Check contents consist of one or more octets. */
  978. if (length == 0) {
  979. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  980. WOLFSSL_MSG("Zero length BIT STRING not allowed");
  981. #endif
  982. return ASN_PARSE_E;
  983. }
  984. #endif
  985. /* Ensure unused bits value is valid range. */
  986. if (input[idx] > 7) {
  987. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  988. WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits too big: %d > 7",
  989. input[idx]);
  990. #endif
  991. return ASN_PARSE_E;
  992. }
  993. /* Ensure unused bits are zero. */
  994. if ((byte)(input[idx + (word32)length - 1] << (8 - input[idx])) != 0) {
  995. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  996. WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits used: %d %02x",
  997. input[idx], input[idx + length - 1]);
  998. #endif
  999. return ASN_PARSE_E;
  1000. }
  1001. return 0;
  1002. }
  1003. /* Get the ASN.1 items from the BER encoding.
  1004. *
  1005. * @param [in] asn ASN.1 item expected.
  1006. * @param [in] data Data array to place found item into.
  1007. * @param [in] input BER encoded data.
  1008. * @param [in] idx Starting index of item data.
  1009. * @param [in] len Length of input buffer upto end of this item's data.
  1010. * @param [in] zeroPadded INTEGER was zero padded to make positive.
  1011. * @return 0 on success.
  1012. * @return ASN_PARSE_E when BER encoded data is invalid.
  1013. * @return ASN_EXPECT_0_E when NULL tagged item has a non-zero length.
  1014. * @return MP_INIT_E when the unable to initialize an mp_int.
  1015. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1016. * @return BAD_STATE_E when the data type is not supported.
  1017. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  1018. */
  1019. static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data,
  1020. const byte* input, word32 idx, int len,
  1021. int zeroPadded)
  1022. {
  1023. int i;
  1024. int err;
  1025. /* Parse data based on data type to extract. */
  1026. switch (data->dataType) {
  1027. /* Parse a data into a number of specified bits. */
  1028. case ASN_DATA_TYPE_WORD8:
  1029. /* Check data is small enough to fit. */
  1030. if (len != 1) {
  1031. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1032. WOLFSSL_MSG_VSNPRINTF("Expecting one byte: %d", len);
  1033. #endif
  1034. return ASN_PARSE_E;
  1035. }
  1036. /* Fill number with all of data. */
  1037. *data->data.u8 = input[idx];
  1038. break;
  1039. case ASN_DATA_TYPE_WORD16:
  1040. /* Check data is small enough to fit. */
  1041. if (len == 0 || len > 2) {
  1042. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1043. WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", len);
  1044. #endif
  1045. return ASN_PARSE_E;
  1046. }
  1047. /* Fill number with all of data. */
  1048. *data->data.u16 = 0;
  1049. for (i = 0; i < len; i++) {
  1050. *data->data.u16 <<= 8;
  1051. *data->data.u16 |= input[idx + (word32)i] ;
  1052. }
  1053. break;
  1054. case ASN_DATA_TYPE_WORD32:
  1055. /* Check data is small enough to fit. */
  1056. if (len == 0 || len > 4) {
  1057. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1058. WOLFSSL_MSG_VSNPRINTF("Expecting 1 to 4 bytes: %d", len);
  1059. #endif
  1060. return ASN_PARSE_E;
  1061. }
  1062. /* Fill number with all of data. */
  1063. *data->data.u32 = 0;
  1064. for (i = 0; i < len; i++) {
  1065. *data->data.u32 <<= 8;
  1066. *data->data.u32 |= input[idx + (word32)i] ;
  1067. }
  1068. break;
  1069. case ASN_DATA_TYPE_BUFFER:
  1070. /* Check buffer is big enough to hold data. */
  1071. if (len > (int)*data->data.buffer.length) {
  1072. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1073. WOLFSSL_MSG_VSNPRINTF("Buffer too small for data: %d %d", len,
  1074. *data->data.buffer.length);
  1075. #endif
  1076. return ASN_PARSE_E;
  1077. }
  1078. /* Copy in data and record actual length seen. */
  1079. XMEMCPY(data->data.buffer.data, input + idx, (size_t)len);
  1080. *data->data.buffer.length = (word32)len;
  1081. break;
  1082. case ASN_DATA_TYPE_EXP_BUFFER:
  1083. /* Check data is same size expected. */
  1084. if (len != (int)data->data.ref.length) {
  1085. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1086. WOLFSSL_MSG_VSNPRINTF("Data not expected length: %d %d", len,
  1087. data->data.ref.length);
  1088. #endif
  1089. return ASN_PARSE_E;
  1090. }
  1091. /* Check data is same as expected. */
  1092. if (XMEMCMP(data->data.ref.data, input + idx, (size_t)len) != 0) {
  1093. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1094. WOLFSSL_MSG("Data not as expected");
  1095. #endif
  1096. return ASN_PARSE_E;
  1097. }
  1098. break;
  1099. case ASN_DATA_TYPE_MP:
  1100. case ASN_DATA_TYPE_MP_POS_NEG:
  1101. /* Initialize mp_int and read in big-endian byte array. */
  1102. if (mp_init(data->data.mp) != MP_OKAY) {
  1103. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1104. WOLFSSL_MSG_VSNPRINTF("Failed to init mp: %p", data->data.mp);
  1105. #endif
  1106. return MP_INIT_E;
  1107. }
  1108. FALL_THROUGH;
  1109. case ASN_DATA_TYPE_MP_INITED:
  1110. err = mp_read_unsigned_bin(data->data.mp, (byte*)input + idx,
  1111. (word32)len);
  1112. if (err != 0) {
  1113. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1114. WOLFSSL_MSG_VSNPRINTF("Failed to read mp: %d", err);
  1115. #endif
  1116. mp_clear(data->data.mp);
  1117. return ASN_GETINT_E;
  1118. }
  1119. #ifdef HAVE_WOLF_BIGINT
  1120. err = wc_bigint_from_unsigned_bin(&data->data.mp->raw, input + idx,
  1121. len);
  1122. if (err != 0) {
  1123. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1124. WOLFSSL_MSG_VSNPRINTF("Failed to create bigint: %d", err);
  1125. #endif
  1126. mp_clear(data->data.mp);
  1127. return ASN_GETINT_E;
  1128. }
  1129. #endif /* HAVE_WOLF_BIGINT */
  1130. #ifdef WOLFSSL_SP_INT_NEGATIVE
  1131. /* Don't always read as positive. */
  1132. if ((data->dataType == ASN_DATA_TYPE_MP_POS_NEG) && (!zeroPadded) &&
  1133. (input[idx] & 0x80)) {
  1134. #ifdef MP_NEG
  1135. data->data.mp->sign = MP_NEG;
  1136. #else
  1137. #ifdef OPENSSL_EXTRA
  1138. /* public API wolfSSL_ASN1_INTEGER_get() depends
  1139. * indirectly on negative bignum handling here.
  1140. */
  1141. #error OPENSSL_EXTRA requires negative bignum support.
  1142. #endif
  1143. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1144. WOLFSSL_MSG_VSNPRINTF("ASN negative integer without bignum support.");
  1145. #endif
  1146. mp_clear(data->data.mp);
  1147. return ASN_GETINT_E;
  1148. #endif
  1149. }
  1150. #else
  1151. (void)zeroPadded;
  1152. #endif
  1153. break;
  1154. case ASN_DATA_TYPE_CHOICE:
  1155. /* Check if tag matched any of the choices specified. */
  1156. for (i = 0; data->data.choice[i] != 0; i++)
  1157. if (data->data.choice[i] == data->tag)
  1158. break;
  1159. if (data->data.choice[i] == 0) {
  1160. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1161. WOLFSSL_MSG("Tag didn't match a choice");
  1162. #endif
  1163. return ASN_PARSE_E;
  1164. }
  1165. /* Store data pointer and length for caller. */
  1166. data->data.ref.data = input + idx;
  1167. data->data.ref.length = (word32)len;
  1168. break;
  1169. case ASN_DATA_TYPE_NONE:
  1170. /* Default behaviour based on tag. */
  1171. if (asn->tag == ASN_BOOLEAN) {
  1172. /* BOOLEAN has only one byte of data in BER. */
  1173. if (len != 1) {
  1174. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1175. WOLFSSL_MSG_VSNPRINTF("BOOLEAN length too long: %d", len);
  1176. #endif
  1177. return ASN_PARSE_E;
  1178. }
  1179. if (data->data.u8 == NULL)
  1180. return BAD_STATE_E;
  1181. /* Store C boolean value. */
  1182. *data->data.u8 = (input[idx] != 0);
  1183. break;
  1184. }
  1185. if (asn->tag == ASN_TAG_NULL) {
  1186. /* NULL has no data in BER. */
  1187. if (len != 0) {
  1188. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1189. WOLFSSL_MSG_VSNPRINTF("NULL length too long: %d", len);
  1190. #endif
  1191. return ASN_EXPECT_0_E;
  1192. }
  1193. data->data.ref.data = input + idx;
  1194. break;
  1195. }
  1196. if (asn->tag == ASN_OBJECT_ID) {
  1197. word32 oidIdx = 0;
  1198. /* Store OID data pointer and length */
  1199. data->data.oid.data = input + idx;
  1200. data->data.oid.length = (word32)len;
  1201. /* Get the OID sum. */
  1202. err = GetOID(input + idx, &oidIdx, &data->data.oid.sum,
  1203. data->data.oid.type, len);
  1204. if (err < 0) {
  1205. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1206. WOLFSSL_MSG_VSNPRINTF("OID check failed: %d", err);
  1207. #endif
  1208. return err;
  1209. }
  1210. break;
  1211. }
  1212. /* Otherwise store data pointer and length. */
  1213. data->data.ref.data = input + idx;
  1214. data->data.ref.length = (word32)len;
  1215. break;
  1216. #ifdef DEBUG_WOLFSSL
  1217. default:
  1218. /* Bad ASN data type. */
  1219. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1220. WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data->dataType);
  1221. #endif
  1222. return BAD_STATE_E;
  1223. #endif
  1224. }
  1225. return 0;
  1226. }
  1227. /* Get the ASN.1 items from the BER encoding.
  1228. *
  1229. * @param [in] asn ASN.1 items expected.
  1230. * @param [in] data Data array to place found items into.
  1231. * @param [in] count Count of items to parse.
  1232. * @param [in] complete Whether the whole buffer is to be used up.
  1233. * @param [in] input BER encoded data.
  1234. * @param [in, out] inOutIdx On in, starting index of data.
  1235. * On out, end of parsed data.
  1236. * @param [in] length Length of input buffer.
  1237. * @return 0 on success.
  1238. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1239. * is invalid.
  1240. * @return BUFFER_E when data in buffer is too small.
  1241. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1242. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1243. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1244. * non-zero length.
  1245. * @return MP_INIT_E when the unable to initialize an mp_int.
  1246. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1247. * @return BAD_STATE_E when the data type is not supported.
  1248. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  1249. */
  1250. int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, int complete,
  1251. const byte* input, word32* inOutIdx, word32 length)
  1252. {
  1253. int i;
  1254. int j;
  1255. int err;
  1256. int len;
  1257. /* Current index into buffer. */
  1258. word32 idx = *inOutIdx;
  1259. /* Initialize the end index at each depth to be the length. */
  1260. word32 endIdx[GET_ASN_MAX_DEPTH] = { length, length, length, length, length,
  1261. length, length };
  1262. /* Set choices to -1 to indicate they haven't been seen or found. */
  1263. signed char choiceMet[GET_ASN_MAX_CHOICES] = { -1, -1 };
  1264. /* Not matching a choice right now. */
  1265. int choice = 0;
  1266. /* Current depth of ASN.1 item. */
  1267. int depth;
  1268. /* Minimum depth value seen. */
  1269. int minDepth;
  1270. /* Integer had a zero prepended. */
  1271. int zeroPadded;
  1272. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1273. WOLFSSL_ENTER("GetASN_Items");
  1274. #endif
  1275. /* Start depth at first items depth. */
  1276. minDepth = depth = asn[0].depth;
  1277. /* Check every ASN.1 item. */
  1278. for (i = 0; i < count; i++) {
  1279. /* Store offset of ASN.1 item. */
  1280. data[i].offset = idx;
  1281. /* Length of data in ASN.1 item starts empty. */
  1282. data[i].length = 0;
  1283. /* Get current item depth. */
  1284. depth = asn[i].depth;
  1285. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1286. if (depth > GET_ASN_MAX_DEPTH) {
  1287. WOLFSSL_MSG("Depth in template too large");
  1288. return ASN_PARSE_E;
  1289. }
  1290. #endif
  1291. /* Keep track of minimum depth. */
  1292. if (depth < minDepth) {
  1293. minDepth = depth;
  1294. }
  1295. /* Reset choice if different from previous. */
  1296. if (choice > 0 && asn[i].optional != choice) {
  1297. choice = 0;
  1298. }
  1299. /* Check if first of numbered choice. */
  1300. if (choice == 0 && asn[i].optional > 1) {
  1301. choice = asn[i].optional;
  1302. if (choiceMet[choice - 2] == -1) {
  1303. /* Choice seen but not found a match yet. */
  1304. choiceMet[choice - 2] = 0;
  1305. }
  1306. }
  1307. /* Check for end of data or not a choice and tag not matching. */
  1308. if (idx == endIdx[depth] || (data[i].dataType != ASN_DATA_TYPE_CHOICE &&
  1309. (input[idx] & ~ASN_CONSTRUCTED) != asn[i].tag)) {
  1310. if (asn[i].optional) {
  1311. /* Skip over ASN.1 items underneath this optional item. */
  1312. for (j = i + 1; j < count; j++) {
  1313. if (asn[i].depth >= asn[j].depth)
  1314. break;
  1315. data[j].offset = idx;
  1316. data[j].length = 0;
  1317. }
  1318. i = j - 1;
  1319. continue;
  1320. }
  1321. /* Check for end of data. */
  1322. if (idx == length) {
  1323. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1324. WOLFSSL_MSG_VSNPRINTF(
  1325. "%2d: %4d %4d %c %*s %-16s%*s (index past end)",
  1326. i, data[i].offset, data[i].length,
  1327. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1328. TagString(asn[i].tag), 6 - asn[i].depth, "");
  1329. WOLFSSL_MSG_VSNPRINTF("Index past end of data: %d %d", idx,
  1330. length);
  1331. #endif
  1332. return BUFFER_E;
  1333. }
  1334. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1335. /* Show expected versus found. */
  1336. WOLFSSL_MSG_VSNPRINTF(
  1337. "%2d: %4d %4d %c %*s %-16s%*s Tag=0x%02x (%s)",
  1338. i, data[i].offset, data[i].length,
  1339. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1340. TagString(asn[i].tag), 6 - asn[i].depth, "",
  1341. input[idx], TagString(input[idx]));
  1342. #endif
  1343. /* Check for end of data at this depth. */
  1344. if (idx == endIdx[depth]) {
  1345. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1346. WOLFSSL_MSG_VSNPRINTF("Index past outer item: %d %d", idx,
  1347. endIdx[depth]);
  1348. #endif
  1349. return ASN_PARSE_E;
  1350. }
  1351. /* Expecting an OBJECT_ID */
  1352. if (asn[i].tag == ASN_OBJECT_ID) {
  1353. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1354. WOLFSSL_MSG("Expecting OBJECT ID");
  1355. #endif
  1356. return ASN_OBJECT_ID_E;
  1357. }
  1358. /* Expecting a BIT_STRING */
  1359. if (asn[i].tag == ASN_BIT_STRING) {
  1360. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1361. WOLFSSL_MSG("Expecting BIT STRING");
  1362. #endif
  1363. return ASN_BITSTR_E;
  1364. }
  1365. /* Not the expected tag. */
  1366. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1367. WOLFSSL_MSG("Bad tag");
  1368. #endif
  1369. return ASN_PARSE_E;
  1370. }
  1371. /* Store found tag in data. */
  1372. data[i].tag = input[idx];
  1373. if (data[i].dataType != ASN_DATA_TYPE_CHOICE) {
  1374. int constructed = (input[idx] & ASN_CONSTRUCTED) == ASN_CONSTRUCTED;
  1375. /* Check constructed match expected for non-choice ASN.1 item. */
  1376. if (asn[i].constructed != constructed) {
  1377. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1378. WOLFSSL_MSG_VSNPRINTF(
  1379. "%2d: %4d %4d %c %*s %-16s%*s Tag=0x%02x (%s)",
  1380. i, data[i].offset, data[i].length,
  1381. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1382. TagString(asn[i].tag), 6 - asn[i].depth, "",
  1383. input[idx], TagString(input[idx]));
  1384. if (!constructed) {
  1385. WOLFSSL_MSG("Not constructed");
  1386. }
  1387. else {
  1388. WOLFSSL_MSG("Not expected to be constructed");
  1389. }
  1390. #endif
  1391. return ASN_PARSE_E;
  1392. }
  1393. }
  1394. /* Move index to start of length. */
  1395. idx++;
  1396. /* Get the encoded length. */
  1397. if (GetASN_Length(input, &idx, &len, endIdx[depth], 1) < 0) {
  1398. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1399. WOLFSSL_MSG_VSNPRINTF("%2d: idx=%d len=%d end=%d", i, idx, len,
  1400. endIdx[depth]);
  1401. #endif
  1402. return ASN_PARSE_E;
  1403. }
  1404. /* Store length of data. */
  1405. data[i].length = (word32)len;
  1406. /* Note the max length of items under this one. */
  1407. endIdx[depth + 1] = idx + (word32)len;
  1408. if (choice > 1) {
  1409. /* Note we found a number choice. */
  1410. choiceMet[choice - 2] = 1;
  1411. }
  1412. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1413. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  1414. data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
  1415. asn[i].depth, "", TagString(data[i].tag));
  1416. #endif
  1417. /* Assume no zero padding on INTEGER. */
  1418. zeroPadded = 0;
  1419. /* Check data types that prepended a byte. */
  1420. if (asn[i].tag == ASN_INTEGER) {
  1421. /* Check validity of first byte. */
  1422. err = GetASN_Integer(input, idx, len,
  1423. data[i].dataType == ASN_DATA_TYPE_MP ||
  1424. data[i].dataType == ASN_DATA_TYPE_MP_INITED);
  1425. if (err != 0)
  1426. return err;
  1427. if (len > 1 && input[idx] == 0) {
  1428. zeroPadded = 1;
  1429. /* Move over prepended byte. */
  1430. idx++;
  1431. len--;
  1432. }
  1433. }
  1434. else if (asn[i].tag == ASN_BIT_STRING) {
  1435. /* Check prepended byte is correct. */
  1436. err = GetASN_BitString(input, idx, len);
  1437. if (err != 0)
  1438. return err;
  1439. /* Move over prepended byte. */
  1440. idx++;
  1441. len--;
  1442. }
  1443. else if ((asn[i].tag == ASN_OBJECT_ID) && (len < 3)) {
  1444. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1445. WOLFSSL_MSG_VSNPRINTF("OID length must be 3 or more: %d", len);
  1446. #endif
  1447. return ASN_PARSE_E;
  1448. }
  1449. /* Don't parse data if only header required. */
  1450. if (asn[i].headerOnly) {
  1451. /* Store reference to data and length. */
  1452. data[i].data.ref.data = input + idx;
  1453. data[i].data.ref.length = (word32)len;
  1454. continue;
  1455. }
  1456. /* Store the data at idx in the ASN data item. */
  1457. err = GetASN_StoreData(&asn[i], &data[i], input, idx, len, zeroPadded);
  1458. if (err != 0) {
  1459. return err;
  1460. }
  1461. /* Move index to next item. */
  1462. idx += (word32)len;
  1463. /* When matched numbered choice ... */
  1464. if (asn[i].optional > 1) {
  1465. /* Skip over other ASN.1 items of the same number. */
  1466. for (j = i + 1; j < count; j++) {
  1467. if (asn[j].depth <= asn[i].depth &&
  1468. asn[j].optional != asn[i].optional) {
  1469. break;
  1470. }
  1471. }
  1472. i = j - 1;
  1473. }
  1474. }
  1475. if (complete) {
  1476. /* When expecting ASN.1 items to completely use data, check we did. */
  1477. for (j = depth; j > minDepth; j--) {
  1478. if (idx < endIdx[j]) {
  1479. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1480. WOLFSSL_MSG_VSNPRINTF(
  1481. "More data in constructed item at depth: %d", j - 1);
  1482. #endif
  1483. return ASN_PARSE_E;
  1484. }
  1485. }
  1486. }
  1487. /* Check all choices where met - found an item for them. */
  1488. for (j = 0; j < GET_ASN_MAX_CHOICES; j++) {
  1489. if (choiceMet[j] == 0) {
  1490. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1491. WOLFSSL_MSG_VSNPRINTF("No choice seen: %d", j + 2);
  1492. #endif
  1493. return ASN_PARSE_E;
  1494. }
  1495. }
  1496. /* Return index after ASN.1 data has been parsed. */
  1497. *inOutIdx = idx;
  1498. return 0;
  1499. }
  1500. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1501. /* Calculate the size of the DER encoding.
  1502. *
  1503. * Call SetASN_Items() to write encoding to a buffer.
  1504. *
  1505. * @param [in] asn ASN.1 items to encode.
  1506. * @param [in, out] data Data to place in each item. Lengths set were not
  1507. * known.
  1508. * @param [in] count Count of items to encode.
  1509. * @param [out] len Length of the DER encoding.
  1510. * @return Size of the DER encoding in bytes.
  1511. */
  1512. static int SizeASN_ItemsDebug(const char* name, const ASNItem* asn,
  1513. ASNSetData *data, int count, int* encSz)
  1514. {
  1515. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1516. return SizeASN_Items(asn, data, count, encSz);
  1517. }
  1518. /* Creates the DER encoding of the ASN.1 items.
  1519. *
  1520. * Assumes the output buffer is large enough to hold encoding.
  1521. * Must call SizeASN_Items() to determine size of encoding and offsets.
  1522. *
  1523. * Displays the template name first.
  1524. *
  1525. * @param [in] name Name of ASN.1 template.
  1526. * @param [in] asn ASN.1 items to encode.
  1527. * @param [in] data Data to place in each item.
  1528. * @param [in] count Count of items to encode.
  1529. * @param [in, out] output Buffer to write encoding into.
  1530. * @return Size of the DER encoding in bytes.
  1531. */
  1532. static int SetASN_ItemsDebug(const char* name, const ASNItem* asn,
  1533. ASNSetData *data, int count, byte* output)
  1534. {
  1535. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1536. return SetASN_Items(asn, data, count, output);
  1537. }
  1538. /* Get the ASN.1 items from the BER encoding.
  1539. *
  1540. * Displays the template name first.
  1541. *
  1542. * @param [in] name Name of ASN.1 template.
  1543. * @param [in] asn ASN.1 items expected.
  1544. * @param [in] data Data array to place found items into.
  1545. * @param [in] count Count of items to parse.
  1546. * @param [in] complete Whether the whole buffer is to be used up.
  1547. * @param [in] input BER encoded data.
  1548. * @param [in, out] inOutIdx On in, starting index of data.
  1549. * On out, end of parsed data.
  1550. * @param [in] maxIdx Maximum index of input data.
  1551. * @return 0 on success.
  1552. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1553. * is invalid.
  1554. * @return BUFFER_E when data in buffer is too small.
  1555. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1556. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1557. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1558. * non-zero length.
  1559. * @return MP_INIT_E when the unable to initialize an mp_int.
  1560. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1561. * @return BAD_STATE_E when the data type is not supported.
  1562. */
  1563. static int GetASN_ItemsDebug(const char* name, const ASNItem* asn,
  1564. ASNGetData *data, int count, int complete, const byte* input,
  1565. word32* inOutIdx, word32 maxIdx)
  1566. {
  1567. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1568. return GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx);
  1569. }
  1570. /* Calculate the size of the DER encoding.
  1571. *
  1572. * Call SetASN_Items() to write encoding to a buffer.
  1573. *
  1574. * @param [in] asn ASN.1 items to encode.
  1575. * @param [in, out] data Data to place in each item. Lengths set were not
  1576. * known.
  1577. * @param [in] count Count of items to encode.
  1578. * @param [out] len Length of the DER encoding.
  1579. * @return Size of the DER encoding in bytes.
  1580. */
  1581. #define SizeASN_Items(asn, data, count, encSz) \
  1582. SizeASN_ItemsDebug(#asn, asn, data, count, encSz)
  1583. /* Creates the DER encoding of the ASN.1 items.
  1584. *
  1585. * Assumes the output buffer is large enough to hold encoding.
  1586. * Must call SizeASN_Items() to determine size of encoding and offsets.
  1587. *
  1588. * Displays the template name first.
  1589. *
  1590. * @param [in] name Name of ASN.1 template.
  1591. * @param [in] asn ASN.1 items to encode.
  1592. * @param [in] data Data to place in each item.
  1593. * @param [in] count Count of items to encode.
  1594. * @param [in, out] output Buffer to write encoding into.
  1595. * @return Size of the DER encoding in bytes.
  1596. */
  1597. #define SetASN_Items(asn, data, count, output) \
  1598. SetASN_ItemsDebug(#asn, asn, data, count, output)
  1599. /* Get the ASN.1 items from the BER encoding.
  1600. *
  1601. * Displays the template name first.
  1602. *
  1603. * @param [in] name Name of ASN.1 template.
  1604. * @param [in] asn ASN.1 items expected.
  1605. * @param [in] data Data array to place found items into.
  1606. * @param [in] count Count of items to parse.
  1607. * @param [in] complete Whether the whole buffer is to be used up.
  1608. * @param [in] input BER encoded data.
  1609. * @param [in, out] inOutIdx On in, starting index of data.
  1610. * On out, end of parsed data.
  1611. * @param [in] maxIdx Maximum index of input data.
  1612. * @return 0 on success.
  1613. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1614. * is invalid.
  1615. * @return BUFFER_E when data in buffer is too small.
  1616. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1617. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1618. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1619. * non-zero length.
  1620. * @return MP_INIT_E when the unable to initialize an mp_int.
  1621. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1622. * @return BAD_STATE_E when the data type is not supported.
  1623. */
  1624. #define GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx) \
  1625. GetASN_ItemsDebug(#asn, asn, data, count, complete, input, inOutIdx, maxIdx)
  1626. #endif /* WOLFSSL_DEBUG_ASN_TEMPLATE */
  1627. /* Decode a BER encoded constructed sequence.
  1628. *
  1629. * @param [in] input Buffer of BER encoded data.
  1630. * @param [in, out] inOutIdx On in, index to start decoding from.
  1631. * On out, index of next encoded byte.
  1632. * @param [out] len Length of data under SEQUENCE.
  1633. * @param [in] maxIdx Maximum index of data. Index of byte after SEQ.
  1634. * @param [in] complete All data used with SEQUENCE and data under.
  1635. * @return 0 on success.
  1636. * @return BUFFER_E when not enough data to complete decode.
  1637. * @return ASN_PARSE when decoding failed.
  1638. */
  1639. static int GetASN_Sequence(const byte* input, word32* inOutIdx, int* len,
  1640. word32 maxIdx, int complete)
  1641. {
  1642. int ret = 0;
  1643. word32 idx = *inOutIdx;
  1644. /* Check buffer big enough for tag. */
  1645. if (idx + 1 > maxIdx) {
  1646. ret = BUFFER_E;
  1647. }
  1648. /* Check it is a constructed SEQUENCE. */
  1649. if ((ret == 0) && (input[idx++] != (ASN_SEQUENCE | ASN_CONSTRUCTED))) {
  1650. ret = ASN_PARSE_E;
  1651. }
  1652. /* Get the length. */
  1653. if ((ret == 0) && (GetASN_Length(input, &idx, len, maxIdx, 1) < 0)) {
  1654. ret = ASN_PARSE_E;
  1655. }
  1656. /* Check all data used if complete set. */
  1657. if ((ret == 0) && complete && (idx + (word32)*len != maxIdx)) {
  1658. ret = ASN_PARSE_E;
  1659. }
  1660. if (ret == 0) {
  1661. /* Return index of next byte of encoded data. */
  1662. *inOutIdx = idx;
  1663. }
  1664. return ret;
  1665. }
  1666. #ifdef WOLFSSL_ASN_TEMPLATE_TYPE_CHECK
  1667. /* Setup ASN data item to get an 8-bit number.
  1668. *
  1669. * @param [in] dataASN Dynamic ASN data item.
  1670. * @param [in] num Pointer to an 8-bit variable.
  1671. */
  1672. void GetASN_Int8Bit(ASNGetData *dataASN, byte* num)
  1673. {
  1674. dataASN->dataType = ASN_DATA_TYPE_WORD8;
  1675. dataASN->data.u8 = num;
  1676. }
  1677. /* Setup ASN data item to get a 16-bit number.
  1678. *
  1679. * @param [in] dataASN Dynamic ASN data item.
  1680. * @param [in] num Pointer to a 16-bit variable.
  1681. */
  1682. void GetASN_Int16Bit(ASNGetData *dataASN, word16* num)
  1683. {
  1684. dataASN->dataType = ASN_DATA_TYPE_WORD16;
  1685. dataASN->data.u16 = num;
  1686. }
  1687. /* Setup ASN data item to get a 32-bit number.
  1688. *
  1689. * @param [in] dataASN Dynamic ASN data item.
  1690. * @param [in] num Pointer to a 32-bit variable.
  1691. */
  1692. void GetASN_Int32Bit(ASNGetData *dataASN, word32* num)
  1693. {
  1694. dataASN->dataType = ASN_DATA_TYPE_WORD32;
  1695. dataASN->data.u32 = num;
  1696. }
  1697. /* Setup ASN data item to get data into a buffer of a specific length.
  1698. *
  1699. * @param [in] dataASN Dynamic ASN data item.
  1700. * @param [in] data Buffer to hold data.
  1701. * @param [in] length Length of buffer in bytes.
  1702. */
  1703. void GetASN_Buffer(ASNGetData *dataASN, byte* data, word32* length)
  1704. {
  1705. dataASN->dataType = ASN_DATA_TYPE_BUFFER;
  1706. dataASN->data.buffer.data = data;
  1707. dataASN->data.buffer.length = length;
  1708. }
  1709. /* Setup ASN data item to check parsed data against expected buffer.
  1710. *
  1711. * @param [in] dataASN Dynamic ASN data item.
  1712. * @param [in] data Buffer containing expected data.
  1713. * @param [in] length Length of buffer in bytes.
  1714. */
  1715. void GetASN_ExpBuffer(ASNGetData *dataASN, const byte* data, word32 length)
  1716. {
  1717. dataASN->dataType = ASN_DATA_TYPE_EXP_BUFFER;
  1718. dataASN->data.ref.data = data;
  1719. dataASN->data.ref.length = length;
  1720. }
  1721. /* Setup ASN data item to get a number into an mp_int.
  1722. *
  1723. * @param [in] dataASN Dynamic ASN data item.
  1724. * @param [in] num Multi-precision number object.
  1725. */
  1726. void GetASN_MP(ASNGetData *dataASN, mp_int* num)
  1727. {
  1728. dataASN->dataType = ASN_DATA_TYPE_MP;
  1729. dataASN->data.mp = num;
  1730. }
  1731. /* Setup ASN data item to get a number into an mp_int that is initialized.
  1732. *
  1733. * @param [in] dataASN Dynamic ASN data item.
  1734. * @param [in] num Multi-precision number object.
  1735. */
  1736. void GetASN_MP_Inited(ASNGetData *dataASN, mp_int* num)
  1737. {
  1738. dataASN->dataType = ASN_DATA_TYPE_MP_INITED;
  1739. dataASN->data.mp = num;
  1740. }
  1741. /* Setup ASN data item to get a positive or negative number into an mp_int.
  1742. *
  1743. * @param [in] dataASN Dynamic ASN data item.
  1744. * @param [in] num Multi-precision number object.
  1745. */
  1746. void GetASN_MP_PosNeg(ASNGetData *dataASN, mp_int* num)
  1747. {
  1748. dataASN->dataType = ASN_DATA_TYPE_MP_POS_NEG;
  1749. dataASN->data.mp = num;
  1750. }
  1751. /* Setup ASN data item to be a choice of tags.
  1752. *
  1753. * @param [in] dataASN Dynamic ASN data item.
  1754. * @param [in] options 0 terminated list of tags that are valid.
  1755. */
  1756. void GetASN_Choice(ASNGetData *dataASN, const byte* options)
  1757. {
  1758. dataASN->dataType = ASN_DATA_TYPE_CHOICE;
  1759. dataASN->data.choice = options;
  1760. }
  1761. /* Setup ASN data item to get a boolean value.
  1762. *
  1763. * @param [in] dataASN Dynamic ASN data item.
  1764. * @param [in] num Pointer to an 8-bit variable.
  1765. */
  1766. void GetASN_Boolean(ASNGetData *dataASN, byte* num)
  1767. {
  1768. dataASN->dataType = ASN_DATA_TYPE_NONE;
  1769. dataASN->data.choice = num;
  1770. }
  1771. /* Setup ASN data item to be a an OID of a specific type.
  1772. *
  1773. * @param [in] dataASN Dynamic ASN data item.
  1774. * @param [in] oidType Type of OID to expect.
  1775. */
  1776. void GetASN_OID(ASNGetData *dataASN, int oidType)
  1777. {
  1778. dataASN->data.oid.type = oidType;
  1779. }
  1780. /* Get the data and length from an ASN data item.
  1781. *
  1782. * @param [in] dataASN Dynamic ASN data item.
  1783. * @param [out] data Pointer to data of item.
  1784. * @param [out] length Length of buffer in bytes.
  1785. */
  1786. void GetASN_GetConstRef(ASNGetData * dataASN, const byte** data, word32* length)
  1787. {
  1788. *data = dataASN->data.ref.data;
  1789. *length = dataASN->data.ref.length;
  1790. }
  1791. /* Get the data and length from an ASN data item.
  1792. *
  1793. * @param [in] dataASN Dynamic ASN data item.
  1794. * @param [out] data Pointer to data of item.
  1795. * @param [out] length Length of buffer in bytes.
  1796. */
  1797. void GetASN_GetRef(ASNGetData * dataASN, byte** data, word32* length)
  1798. {
  1799. *data = (byte*)dataASN->data.ref.data;
  1800. *length = dataASN->data.ref.length;
  1801. }
  1802. /* Get the data and length from an ASN data item that is an OID.
  1803. *
  1804. * @param [in] dataASN Dynamic ASN data item.
  1805. * @param [out] data Pointer to .
  1806. * @param [out] length Length of buffer in bytes.
  1807. */
  1808. void GetASN_OIDData(ASNGetData * dataASN, byte** data, word32* length)
  1809. {
  1810. *data = (byte*)dataASN->data.oid.data;
  1811. *length = dataASN->data.oid.length;
  1812. }
  1813. /* Setup an ASN data item to set a boolean.
  1814. *
  1815. * @param [in] dataASN Dynamic ASN data item.
  1816. * @param [in] val Boolean value.
  1817. */
  1818. void SetASN_Boolean(ASNSetData *dataASN, byte val)
  1819. {
  1820. dataASN->dataType = ASN_DATA_TYPE_NONE;
  1821. dataASN->data.u8 = val;
  1822. }
  1823. /* Setup an ASN data item to set an 8-bit number.
  1824. *
  1825. * @param [in] dataASN Dynamic ASN data item.
  1826. * @param [in] num 8-bit number to set.
  1827. */
  1828. void SetASN_Int8Bit(ASNSetData *dataASN, byte num)
  1829. {
  1830. dataASN->dataType = ASN_DATA_TYPE_WORD8;
  1831. dataASN->data.u8 = num;
  1832. }
  1833. /* Setup an ASN data item to set a 16-bit number.
  1834. *
  1835. * @param [in] dataASN Dynamic ASN data item.
  1836. * @param [in] num 16-bit number to set.
  1837. */
  1838. void SetASN_Int16Bit(ASNSetData *dataASN, word16 num)
  1839. {
  1840. dataASN->dataType = ASN_DATA_TYPE_WORD16;
  1841. dataASN->data.u16 = num;
  1842. }
  1843. /* Setup an ASN data item to set the data in a buffer.
  1844. *
  1845. * @param [in] dataASN Dynamic ASN data item.
  1846. * @param [in] data Buffer containing data to set.
  1847. * @param [in] length Length of data in buffer in bytes.
  1848. */
  1849. void SetASN_Buffer(ASNSetData *dataASN, const byte* data, word32 length)
  1850. {
  1851. dataASN->data.buffer.data = data;
  1852. dataASN->data.buffer.length = length;
  1853. }
  1854. /* Setup an ASN data item to set the DER encode data in a buffer.
  1855. *
  1856. * @param [in] dataASN Dynamic ASN data item.
  1857. * @param [in] data Buffer containing BER encoded data to set.
  1858. * @param [in] length Length of data in buffer in bytes.
  1859. */
  1860. void SetASN_ReplaceBuffer(ASNSetData *dataASN, const byte* data, word32 length)
  1861. {
  1862. dataASN->dataType = ASN_DATA_TYPE_REPLACE_BUFFER;
  1863. dataASN->data.buffer.data = data;
  1864. dataASN->data.buffer.length = length;
  1865. }
  1866. /* Setup an ASN data item to set an multi-precision number.
  1867. *
  1868. * @param [in] dataASN Dynamic ASN data item.
  1869. * @param [in] num Multi-precision number.
  1870. */
  1871. void SetASN_MP(ASNSetData *dataASN, mp_int* num)
  1872. {
  1873. dataASN->dataType = ASN_DATA_TYPE_MP;
  1874. dataASN->data.mp = num;
  1875. }
  1876. /* Setup an ASN data item to set an OID based on id and type.
  1877. *
  1878. * oid and oidType pair are unique.
  1879. *
  1880. * @param [in] dataASN Dynamic ASN data item.
  1881. * @param [in] oid OID identifier.
  1882. * @param [in] oidType Type of OID.
  1883. */
  1884. void SetASN_OID(ASNSetData *dataASN, int oid, int oidType)
  1885. {
  1886. dataASN->data.buffer.data = OidFromId(oid, oidType,
  1887. &dataASN->data.buffer.length);
  1888. }
  1889. #endif /* WOLFSSL_ASN_TEMPLATE_TYPE_CHECK */
  1890. #ifdef CRLDP_VALIDATE_DATA
  1891. /* Get the data of the BIT_STRING as a 16-bit number.
  1892. *
  1893. * @param [in] dataASN Dynamic ASN data item.
  1894. * @param [out] val ASN.1 item's data as a 16-bit number.
  1895. * @return 0 on success.
  1896. * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
  1897. * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
  1898. */
  1899. static int GetASN_BitString_Int16Bit(ASNGetData* dataASN, word16* val)
  1900. {
  1901. int ret;
  1902. int i;
  1903. const byte* input = dataASN->data.ref.data;
  1904. int length = dataASN->data.ref.length;
  1905. /* Validate the BIT_STRING data. */
  1906. ret = GetASN_BitString(input, 0, length);
  1907. if (ret == 0) {
  1908. /* Skip unused bits byte. */
  1909. input++;
  1910. length--;
  1911. /* Check the data is usable. */
  1912. if (length == 0 || length > 2) {
  1913. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1914. WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", length);
  1915. #endif
  1916. ret = ASN_PARSE_E;
  1917. }
  1918. }
  1919. if (ret == 0) {
  1920. /* Fill 16-bit var with all the data. */
  1921. *val = 0;
  1922. for (i = 0; i < length; i++) {
  1923. *val <<= 8;
  1924. *val |= input[i];
  1925. }
  1926. }
  1927. return ret;
  1928. }
  1929. #endif /* CRLDP_VALIDATE_DATA */
  1930. #endif /* WOLFSSL_ASN_TEMPLATE */
  1931. /* Decode the BER/DER length field.
  1932. *
  1933. * @param [in] input BER encoded data.
  1934. * @param [in, out] inOutIdx On in, starting index of length.
  1935. * On out, end of parsed length.
  1936. * @param [out] len Length value decoded.
  1937. * @param [in] maxIdx Maximum index of input data.
  1938. * @return Length on success.
  1939. * @return ASN_PARSE_E if the encoding is invalid.
  1940. * @return BUFFER_E when not enough data to complete decode.
  1941. */
  1942. int GetLength(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  1943. {
  1944. return GetLength_ex(input, inOutIdx, len, maxIdx, 1);
  1945. }
  1946. /* Decode the BER/DER length field and check the length is valid on request.
  1947. *
  1948. * BER/DER has Type-Length-Value triplets.
  1949. * When requested will check that the Length decoded, indicating the number
  1950. * of bytes in the Value, is available in the buffer after the Length bytes.
  1951. *
  1952. * Only supporting a length upto INT_MAX.
  1953. *
  1954. * @param [in] input BER encoded data.
  1955. * @param [in, out] inOutIdx On in, starting index of length.
  1956. * On out, end of parsed length.
  1957. * @param [out] len Length value decoded.
  1958. * @param [in] maxIdx Maximum index of input data.
  1959. * @param [in] check Whether to check the buffer has at least the
  1960. * decoded length of bytes remaining.
  1961. * @return Length on success.
  1962. * @return ASN_PARSE_E if the encoding is invalid.
  1963. * @return BUFFER_E when not enough data to complete decode.
  1964. */
  1965. int GetLength_ex(const byte* input, word32* inOutIdx, int* len, word32 maxIdx,
  1966. int check)
  1967. {
  1968. int length = 0;
  1969. word32 idx = (word32)*inOutIdx;
  1970. byte b;
  1971. /* Ensure zero return length on error. */
  1972. *len = 0;
  1973. /* Check there is at least one byte available containing length information.
  1974. */
  1975. if ((idx + 1) > maxIdx) {
  1976. WOLFSSL_MSG("GetLength - bad index on input");
  1977. return BUFFER_E;
  1978. }
  1979. /* Get the first length byte. */
  1980. b = input[idx++];
  1981. /* Check if the first byte indicates the count of bytes. */
  1982. if (b >= ASN_LONG_LENGTH) {
  1983. /* Bottom 7 bits are the number of bytes to calculate length with.
  1984. * Note: 0 indicates indefinite length encoding *not* 0 bytes of length.
  1985. */
  1986. word32 bytes = (word32)b & 0x7FU;
  1987. int minLen;
  1988. /* Calculate minimum length to be encoded with bytes. */
  1989. if (b == ASN_INDEF_LENGTH) {
  1990. /* Indefinite length encoding - no length bytes. */
  1991. minLen = 0;
  1992. }
  1993. else if (bytes == 1) {
  1994. minLen = 0x80;
  1995. }
  1996. /* Only support up to the number of bytes that fit into return var. */
  1997. else if (bytes > sizeof(length)) {
  1998. WOLFSSL_MSG("GetLength - overlong data length spec");
  1999. return ASN_PARSE_E;
  2000. } else {
  2001. minLen = 1 << ((bytes - 1) * 8);
  2002. }
  2003. /* Check the number of bytes required are available. */
  2004. if ((idx + bytes) > maxIdx) {
  2005. WOLFSSL_MSG("GetLength - bad long length");
  2006. return BUFFER_E;
  2007. }
  2008. /* Big-endian encoding of number. */
  2009. while (bytes--) {
  2010. b = input[idx++];
  2011. length = (length << 8) | b;
  2012. }
  2013. /* Negative value indicates we overflowed the signed int. */
  2014. if (length < 0) {
  2015. return ASN_PARSE_E;
  2016. }
  2017. /* Don't allow lengths that are longer than strictly required. */
  2018. if (length < minLen) {
  2019. return ASN_PARSE_E;
  2020. }
  2021. }
  2022. else {
  2023. /* Length in first byte. */
  2024. length = b;
  2025. }
  2026. /* When requested, check the buffer has at least length bytes left. */
  2027. if (check && ((idx + (word32)length) > maxIdx)) {
  2028. WOLFSSL_MSG("GetLength - value exceeds buffer length");
  2029. return BUFFER_E;
  2030. }
  2031. /* Return index after length encoding. */
  2032. *inOutIdx = idx;
  2033. /* Return length if valid. */
  2034. if (length > 0) {
  2035. *len = length;
  2036. }
  2037. /* Return length calculated or error code. */
  2038. return length;
  2039. }
  2040. /* Gets the tag of next BER/DER encoded item.
  2041. *
  2042. * Checks there is enough data in the buffer for the tag byte.
  2043. *
  2044. * @param [in] input BER encoded data.
  2045. * @param [in, out] inOutIdx On in, starting index of tag.
  2046. * On out, end of parsed tag.
  2047. * @param [out] tag Tag value found.
  2048. * @param [in] maxIdx Maximum index of input data.
  2049. *
  2050. * return 0 on success
  2051. * return BAD_FUNC_ARG when tag, inOutIdx or input is NULL.
  2052. * return BUFFER_E when not enough space in buffer for tag.
  2053. */
  2054. int GetASNTag(const byte* input, word32* inOutIdx, byte* tag, word32 maxIdx)
  2055. {
  2056. int ret = 0;
  2057. word32 idx = 0;
  2058. /* Check validity of parameters. */
  2059. if ((tag == NULL) || (inOutIdx == NULL) || (input == NULL)) {
  2060. ret = BAD_FUNC_ARG;
  2061. }
  2062. if (ret == 0) {
  2063. /* Get index and ensure space for tag. */
  2064. idx = *inOutIdx;
  2065. if (idx + ASN_TAG_SZ > maxIdx) {
  2066. WOLFSSL_MSG("Buffer too small for ASN tag");
  2067. ret = BUFFER_E;
  2068. }
  2069. }
  2070. if (ret == 0) {
  2071. /* Return the tag and the index after tag. */
  2072. *tag = input[idx];
  2073. *inOutIdx = idx + ASN_TAG_SZ;
  2074. }
  2075. /* Return error code. */
  2076. return ret;
  2077. }
  2078. /* Decode the DER/BER header (Type-Length) and check the length when requested.
  2079. *
  2080. * BER/DER has Type-Length-Value triplets.
  2081. * Check that the tag/type is the required value.
  2082. * When requested will check that the Length decoded, indicating the number
  2083. * of bytes in the Value, is available in the buffer after the Length bytes.
  2084. *
  2085. * Only supporting a length upto INT_MAX.
  2086. *
  2087. * @param [in] input Buffer holding DER/BER encoded data.
  2088. * @param [in] tag ASN.1 tag value expected in header.
  2089. * @param [in, out] inOutIdx On in, starting index of header.
  2090. * On out, end of parsed header.
  2091. * @param [out] len Number of bytes in the ASN.1 data.
  2092. * @param [in] maxIdx Length of data in buffer.
  2093. * @param [in] check Whether to check the buffer has at least the
  2094. * decoded length of bytes remaining.
  2095. * @return Number of bytes in the ASN.1 data on success.
  2096. * @return BUFFER_E when there is not enough data to parse.
  2097. * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
  2098. */
  2099. static int GetASNHeader_ex(const byte* input, byte tag, word32* inOutIdx,
  2100. int* len, word32 maxIdx, int check)
  2101. {
  2102. int ret = 0;
  2103. word32 idx = *inOutIdx;
  2104. byte tagFound;
  2105. int length = 0;
  2106. /* Get tag/type. */
  2107. if (GetASNTag(input, &idx, &tagFound, maxIdx) != 0) {
  2108. ret = ASN_PARSE_E;
  2109. }
  2110. /* Ensure tag is the expected value. */
  2111. if ((ret == 0) && (tagFound != tag)) {
  2112. ret = ASN_PARSE_E;
  2113. }
  2114. /* Get the encoded length. */
  2115. if ((ret == 0) && (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)) {
  2116. ret = ASN_PARSE_E;
  2117. }
  2118. if (ret == 0) {
  2119. /* Return the length of data and index after header. */
  2120. *len = length;
  2121. *inOutIdx = idx;
  2122. ret = length;
  2123. }
  2124. /* Return number of data bytes or error code. */
  2125. return ret;
  2126. }
  2127. /* Decode the DER/BER header (Type-Length) and check the length.
  2128. *
  2129. * BER/DER has Type-Length-Value triplets.
  2130. * Check that the tag/type is the required value.
  2131. * Checks that the Length decoded, indicating the number of bytes in the Value,
  2132. * is available in the buffer after the Length bytes.
  2133. *
  2134. * @param [in] input Buffer holding DER/BER encoded data.
  2135. * @param [in] tag ASN.1 tag value expected in header.
  2136. * @param [in, out] inOutIdx On in, starting index of header.
  2137. * On out, end of parsed header.
  2138. * @param [out] len Number of bytes in the ASN.1 data.
  2139. * @param [in] maxIdx Length of data in buffer.
  2140. * @return Number of bytes in the ASN.1 data on success.
  2141. * @return BUFFER_E when there is not enough data to parse.
  2142. * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
  2143. */
  2144. static int GetASNHeader(const byte* input, byte tag, word32* inOutIdx, int* len,
  2145. word32 maxIdx)
  2146. {
  2147. return GetASNHeader_ex(input, tag, inOutIdx, len, maxIdx, 1);
  2148. }
  2149. #ifndef WOLFSSL_ASN_TEMPLATE
  2150. static int GetHeader(const byte* input, byte* tag, word32* inOutIdx, int* len,
  2151. word32 maxIdx, int check)
  2152. {
  2153. word32 idx = *inOutIdx;
  2154. int length;
  2155. if ((idx + 1) > maxIdx)
  2156. return BUFFER_E;
  2157. *tag = input[idx++];
  2158. if (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)
  2159. return ASN_PARSE_E;
  2160. *len = length;
  2161. *inOutIdx = idx;
  2162. return length;
  2163. }
  2164. #endif
  2165. /* Decode the header of a BER/DER encoded SEQUENCE.
  2166. *
  2167. * @param [in] input Buffer holding DER/BER encoded data.
  2168. * @param [in, out] inOutIdx On in, starting index of header.
  2169. * On out, end of parsed header.
  2170. * @param [out] len Number of bytes in the ASN.1 data.
  2171. * @param [in] maxIdx Length of data in buffer.
  2172. * @return Number of bytes in the ASN.1 data on success.
  2173. * @return BUFFER_E when there is not enough data to parse.
  2174. * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
  2175. */
  2176. int GetSequence(const byte* input, word32* inOutIdx, int* len,
  2177. word32 maxIdx)
  2178. {
  2179. return GetASNHeader(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  2180. maxIdx);
  2181. }
  2182. /* Decode the header of a BER/DER encoded SEQUENCE.
  2183. *
  2184. * @param [in] input Buffer holding DER/BER encoded data.
  2185. * @param [in, out] inOutIdx On in, starting index of header.
  2186. * On out, end of parsed header.
  2187. * @param [out] len Number of bytes in the ASN.1 data.
  2188. * @param [in] maxIdx Length of data in buffer.
  2189. * @param [in] check Whether to check the buffer has at least the
  2190. * decoded length of bytes remaining.
  2191. * @return Number of bytes in the ASN.1 data on success.
  2192. * @return BUFFER_E when there is not enough data to parse.
  2193. * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
  2194. */
  2195. int GetSequence_ex(const byte* input, word32* inOutIdx, int* len,
  2196. word32 maxIdx, int check)
  2197. {
  2198. return GetASNHeader_ex(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  2199. maxIdx, check);
  2200. }
  2201. /* Decode the header of a BER/DER encoded SET.
  2202. *
  2203. * @param [in] input Buffer holding DER/BER encoded data.
  2204. * @param [in, out] inOutIdx On in, starting index of header.
  2205. * On out, end of parsed header.
  2206. * @param [out] len Number of bytes in the ASN.1 data.
  2207. * @param [in] maxIdx Length of data in buffer.
  2208. * @return Number of bytes in the ASN.1 data on success.
  2209. * @return BUFFER_E when there is not enough data to parse.
  2210. * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
  2211. */
  2212. int GetSet(const byte* input, word32* inOutIdx, int* len,
  2213. word32 maxIdx)
  2214. {
  2215. return GetASNHeader(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  2216. maxIdx);
  2217. }
  2218. /* Decode the header of a BER/DER encoded SET.
  2219. *
  2220. * @param [in] input Buffer holding DER/BER encoded data.
  2221. * @param [in, out] inOutIdx On in, starting index of header.
  2222. * On out, end of parsed header.
  2223. * @param [out] len Number of bytes in the ASN.1 data.
  2224. * @param [in] maxIdx Length of data in buffer.
  2225. * @param [in] check Whether to check the buffer has at least the
  2226. * decoded length of bytes remaining.
  2227. * @return Number of bytes in the ASN.1 data on success.
  2228. * @return BUFFER_E when there is not enough data to parse.
  2229. * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
  2230. */
  2231. int GetSet_ex(const byte* input, word32* inOutIdx, int* len,
  2232. word32 maxIdx, int check)
  2233. {
  2234. return GetASNHeader_ex(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  2235. maxIdx, check);
  2236. }
  2237. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_OCSP)
  2238. /* Decode the BER/DER encoded NULL.
  2239. *
  2240. * No data in a NULL ASN.1 item.
  2241. * Ensure that the all fields are as expected and move index past the element.
  2242. *
  2243. * @param [in] input Buffer holding DER/BER encoded data.
  2244. * @param [in, out] inOutIdx On in, starting index of NULL item.
  2245. * On out, end of parsed NULL item.
  2246. * @param [in] maxIdx Length of data in buffer.
  2247. * @return 0 on success.
  2248. * @return BUFFER_E when there is not enough data to parse.
  2249. * @return ASN_TAG_NULL_E when the NULL tag is not found.
  2250. * @return ASN_EXPECT_0_E when the length is not zero.
  2251. */
  2252. static int GetASNNull(const byte* input, word32* inOutIdx, word32 maxIdx)
  2253. {
  2254. int ret = 0;
  2255. word32 idx = *inOutIdx;
  2256. /* Check buffer has enough data for a NULL item. */
  2257. if ((idx + 2) > maxIdx) {
  2258. ret = BUFFER_E;
  2259. }
  2260. /* Check the tag is NULL. */
  2261. if ((ret == 0) && (input[idx++] != ASN_TAG_NULL)) {
  2262. ret = ASN_TAG_NULL_E;
  2263. }
  2264. /* Check the length is zero. */
  2265. if ((ret == 0) && (input[idx++] != 0)) {
  2266. ret = ASN_EXPECT_0_E;
  2267. }
  2268. if (ret == 0) {
  2269. /* Return the index after NULL tag. */
  2270. *inOutIdx = idx;
  2271. }
  2272. /* Return error code. */
  2273. return ret;
  2274. }
  2275. #endif
  2276. #ifndef WOLFSSL_ASN_TEMPLATE
  2277. /* Set the DER/BER encoding of the ASN.1 NULL element.
  2278. *
  2279. * output Buffer to write into.
  2280. * returns the number of bytes added to the buffer.
  2281. */
  2282. static int SetASNNull(byte* output)
  2283. {
  2284. output[0] = ASN_TAG_NULL;
  2285. output[1] = 0;
  2286. return 2;
  2287. }
  2288. #endif
  2289. #ifndef NO_CERTS
  2290. #ifndef WOLFSSL_ASN_TEMPLATE
  2291. /* Get the DER/BER encoding of an ASN.1 BOOLEAN.
  2292. *
  2293. * input Buffer holding DER/BER encoded data.
  2294. * inOutIdx Current index into buffer to parse.
  2295. * maxIdx Length of data in buffer.
  2296. * returns BUFFER_E when there is not enough data to parse.
  2297. * ASN_PARSE_E when the BOOLEAN tag is not found or length is not 1.
  2298. * Otherwise, 0 to indicate the value was false and 1 to indicate true.
  2299. */
  2300. static int GetBoolean(const byte* input, word32* inOutIdx, word32 maxIdx)
  2301. {
  2302. word32 idx = *inOutIdx;
  2303. byte b;
  2304. if ((idx + 3) > maxIdx)
  2305. return BUFFER_E;
  2306. b = input[idx++];
  2307. if (b != ASN_BOOLEAN)
  2308. return ASN_PARSE_E;
  2309. if (input[idx++] != 1)
  2310. return ASN_PARSE_E;
  2311. b = input[idx++] != 0;
  2312. *inOutIdx = idx;
  2313. return b;
  2314. }
  2315. #endif
  2316. #endif /* !NO_CERTS*/
  2317. /* Decode the header of a BER/DER encoded OCTET STRING.
  2318. *
  2319. * @param [in] input Buffer holding DER/BER encoded data.
  2320. * @param [in, out] inOutIdx On in, starting index of header.
  2321. * On out, end of parsed header.
  2322. * @param [out] len Number of bytes in the ASN.1 data.
  2323. * @param [in] maxIdx Length of data in buffer.
  2324. * @return Number of bytes in the ASN.1 data on success.
  2325. * @return BUFFER_E when there is not enough data to parse.
  2326. * @return ASN_PARSE_E when the tag is not a OCTET STRING or length is invalid.
  2327. */
  2328. int GetOctetString(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  2329. {
  2330. return GetASNHeader(input, ASN_OCTET_STRING, inOutIdx, len, maxIdx);
  2331. }
  2332. #ifndef WOLFSSL_ASN_TEMPLATE
  2333. /* Get the DER/BER encoding of an ASN.1 INTEGER header.
  2334. *
  2335. * Removes the leading zero byte when found.
  2336. *
  2337. * input Buffer holding DER/BER encoded data.
  2338. * inOutIdx Current index into buffer to parse.
  2339. * len The number of bytes in the ASN.1 data (excluding any leading zero).
  2340. * maxIdx Length of data in buffer.
  2341. * returns BUFFER_E when there is not enough data to parse.
  2342. * ASN_PARSE_E when the INTEGER tag is not found, length is invalid,
  2343. * or invalid use of or missing leading zero.
  2344. * Otherwise, 0 to indicate success.
  2345. */
  2346. static int GetASNInt(const byte* input, word32* inOutIdx, int* len,
  2347. word32 maxIdx)
  2348. {
  2349. int ret;
  2350. ret = GetASNHeader(input, ASN_INTEGER, inOutIdx, len, maxIdx);
  2351. if (ret < 0)
  2352. return ret;
  2353. if (*len > 0) {
  2354. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2355. /* check for invalid padding on negative integer.
  2356. * c.f. X.690 (ISO/IEC 8825-2:2003 (E)) 10.4.6; RFC 5280 4.1
  2357. */
  2358. if (*len > 1) {
  2359. if ((input[*inOutIdx] == 0xff) && (input[*inOutIdx + 1] & 0x80))
  2360. return ASN_PARSE_E;
  2361. }
  2362. #endif
  2363. /* remove leading zero, unless there is only one 0x00 byte */
  2364. if ((input[*inOutIdx] == 0x00) && (*len > 1)) {
  2365. (*inOutIdx)++;
  2366. (*len)--;
  2367. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2368. if (*len > 0 && (input[*inOutIdx] & 0x80) == 0)
  2369. return ASN_PARSE_E;
  2370. #endif
  2371. }
  2372. }
  2373. return 0;
  2374. }
  2375. #ifndef NO_CERTS
  2376. /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
  2377. * 7 bits.
  2378. *
  2379. * input Buffer holding DER/BER encoded data.
  2380. * inOutIdx Current index into buffer to parse.
  2381. * maxIdx Length of data in buffer.
  2382. * returns BUFFER_E when there is not enough data to parse.
  2383. * ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
  2384. * Otherwise, the 7-bit value.
  2385. */
  2386. static int GetInteger7Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
  2387. {
  2388. word32 idx = *inOutIdx;
  2389. byte b;
  2390. if ((idx + 3) > maxIdx)
  2391. return BUFFER_E;
  2392. if (GetASNTag(input, &idx, &b, maxIdx) != 0)
  2393. return ASN_PARSE_E;
  2394. if (b != ASN_INTEGER)
  2395. return ASN_PARSE_E;
  2396. if (input[idx++] != 1)
  2397. return ASN_PARSE_E;
  2398. b = input[idx++];
  2399. *inOutIdx = idx;
  2400. return b;
  2401. }
  2402. #endif /* !NO_CERTS */
  2403. #if defined(WC_RSA_PSS) && !defined(NO_RSA)
  2404. /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
  2405. * 16 bits.
  2406. *
  2407. * input Buffer holding DER/BER encoded data.
  2408. * inOutIdx Current index into buffer to parse.
  2409. * maxIdx Length of data in buffer.
  2410. * returns BUFFER_E when there is not enough data to parse.
  2411. * ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
  2412. * Otherwise, the 16-bit value.
  2413. */
  2414. static int GetInteger16Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
  2415. {
  2416. word32 idx = *inOutIdx;
  2417. byte tag;
  2418. word16 n;
  2419. if ((idx + 2) > maxIdx)
  2420. return BUFFER_E;
  2421. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2422. return ASN_PARSE_E;
  2423. if (tag != ASN_INTEGER)
  2424. return ASN_PARSE_E;
  2425. if (input[idx] == 1) {
  2426. idx++;
  2427. if ((idx + 1) > maxIdx) {
  2428. return ASN_PARSE_E;
  2429. }
  2430. n = input[idx++];
  2431. }
  2432. else if (input[idx] == 2) {
  2433. idx++;
  2434. if ((idx + 2) > maxIdx) {
  2435. return ASN_PARSE_E;
  2436. }
  2437. n = input[idx++];
  2438. n = (n << 8) | input[idx++];
  2439. }
  2440. else
  2441. return ASN_PARSE_E;
  2442. *inOutIdx = idx;
  2443. return n;
  2444. }
  2445. #endif /* WC_RSA_PSS && !NO_RSA */
  2446. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2447. #if !defined(NO_DSA) && !defined(NO_SHA)
  2448. static const char sigSha1wDsaName[] = "SHAwDSA";
  2449. static const char sigSha256wDsaName[] = "SHA256wDSA";
  2450. #endif /* NO_DSA */
  2451. #ifndef NO_RSA
  2452. #ifdef WOLFSSL_MD2
  2453. static const char sigMd2wRsaName[] = "md2WithRSAEncryption";
  2454. #endif
  2455. #ifndef NO_MD5
  2456. static const char sigMd5wRsaName[] = "md5WithRSAEncryption";
  2457. #endif
  2458. #ifndef NO_SHA
  2459. static const char sigSha1wRsaName[] = "sha1WithRSAEncryption";
  2460. #endif
  2461. #ifdef WOLFSSL_SHA224
  2462. static const char sigSha224wRsaName[] = "sha224WithRSAEncryption";
  2463. #endif
  2464. #ifndef NO_SHA256
  2465. static const char sigSha256wRsaName[] = "sha256WithRSAEncryption";
  2466. #endif
  2467. #ifdef WOLFSSL_SHA384
  2468. static const char sigSha384wRsaName[] = "sha384WithRSAEncryption";
  2469. #endif
  2470. #ifdef WOLFSSL_SHA512
  2471. static const char sigSha512wRsaName[] = "sha512WithRSAEncryption";
  2472. #endif
  2473. #ifdef WOLFSSL_SHA3
  2474. #ifndef WOLFSSL_NOSHA3_224
  2475. static const char sigSha3_224wRsaName[] = "sha3_224WithRSAEncryption";
  2476. #endif
  2477. #ifndef WOLFSSL_NOSHA3_256
  2478. static const char sigSha3_256wRsaName[] = "sha3_256WithRSAEncryption";
  2479. #endif
  2480. #ifndef WOLFSSL_NOSHA3_384
  2481. static const char sigSha3_384wRsaName[] = "sha3_384WithRSAEncryption";
  2482. #endif
  2483. #ifndef WOLFSSL_NOSHA3_512
  2484. static const char sigSha3_512wRsaName[] = "sha3_512WithRSAEncryption";
  2485. #endif
  2486. #endif
  2487. #ifdef WC_RSA_PSS
  2488. static const char sigRsaSsaPssName[] = "rsassaPss";
  2489. #endif
  2490. #endif /* NO_RSA */
  2491. #ifdef HAVE_ECC
  2492. #ifndef NO_SHA
  2493. static const char sigSha1wEcdsaName[] = "SHAwECDSA";
  2494. #endif
  2495. #ifdef WOLFSSL_SHA224
  2496. static const char sigSha224wEcdsaName[] = "SHA224wECDSA";
  2497. #endif
  2498. #ifndef NO_SHA256
  2499. static const char sigSha256wEcdsaName[] = "SHA256wECDSA";
  2500. #endif
  2501. #ifdef WOLFSSL_SHA384
  2502. static const char sigSha384wEcdsaName[] = "SHA384wECDSA";
  2503. #endif
  2504. #ifdef WOLFSSL_SHA512
  2505. static const char sigSha512wEcdsaName[] = "SHA512wECDSA";
  2506. #endif
  2507. #ifdef WOLFSSL_SHA3
  2508. #ifndef WOLFSSL_NOSHA3_224
  2509. static const char sigSha3_224wEcdsaName[] = "SHA3_224wECDSA";
  2510. #endif
  2511. #ifndef WOLFSSL_NOSHA3_256
  2512. static const char sigSha3_256wEcdsaName[] = "SHA3_256wECDSA";
  2513. #endif
  2514. #ifndef WOLFSSL_NOSHA3_384
  2515. static const char sigSha3_384wEcdsaName[] = "SHA3_384wECDSA";
  2516. #endif
  2517. #ifndef WOLFSSL_NOSHA3_512
  2518. static const char sigSha3_512wEcdsaName[] = "SHA3_512wECDSA";
  2519. #endif
  2520. #endif
  2521. #endif /* HAVE_ECC */
  2522. static const char sigUnknownName[] = "Unknown";
  2523. /* Get the human readable string for a signature type
  2524. *
  2525. * oid Oid value for signature
  2526. */
  2527. const char* GetSigName(int oid) {
  2528. switch (oid) {
  2529. #if !defined(NO_DSA) && !defined(NO_SHA)
  2530. case CTC_SHAwDSA:
  2531. return sigSha1wDsaName;
  2532. case CTC_SHA256wDSA:
  2533. return sigSha256wDsaName;
  2534. #endif /* NO_DSA && NO_SHA */
  2535. #ifndef NO_RSA
  2536. #ifdef WOLFSSL_MD2
  2537. case CTC_MD2wRSA:
  2538. return sigMd2wRsaName;
  2539. #endif
  2540. #ifndef NO_MD5
  2541. case CTC_MD5wRSA:
  2542. return sigMd5wRsaName;
  2543. #endif
  2544. #ifndef NO_SHA
  2545. case CTC_SHAwRSA:
  2546. return sigSha1wRsaName;
  2547. #endif
  2548. #ifdef WOLFSSL_SHA224
  2549. case CTC_SHA224wRSA:
  2550. return sigSha224wRsaName;
  2551. #endif
  2552. #ifndef NO_SHA256
  2553. case CTC_SHA256wRSA:
  2554. return sigSha256wRsaName;
  2555. #endif
  2556. #ifdef WOLFSSL_SHA384
  2557. case CTC_SHA384wRSA:
  2558. return sigSha384wRsaName;
  2559. #endif
  2560. #ifdef WOLFSSL_SHA512
  2561. case CTC_SHA512wRSA:
  2562. return sigSha512wRsaName;
  2563. #endif
  2564. #ifdef WOLFSSL_SHA3
  2565. #ifndef WOLFSSL_NOSHA3_224
  2566. case CTC_SHA3_224wRSA:
  2567. return sigSha3_224wRsaName;
  2568. #endif
  2569. #ifndef WOLFSSL_NOSHA3_256
  2570. case CTC_SHA3_256wRSA:
  2571. return sigSha3_256wRsaName;
  2572. #endif
  2573. #ifndef WOLFSSL_NOSHA3_384
  2574. case CTC_SHA3_384wRSA:
  2575. return sigSha3_384wRsaName;
  2576. #endif
  2577. #ifndef WOLFSSL_NOSHA3_512
  2578. case CTC_SHA3_512wRSA:
  2579. return sigSha3_512wRsaName;
  2580. #endif
  2581. #endif
  2582. #ifdef WC_RSA_PSS
  2583. case CTC_RSASSAPSS:
  2584. return sigRsaSsaPssName;
  2585. #endif
  2586. #endif /* NO_RSA */
  2587. #ifdef HAVE_ECC
  2588. #ifndef NO_SHA
  2589. case CTC_SHAwECDSA:
  2590. return sigSha1wEcdsaName;
  2591. #endif
  2592. #ifdef WOLFSSL_SHA224
  2593. case CTC_SHA224wECDSA:
  2594. return sigSha224wEcdsaName;
  2595. #endif
  2596. #ifndef NO_SHA256
  2597. case CTC_SHA256wECDSA:
  2598. return sigSha256wEcdsaName;
  2599. #endif
  2600. #ifdef WOLFSSL_SHA384
  2601. case CTC_SHA384wECDSA:
  2602. return sigSha384wEcdsaName;
  2603. #endif
  2604. #ifdef WOLFSSL_SHA512
  2605. case CTC_SHA512wECDSA:
  2606. return sigSha512wEcdsaName;
  2607. #endif
  2608. #ifdef WOLFSSL_SHA3
  2609. #ifndef WOLFSSL_NOSHA3_224
  2610. case CTC_SHA3_224wECDSA:
  2611. return sigSha3_224wEcdsaName;
  2612. #endif
  2613. #ifndef WOLFSSL_NOSHA3_256
  2614. case CTC_SHA3_256wECDSA:
  2615. return sigSha3_256wEcdsaName;
  2616. #endif
  2617. #ifndef WOLFSSL_NOSHA3_384
  2618. case CTC_SHA3_384wECDSA:
  2619. return sigSha3_384wEcdsaName;
  2620. #endif
  2621. #ifndef WOLFSSL_NOSHA3_512
  2622. case CTC_SHA3_512wECDSA:
  2623. return sigSha3_512wEcdsaName;
  2624. #endif
  2625. #endif
  2626. #endif /* HAVE_ECC */
  2627. default:
  2628. return sigUnknownName;
  2629. }
  2630. }
  2631. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7) || \
  2632. defined(OPENSSL_EXTRA)
  2633. #if !defined(NO_DSA) || defined(HAVE_ECC) || !defined(NO_CERTS) || \
  2634. (!defined(NO_RSA) && \
  2635. (defined(WOLFSSL_CERT_GEN) || \
  2636. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA))))
  2637. /* Set the DER/BER encoding of the ASN.1 INTEGER header.
  2638. *
  2639. * When output is NULL, calculate the header length only.
  2640. *
  2641. * @param [in] len Length of INTEGER data in bytes.
  2642. * @param [in] firstByte First byte of data, most significant byte of integer,
  2643. * to encode.
  2644. * @param [out] output Buffer to write into.
  2645. * @return Number of bytes added to the buffer.
  2646. */
  2647. int SetASNInt(int len, byte firstByte, byte* output)
  2648. {
  2649. int idx = 0;
  2650. if (output) {
  2651. /* Write out tag. */
  2652. output[idx] = ASN_INTEGER;
  2653. }
  2654. /* Step over tag. */
  2655. idx += ASN_TAG_SZ;
  2656. /* Check if first byte has top bit set in which case a 0 is needed to
  2657. * maintain positive value. */
  2658. if (firstByte & 0x80) {
  2659. /* Add pre-prepended byte to length of data in INTEGER. */
  2660. len++;
  2661. }
  2662. /* Encode length - passing NULL for output will not encode. */
  2663. idx += (int)SetLength((word32)len, output ? output + idx : NULL);
  2664. /* Put out prepended 0 as well. */
  2665. if (firstByte & 0x80) {
  2666. if (output) {
  2667. /* Write out 0 byte. */
  2668. output[idx] = 0x00;
  2669. }
  2670. /* Update index. */
  2671. idx++;
  2672. }
  2673. /* Return index after header. */
  2674. return idx;
  2675. }
  2676. #endif
  2677. #endif
  2678. #ifndef WOLFSSL_ASN_TEMPLATE
  2679. #if !defined(NO_DSA) || defined(HAVE_ECC) || (defined(WOLFSSL_CERT_GEN) && \
  2680. !defined(NO_RSA)) || ((defined(WOLFSSL_KEY_GEN) || \
  2681. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)) || \
  2682. defined(OPENSSL_EXTRA)) && !defined(NO_RSA) && !defined(HAVE_USER_RSA))
  2683. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int.
  2684. * The number is assumed to be positive.
  2685. *
  2686. * n Multi-precision integer to encode.
  2687. * maxSz Maximum size of the encoded integer.
  2688. * A negative value indicates no check of length requested.
  2689. * output Buffer to write into.
  2690. * returns BUFFER_E when the data is too long for the buffer.
  2691. * MP_TO_E when encoding the integer fails.
  2692. * Otherwise, the number of bytes added to the buffer.
  2693. */
  2694. static int SetASNIntMP(mp_int* n, int maxSz, byte* output)
  2695. {
  2696. int idx = 0;
  2697. int leadingBit;
  2698. int length;
  2699. leadingBit = mp_leading_bit(n);
  2700. length = mp_unsigned_bin_size(n);
  2701. if (maxSz >= 0 && (1 + length + (leadingBit ? 1 : 0)) > maxSz)
  2702. return BUFFER_E;
  2703. idx = SetASNInt(length, (byte)(leadingBit ? 0x80U : 0x00U), output);
  2704. if (maxSz >= 0 && (idx + length) > maxSz)
  2705. return BUFFER_E;
  2706. if (output) {
  2707. int err = mp_to_unsigned_bin(n, output + idx);
  2708. if (err != MP_OKAY)
  2709. return MP_TO_E;
  2710. }
  2711. idx += length;
  2712. return idx;
  2713. }
  2714. #endif
  2715. #if !defined(NO_RSA) && defined(HAVE_USER_RSA) && \
  2716. (defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA))
  2717. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int from
  2718. * an RSA key.
  2719. * The number is assumed to be positive.
  2720. *
  2721. * n Multi-precision integer to encode.
  2722. * output Buffer to write into.
  2723. * returns BUFFER_E when the data is too long for the buffer.
  2724. * MP_TO_E when encoding the integer fails.
  2725. * Otherwise, the number of bytes added to the buffer.
  2726. */
  2727. static int SetASNIntRSA(void* n, byte* output)
  2728. {
  2729. int idx = 0;
  2730. int leadingBit;
  2731. int length;
  2732. leadingBit = wc_Rsa_leading_bit(n);
  2733. length = wc_Rsa_unsigned_bin_size(n);
  2734. idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output);
  2735. if ((idx + length) > MAX_RSA_INT_SZ)
  2736. return BUFFER_E;
  2737. if (output) {
  2738. int err = wc_Rsa_to_unsigned_bin(n, output + idx, length);
  2739. if (err != MP_OKAY)
  2740. return MP_TO_E;
  2741. }
  2742. idx += length;
  2743. return idx;
  2744. }
  2745. #endif /* !NO_RSA && HAVE_USER_RSA && WOLFSSL_CERT_GEN */
  2746. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2747. #ifdef WOLFSSL_ASN_TEMPLATE
  2748. /* ASN.1 template for an INTEGER. */
  2749. static const ASNItem intASN[] = {
  2750. /* INT */ { 0, ASN_INTEGER, 0, 0, 0 }
  2751. };
  2752. enum {
  2753. INTASN_IDX_INT = 0
  2754. };
  2755. /* Number of items in ASN.1 template for an INTEGER. */
  2756. #define intASN_Length (sizeof(intASN) / sizeof(ASNItem))
  2757. #endif /* WOLFSSL_ASN_TEMPLATE */
  2758. /* Windows header clash for WinCE using GetVersion */
  2759. /* Decode Version - one byte INTEGER.
  2760. *
  2761. * @param [in] input Buffer of BER data.
  2762. * @param [in, out] inOutIdx On in, start of encoded Version.
  2763. * On out, start of next encode ASN.1 item.
  2764. * @param [out] version Number encoded in INTEGER.
  2765. * @param [in] maxIdx Maximum index of data in buffer.
  2766. * @return 0 on success.
  2767. * @return ASN_PARSE_E when encoding is invalid.
  2768. * @return BUFFER_E when data in buffer is too small.
  2769. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2770. */
  2771. int GetMyVersion(const byte* input, word32* inOutIdx,
  2772. int* version, word32 maxIdx)
  2773. {
  2774. #ifndef WOLFSSL_ASN_TEMPLATE
  2775. word32 idx = *inOutIdx;
  2776. byte tag;
  2777. if ((idx + MIN_VERSION_SZ) > maxIdx)
  2778. return ASN_PARSE_E;
  2779. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2780. return ASN_PARSE_E;
  2781. if (tag != ASN_INTEGER)
  2782. return ASN_PARSE_E;
  2783. if (input[idx++] != 0x01)
  2784. return ASN_VERSION_E;
  2785. *version = input[idx++];
  2786. *inOutIdx = idx;
  2787. return *version;
  2788. #else
  2789. ASNGetData dataASN[intASN_Length];
  2790. int ret;
  2791. byte num;
  2792. /* Clear dynamic data and set the version number variable. */
  2793. XMEMSET(dataASN, 0, sizeof(dataASN));
  2794. GetASN_Int8Bit(&dataASN[INTASN_IDX_INT], &num);
  2795. /* Decode the version (INTEGER). */
  2796. ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2797. maxIdx);
  2798. if (ret == 0) {
  2799. /* Return version through variable and return value. */
  2800. *version = num;
  2801. ret = num;
  2802. }
  2803. return ret;
  2804. #endif /* WOLFSSL_ASN_TEMPLATE */
  2805. }
  2806. #ifndef NO_PWDBASED
  2807. /* Decode small integer, 32 bits or less.
  2808. *
  2809. * @param [in] input Buffer of BER data.
  2810. * @param [in, out] inOutIdx On in, start of encoded INTEGER.
  2811. * On out, start of next encode ASN.1 item.
  2812. * @param [out] number Number encoded in INTEGER.
  2813. * @param [in] maxIdx Maximum index of data in buffer.
  2814. * @return 0 on success.
  2815. * @return ASN_PARSE_E when encoding is invalid.
  2816. * @return BUFFER_E when data in buffer is too small.
  2817. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2818. */
  2819. int GetShortInt(const byte* input, word32* inOutIdx, int* number, word32 maxIdx)
  2820. {
  2821. #ifndef WOLFSSL_ASN_TEMPLATE
  2822. word32 idx = *inOutIdx;
  2823. word32 len;
  2824. byte tag;
  2825. *number = 0;
  2826. /* check for type and length bytes */
  2827. if ((idx + 2) > maxIdx)
  2828. return BUFFER_E;
  2829. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2830. return ASN_PARSE_E;
  2831. if (tag != ASN_INTEGER)
  2832. return ASN_PARSE_E;
  2833. len = input[idx++];
  2834. if (len > 4)
  2835. return ASN_PARSE_E;
  2836. if (len + idx > maxIdx)
  2837. return ASN_PARSE_E;
  2838. while (len--) {
  2839. *number = *number << 8 | input[idx++];
  2840. }
  2841. *inOutIdx = idx;
  2842. return *number;
  2843. #else
  2844. ASNGetData dataASN[intASN_Length];
  2845. int ret;
  2846. word32 num;
  2847. /* Clear dynamic data and set the 32-bit number variable. */
  2848. XMEMSET(dataASN, 0, sizeof(dataASN));
  2849. GetASN_Int32Bit(&dataASN[INTASN_IDX_INT], &num);
  2850. /* Decode the short int (INTEGER). */
  2851. ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2852. maxIdx);
  2853. if (ret == 0) {
  2854. /* Return number through variable and return value. */
  2855. *number = (int)num;
  2856. ret = (int)num;
  2857. }
  2858. return ret;
  2859. #endif
  2860. }
  2861. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS8) || \
  2862. defined(HAVE_PKCS12)
  2863. /* Set small integer, 32 bits or less. DER encoding with no leading 0s
  2864. * returns total amount written including ASN tag and length byte on success */
  2865. int SetShortInt(byte* input, word32* inOutIdx, word32 number, word32 maxIdx)
  2866. {
  2867. word32 idx = *inOutIdx;
  2868. int len = 0;
  2869. int i;
  2870. byte ar[MAX_LENGTH_SZ];
  2871. /* check for room for type and length bytes */
  2872. if ((idx + 2) > maxIdx)
  2873. return BUFFER_E;
  2874. input[idx++] = ASN_INTEGER;
  2875. idx++; /* place holder for length byte */
  2876. if (MAX_LENGTH_SZ + idx > maxIdx)
  2877. return ASN_PARSE_E;
  2878. /* find first non zero byte */
  2879. XMEMSET(ar, 0, MAX_LENGTH_SZ);
  2880. c32toa(number, ar);
  2881. for (i = 0; i < MAX_LENGTH_SZ; i++) {
  2882. if (ar[i] != 0) {
  2883. break;
  2884. }
  2885. }
  2886. /* handle case of 0 */
  2887. if (i == MAX_LENGTH_SZ) {
  2888. input[idx++] = 0; len++;
  2889. }
  2890. for (; i < MAX_LENGTH_SZ && idx < maxIdx; i++) {
  2891. input[idx++] = ar[i]; len++;
  2892. }
  2893. /* jump back to beginning of input buffer using unaltered inOutIdx value
  2894. * and set number of bytes for integer, then update the index value */
  2895. input[*inOutIdx + 1] = (byte)len;
  2896. *inOutIdx = idx;
  2897. return len + 2; /* size of integer bytes plus ASN TAG and length byte */
  2898. }
  2899. #endif /* !WOLFSSL_ASN_TEMPLATE || HAVE_PKCS8 || HAVE_PKCS12 */
  2900. #endif /* !NO_PWDBASED */
  2901. #if !defined(WOLFSSL_ASN_TEMPLATE) && !defined(NO_CERTS)
  2902. /* May not have one, not an error */
  2903. static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version,
  2904. word32 maxIdx)
  2905. {
  2906. word32 idx = *inOutIdx;
  2907. byte tag;
  2908. WOLFSSL_ENTER("GetExplicitVersion");
  2909. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2910. return ASN_PARSE_E;
  2911. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  2912. int ret;
  2913. *inOutIdx = ++idx; /* skip header */
  2914. ret = GetMyVersion(input, inOutIdx, version, maxIdx);
  2915. if (ret >= 0) {
  2916. /* check if version is expected value rfc 5280 4.1 {0, 1, 2} */
  2917. if (*version > MAX_X509_VERSION || *version < MIN_X509_VERSION) {
  2918. WOLFSSL_MSG("Unexpected certificate version");
  2919. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  2920. ret = ASN_VERSION_E;
  2921. }
  2922. }
  2923. return ret;
  2924. }
  2925. /* go back as is */
  2926. *version = 0;
  2927. return 0;
  2928. }
  2929. #endif
  2930. /* Decode small integer, 32 bits or less.
  2931. *
  2932. * mp_int is initialized.
  2933. *
  2934. * @param [out] mpi mp_int to hold number.
  2935. * @param [in] input Buffer of BER data.
  2936. * @param [in, out] inOutIdx On in, start of encoded INTEGER.
  2937. * On out, start of next encode ASN.1 item.
  2938. * @param [in] maxIdx Maximum index of data in buffer.
  2939. * @return 0 on success.
  2940. * @return ASN_PARSE_E when encoding is invalid.
  2941. * @return BUFFER_E when data in buffer is too small.
  2942. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2943. * @return MP_INIT_E when the unable to initialize an mp_int.
  2944. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  2945. */
  2946. int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, word32 maxIdx)
  2947. {
  2948. #ifndef WOLFSSL_ASN_TEMPLATE
  2949. word32 idx = *inOutIdx;
  2950. int ret;
  2951. int length;
  2952. ret = GetASNInt(input, &idx, &length, maxIdx);
  2953. if (ret != 0)
  2954. return ret;
  2955. if (mp_init(mpi) != MP_OKAY)
  2956. return MP_INIT_E;
  2957. if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) {
  2958. mp_clear(mpi);
  2959. return ASN_GETINT_E;
  2960. }
  2961. #ifdef HAVE_WOLF_BIGINT
  2962. if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
  2963. mp_clear(mpi);
  2964. return ASN_GETINT_E;
  2965. }
  2966. #endif /* HAVE_WOLF_BIGINT */
  2967. *inOutIdx = idx + (word32)length;
  2968. return 0;
  2969. #else
  2970. ASNGetData dataASN[intASN_Length];
  2971. /* Clear dynamic data and set the mp_int to fill with value. */
  2972. XMEMSET(dataASN, 0, sizeof(dataASN));
  2973. GetASN_MP_PosNeg(&dataASN[INTASN_IDX_INT], mpi);
  2974. /* Decode the big number (INTEGER). */
  2975. return GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2976. maxIdx);
  2977. #endif
  2978. }
  2979. #if (defined(HAVE_ECC) || !defined(NO_DSA)) && !defined(WOLFSSL_ASN_TEMPLATE)
  2980. static int GetIntPositive(mp_int* mpi, const byte* input, word32* inOutIdx,
  2981. word32 maxIdx, int initNum)
  2982. {
  2983. word32 idx = *inOutIdx;
  2984. int ret;
  2985. int length;
  2986. ret = GetASNInt(input, &idx, &length, maxIdx);
  2987. if (ret != 0)
  2988. return ret;
  2989. if (((input[idx] & 0x80) == 0x80) && (input[idx - 1] != 0x00))
  2990. return MP_INIT_E;
  2991. if (initNum) {
  2992. if (mp_init(mpi) != MP_OKAY)
  2993. return MP_INIT_E;
  2994. }
  2995. if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) {
  2996. mp_clear(mpi);
  2997. return ASN_GETINT_E;
  2998. }
  2999. #ifdef HAVE_WOLF_BIGINT
  3000. if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
  3001. mp_clear(mpi);
  3002. return ASN_GETINT_E;
  3003. }
  3004. #endif /* HAVE_WOLF_BIGINT */
  3005. *inOutIdx = idx + (word32)length;
  3006. return 0;
  3007. }
  3008. #endif /* (ECC || !NO_DSA) && !WOLFSSL_ASN_TEMPLATE */
  3009. #ifndef WOLFSSL_ASN_TEMPLATE
  3010. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA)) || !defined(NO_DSA)
  3011. static int SkipInt(const byte* input, word32* inOutIdx, word32 maxIdx)
  3012. {
  3013. word32 idx = *inOutIdx;
  3014. int ret;
  3015. int length;
  3016. ret = GetASNInt(input, &idx, &length, maxIdx);
  3017. if (ret != 0)
  3018. return ret;
  3019. *inOutIdx = idx + (word32)length;
  3020. return 0;
  3021. }
  3022. #endif
  3023. #endif /* !WOLFSSL_ASN_TEMPLATE */
  3024. #ifdef WOLFSSL_ASN_TEMPLATE
  3025. /* ASN.1 template for a BIT_STRING. */
  3026. static const ASNItem bitStringASN[] = {
  3027. /* BIT_STR */ { 0, ASN_BIT_STRING, 0, 1, 0 }
  3028. };
  3029. enum {
  3030. BITSTRINGASN_IDX_BIT_STR = 0
  3031. };
  3032. /* Number of items in ASN.1 template for a BIT_STRING. */
  3033. #define bitStringASN_Length (sizeof(bitStringASN) / sizeof(ASNItem))
  3034. #endif
  3035. /* Decode and check the BIT_STRING is valid. Return length and unused bits.
  3036. *
  3037. * @param [in] input Buffer holding BER encoding.
  3038. * @param [in, out] inOutIdx On in, start of BIT_STRING.
  3039. * On out, start of ASN.1 item after BIT_STRING.
  3040. * @param [out] len Length of BIT_STRING data.
  3041. * @param [in] maxIdx Maximum index of data in buffer.
  3042. * @param [in] zeroBits Indicates whether zero unused bits is expected.
  3043. * @param [in] unusedBits Number of unused bits in last byte.
  3044. * @return 0 on success.
  3045. * @return ASN_PARSE_E when encoding is invalid.
  3046. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  3047. * @return BUFFER_E when data in buffer is too small.
  3048. * @return ASN_EXPECT_0_E when unused bits is not zero when expected.
  3049. */
  3050. int CheckBitString(const byte* input, word32* inOutIdx, int* len,
  3051. word32 maxIdx, int zeroBits, byte* unusedBits)
  3052. {
  3053. #ifndef WOLFSSL_ASN_TEMPLATE
  3054. word32 idx = *inOutIdx;
  3055. int length;
  3056. byte b;
  3057. if (GetASNTag(input, &idx, &b, maxIdx) != 0) {
  3058. return ASN_BITSTR_E;
  3059. }
  3060. if (b != ASN_BIT_STRING) {
  3061. return ASN_BITSTR_E;
  3062. }
  3063. if (GetLength(input, &idx, &length, maxIdx) < 0)
  3064. return ASN_PARSE_E;
  3065. /* extra sanity check that length is greater than 0 */
  3066. if (length <= 0) {
  3067. WOLFSSL_MSG("Error length was 0 in CheckBitString");
  3068. return BUFFER_E;
  3069. }
  3070. if (idx + 1 > maxIdx) {
  3071. WOLFSSL_MSG("Attempted buffer read larger than input buffer");
  3072. return BUFFER_E;
  3073. }
  3074. b = input[idx];
  3075. if (zeroBits && b != 0x00)
  3076. return ASN_EXPECT_0_E;
  3077. if (b >= 0x08)
  3078. return ASN_PARSE_E;
  3079. if (b != 0) {
  3080. if ((byte)(input[idx + (word32)length - 1] << (8 - b)) != 0)
  3081. return ASN_PARSE_E;
  3082. }
  3083. idx++;
  3084. length--; /* length has been checked for greater than 0 */
  3085. *inOutIdx = idx;
  3086. if (len != NULL)
  3087. *len = length;
  3088. if (unusedBits != NULL)
  3089. *unusedBits = b;
  3090. return 0;
  3091. #else
  3092. ASNGetData dataASN[bitStringASN_Length];
  3093. int ret;
  3094. int bits;
  3095. /* Parse BIT_STRING and check validity of unused bits. */
  3096. XMEMSET(dataASN, 0, sizeof(dataASN));
  3097. /* Decode BIT_STRING. */
  3098. ret = GetASN_Items(bitStringASN, dataASN, bitStringASN_Length, 0, input,
  3099. inOutIdx, maxIdx);
  3100. if (ret == 0) {
  3101. /* Get unused bits from dynamic ASN.1 data. */
  3102. bits = GetASNItem_UnusedBits(dataASN[BITSTRINGASN_IDX_BIT_STR]);
  3103. /* Check unused bits is 0 when expected. */
  3104. if (zeroBits && (bits != 0)) {
  3105. ret = ASN_EXPECT_0_E;
  3106. }
  3107. }
  3108. if (ret == 0) {
  3109. /* Return length of data and unused bits if required. */
  3110. if (len != NULL) {
  3111. *len = (int)dataASN[BITSTRINGASN_IDX_BIT_STR].data.ref.length;
  3112. }
  3113. if (unusedBits != NULL) {
  3114. *unusedBits = (byte)bits;
  3115. }
  3116. }
  3117. return ret;
  3118. #endif
  3119. }
  3120. /* RSA (with CertGen or KeyGen) OR ECC OR ED25519 OR ED448 (with CertGen or
  3121. * KeyGen) */
  3122. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
  3123. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
  3124. defined(OPENSSL_EXTRA))) || \
  3125. (defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)) || \
  3126. ((defined(HAVE_ED25519) || defined(HAVE_ED448)) && \
  3127. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
  3128. defined(OPENSSL_EXTRA))) || \
  3129. (defined(WC_ENABLE_ASYM_KEY_EXPORT) && !defined(NO_CERT)) || \
  3130. (!defined(NO_DSA) && !defined(HAVE_SELFTEST) && defined(WOLFSSL_KEY_GEN)) || \
  3131. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA))
  3132. /* Set the DER/BER encoding of the ASN.1 BIT STRING header.
  3133. *
  3134. * When output is NULL, calculate the header length only.
  3135. *
  3136. * @param [in] len Length of BIT STRING data.
  3137. * That is, the number of least significant zero bits
  3138. * before a one.
  3139. * The last byte is the most-significant non-zero byte
  3140. * of a number.
  3141. * @param [out] output Buffer to write into.
  3142. * @return Number of bytes added to the buffer.
  3143. */
  3144. word32 SetBitString(word32 len, byte unusedBits, byte* output)
  3145. {
  3146. word32 idx = 0;
  3147. if (output) {
  3148. /* Write out tag. */
  3149. output[idx] = ASN_BIT_STRING;
  3150. }
  3151. /* Step over tag. */
  3152. idx += ASN_TAG_SZ;
  3153. /* Encode length - passing NULL for output will not encode.
  3154. * Add one to length for unused bits. */
  3155. idx += SetLength(len + 1, output ? output + idx : NULL);
  3156. if (output) {
  3157. /* Write out unused bits. */
  3158. output[idx] = unusedBits;
  3159. }
  3160. /* Skip over unused bits. */
  3161. idx++;
  3162. /* Return index after header. */
  3163. return idx;
  3164. }
  3165. #endif /* !NO_RSA || HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  3166. #ifdef ASN_BER_TO_DER
  3167. /* Convert BER to DER */
  3168. /* Pull informtation from the ASN.1 BER encoded item header */
  3169. static int GetBerHeader(const byte* data, word32* idx, word32 maxIdx,
  3170. byte* pTag, word32* pLen, int* indef)
  3171. {
  3172. int len = 0;
  3173. byte tag;
  3174. word32 i = *idx;
  3175. *indef = 0;
  3176. /* Check there is enough data for a minimal header */
  3177. if (i + 2 > maxIdx) {
  3178. return ASN_PARSE_E;
  3179. }
  3180. /* Retrieve tag */
  3181. tag = data[i++];
  3182. /* Indefinite length handled specially */
  3183. if (data[i] == ASN_INDEF_LENGTH) {
  3184. /* Check valid tag for indefinite */
  3185. if (((tag & 0xc0) == 0) && ((tag & ASN_CONSTRUCTED) == 0x00)) {
  3186. return ASN_PARSE_E;
  3187. }
  3188. i++;
  3189. *indef = 1;
  3190. }
  3191. else if (GetLength(data, &i, &len, maxIdx) < 0) {
  3192. return ASN_PARSE_E;
  3193. }
  3194. /* Return tag, length and index after BER item header */
  3195. *pTag = tag;
  3196. *pLen = (word32)len;
  3197. *idx = i;
  3198. return 0;
  3199. }
  3200. #ifndef INDEF_ITEMS_MAX
  3201. #define INDEF_ITEMS_MAX 20
  3202. #endif
  3203. /* Indef length item data */
  3204. typedef struct Indef {
  3205. word32 start;
  3206. int depth;
  3207. int headerLen;
  3208. word32 len;
  3209. } Indef;
  3210. /* Indef length items */
  3211. typedef struct IndefItems
  3212. {
  3213. Indef len[INDEF_ITEMS_MAX];
  3214. int cnt;
  3215. int idx;
  3216. int depth;
  3217. } IndefItems;
  3218. /* Get header length of current item */
  3219. static int IndefItems_HeaderLen(IndefItems* items)
  3220. {
  3221. return items->len[items->idx].headerLen;
  3222. }
  3223. /* Get data length of current item */
  3224. static word32 IndefItems_Len(IndefItems* items)
  3225. {
  3226. return items->len[items->idx].len;
  3227. }
  3228. /* Add a indefinite length item */
  3229. static int IndefItems_AddItem(IndefItems* items, word32 start)
  3230. {
  3231. int ret = 0;
  3232. int i;
  3233. if (items->cnt == INDEF_ITEMS_MAX) {
  3234. ret = MEMORY_E;
  3235. }
  3236. else {
  3237. i = items->cnt++;
  3238. items->len[i].start = start;
  3239. items->len[i].depth = items->depth++;
  3240. items->len[i].headerLen = 1;
  3241. items->len[i].len = 0;
  3242. items->idx = i;
  3243. }
  3244. return ret;
  3245. }
  3246. /* Increase data length of current item */
  3247. static void IndefItems_AddData(IndefItems* items, word32 length)
  3248. {
  3249. items->len[items->idx].len += length;
  3250. }
  3251. /* Update header length of current item to reflect data length */
  3252. static void IndefItems_UpdateHeaderLen(IndefItems* items)
  3253. {
  3254. items->len[items->idx].headerLen +=
  3255. (int)SetLength(items->len[items->idx].len, NULL);
  3256. }
  3257. /* Go to indefinite parent of current item */
  3258. static void IndefItems_Up(IndefItems* items)
  3259. {
  3260. int i;
  3261. int depth = items->len[items->idx].depth - 1;
  3262. for (i = items->cnt - 1; i >= 0; i--) {
  3263. if (items->len[i].depth == depth) {
  3264. break;
  3265. }
  3266. }
  3267. items->idx = i;
  3268. items->depth = depth + 1;
  3269. }
  3270. /* Calculate final length by adding length of indefinite child items */
  3271. static void IndefItems_CalcLength(IndefItems* items)
  3272. {
  3273. int i;
  3274. int idx = items->idx;
  3275. for (i = idx + 1; i < items->cnt; i++) {
  3276. if (items->len[i].depth == items->depth) {
  3277. items->len[idx].len += (word32)items->len[i].headerLen;
  3278. items->len[idx].len += items->len[i].len;
  3279. }
  3280. }
  3281. items->len[idx].headerLen += (int)SetLength(items->len[idx].len, NULL);
  3282. }
  3283. /* Add more data to indefinite length item */
  3284. static void IndefItems_MoreData(IndefItems* items, word32 length)
  3285. {
  3286. if (items->cnt > 0 && items->idx >= 0) {
  3287. items->len[items->idx].len += length;
  3288. }
  3289. }
  3290. /* Convert a BER encoding with indefinite length items to DER.
  3291. *
  3292. * ber BER encoded data.
  3293. * berSz Length of BER encoded data.
  3294. * der Buffer to hold DER encoded version of data.
  3295. * NULL indicates only the length is required.
  3296. * derSz The size of the buffer to hold the DER encoded data.
  3297. * Will be set if der is NULL, otherwise the value is checked as der is
  3298. * filled.
  3299. * returns ASN_PARSE_E if the BER data is invalid and BAD_FUNC_ARG if ber or
  3300. * derSz are NULL.
  3301. */
  3302. int wc_BerToDer(const byte* ber, word32 berSz, byte* der, word32* derSz)
  3303. {
  3304. int ret = 0;
  3305. word32 i, j;
  3306. #ifdef WOLFSSL_SMALL_STACK
  3307. IndefItems* indefItems = NULL;
  3308. #else
  3309. IndefItems indefItems[1];
  3310. #endif
  3311. byte tag, basic;
  3312. word32 length;
  3313. int indef;
  3314. if (ber == NULL || derSz == NULL)
  3315. return BAD_FUNC_ARG;
  3316. #ifdef WOLFSSL_SMALL_STACK
  3317. indefItems = (IndefItems *)XMALLOC(sizeof(IndefItems), NULL,
  3318. DYNAMIC_TYPE_TMP_BUFFER);
  3319. if (indefItems == NULL) {
  3320. ret = MEMORY_E;
  3321. goto end;
  3322. }
  3323. #endif
  3324. XMEMSET(indefItems, 0, sizeof(*indefItems));
  3325. /* Calculate indefinite item lengths */
  3326. for (i = 0; i < berSz; ) {
  3327. word32 start = i;
  3328. /* Get next BER item */
  3329. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3330. if (ret != 0) {
  3331. goto end;
  3332. }
  3333. if (indef) {
  3334. /* Indefinite item - add to list */
  3335. ret = IndefItems_AddItem(indefItems, i);
  3336. if (ret != 0) {
  3337. goto end;
  3338. }
  3339. if ((tag & 0xC0) == 0 &&
  3340. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3341. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3342. /* Constructed basic type - get repeating tag */
  3343. basic = (byte)(tag & (~ASN_CONSTRUCTED));
  3344. /* Add up lengths of each item below */
  3345. for (; i < berSz; ) {
  3346. /* Get next BER_item */
  3347. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3348. if (ret != 0) {
  3349. goto end;
  3350. }
  3351. /* End of content closes item */
  3352. if (tag == ASN_EOC) {
  3353. /* Must be zero length */
  3354. if (length != 0) {
  3355. ret = ASN_PARSE_E;
  3356. goto end;
  3357. }
  3358. break;
  3359. }
  3360. /* Must not be indefinite and tag must match parent */
  3361. if (indef || tag != basic) {
  3362. ret = ASN_PARSE_E;
  3363. goto end;
  3364. }
  3365. /* Add to length */
  3366. IndefItems_AddData(indefItems, length);
  3367. /* Skip data */
  3368. i += length;
  3369. }
  3370. /* Ensure we got an EOC and not end of data */
  3371. if (tag != ASN_EOC) {
  3372. ret = ASN_PARSE_E;
  3373. goto end;
  3374. }
  3375. /* Set the header length to include the length field */
  3376. IndefItems_UpdateHeaderLen(indefItems);
  3377. /* Go to indefinite parent item */
  3378. IndefItems_Up(indefItems);
  3379. }
  3380. }
  3381. else if (tag == ASN_EOC) {
  3382. /* End-of-content must be 0 length */
  3383. if (length != 0) {
  3384. ret = ASN_PARSE_E;
  3385. goto end;
  3386. }
  3387. /* Check there is an item to close - missing EOC */
  3388. if (indefItems->depth == 0) {
  3389. ret = ASN_PARSE_E;
  3390. goto end;
  3391. }
  3392. /* Finish calculation of data length for indefinite item */
  3393. IndefItems_CalcLength(indefItems);
  3394. /* Go to indefinite parent item */
  3395. IndefItems_Up(indefItems);
  3396. }
  3397. else {
  3398. /* Known length item to add in - make sure enough data for it */
  3399. if (i + length > berSz) {
  3400. ret = ASN_PARSE_E;
  3401. goto end;
  3402. }
  3403. /* Include all data - can't have indefinite inside definite */
  3404. i += length;
  3405. /* Add entire item to current indefinite item */
  3406. IndefItems_MoreData(indefItems, i - start);
  3407. }
  3408. }
  3409. /* Check we had a EOC for each indefinite item */
  3410. if (indefItems->depth != 0) {
  3411. ret = ASN_PARSE_E;
  3412. goto end;
  3413. }
  3414. /* Write out DER */
  3415. j = 0;
  3416. /* Reset index */
  3417. indefItems->idx = 0;
  3418. for (i = 0; i < berSz; ) {
  3419. word32 start = i;
  3420. /* Get item - checked above */
  3421. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3422. if (indef) {
  3423. if (der != NULL) {
  3424. /* Check enough space for header */
  3425. if (j + (word32)IndefItems_HeaderLen(indefItems) > *derSz) {
  3426. ret = BUFFER_E;
  3427. goto end;
  3428. }
  3429. if ((tag & 0xC0) == 0 &&
  3430. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3431. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3432. /* Remove constructed tag for basic types */
  3433. tag &= (byte)~ASN_CONSTRUCTED;
  3434. }
  3435. /* Add tag and length */
  3436. der[j] = tag;
  3437. (void)SetLength(IndefItems_Len(indefItems), der + j + 1);
  3438. }
  3439. /* Add header length of indefinite item */
  3440. j += (word32)IndefItems_HeaderLen(indefItems);
  3441. if ((tag & 0xC0) == 0 &&
  3442. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3443. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3444. /* For basic type - get each child item and add data */
  3445. for (; i < berSz; ) {
  3446. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3447. if (tag == ASN_EOC) {
  3448. break;
  3449. }
  3450. if (der != NULL) {
  3451. if (j + length > *derSz) {
  3452. ret = BUFFER_E;
  3453. goto end;
  3454. }
  3455. XMEMCPY(der + j, ber + i, length);
  3456. }
  3457. j += length;
  3458. i += length;
  3459. }
  3460. }
  3461. /* Move to next indef item in list */
  3462. indefItems->idx++;
  3463. }
  3464. else if (tag == ASN_EOC) {
  3465. /* End-Of-Content is not written out in DER */
  3466. }
  3467. else {
  3468. /* Write out definite length item as is. */
  3469. i += length;
  3470. if (der != NULL) {
  3471. /* Ensure space for item */
  3472. if (j + i - start > *derSz) {
  3473. ret = BUFFER_E;
  3474. goto end;
  3475. }
  3476. /* Copy item as is */
  3477. XMEMCPY(der + j, ber + start, i - start);
  3478. }
  3479. j += i - start;
  3480. }
  3481. }
  3482. /* Return the length of the DER encoded ASN.1 */
  3483. *derSz = j;
  3484. if (der == NULL) {
  3485. ret = LENGTH_ONLY_E;
  3486. }
  3487. end:
  3488. #ifdef WOLFSSL_SMALL_STACK
  3489. if (indefItems != NULL) {
  3490. XFREE(indefItems, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3491. }
  3492. #endif
  3493. return ret;
  3494. }
  3495. #endif
  3496. #ifndef WOLFSSL_ASN_TEMPLATE
  3497. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)
  3498. /* Set the DER/BER encoding of the ASN.1 BIT_STRING with a 16-bit value.
  3499. *
  3500. * val 16-bit value to encode.
  3501. * output Buffer to write into.
  3502. * returns the number of bytes added to the buffer.
  3503. */
  3504. static word32 SetBitString16Bit(word16 val, byte* output)
  3505. {
  3506. word32 idx;
  3507. int len;
  3508. byte lastByte;
  3509. byte unusedBits = 0;
  3510. if ((val >> 8) != 0) {
  3511. len = 2;
  3512. lastByte = (byte)(val >> 8);
  3513. }
  3514. else {
  3515. len = 1;
  3516. lastByte = (byte)val;
  3517. }
  3518. while (((lastByte >> unusedBits) & 0x01) == 0x00)
  3519. unusedBits++;
  3520. idx = SetBitString((word32)len, unusedBits, output);
  3521. output[idx++] = (byte)val;
  3522. if (len > 1)
  3523. output[idx++] = (byte)(val >> 8);
  3524. return idx;
  3525. }
  3526. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_CERT_GEN */
  3527. #endif /* !WOLFSSL_ASN_TEMPLATE */
  3528. /* hashType */
  3529. #ifdef WOLFSSL_MD2
  3530. static const byte hashMd2hOid[] = {42, 134, 72, 134, 247, 13, 2, 2};
  3531. #endif
  3532. #ifndef NO_MD5
  3533. static const byte hashMd5hOid[] = {42, 134, 72, 134, 247, 13, 2, 5};
  3534. #endif
  3535. #ifndef NO_SHA
  3536. static const byte hashSha1hOid[] = {43, 14, 3, 2, 26};
  3537. #endif
  3538. #ifdef WOLFSSL_SHA224
  3539. static const byte hashSha224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 4};
  3540. #endif
  3541. #ifndef NO_SHA256
  3542. static const byte hashSha256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 1};
  3543. #endif
  3544. #ifdef WOLFSSL_SHA384
  3545. static const byte hashSha384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 2};
  3546. #endif
  3547. #ifdef WOLFSSL_SHA512
  3548. static const byte hashSha512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 3};
  3549. #ifndef WOLFSSL_NOSHA512_224
  3550. static const byte hashSha512_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 5};
  3551. #endif
  3552. #ifndef WOLFSSL_NOSHA512_256
  3553. static const byte hashSha512_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 6};
  3554. #endif
  3555. #endif
  3556. #ifdef WOLFSSL_SHA3
  3557. #ifndef WOLFSSL_NOSHA3_224
  3558. static const byte hashSha3_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 7};
  3559. #endif /* WOLFSSL_NOSHA3_224 */
  3560. #ifndef WOLFSSL_NOSHA3_256
  3561. static const byte hashSha3_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 8};
  3562. #endif /* WOLFSSL_NOSHA3_256 */
  3563. #ifndef WOLFSSL_NOSHA3_384
  3564. static const byte hashSha3_384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 9};
  3565. #endif /* WOLFSSL_NOSHA3_384 */
  3566. #ifndef WOLFSSL_NOSHA3_512
  3567. static const byte hashSha3_512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 10};
  3568. #endif /* WOLFSSL_NOSHA3_512 */
  3569. #endif /* WOLFSSL_SHA3 */
  3570. /* hmacType */
  3571. #ifndef NO_HMAC
  3572. #ifdef WOLFSSL_SHA224
  3573. static const byte hmacSha224Oid[] = {42, 134, 72, 134, 247, 13, 2, 8};
  3574. #endif
  3575. #ifndef NO_SHA256
  3576. static const byte hmacSha256Oid[] = {42, 134, 72, 134, 247, 13, 2, 9};
  3577. #endif
  3578. #ifdef WOLFSSL_SHA384
  3579. static const byte hmacSha384Oid[] = {42, 134, 72, 134, 247, 13, 2, 10};
  3580. #endif
  3581. #ifdef WOLFSSL_SHA512
  3582. static const byte hmacSha512Oid[] = {42, 134, 72, 134, 247, 13, 2, 11};
  3583. #endif
  3584. #endif
  3585. /* sigType */
  3586. #if !defined(NO_DSA) && !defined(NO_SHA)
  3587. static const byte sigSha1wDsaOid[] = {42, 134, 72, 206, 56, 4, 3};
  3588. static const byte sigSha256wDsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 2};
  3589. #endif /* NO_DSA */
  3590. #ifndef NO_RSA
  3591. #ifdef WOLFSSL_MD2
  3592. static const byte sigMd2wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 2};
  3593. #endif
  3594. #ifndef NO_MD5
  3595. static const byte sigMd5wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 4};
  3596. #endif
  3597. #ifndef NO_SHA
  3598. static const byte sigSha1wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 5};
  3599. #endif
  3600. #ifdef WOLFSSL_SHA224
  3601. static const byte sigSha224wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,14};
  3602. #endif
  3603. #ifndef NO_SHA256
  3604. static const byte sigSha256wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,11};
  3605. #endif
  3606. #ifdef WOLFSSL_SHA384
  3607. static const byte sigSha384wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,12};
  3608. #endif
  3609. #ifdef WOLFSSL_SHA512
  3610. static const byte sigSha512wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,13};
  3611. #endif
  3612. #ifdef WOLFSSL_SHA3
  3613. #ifndef WOLFSSL_NOSHA3_224
  3614. static const byte sigSha3_224wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 13};
  3615. #endif
  3616. #ifndef WOLFSSL_NOSHA3_256
  3617. static const byte sigSha3_256wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 14};
  3618. #endif
  3619. #ifndef WOLFSSL_NOSHA3_384
  3620. static const byte sigSha3_384wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 15};
  3621. #endif
  3622. #ifndef WOLFSSL_NOSHA3_512
  3623. static const byte sigSha3_512wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 16};
  3624. #endif
  3625. #endif
  3626. #ifdef WC_RSA_PSS
  3627. static const byte sigRsaSsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
  3628. #endif
  3629. #endif /* NO_RSA */
  3630. #ifdef HAVE_ECC
  3631. #ifndef NO_SHA
  3632. static const byte sigSha1wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 1};
  3633. #endif
  3634. #ifdef WOLFSSL_SHA224
  3635. static const byte sigSha224wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 1};
  3636. #endif
  3637. #ifndef NO_SHA256
  3638. static const byte sigSha256wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 2};
  3639. #endif
  3640. #ifdef WOLFSSL_SHA384
  3641. static const byte sigSha384wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 3};
  3642. #endif
  3643. #ifdef WOLFSSL_SHA512
  3644. static const byte sigSha512wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 4};
  3645. #endif
  3646. #ifdef WOLFSSL_SHA3
  3647. #ifndef WOLFSSL_NOSHA3_224
  3648. static const byte sigSha3_224wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 9};
  3649. #endif
  3650. #ifndef WOLFSSL_NOSHA3_256
  3651. static const byte sigSha3_256wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 10};
  3652. #endif
  3653. #ifndef WOLFSSL_NOSHA3_384
  3654. static const byte sigSha3_384wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 11};
  3655. #endif
  3656. #ifndef WOLFSSL_NOSHA3_512
  3657. static const byte sigSha3_512wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 12};
  3658. #endif
  3659. #endif
  3660. #endif /* HAVE_ECC */
  3661. #ifdef HAVE_ED25519
  3662. static const byte sigEd25519Oid[] = {43, 101, 112};
  3663. #endif /* HAVE_ED25519 */
  3664. #ifdef HAVE_ED448
  3665. static const byte sigEd448Oid[] = {43, 101, 113};
  3666. #endif /* HAVE_ED448 */
  3667. #ifdef HAVE_PQC
  3668. #ifdef HAVE_FALCON
  3669. /* Falcon Level 1: 1 3 9999 3 1 */
  3670. static const byte sigFalcon_Level1Oid[] = {43, 206, 15, 3, 1};
  3671. /* Falcon Level 5: 1 3 9999 3 4 */
  3672. static const byte sigFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
  3673. #endif /* HAVE_FACON */
  3674. #ifdef HAVE_DILITHIUM
  3675. /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
  3676. static const byte sigDilithium_Level2Oid[] =
  3677. {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};
  3678. /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
  3679. static const byte sigDilithium_Level3Oid[] =
  3680. {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};
  3681. /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
  3682. static const byte sigDilithium_Level5Oid[] =
  3683. {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
  3684. #endif /* HAVE_DILITHIUM */
  3685. #ifdef HAVE_SPHINCS
  3686. /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
  3687. static const byte sigSphincsFast_Level1Oid[] =
  3688. {43, 206, 15, 6, 7, 4};
  3689. /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
  3690. static const byte sigSphincsFast_Level3Oid[] =
  3691. {43, 206, 15, 6, 8, 3};
  3692. /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
  3693. static const byte sigSphincsFast_Level5Oid[] =
  3694. {43, 206, 15, 6, 9, 3};
  3695. /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
  3696. static const byte sigSphincsSmall_Level1Oid[] =
  3697. {43, 206, 15, 6, 7, 10};
  3698. /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
  3699. static const byte sigSphincsSmall_Level3Oid[] =
  3700. {43, 206, 15, 6, 8, 7};
  3701. /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
  3702. static const byte sigSphincsSmall_Level5Oid[] =
  3703. {43, 206, 15, 6, 9, 7};
  3704. #endif /* HAVE_SPHINCS */
  3705. #endif /* HAVE_PQC */
  3706. /* keyType */
  3707. #ifndef NO_DSA
  3708. static const byte keyDsaOid[] = {42, 134, 72, 206, 56, 4, 1};
  3709. #endif /* NO_DSA */
  3710. #ifndef NO_RSA
  3711. static const byte keyRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 1};
  3712. #ifdef WC_RSA_PSS
  3713. static const byte keyRsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
  3714. #endif
  3715. #endif /* NO_RSA */
  3716. #ifdef HAVE_ECC
  3717. static const byte keyEcdsaOid[] = {42, 134, 72, 206, 61, 2, 1};
  3718. #endif /* HAVE_ECC */
  3719. #ifdef HAVE_ED25519
  3720. static const byte keyEd25519Oid[] = {43, 101, 112};
  3721. #endif /* HAVE_ED25519 */
  3722. #ifdef HAVE_CURVE25519
  3723. static const byte keyCurve25519Oid[] = {43, 101, 110};
  3724. #endif
  3725. #ifdef HAVE_ED448
  3726. static const byte keyEd448Oid[] = {43, 101, 113};
  3727. #endif /* HAVE_ED448 */
  3728. #ifdef HAVE_CURVE448
  3729. static const byte keyCurve448Oid[] = {43, 101, 111};
  3730. #endif /* HAVE_CURVE448 */
  3731. #ifndef NO_DH
  3732. static const byte keyDhOid[] = {42, 134, 72, 134, 247, 13, 1, 3, 1};
  3733. #endif /* !NO_DH */
  3734. #ifdef HAVE_PQC
  3735. #ifdef HAVE_FALCON
  3736. /* Falcon Level 1: 1 3 9999 3 1 */
  3737. static const byte keyFalcon_Level1Oid[] = {43, 206, 15, 3, 1};
  3738. /* Falcon Level 5: 1 3 9999 3 4 */
  3739. static const byte keyFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
  3740. #endif /* HAVE_FALCON */
  3741. #ifdef HAVE_DILITHIUM
  3742. /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
  3743. static const byte keyDilithium_Level2Oid[] =
  3744. {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};
  3745. /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
  3746. static const byte keyDilithium_Level3Oid[] =
  3747. {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};
  3748. /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
  3749. static const byte keyDilithium_Level5Oid[] =
  3750. {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
  3751. #endif /* HAVE_DILITHIUM */
  3752. #ifdef HAVE_SPHINCS
  3753. /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
  3754. static const byte keySphincsFast_Level1Oid[] =
  3755. {43, 206, 15, 6, 7, 4};
  3756. /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
  3757. static const byte keySphincsFast_Level3Oid[] =
  3758. {43, 206, 15, 6, 8, 3};
  3759. /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
  3760. static const byte keySphincsFast_Level5Oid[] =
  3761. {43, 206, 15, 6, 9, 3};
  3762. /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
  3763. static const byte keySphincsSmall_Level1Oid[] =
  3764. {43, 206, 15, 6, 7, 10};
  3765. /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
  3766. static const byte keySphincsSmall_Level3Oid[] =
  3767. {43, 206, 15, 6, 8, 7};
  3768. /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
  3769. static const byte keySphincsSmall_Level5Oid[] =
  3770. {43, 206, 15, 6, 9, 7};
  3771. #endif /* HAVE_SPHINCS */
  3772. #endif /* HAVE_PQC */
  3773. /* curveType */
  3774. #ifdef HAVE_ECC
  3775. /* See "ecc_sets" table in ecc.c */
  3776. #endif /* HAVE_ECC */
  3777. #ifdef HAVE_AES_CBC
  3778. /* blkType */
  3779. #ifdef WOLFSSL_AES_128
  3780. static const byte blkAes128CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 2};
  3781. #endif
  3782. #ifdef WOLFSSL_AES_192
  3783. static const byte blkAes192CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 22};
  3784. #endif
  3785. #ifdef WOLFSSL_AES_256
  3786. static const byte blkAes256CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 42};
  3787. #endif
  3788. #endif /* HAVE_AES_CBC */
  3789. #ifdef HAVE_AESGCM
  3790. #ifdef WOLFSSL_AES_128
  3791. static const byte blkAes128GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 6};
  3792. #endif
  3793. #ifdef WOLFSSL_AES_192
  3794. static const byte blkAes192GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 26};
  3795. #endif
  3796. #ifdef WOLFSSL_AES_256
  3797. static const byte blkAes256GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 46};
  3798. #endif
  3799. #endif /* HAVE_AESGCM */
  3800. #ifdef HAVE_AESCCM
  3801. #ifdef WOLFSSL_AES_128
  3802. static const byte blkAes128CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 7};
  3803. #endif
  3804. #ifdef WOLFSSL_AES_192
  3805. static const byte blkAes192CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 27};
  3806. #endif
  3807. #ifdef WOLFSSL_AES_256
  3808. static const byte blkAes256CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 47};
  3809. #endif
  3810. #endif /* HAVE_AESCCM */
  3811. #ifndef NO_DES3
  3812. static const byte blkDesCbcOid[] = {43, 14, 3, 2, 7};
  3813. static const byte blkDes3CbcOid[] = {42, 134, 72, 134, 247, 13, 3, 7};
  3814. #endif
  3815. /* keyWrapType */
  3816. #ifdef WOLFSSL_AES_128
  3817. static const byte wrapAes128Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 5};
  3818. #endif
  3819. #ifdef WOLFSSL_AES_192
  3820. static const byte wrapAes192Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 25};
  3821. #endif
  3822. #ifdef WOLFSSL_AES_256
  3823. static const byte wrapAes256Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 45};
  3824. #endif
  3825. #ifdef HAVE_PKCS7
  3826. /* From RFC 3211 */
  3827. static const byte wrapPwriKekOid[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3,9};
  3828. #endif
  3829. /* cmsKeyAgreeType */
  3830. #ifndef NO_SHA
  3831. static const byte dhSinglePass_stdDH_sha1kdf_Oid[] =
  3832. {43, 129, 5, 16, 134, 72, 63, 0, 2};
  3833. #endif
  3834. #ifdef WOLFSSL_SHA224
  3835. static const byte dhSinglePass_stdDH_sha224kdf_Oid[] = {43, 129, 4, 1, 11, 0};
  3836. #endif
  3837. #ifndef NO_SHA256
  3838. static const byte dhSinglePass_stdDH_sha256kdf_Oid[] = {43, 129, 4, 1, 11, 1};
  3839. #endif
  3840. #ifdef WOLFSSL_SHA384
  3841. static const byte dhSinglePass_stdDH_sha384kdf_Oid[] = {43, 129, 4, 1, 11, 2};
  3842. #endif
  3843. #ifdef WOLFSSL_SHA512
  3844. static const byte dhSinglePass_stdDH_sha512kdf_Oid[] = {43, 129, 4, 1, 11, 3};
  3845. #endif
  3846. /* ocspType */
  3847. #ifdef HAVE_OCSP
  3848. static const byte ocspBasicOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 1};
  3849. static const byte ocspNonceOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 2};
  3850. static const byte ocspNoCheckOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 5};
  3851. #endif /* HAVE_OCSP */
  3852. /* certExtType */
  3853. static const byte extBasicCaOid[] = {85, 29, 19};
  3854. static const byte extAltNamesOid[] = {85, 29, 17};
  3855. static const byte extCrlDistOid[] = {85, 29, 31};
  3856. static const byte extAuthInfoOid[] = {43, 6, 1, 5, 5, 7, 1, 1};
  3857. static const byte extAuthKeyOid[] = {85, 29, 35};
  3858. static const byte extSubjKeyOid[] = {85, 29, 14};
  3859. static const byte extCertPolicyOid[] = {85, 29, 32};
  3860. static const byte extKeyUsageOid[] = {85, 29, 15};
  3861. static const byte extInhibitAnyOid[] = {85, 29, 54};
  3862. static const byte extExtKeyUsageOid[] = {85, 29, 37};
  3863. #ifndef IGNORE_NAME_CONSTRAINTS
  3864. static const byte extNameConsOid[] = {85, 29, 30};
  3865. #endif
  3866. #ifdef HAVE_CRL
  3867. static const byte extCrlNumberOid[] = {85, 29, 20};
  3868. #endif
  3869. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  3870. static const byte extSubjDirAttrOid[] = {85, 29, 9};
  3871. #endif
  3872. #ifdef WOLFSSL_SUBJ_INFO_ACC
  3873. static const byte extSubjInfoAccessOid[] = {43, 6, 1, 5, 5, 7, 1, 11};
  3874. #endif
  3875. /* certAuthInfoType */
  3876. static const byte extAuthInfoOcspOid[] = {43, 6, 1, 5, 5, 7, 48, 1};
  3877. static const byte extAuthInfoCaIssuerOid[] = {43, 6, 1, 5, 5, 7, 48, 2};
  3878. #ifdef WOLFSSL_SUBJ_INFO_ACC
  3879. static const byte extAuthInfoCaRespOid[] = {43, 6, 1, 5, 5, 7, 48, 5};
  3880. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  3881. /* certPolicyType */
  3882. static const byte extCertPolicyAnyOid[] = {85, 29, 32, 0};
  3883. #ifdef WOLFSSL_FPKI
  3884. #define CERT_POLICY_TYPE_OID_BASE(num) {96, 134, 72, 1, 101, 3, 2, 1, 3, num}
  3885. static const byte extCertPolicyFpkiCommonAuthOid[] =
  3886. CERT_POLICY_TYPE_OID_BASE(13);
  3887. static const byte extCertPolicyFpkiPivAuthOid[] =
  3888. CERT_POLICY_TYPE_OID_BASE(40);
  3889. static const byte extCertPolicyFpkiPivAuthHwOid[] =
  3890. CERT_POLICY_TYPE_OID_BASE(41);
  3891. static const byte extCertPolicyFpkiPiviAuthOid[] =
  3892. CERT_POLICY_TYPE_OID_BASE(45);
  3893. #endif /* WOLFSSL_FPKI */
  3894. /* certAltNameType */
  3895. static const byte extAltNamesHwNameOid[] = {43, 6, 1, 5, 5, 7, 8, 4};
  3896. /* certKeyUseType */
  3897. static const byte extExtKeyUsageAnyOid[] = {85, 29, 37, 0};
  3898. static const byte extExtKeyUsageServerAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 1};
  3899. static const byte extExtKeyUsageClientAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 2};
  3900. static const byte extExtKeyUsageCodeSigningOid[] = {43, 6, 1, 5, 5, 7, 3, 3};
  3901. static const byte extExtKeyUsageEmailProtectOid[] = {43, 6, 1, 5, 5, 7, 3, 4};
  3902. static const byte extExtKeyUsageTimestampOid[] = {43, 6, 1, 5, 5, 7, 3, 8};
  3903. static const byte extExtKeyUsageOcspSignOid[] = {43, 6, 1, 5, 5, 7, 3, 9};
  3904. #ifdef WOLFSSL_WOLFSSH
  3905. #define EXT_KEY_USAGE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 3, num}
  3906. static const byte extExtKeyUsageSshClientAuthOid[] =
  3907. EXT_KEY_USAGE_OID_BASE(21);
  3908. static const byte extExtKeyUsageSshMSCLOid[] =
  3909. {43, 6, 1, 4, 1, 130, 55, 20, 2, 2};
  3910. static const byte extExtKeyUsageSshKpClientAuthOid[] =
  3911. {43, 6, 1, 5, 2, 3, 4};
  3912. #endif /* WOLFSSL_WOLFSSH */
  3913. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  3914. #define SUBJ_DIR_ATTR_TYPE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 9, num}
  3915. static const byte extSubjDirAttrDobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(1);
  3916. static const byte extSubjDirAttrPobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(2);
  3917. static const byte extSubjDirAttrGenderOid[] =
  3918. SUBJ_DIR_ATTR_TYPE_OID_BASE(3);
  3919. static const byte extSubjDirAttrCocOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(4);
  3920. static const byte extSubjDirAttrCorOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(5);
  3921. #endif
  3922. #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3923. defined(WOLFSSL_ASN_TEMPLATE) || defined(OPENSSL_EXTRA) || \
  3924. defined(OPENSSL_EXTRA_X509_SMALL)
  3925. /* csrAttrType */
  3926. #define CSR_ATTR_TYPE_OID_BASE(num) {42, 134, 72, 134, 247, 13, 1, 9, num}
  3927. #if !defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3928. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  3929. defined(WOLFSSL_ASN_TEMPLATE)
  3930. static const byte attrEmailOid[] = CSR_ATTR_TYPE_OID_BASE(1);
  3931. #endif
  3932. #ifdef WOLFSSL_CERT_REQ
  3933. static const byte attrUnstructuredNameOid[] = CSR_ATTR_TYPE_OID_BASE(2);
  3934. static const byte attrPkcs9ContentTypeOid[] = CSR_ATTR_TYPE_OID_BASE(3);
  3935. static const byte attrChallengePasswordOid[] = CSR_ATTR_TYPE_OID_BASE(7);
  3936. static const byte attrExtensionRequestOid[] = CSR_ATTR_TYPE_OID_BASE(14);
  3937. static const byte attrSerialNumberOid[] = {85, 4, 5};
  3938. static const byte attrDnQualifier[] = {85, 4, 46};
  3939. static const byte attrInitals[] = {85, 4, 43};
  3940. static const byte attrSurname[] = {85, 4, 4};
  3941. static const byte attrGivenName[] = {85, 4, 42};
  3942. #endif
  3943. #endif
  3944. /* kdfType */
  3945. static const byte pbkdf2Oid[] = {42, 134, 72, 134, 247, 13, 1, 5, 12};
  3946. /* PKCS5 */
  3947. #if !defined(NO_DES3) && !defined(NO_MD5)
  3948. static const byte pbeMd5Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 3};
  3949. #endif
  3950. #if !defined(NO_DES3) && !defined(NO_SHA)
  3951. static const byte pbeSha1Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 10};
  3952. #endif
  3953. static const byte pbes2[] = {42, 134, 72, 134, 247, 13, 1, 5, 13};
  3954. /* PKCS12 */
  3955. #if !defined(NO_RC4) && !defined(NO_SHA)
  3956. static const byte pbeSha1RC4128[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 1};
  3957. #endif
  3958. #if !defined(NO_DES3) && !defined(NO_SHA)
  3959. static const byte pbeSha1Des3[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 3};
  3960. #endif
  3961. #if defined(WC_RC2) && !defined(NO_SHA)
  3962. static const byte pbe40Rc2Cbc[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 6};
  3963. #endif
  3964. #ifdef HAVE_LIBZ
  3965. /* zlib compression */
  3966. static const byte zlibCompress[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3, 8};
  3967. #endif
  3968. #ifdef WOLFSSL_APACHE_HTTPD
  3969. /* tlsExtType */
  3970. static const byte tlsFeatureOid[] = {43, 6, 1, 5, 5, 7, 1, 24};
  3971. /* certNameType */
  3972. static const byte dnsSRVOid[] = {43, 6, 1, 5, 5, 7, 8, 7};
  3973. #endif
  3974. #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3975. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  3976. defined(WOLFSSL_ASN_TEMPLATE)
  3977. /* Pilot attribute types (0.9.2342.19200300.100.1.*) */
  3978. #define PLT_ATTR_TYPE_OID_BASE(num) {9, 146, 38, 137, 147, 242, 44, 100, 1, num}
  3979. static const byte uidOid[] = PLT_ATTR_TYPE_OID_BASE(1); /* user id */
  3980. static const byte fvrtDrk[] = PLT_ATTR_TYPE_OID_BASE(5);/* favourite drink*/
  3981. #endif
  3982. #if defined(WOLFSSL_CERT_GEN) || \
  3983. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  3984. defined(WOLFSSL_ASN_TEMPLATE)
  3985. static const byte dcOid[] = {9, 146, 38, 137, 147, 242, 44, 100, 1, 25}; /* domain component */
  3986. #endif
  3987. /* Looks up the ID/type of an OID.
  3988. *
  3989. * When known returns the OID as a byte array and its length.
  3990. * ID-type are unique.
  3991. *
  3992. * Use oidIgnoreType to autofail.
  3993. *
  3994. * @param [in] id OID id.
  3995. * @param [in] type Type of OID (enum Oid_Types).
  3996. * @param [out] oidSz Length of OID byte array returned.
  3997. * @return Array of bytes for the OID.
  3998. * @return NULL when ID/type not recognized.
  3999. */
  4000. const byte* OidFromId(word32 id, word32 type, word32* oidSz)
  4001. {
  4002. const byte* oid = NULL;
  4003. *oidSz = 0;
  4004. switch (type) {
  4005. case oidHashType:
  4006. switch (id) {
  4007. #ifdef WOLFSSL_MD2
  4008. case MD2h:
  4009. oid = hashMd2hOid;
  4010. *oidSz = sizeof(hashMd2hOid);
  4011. break;
  4012. #endif
  4013. #ifndef NO_MD5
  4014. case MD5h:
  4015. oid = hashMd5hOid;
  4016. *oidSz = sizeof(hashMd5hOid);
  4017. break;
  4018. #endif
  4019. #ifndef NO_SHA
  4020. case SHAh:
  4021. oid = hashSha1hOid;
  4022. *oidSz = sizeof(hashSha1hOid);
  4023. break;
  4024. #endif
  4025. #ifdef WOLFSSL_SHA224
  4026. case SHA224h:
  4027. oid = hashSha224hOid;
  4028. *oidSz = sizeof(hashSha224hOid);
  4029. break;
  4030. #endif
  4031. #ifndef NO_SHA256
  4032. case SHA256h:
  4033. oid = hashSha256hOid;
  4034. *oidSz = sizeof(hashSha256hOid);
  4035. break;
  4036. #endif
  4037. #ifdef WOLFSSL_SHA384
  4038. case SHA384h:
  4039. oid = hashSha384hOid;
  4040. *oidSz = sizeof(hashSha384hOid);
  4041. break;
  4042. #endif
  4043. #ifdef WOLFSSL_SHA512
  4044. #ifndef WOLFSSL_NOSHA512_224
  4045. case SHA512_224h:
  4046. oid = hashSha512_224hOid;
  4047. *oidSz = sizeof(hashSha512_224hOid);
  4048. break;
  4049. #endif
  4050. #ifndef WOLFSSL_NOSHA512_256
  4051. case SHA512_256h:
  4052. oid = hashSha512_256hOid;
  4053. *oidSz = sizeof(hashSha512_256hOid);
  4054. break;
  4055. #endif
  4056. case SHA512h:
  4057. oid = hashSha512hOid;
  4058. *oidSz = sizeof(hashSha512hOid);
  4059. break;
  4060. #endif
  4061. #ifdef WOLFSSL_SHA3
  4062. #ifndef WOLFSSL_NOSHA3_224
  4063. case SHA3_224h:
  4064. oid = hashSha3_224hOid;
  4065. *oidSz = sizeof(hashSha3_224hOid);
  4066. break;
  4067. #endif /* WOLFSSL_NOSHA3_224 */
  4068. #ifndef WOLFSSL_NOSHA3_256
  4069. case SHA3_256h:
  4070. oid = hashSha3_256hOid;
  4071. *oidSz = sizeof(hashSha3_256hOid);
  4072. break;
  4073. #endif /* WOLFSSL_NOSHA3_256 */
  4074. #ifndef WOLFSSL_NOSHA3_384
  4075. case SHA3_384h:
  4076. oid = hashSha3_384hOid;
  4077. *oidSz = sizeof(hashSha3_384hOid);
  4078. break;
  4079. #endif /* WOLFSSL_NOSHA3_384 */
  4080. #ifndef WOLFSSL_NOSHA3_512
  4081. case SHA3_512h:
  4082. oid = hashSha3_512hOid;
  4083. *oidSz = sizeof(hashSha3_512hOid);
  4084. break;
  4085. #endif /* WOLFSSL_NOSHA3_512 */
  4086. #endif /* WOLFSSL_SHA3 */
  4087. default:
  4088. break;
  4089. }
  4090. break;
  4091. case oidSigType:
  4092. switch (id) {
  4093. #if !defined(NO_DSA) && !defined(NO_SHA)
  4094. case CTC_SHAwDSA:
  4095. oid = sigSha1wDsaOid;
  4096. *oidSz = sizeof(sigSha1wDsaOid);
  4097. break;
  4098. case CTC_SHA256wDSA:
  4099. oid = sigSha256wDsaOid;
  4100. *oidSz = sizeof(sigSha256wDsaOid);
  4101. break;
  4102. #endif /* NO_DSA */
  4103. #ifndef NO_RSA
  4104. #ifdef WOLFSSL_MD2
  4105. case CTC_MD2wRSA:
  4106. oid = sigMd2wRsaOid;
  4107. *oidSz = sizeof(sigMd2wRsaOid);
  4108. break;
  4109. #endif
  4110. #ifndef NO_MD5
  4111. case CTC_MD5wRSA:
  4112. oid = sigMd5wRsaOid;
  4113. *oidSz = sizeof(sigMd5wRsaOid);
  4114. break;
  4115. #endif
  4116. #ifndef NO_SHA
  4117. case CTC_SHAwRSA:
  4118. oid = sigSha1wRsaOid;
  4119. *oidSz = sizeof(sigSha1wRsaOid);
  4120. break;
  4121. #endif
  4122. #ifdef WOLFSSL_SHA224
  4123. case CTC_SHA224wRSA:
  4124. oid = sigSha224wRsaOid;
  4125. *oidSz = sizeof(sigSha224wRsaOid);
  4126. break;
  4127. #endif
  4128. #ifndef NO_SHA256
  4129. case CTC_SHA256wRSA:
  4130. oid = sigSha256wRsaOid;
  4131. *oidSz = sizeof(sigSha256wRsaOid);
  4132. break;
  4133. #endif
  4134. #ifdef WOLFSSL_SHA384
  4135. case CTC_SHA384wRSA:
  4136. oid = sigSha384wRsaOid;
  4137. *oidSz = sizeof(sigSha384wRsaOid);
  4138. break;
  4139. #endif
  4140. #ifdef WOLFSSL_SHA512
  4141. case CTC_SHA512wRSA:
  4142. oid = sigSha512wRsaOid;
  4143. *oidSz = sizeof(sigSha512wRsaOid);
  4144. break;
  4145. #endif /* WOLFSSL_SHA512 */
  4146. #ifdef WOLFSSL_SHA3
  4147. #ifndef WOLFSSL_NOSHA3_224
  4148. case CTC_SHA3_224wRSA:
  4149. oid = sigSha3_224wRsaOid;
  4150. *oidSz = sizeof(sigSha3_224wRsaOid);
  4151. break;
  4152. #endif
  4153. #ifndef WOLFSSL_NOSHA3_256
  4154. case CTC_SHA3_256wRSA:
  4155. oid = sigSha3_256wRsaOid;
  4156. *oidSz = sizeof(sigSha3_256wRsaOid);
  4157. break;
  4158. #endif
  4159. #ifndef WOLFSSL_NOSHA3_384
  4160. case CTC_SHA3_384wRSA:
  4161. oid = sigSha3_384wRsaOid;
  4162. *oidSz = sizeof(sigSha3_384wRsaOid);
  4163. break;
  4164. #endif
  4165. #ifndef WOLFSSL_NOSHA3_512
  4166. case CTC_SHA3_512wRSA:
  4167. oid = sigSha3_512wRsaOid;
  4168. *oidSz = sizeof(sigSha3_512wRsaOid);
  4169. break;
  4170. #endif
  4171. #endif
  4172. #ifdef WC_RSA_PSS
  4173. case CTC_RSASSAPSS:
  4174. oid = sigRsaSsaPssOid;
  4175. *oidSz = sizeof(sigRsaSsaPssOid);
  4176. break;
  4177. #endif
  4178. #endif /* NO_RSA */
  4179. #ifdef HAVE_ECC
  4180. #ifndef NO_SHA
  4181. case CTC_SHAwECDSA:
  4182. oid = sigSha1wEcdsaOid;
  4183. *oidSz = sizeof(sigSha1wEcdsaOid);
  4184. break;
  4185. #endif
  4186. #ifdef WOLFSSL_SHA224
  4187. case CTC_SHA224wECDSA:
  4188. oid = sigSha224wEcdsaOid;
  4189. *oidSz = sizeof(sigSha224wEcdsaOid);
  4190. break;
  4191. #endif
  4192. #ifndef NO_SHA256
  4193. case CTC_SHA256wECDSA:
  4194. oid = sigSha256wEcdsaOid;
  4195. *oidSz = sizeof(sigSha256wEcdsaOid);
  4196. break;
  4197. #endif
  4198. #ifdef WOLFSSL_SHA384
  4199. case CTC_SHA384wECDSA:
  4200. oid = sigSha384wEcdsaOid;
  4201. *oidSz = sizeof(sigSha384wEcdsaOid);
  4202. break;
  4203. #endif
  4204. #ifdef WOLFSSL_SHA512
  4205. case CTC_SHA512wECDSA:
  4206. oid = sigSha512wEcdsaOid;
  4207. *oidSz = sizeof(sigSha512wEcdsaOid);
  4208. break;
  4209. #endif
  4210. #ifdef WOLFSSL_SHA3
  4211. #ifndef WOLFSSL_NOSHA3_224
  4212. case CTC_SHA3_224wECDSA:
  4213. oid = sigSha3_224wEcdsaOid;
  4214. *oidSz = sizeof(sigSha3_224wEcdsaOid);
  4215. break;
  4216. #endif
  4217. #ifndef WOLFSSL_NOSHA3_256
  4218. case CTC_SHA3_256wECDSA:
  4219. oid = sigSha3_256wEcdsaOid;
  4220. *oidSz = sizeof(sigSha3_256wEcdsaOid);
  4221. break;
  4222. #endif
  4223. #ifndef WOLFSSL_NOSHA3_384
  4224. case CTC_SHA3_384wECDSA:
  4225. oid = sigSha3_384wEcdsaOid;
  4226. *oidSz = sizeof(sigSha3_384wEcdsaOid);
  4227. break;
  4228. #endif
  4229. #ifndef WOLFSSL_NOSHA3_512
  4230. case CTC_SHA3_512wECDSA:
  4231. oid = sigSha3_512wEcdsaOid;
  4232. *oidSz = sizeof(sigSha3_512wEcdsaOid);
  4233. break;
  4234. #endif
  4235. #endif
  4236. #endif /* HAVE_ECC */
  4237. #ifdef HAVE_ED25519
  4238. case CTC_ED25519:
  4239. oid = sigEd25519Oid;
  4240. *oidSz = sizeof(sigEd25519Oid);
  4241. break;
  4242. #endif
  4243. #ifdef HAVE_ED448
  4244. case CTC_ED448:
  4245. oid = sigEd448Oid;
  4246. *oidSz = sizeof(sigEd448Oid);
  4247. break;
  4248. #endif
  4249. #ifdef HAVE_PQC
  4250. #ifdef HAVE_FALCON
  4251. case CTC_FALCON_LEVEL1:
  4252. oid = sigFalcon_Level1Oid;
  4253. *oidSz = sizeof(sigFalcon_Level1Oid);
  4254. break;
  4255. case CTC_FALCON_LEVEL5:
  4256. oid = sigFalcon_Level5Oid;
  4257. *oidSz = sizeof(sigFalcon_Level5Oid);
  4258. break;
  4259. #endif /* HAVE_FALCON */
  4260. #ifdef HAVE_DILITHIUM
  4261. case CTC_DILITHIUM_LEVEL2:
  4262. oid = sigDilithium_Level2Oid;
  4263. *oidSz = sizeof(sigDilithium_Level2Oid);
  4264. break;
  4265. case CTC_DILITHIUM_LEVEL3:
  4266. oid = sigDilithium_Level3Oid;
  4267. *oidSz = sizeof(sigDilithium_Level3Oid);
  4268. break;
  4269. case CTC_DILITHIUM_LEVEL5:
  4270. oid = sigDilithium_Level5Oid;
  4271. *oidSz = sizeof(sigDilithium_Level5Oid);
  4272. break;
  4273. #endif /* HAVE_DILITHIUM */
  4274. #ifdef HAVE_SPHINCS
  4275. case CTC_SPHINCS_FAST_LEVEL1:
  4276. oid = sigSphincsFast_Level1Oid;
  4277. *oidSz = sizeof(sigSphincsFast_Level1Oid);
  4278. break;
  4279. case CTC_SPHINCS_FAST_LEVEL3:
  4280. oid = sigSphincsFast_Level3Oid;
  4281. *oidSz = sizeof(sigSphincsFast_Level3Oid);
  4282. break;
  4283. case CTC_SPHINCS_FAST_LEVEL5:
  4284. oid = sigSphincsFast_Level5Oid;
  4285. *oidSz = sizeof(sigSphincsFast_Level5Oid);
  4286. break;
  4287. case CTC_SPHINCS_SMALL_LEVEL1:
  4288. oid = sigSphincsSmall_Level1Oid;
  4289. *oidSz = sizeof(sigSphincsSmall_Level1Oid);
  4290. break;
  4291. case CTC_SPHINCS_SMALL_LEVEL3:
  4292. oid = sigSphincsSmall_Level3Oid;
  4293. *oidSz = sizeof(sigSphincsSmall_Level3Oid);
  4294. break;
  4295. case CTC_SPHINCS_SMALL_LEVEL5:
  4296. oid = sigSphincsSmall_Level5Oid;
  4297. *oidSz = sizeof(sigSphincsSmall_Level5Oid);
  4298. break;
  4299. #endif /* HAVE_SPHINCS */
  4300. #endif /* HAVE_PQC */
  4301. default:
  4302. break;
  4303. }
  4304. break;
  4305. case oidKeyType:
  4306. switch (id) {
  4307. #ifndef NO_DSA
  4308. case DSAk:
  4309. oid = keyDsaOid;
  4310. *oidSz = sizeof(keyDsaOid);
  4311. break;
  4312. #endif /* NO_DSA */
  4313. #ifndef NO_RSA
  4314. case RSAk:
  4315. oid = keyRsaOid;
  4316. *oidSz = sizeof(keyRsaOid);
  4317. break;
  4318. #ifdef WC_RSA_PSS
  4319. case RSAPSSk:
  4320. oid = keyRsaPssOid;
  4321. *oidSz = sizeof(keyRsaPssOid);
  4322. break;
  4323. #endif
  4324. #endif /* NO_RSA */
  4325. #ifdef HAVE_ECC
  4326. case ECDSAk:
  4327. oid = keyEcdsaOid;
  4328. *oidSz = sizeof(keyEcdsaOid);
  4329. break;
  4330. #endif /* HAVE_ECC */
  4331. #ifdef HAVE_ED25519
  4332. case ED25519k:
  4333. oid = keyEd25519Oid;
  4334. *oidSz = sizeof(keyEd25519Oid);
  4335. break;
  4336. #endif /* HAVE_ED25519 */
  4337. #ifdef HAVE_CURVE25519
  4338. case X25519k:
  4339. oid = keyCurve25519Oid;
  4340. *oidSz = sizeof(keyCurve25519Oid);
  4341. break;
  4342. #endif /* HAVE_CURVE25519 */
  4343. #ifdef HAVE_ED448
  4344. case ED448k:
  4345. oid = keyEd448Oid;
  4346. *oidSz = sizeof(keyEd448Oid);
  4347. break;
  4348. #endif /* HAVE_ED448 */
  4349. #ifdef HAVE_CURVE448
  4350. case X448k:
  4351. oid = keyCurve448Oid;
  4352. *oidSz = sizeof(keyCurve448Oid);
  4353. break;
  4354. #endif /* HAVE_CURVE448 */
  4355. #ifndef NO_DH
  4356. case DHk:
  4357. oid = keyDhOid;
  4358. *oidSz = sizeof(keyDhOid);
  4359. break;
  4360. #endif /* !NO_DH */
  4361. #ifdef HAVE_PQC
  4362. #ifdef HAVE_FALCON
  4363. case FALCON_LEVEL1k:
  4364. oid = keyFalcon_Level1Oid;
  4365. *oidSz = sizeof(keyFalcon_Level1Oid);
  4366. break;
  4367. case FALCON_LEVEL5k:
  4368. oid = keyFalcon_Level5Oid;
  4369. *oidSz = sizeof(keyFalcon_Level5Oid);
  4370. break;
  4371. #endif /* HAVE_FALCON */
  4372. #ifdef HAVE_DILITHIUM
  4373. case DILITHIUM_LEVEL2k:
  4374. oid = keyDilithium_Level2Oid;
  4375. *oidSz = sizeof(keyDilithium_Level2Oid);
  4376. break;
  4377. case DILITHIUM_LEVEL3k:
  4378. oid = keyDilithium_Level3Oid;
  4379. *oidSz = sizeof(keyDilithium_Level3Oid);
  4380. break;
  4381. case DILITHIUM_LEVEL5k:
  4382. oid = keyDilithium_Level5Oid;
  4383. *oidSz = sizeof(keyDilithium_Level5Oid);
  4384. break;
  4385. #endif /* HAVE_DILITHIUM */
  4386. #ifdef HAVE_SPHINCS
  4387. case SPHINCS_FAST_LEVEL1k:
  4388. oid = keySphincsFast_Level1Oid;
  4389. *oidSz = sizeof(keySphincsFast_Level1Oid);
  4390. break;
  4391. case SPHINCS_FAST_LEVEL3k:
  4392. oid = keySphincsFast_Level3Oid;
  4393. *oidSz = sizeof(keySphincsFast_Level3Oid);
  4394. break;
  4395. case SPHINCS_FAST_LEVEL5k:
  4396. oid = keySphincsFast_Level5Oid;
  4397. *oidSz = sizeof(keySphincsFast_Level5Oid);
  4398. break;
  4399. case SPHINCS_SMALL_LEVEL1k:
  4400. oid = keySphincsSmall_Level1Oid;
  4401. *oidSz = sizeof(keySphincsSmall_Level1Oid);
  4402. break;
  4403. case SPHINCS_SMALL_LEVEL3k:
  4404. oid = keySphincsSmall_Level3Oid;
  4405. *oidSz = sizeof(keySphincsSmall_Level3Oid);
  4406. break;
  4407. case SPHINCS_SMALL_LEVEL5k:
  4408. oid = keySphincsSmall_Level5Oid;
  4409. *oidSz = sizeof(keySphincsSmall_Level5Oid);
  4410. break;
  4411. #endif /* HAVE_SPHINCS */
  4412. #endif /* HAVE_PQC */
  4413. default:
  4414. break;
  4415. }
  4416. break;
  4417. #ifdef HAVE_ECC
  4418. case oidCurveType:
  4419. if (wc_ecc_get_oid(id, &oid, oidSz) < 0) {
  4420. WOLFSSL_MSG("ECC OID not found");
  4421. }
  4422. break;
  4423. #endif /* HAVE_ECC */
  4424. case oidBlkType:
  4425. switch (id) {
  4426. #ifdef HAVE_AES_CBC
  4427. #ifdef WOLFSSL_AES_128
  4428. case AES128CBCb:
  4429. oid = blkAes128CbcOid;
  4430. *oidSz = sizeof(blkAes128CbcOid);
  4431. break;
  4432. #endif
  4433. #ifdef WOLFSSL_AES_192
  4434. case AES192CBCb:
  4435. oid = blkAes192CbcOid;
  4436. *oidSz = sizeof(blkAes192CbcOid);
  4437. break;
  4438. #endif
  4439. #ifdef WOLFSSL_AES_256
  4440. case AES256CBCb:
  4441. oid = blkAes256CbcOid;
  4442. *oidSz = sizeof(blkAes256CbcOid);
  4443. break;
  4444. #endif
  4445. #endif /* HAVE_AES_CBC */
  4446. #ifdef HAVE_AESGCM
  4447. #ifdef WOLFSSL_AES_128
  4448. case AES128GCMb:
  4449. oid = blkAes128GcmOid;
  4450. *oidSz = sizeof(blkAes128GcmOid);
  4451. break;
  4452. #endif
  4453. #ifdef WOLFSSL_AES_192
  4454. case AES192GCMb:
  4455. oid = blkAes192GcmOid;
  4456. *oidSz = sizeof(blkAes192GcmOid);
  4457. break;
  4458. #endif
  4459. #ifdef WOLFSSL_AES_256
  4460. case AES256GCMb:
  4461. oid = blkAes256GcmOid;
  4462. *oidSz = sizeof(blkAes256GcmOid);
  4463. break;
  4464. #endif
  4465. #endif /* HAVE_AESGCM */
  4466. #ifdef HAVE_AESCCM
  4467. #ifdef WOLFSSL_AES_128
  4468. case AES128CCMb:
  4469. oid = blkAes128CcmOid;
  4470. *oidSz = sizeof(blkAes128CcmOid);
  4471. break;
  4472. #endif
  4473. #ifdef WOLFSSL_AES_192
  4474. case AES192CCMb:
  4475. oid = blkAes192CcmOid;
  4476. *oidSz = sizeof(blkAes192CcmOid);
  4477. break;
  4478. #endif
  4479. #ifdef WOLFSSL_AES_256
  4480. case AES256CCMb:
  4481. oid = blkAes256CcmOid;
  4482. *oidSz = sizeof(blkAes256CcmOid);
  4483. break;
  4484. #endif
  4485. #endif /* HAVE_AESCCM */
  4486. #ifndef NO_DES3
  4487. case DESb:
  4488. oid = blkDesCbcOid;
  4489. *oidSz = sizeof(blkDesCbcOid);
  4490. break;
  4491. case DES3b:
  4492. oid = blkDes3CbcOid;
  4493. *oidSz = sizeof(blkDes3CbcOid);
  4494. break;
  4495. #endif /* !NO_DES3 */
  4496. default:
  4497. break;
  4498. }
  4499. break;
  4500. #ifdef HAVE_OCSP
  4501. case oidOcspType:
  4502. switch (id) {
  4503. case OCSP_BASIC_OID:
  4504. oid = ocspBasicOid;
  4505. *oidSz = sizeof(ocspBasicOid);
  4506. break;
  4507. case OCSP_NONCE_OID:
  4508. oid = ocspNonceOid;
  4509. *oidSz = sizeof(ocspNonceOid);
  4510. break;
  4511. default:
  4512. break;
  4513. }
  4514. break;
  4515. #endif /* HAVE_OCSP */
  4516. case oidCertExtType:
  4517. switch (id) {
  4518. case BASIC_CA_OID:
  4519. oid = extBasicCaOid;
  4520. *oidSz = sizeof(extBasicCaOid);
  4521. break;
  4522. case ALT_NAMES_OID:
  4523. oid = extAltNamesOid;
  4524. *oidSz = sizeof(extAltNamesOid);
  4525. break;
  4526. case CRL_DIST_OID:
  4527. oid = extCrlDistOid;
  4528. *oidSz = sizeof(extCrlDistOid);
  4529. break;
  4530. case AUTH_INFO_OID:
  4531. oid = extAuthInfoOid;
  4532. *oidSz = sizeof(extAuthInfoOid);
  4533. break;
  4534. case AUTH_KEY_OID:
  4535. oid = extAuthKeyOid;
  4536. *oidSz = sizeof(extAuthKeyOid);
  4537. break;
  4538. case SUBJ_KEY_OID:
  4539. oid = extSubjKeyOid;
  4540. *oidSz = sizeof(extSubjKeyOid);
  4541. break;
  4542. case CERT_POLICY_OID:
  4543. oid = extCertPolicyOid;
  4544. *oidSz = sizeof(extCertPolicyOid);
  4545. break;
  4546. case KEY_USAGE_OID:
  4547. oid = extKeyUsageOid;
  4548. *oidSz = sizeof(extKeyUsageOid);
  4549. break;
  4550. case INHIBIT_ANY_OID:
  4551. oid = extInhibitAnyOid;
  4552. *oidSz = sizeof(extInhibitAnyOid);
  4553. break;
  4554. case EXT_KEY_USAGE_OID:
  4555. oid = extExtKeyUsageOid;
  4556. *oidSz = sizeof(extExtKeyUsageOid);
  4557. break;
  4558. #ifndef IGNORE_NAME_CONSTRAINTS
  4559. case NAME_CONS_OID:
  4560. oid = extNameConsOid;
  4561. *oidSz = sizeof(extNameConsOid);
  4562. break;
  4563. #endif
  4564. #ifdef HAVE_OCSP
  4565. case OCSP_NOCHECK_OID:
  4566. oid = ocspNoCheckOid;
  4567. *oidSz = sizeof(ocspNoCheckOid);
  4568. break;
  4569. #endif
  4570. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  4571. case SUBJ_DIR_ATTR_OID:
  4572. oid = extSubjDirAttrOid;
  4573. *oidSz = sizeof(extSubjDirAttrOid);
  4574. break;
  4575. #endif
  4576. #ifdef WOLFSSL_SUBJ_INFO_ACC
  4577. case SUBJ_INFO_ACC_OID:
  4578. oid = extSubjInfoAccessOid;
  4579. *oidSz = sizeof(extSubjInfoAccessOid);
  4580. break;
  4581. #endif
  4582. default:
  4583. break;
  4584. }
  4585. break;
  4586. case oidCrlExtType:
  4587. #ifdef HAVE_CRL
  4588. switch (id) {
  4589. case AUTH_KEY_OID:
  4590. oid = extAuthKeyOid;
  4591. *oidSz = sizeof(extAuthKeyOid);
  4592. break;
  4593. case CRL_NUMBER_OID:
  4594. oid = extCrlNumberOid;
  4595. *oidSz = sizeof(extCrlNumberOid);
  4596. break;
  4597. default:
  4598. break;
  4599. }
  4600. #endif
  4601. break;
  4602. case oidCertAuthInfoType:
  4603. switch (id) {
  4604. case AIA_OCSP_OID:
  4605. oid = extAuthInfoOcspOid;
  4606. *oidSz = sizeof(extAuthInfoOcspOid);
  4607. break;
  4608. case AIA_CA_ISSUER_OID:
  4609. oid = extAuthInfoCaIssuerOid;
  4610. *oidSz = sizeof(extAuthInfoCaIssuerOid);
  4611. break;
  4612. #ifdef WOLFSSL_SUBJ_INFO_ACC
  4613. case AIA_CA_REPO_OID:
  4614. oid = extAuthInfoCaRespOid;
  4615. *oidSz = sizeof(extAuthInfoCaRespOid);
  4616. break;
  4617. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  4618. default:
  4619. break;
  4620. }
  4621. break;
  4622. case oidCertPolicyType:
  4623. switch (id) {
  4624. case CP_ANY_OID:
  4625. oid = extCertPolicyAnyOid;
  4626. *oidSz = sizeof(extCertPolicyAnyOid);
  4627. break;
  4628. #if defined(WOLFSSL_FPKI)
  4629. case CP_FPKI_COMMON_AUTH_OID:
  4630. oid = extCertPolicyFpkiCommonAuthOid;
  4631. *oidSz = sizeof(extCertPolicyFpkiCommonAuthOid);
  4632. break;
  4633. case CP_FPKI_PIV_AUTH_OID:
  4634. oid = extCertPolicyFpkiPivAuthOid;
  4635. *oidSz = sizeof(extCertPolicyFpkiPivAuthOid);
  4636. break;
  4637. case CP_FPKI_PIV_AUTH_HW_OID: /* collision with AES256CBCb */
  4638. oid = extCertPolicyFpkiPivAuthHwOid;
  4639. *oidSz = sizeof(extCertPolicyFpkiPivAuthHwOid);
  4640. break;
  4641. case CP_FPKI_PIVI_AUTH_OID:
  4642. oid = extCertPolicyFpkiPiviAuthOid;
  4643. *oidSz = sizeof(extCertPolicyFpkiPiviAuthOid);
  4644. break;
  4645. #endif /* WOLFSSL_FPKI */
  4646. default:
  4647. break;
  4648. }
  4649. break;
  4650. case oidCertAltNameType:
  4651. switch (id) {
  4652. case HW_NAME_OID:
  4653. oid = extAltNamesHwNameOid;
  4654. *oidSz = sizeof(extAltNamesHwNameOid);
  4655. break;
  4656. default:
  4657. break;
  4658. }
  4659. break;
  4660. case oidCertKeyUseType:
  4661. switch (id) {
  4662. case EKU_ANY_OID:
  4663. oid = extExtKeyUsageAnyOid;
  4664. *oidSz = sizeof(extExtKeyUsageAnyOid);
  4665. break;
  4666. case EKU_SERVER_AUTH_OID:
  4667. oid = extExtKeyUsageServerAuthOid;
  4668. *oidSz = sizeof(extExtKeyUsageServerAuthOid);
  4669. break;
  4670. case EKU_CLIENT_AUTH_OID:
  4671. oid = extExtKeyUsageClientAuthOid;
  4672. *oidSz = sizeof(extExtKeyUsageClientAuthOid);
  4673. break;
  4674. case EKU_CODESIGNING_OID:
  4675. oid = extExtKeyUsageCodeSigningOid;
  4676. *oidSz = sizeof(extExtKeyUsageCodeSigningOid);
  4677. break;
  4678. case EKU_EMAILPROTECT_OID:
  4679. oid = extExtKeyUsageEmailProtectOid;
  4680. *oidSz = sizeof(extExtKeyUsageEmailProtectOid);
  4681. break;
  4682. case EKU_TIMESTAMP_OID:
  4683. oid = extExtKeyUsageTimestampOid;
  4684. *oidSz = sizeof(extExtKeyUsageTimestampOid);
  4685. break;
  4686. case EKU_OCSP_SIGN_OID:
  4687. oid = extExtKeyUsageOcspSignOid;
  4688. *oidSz = sizeof(extExtKeyUsageOcspSignOid);
  4689. break;
  4690. #ifdef WOLFSSL_WOLFSSH
  4691. case EKU_SSH_CLIENT_AUTH_OID:
  4692. oid = extExtKeyUsageSshClientAuthOid;
  4693. *oidSz = sizeof(extExtKeyUsageSshClientAuthOid);
  4694. break;
  4695. case EKU_SSH_MSCL_OID:
  4696. oid = extExtKeyUsageSshMSCLOid;
  4697. *oidSz = sizeof(extExtKeyUsageSshMSCLOid);
  4698. break;
  4699. case EKU_SSH_KP_CLIENT_AUTH_OID:
  4700. oid = extExtKeyUsageSshKpClientAuthOid;
  4701. *oidSz = sizeof(extExtKeyUsageSshKpClientAuthOid);
  4702. break;
  4703. #endif /* WOLFSSL_WOLFSSH */
  4704. default:
  4705. break;
  4706. }
  4707. break;
  4708. case oidKdfType:
  4709. switch (id) {
  4710. case PBKDF2_OID:
  4711. oid = pbkdf2Oid;
  4712. *oidSz = sizeof(pbkdf2Oid);
  4713. break;
  4714. default:
  4715. break;
  4716. }
  4717. break;
  4718. case oidPBEType:
  4719. switch (id) {
  4720. #if !defined(NO_SHA) && !defined(NO_RC4)
  4721. case PBE_SHA1_RC4_128_SUM:
  4722. case PBE_SHA1_RC4_128:
  4723. oid = pbeSha1RC4128;
  4724. *oidSz = sizeof(pbeSha1RC4128);
  4725. break;
  4726. #endif
  4727. #if !defined(NO_MD5) && !defined(NO_DES3)
  4728. case PBE_MD5_DES_SUM:
  4729. case PBE_MD5_DES:
  4730. oid = pbeMd5Des;
  4731. *oidSz = sizeof(pbeMd5Des);
  4732. break;
  4733. #endif
  4734. #if !defined(NO_SHA) && !defined(NO_DES3)
  4735. case PBE_SHA1_DES_SUM:
  4736. case PBE_SHA1_DES:
  4737. oid = pbeSha1Des;
  4738. *oidSz = sizeof(pbeSha1Des);
  4739. break;
  4740. #endif
  4741. #if !defined(NO_SHA) && !defined(NO_DES3)
  4742. case PBE_SHA1_DES3_SUM:
  4743. case PBE_SHA1_DES3:
  4744. oid = pbeSha1Des3;
  4745. *oidSz = sizeof(pbeSha1Des3);
  4746. break;
  4747. #endif
  4748. #if !defined(NO_SHA) && defined(WC_RC2)
  4749. case PBE_SHA1_40RC2_CBC_SUM:
  4750. case PBE_SHA1_40RC2_CBC:
  4751. oid = pbe40Rc2Cbc;
  4752. *oidSz = sizeof(pbe40Rc2Cbc);
  4753. break;
  4754. #endif
  4755. case PBES2_SUM:
  4756. case PBES2:
  4757. oid = pbes2;
  4758. *oidSz = sizeof(pbes2);
  4759. break;
  4760. default:
  4761. break;
  4762. }
  4763. break;
  4764. case oidKeyWrapType:
  4765. switch (id) {
  4766. #ifdef WOLFSSL_AES_128
  4767. case AES128_WRAP:
  4768. oid = wrapAes128Oid;
  4769. *oidSz = sizeof(wrapAes128Oid);
  4770. break;
  4771. #endif
  4772. #ifdef WOLFSSL_AES_192
  4773. case AES192_WRAP:
  4774. oid = wrapAes192Oid;
  4775. *oidSz = sizeof(wrapAes192Oid);
  4776. break;
  4777. #endif
  4778. #ifdef WOLFSSL_AES_256
  4779. case AES256_WRAP:
  4780. oid = wrapAes256Oid;
  4781. *oidSz = sizeof(wrapAes256Oid);
  4782. break;
  4783. #endif
  4784. #ifdef HAVE_PKCS7
  4785. case PWRI_KEK_WRAP:
  4786. oid = wrapPwriKekOid;
  4787. *oidSz = sizeof(wrapPwriKekOid);
  4788. break;
  4789. #endif
  4790. default:
  4791. break;
  4792. }
  4793. break;
  4794. case oidCmsKeyAgreeType:
  4795. switch (id) {
  4796. #ifndef NO_SHA
  4797. case dhSinglePass_stdDH_sha1kdf_scheme:
  4798. oid = dhSinglePass_stdDH_sha1kdf_Oid;
  4799. *oidSz = sizeof(dhSinglePass_stdDH_sha1kdf_Oid);
  4800. break;
  4801. #endif
  4802. #ifdef WOLFSSL_SHA224
  4803. case dhSinglePass_stdDH_sha224kdf_scheme:
  4804. oid = dhSinglePass_stdDH_sha224kdf_Oid;
  4805. *oidSz = sizeof(dhSinglePass_stdDH_sha224kdf_Oid);
  4806. break;
  4807. #endif
  4808. #ifndef NO_SHA256
  4809. case dhSinglePass_stdDH_sha256kdf_scheme:
  4810. oid = dhSinglePass_stdDH_sha256kdf_Oid;
  4811. *oidSz = sizeof(dhSinglePass_stdDH_sha256kdf_Oid);
  4812. break;
  4813. #endif
  4814. #ifdef WOLFSSL_SHA384
  4815. case dhSinglePass_stdDH_sha384kdf_scheme:
  4816. oid = dhSinglePass_stdDH_sha384kdf_Oid;
  4817. *oidSz = sizeof(dhSinglePass_stdDH_sha384kdf_Oid);
  4818. break;
  4819. #endif
  4820. #ifdef WOLFSSL_SHA512
  4821. case dhSinglePass_stdDH_sha512kdf_scheme:
  4822. oid = dhSinglePass_stdDH_sha512kdf_Oid;
  4823. *oidSz = sizeof(dhSinglePass_stdDH_sha512kdf_Oid);
  4824. break;
  4825. #endif
  4826. default:
  4827. break;
  4828. }
  4829. break;
  4830. #ifndef NO_HMAC
  4831. case oidHmacType:
  4832. switch (id) {
  4833. #ifdef WOLFSSL_SHA224
  4834. case HMAC_SHA224_OID:
  4835. oid = hmacSha224Oid;
  4836. *oidSz = sizeof(hmacSha224Oid);
  4837. break;
  4838. #endif
  4839. #ifndef NO_SHA256
  4840. case HMAC_SHA256_OID:
  4841. oid = hmacSha256Oid;
  4842. *oidSz = sizeof(hmacSha256Oid);
  4843. break;
  4844. #endif
  4845. #ifdef WOLFSSL_SHA384
  4846. case HMAC_SHA384_OID:
  4847. oid = hmacSha384Oid;
  4848. *oidSz = sizeof(hmacSha384Oid);
  4849. break;
  4850. #endif
  4851. #ifdef WOLFSSL_SHA512
  4852. case HMAC_SHA512_OID:
  4853. oid = hmacSha512Oid;
  4854. *oidSz = sizeof(hmacSha512Oid);
  4855. break;
  4856. #endif
  4857. default:
  4858. break;
  4859. }
  4860. break;
  4861. #endif /* !NO_HMAC */
  4862. #ifdef HAVE_LIBZ
  4863. case oidCompressType:
  4864. switch (id) {
  4865. case ZLIBc:
  4866. oid = zlibCompress;
  4867. *oidSz = sizeof(zlibCompress);
  4868. break;
  4869. default:
  4870. break;
  4871. }
  4872. break;
  4873. #endif /* HAVE_LIBZ */
  4874. #ifdef WOLFSSL_APACHE_HTTPD
  4875. case oidCertNameType:
  4876. switch (id) {
  4877. case NID_id_on_dnsSRV:
  4878. oid = dnsSRVOid;
  4879. *oidSz = sizeof(dnsSRVOid);
  4880. break;
  4881. default:
  4882. break;
  4883. }
  4884. break;
  4885. case oidTlsExtType:
  4886. switch (id) {
  4887. case TLS_FEATURE_OID:
  4888. oid = tlsFeatureOid;
  4889. *oidSz = sizeof(tlsFeatureOid);
  4890. break;
  4891. default:
  4892. break;
  4893. }
  4894. break;
  4895. #endif /* WOLFSSL_APACHE_HTTPD */
  4896. #ifdef WOLFSSL_CERT_REQ
  4897. case oidCsrAttrType:
  4898. switch (id) {
  4899. case GIVEN_NAME_OID:
  4900. oid = attrGivenName;
  4901. *oidSz = sizeof(attrGivenName);
  4902. break;
  4903. case SURNAME_OID:
  4904. oid = attrSurname;
  4905. *oidSz = sizeof(attrSurname);
  4906. break;
  4907. case INITIALS_OID:
  4908. oid = attrInitals;
  4909. *oidSz = sizeof(attrInitals);
  4910. break;
  4911. case DNQUALIFIER_OID:
  4912. oid = attrDnQualifier;
  4913. *oidSz = sizeof(attrDnQualifier);
  4914. break;
  4915. case UNSTRUCTURED_NAME_OID:
  4916. oid = attrUnstructuredNameOid;
  4917. *oidSz = sizeof(attrUnstructuredNameOid);
  4918. break;
  4919. case PKCS9_CONTENT_TYPE_OID:
  4920. oid = attrPkcs9ContentTypeOid;
  4921. *oidSz = sizeof(attrPkcs9ContentTypeOid);
  4922. break;
  4923. case CHALLENGE_PASSWORD_OID:
  4924. oid = attrChallengePasswordOid;
  4925. *oidSz = sizeof(attrChallengePasswordOid);
  4926. break;
  4927. case SERIAL_NUMBER_OID:
  4928. oid = attrSerialNumberOid;
  4929. *oidSz = sizeof(attrSerialNumberOid);
  4930. break;
  4931. case USER_ID_OID:
  4932. oid = uidOid;
  4933. *oidSz = sizeof(uidOid);
  4934. break;
  4935. case EXTENSION_REQUEST_OID:
  4936. oid = attrExtensionRequestOid;
  4937. *oidSz = sizeof(attrExtensionRequestOid);
  4938. break;
  4939. default:
  4940. break;
  4941. }
  4942. break;
  4943. #endif
  4944. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  4945. case oidSubjDirAttrType:
  4946. switch (id) {
  4947. case SDA_DOB_OID:
  4948. oid = extSubjDirAttrDobOid;
  4949. *oidSz = sizeof(extSubjDirAttrDobOid);
  4950. break;
  4951. case SDA_POB_OID:
  4952. oid = extSubjDirAttrPobOid;
  4953. *oidSz = sizeof(extSubjDirAttrPobOid);
  4954. break;
  4955. case SDA_GENDER_OID:
  4956. oid = extSubjDirAttrGenderOid;
  4957. *oidSz = sizeof(extSubjDirAttrGenderOid);
  4958. break;
  4959. case SDA_COC_OID:
  4960. oid = extSubjDirAttrCocOid;
  4961. *oidSz = sizeof(extSubjDirAttrCocOid);
  4962. break;
  4963. case SDA_COR_OID:
  4964. oid = extSubjDirAttrCorOid;
  4965. *oidSz = sizeof(extSubjDirAttrCorOid);
  4966. break;
  4967. default:
  4968. break;
  4969. }
  4970. break;
  4971. #endif /* WOLFSSL_SUBJ_DIR_ATTR */
  4972. case oidIgnoreType:
  4973. default:
  4974. break;
  4975. }
  4976. return oid;
  4977. }
  4978. #ifdef HAVE_ECC
  4979. /* Check the OID id is for a known elliptic curve.
  4980. *
  4981. * @param [in] oid OID id.
  4982. * @return ECC set id on success.
  4983. * @return ECC_CURVE_OID_E when OID id is 0 or not supported.
  4984. */
  4985. static int CheckCurve(word32 oid)
  4986. {
  4987. int ret;
  4988. word32 oidSz;
  4989. /* Lookup OID id. */
  4990. ret = wc_ecc_get_oid(oid, NULL, &oidSz);
  4991. /* Check for error or zero length OID size (can't get OID for encoding). */
  4992. if ((ret < 0) || (oidSz == 0)) {
  4993. WOLFSSL_MSG("CheckCurve not found");
  4994. WOLFSSL_ERROR_VERBOSE(ECC_CURVE_OID_E);
  4995. ret = ECC_CURVE_OID_E;
  4996. }
  4997. /* Return ECC set id or error code. */
  4998. return ret;
  4999. }
  5000. #endif
  5001. #ifdef HAVE_OID_ENCODING
  5002. /* Encode dotted form of OID into byte array version.
  5003. *
  5004. * @param [in] in Dotted form of OID.
  5005. * @param [in] inSz Count of numbers in dotted form.
  5006. * @param [in] out Buffer to hold OID.
  5007. * @param [in, out] outSz On in, size of buffer.
  5008. * On out, number of bytes in buffer.
  5009. * @return 0 on success
  5010. * @return BAD_FUNC_ARG when in or outSz is NULL.
  5011. * @return BUFFER_E when buffer too small.
  5012. */
  5013. int EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz)
  5014. {
  5015. int i, x, len;
  5016. word32 d, t;
  5017. /* check args */
  5018. if (in == NULL || outSz == NULL) {
  5019. return BAD_FUNC_ARG;
  5020. }
  5021. /* compute length of encoded OID */
  5022. d = (in[0] * 40) + in[1];
  5023. len = 0;
  5024. for (i = 1; i < (int)inSz; i++) {
  5025. x = 0;
  5026. t = d;
  5027. while (t) {
  5028. x++;
  5029. t >>= 1;
  5030. }
  5031. len += (x / 7) + ((x % 7) ? 1 : 0) + (d == 0 ? 1 : 0);
  5032. if (i < (int)inSz - 1) {
  5033. d = in[i + 1];
  5034. }
  5035. }
  5036. if (out) {
  5037. /* verify length */
  5038. if ((int)*outSz < len) {
  5039. return BUFFER_E; /* buffer provided is not large enough */
  5040. }
  5041. /* calc first byte */
  5042. d = (in[0] * 40) + in[1];
  5043. /* encode bytes */
  5044. x = 0;
  5045. for (i = 1; i < (int)inSz; i++) {
  5046. if (d) {
  5047. int y = x, z;
  5048. byte mask = 0;
  5049. while (d) {
  5050. out[x++] = (byte)((d & 0x7F) | mask);
  5051. d >>= 7;
  5052. mask |= 0x80; /* upper bit is set on all but the last byte */
  5053. }
  5054. /* now swap bytes y...x-1 */
  5055. z = x - 1;
  5056. while (y < z) {
  5057. mask = out[y];
  5058. out[y] = out[z];
  5059. out[z] = mask;
  5060. ++y;
  5061. --z;
  5062. }
  5063. }
  5064. else {
  5065. out[x++] = 0x00; /* zero value */
  5066. }
  5067. /* next word */
  5068. if (i < (int)inSz - 1) {
  5069. d = in[i + 1];
  5070. }
  5071. }
  5072. }
  5073. /* return length */
  5074. *outSz = len;
  5075. return 0;
  5076. }
  5077. #endif /* HAVE_OID_ENCODING */
  5078. #if defined(HAVE_OID_DECODING) || defined(WOLFSSL_ASN_PRINT)
  5079. /* Encode dotted form of OID into byte array version.
  5080. *
  5081. * @param [in] in Byte array containing OID.
  5082. * @param [in] inSz Size of OID in bytes.
  5083. * @param [in] out Array to hold dotted form of OID.
  5084. * @param [in, out] outSz On in, number of elements in array.
  5085. * On out, count of numbers in dotted form.
  5086. * @return 0 on success
  5087. * @return BAD_FUNC_ARG when in or outSz is NULL.
  5088. * @return BUFFER_E when dotted form buffer too small.
  5089. */
  5090. int DecodeObjectId(const byte* in, word32 inSz, word16* out, word32* outSz)
  5091. {
  5092. int x = 0, y = 0;
  5093. word32 t = 0;
  5094. /* check args */
  5095. if (in == NULL || outSz == NULL) {
  5096. return BAD_FUNC_ARG;
  5097. }
  5098. /* decode bytes */
  5099. while (inSz--) {
  5100. t = (t << 7) | (in[x] & 0x7F);
  5101. if (!(in[x] & 0x80)) {
  5102. if (y >= (int)*outSz) {
  5103. return BUFFER_E;
  5104. }
  5105. if (y == 0) {
  5106. out[0] = (word16)(t / 40);
  5107. out[1] = (word16)(t % 40);
  5108. y = 2;
  5109. }
  5110. else {
  5111. out[y++] = (word16)t;
  5112. }
  5113. t = 0; /* reset tmp */
  5114. }
  5115. x++;
  5116. }
  5117. /* return length */
  5118. *outSz = (word32)y;
  5119. return 0;
  5120. }
  5121. #endif /* HAVE_OID_DECODING */
  5122. /* Decode the header of a BER/DER encoded OBJECT ID.
  5123. *
  5124. * @param [in] input Buffer holding DER/BER encoded data.
  5125. * @param [in, out] inOutIdx On in, starting index of header.
  5126. * On out, end of parsed header.
  5127. * @param [out] len Number of bytes in the ASN.1 data.
  5128. * @param [in] maxIdx Length of data in buffer.
  5129. * @return 0 on success.
  5130. * @return BUFFER_E when there is not enough data to parse.
  5131. * @return ASN_PARSE_E when the tag is not a OBJECT ID or length is invalid.
  5132. */
  5133. int GetASNObjectId(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  5134. {
  5135. int ret = GetASNHeader(input, ASN_OBJECT_ID, inOutIdx, len, maxIdx);
  5136. if (ret > 0) {
  5137. /* Only return 0 on success. */
  5138. ret = 0;
  5139. }
  5140. return ret;
  5141. }
  5142. /* Set the DER/BER encoding of the ASN.1 OBJECT ID header.
  5143. *
  5144. * When output is NULL, calculate the header length only.
  5145. *
  5146. * @param [in] len Length of OBJECT ID data in bytes.
  5147. * @param [out] output Buffer to write into.
  5148. * @return Number of bytes added to the buffer.
  5149. */
  5150. int SetObjectId(int len, byte* output)
  5151. {
  5152. int idx = 0;
  5153. if (output) {
  5154. /* Write out tag. */
  5155. output[idx] = ASN_OBJECT_ID;
  5156. }
  5157. /* Skip tag. */
  5158. idx += ASN_TAG_SZ;
  5159. /* Encode length - passing NULL for output will not encode. */
  5160. idx += (int)SetLength((word32)len, output ? output + idx : NULL);
  5161. /* Return index after header. */
  5162. return idx;
  5163. }
  5164. #ifdef ASN_DUMP_OID
  5165. /* Dump the OID information.
  5166. *
  5167. * Decode the OID too if function available.
  5168. *
  5169. * @param [in] oidData OID data from buffer.
  5170. * @param [in] oidSz Size of OID data in buffer.
  5171. * @param [in] oid OID id.
  5172. * @param [in] oidType Type of OID.
  5173. * @return 0 on success.
  5174. * @return BUFFER_E when not enough bytes for proper decode.
  5175. * (HAVE_OID_DECODING)
  5176. */
  5177. static int DumpOID(const byte* oidData, word32 oidSz, word32 oid,
  5178. word32 oidType)
  5179. {
  5180. int ret = 0;
  5181. word32 i;
  5182. /* support for dumping OID information */
  5183. printf("OID (Type %d, Sz %d, Sum %d): ", oidType, oidSz, oid);
  5184. /* Dump bytes in decimal. */
  5185. for (i = 0; i < oidSz; i++) {
  5186. printf("%d, ", oidData[i]);
  5187. }
  5188. printf("\n");
  5189. /* Dump bytes in hexadecimal. */
  5190. for (i = 0; i < oidSz; i++) {
  5191. printf("%02x, ", oidData[i]);
  5192. }
  5193. printf("\n");
  5194. #ifdef HAVE_OID_DECODING
  5195. {
  5196. word16 decOid[MAX_OID_SZ];
  5197. word32 decOidSz = sizeof(decOid);
  5198. /* Decode the OID into dotted form. */
  5199. ret = DecodeObjectId(oidData, oidSz, decOid, &decOidSz);
  5200. if (ret == 0) {
  5201. printf(" Decoded (Sz %d): ", decOidSz);
  5202. for (i=0; i<decOidSz; i++) {
  5203. printf("%d.", decOid[i]);
  5204. }
  5205. printf("\n");
  5206. }
  5207. else {
  5208. printf("DecodeObjectId failed: %d\n", ret);
  5209. }
  5210. }
  5211. #endif /* HAVE_OID_DECODING */
  5212. return ret;
  5213. }
  5214. #endif /* ASN_DUMP_OID */
  5215. /* Get the OID data and verify it is of the type specified when compiled in.
  5216. *
  5217. * @param [in] input Buffer holding OID.
  5218. * @param [in, out] inOutIdx On in, starting index of OID.
  5219. * On out, end of parsed OID.
  5220. * @param [out] oid OID id.
  5221. * @param [in] oidType Expected type of OID. Define NO_VERIFY_OID to
  5222. * not compile in check.
  5223. * @param [in] length Length of OID data in buffer.
  5224. * @return 0 on success.
  5225. * @return ASN_UNKNOWN_OID_E when OID is not recognized.
  5226. * @return BUFFER_E when not enough bytes for proper decode. (ASN_DUMP_OID and
  5227. * HAVE_OID_DECODING)
  5228. */
  5229. static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
  5230. word32 oidType, int length)
  5231. {
  5232. int ret = 0;
  5233. word32 idx = *inOutIdx;
  5234. #ifndef NO_VERIFY_OID
  5235. word32 actualOidSz;
  5236. const byte* actualOid;
  5237. const byte* checkOid = NULL;
  5238. word32 checkOidSz;
  5239. #endif /* NO_VERIFY_OID */
  5240. #ifdef HAVE_PQC
  5241. word32 found_collision = 0;
  5242. #endif
  5243. (void)oidType;
  5244. *oid = 0;
  5245. #ifndef NO_VERIFY_OID
  5246. /* Keep references to OID data and length for check. */
  5247. actualOid = &input[idx];
  5248. actualOidSz = (word32)length;
  5249. #endif /* NO_VERIFY_OID */
  5250. #if defined(HAVE_PQC) && defined(HAVE_LIBOQS)
  5251. /* Since we are summing it up, there could be collisions...and indeed there
  5252. * are: SPHINCS_FAST_LEVEL1 and SPHINCS_FAST_LEVEL3.
  5253. *
  5254. * We will look for the special case of SPHINCS_FAST_LEVEL3 and set *oid to
  5255. * 283 instead of 281; 282 is taken.
  5256. *
  5257. * These hacks will hopefully disappear when new standardized OIDs appear.
  5258. */
  5259. if (memcmp(&input[idx], sigSphincsFast_Level3Oid,
  5260. sizeof(sigSphincsFast_Level3Oid)) == 0) {
  5261. found_collision = SPHINCS_FAST_LEVEL3k;
  5262. }
  5263. #endif /* HAVE_PQC */
  5264. /* Sum it up for now. */
  5265. while (length--) {
  5266. /* odd HC08 compiler behavior here when input[idx++] */
  5267. *oid += (word32)input[idx];
  5268. idx++;
  5269. }
  5270. #ifdef HAVE_PQC
  5271. if (found_collision) {
  5272. *oid = found_collision;
  5273. }
  5274. #endif /* HAVE_PQC */
  5275. /* Return the index after the OID data. */
  5276. *inOutIdx = idx;
  5277. #ifndef NO_VERIFY_OID
  5278. /* 'Ignore' type means we don't care which OID it is. */
  5279. if (oidType != oidIgnoreType) {
  5280. /* Get the OID data for the id-type. */
  5281. checkOid = OidFromId(*oid, oidType, &checkOidSz);
  5282. #if defined(WOLFSSL_FPKI)
  5283. /* Handle OID sum collision of
  5284. AES256CBCb (454) 2.16.840.1.101.3.4.1.42
  5285. CP_FPKI_PIV_AUTH_HW_OID (454) 2.16.840.1.101.3.2.1.3.41
  5286. */
  5287. #if defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  5288. if ((actualOidSz == (word32)sizeof(blkAes256CbcOid)) &&
  5289. (XMEMCMP(actualOid, blkAes256CbcOid,
  5290. sizeof(blkAes256CbcOid)) == 0)) {
  5291. checkOid = blkAes256CbcOid;
  5292. checkOidSz = sizeof(blkAes256CbcOid);
  5293. }
  5294. #endif /* HAVE_AES_CBC */
  5295. #endif /* WOLFSSL_FPKI */
  5296. #ifdef ASN_DUMP_OID
  5297. /* Dump out the data for debug. */
  5298. ret = DumpOID(actualOid, actualOidSz, *oid, oidType);
  5299. #endif
  5300. /* TODO: Want to fail when checkOid is NULL.
  5301. * Can't as too many situations where unknown OID is to be
  5302. * supported. Extra parameter for must not be NULL?
  5303. */
  5304. /* Check that the OID data matches what we found for the OID id. */
  5305. if ((ret == 0) && (checkOid != NULL) && ((checkOidSz != actualOidSz) ||
  5306. (XMEMCMP(actualOid, checkOid, checkOidSz) != 0))) {
  5307. WOLFSSL_MSG("OID Check Failed");
  5308. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  5309. ret = ASN_UNKNOWN_OID_E;
  5310. }
  5311. }
  5312. #endif /* NO_VERIFY_OID */
  5313. return ret;
  5314. }
  5315. #ifdef WOLFSSL_ASN_TEMPLATE
  5316. /* ASN.1 template for an OBJECT_ID. */
  5317. static const ASNItem objectIdASN[] = {
  5318. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 }
  5319. };
  5320. enum {
  5321. OBJECTIDASN_IDX_OID = 0
  5322. };
  5323. /* Number of items in ASN.1 template for an OBJECT_ID. */
  5324. #define objectIdASN_Length (sizeof(objectIdASN) / sizeof(ASNItem))
  5325. #endif
  5326. /* Get the OID id/sum from the BER encoded OBJECT_ID.
  5327. *
  5328. * @param [in] input Buffer holding BER encoded data.
  5329. * @param [in, out] inOutIdx On in, start of OBJECT_ID.
  5330. * On out, start of ASN.1 item after OBJECT_ID.
  5331. * @param [out] oid Id of OID in OBJECT_ID data.
  5332. * @param [in] oidType Type of OID to expect.
  5333. * @param [in] maxIdx Maximum index of data in buffer.
  5334. * @return 0 on success.
  5335. * @return ASN_PARSE_E when encoding is invalid.
  5336. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  5337. */
  5338. int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
  5339. word32 oidType, word32 maxIdx)
  5340. {
  5341. #ifndef WOLFSSL_ASN_TEMPLATE
  5342. int ret, length;
  5343. WOLFSSL_ENTER("GetObjectId");
  5344. ret = GetASNObjectId(input, inOutIdx, &length, maxIdx);
  5345. if (ret != 0)
  5346. return ret;
  5347. return GetOID(input, inOutIdx, oid, oidType, length);
  5348. #else
  5349. ASNGetData dataASN[objectIdASN_Length];
  5350. int ret;
  5351. WOLFSSL_ENTER("GetObjectId");
  5352. /* Clear dynamic data and set OID type expected. */
  5353. XMEMSET(dataASN, 0, sizeof(dataASN));
  5354. GetASN_OID(&dataASN[OBJECTIDASN_IDX_OID], oidType);
  5355. /* Decode OBJECT_ID. */
  5356. ret = GetASN_Items(objectIdASN, dataASN, objectIdASN_Length, 0, input,
  5357. inOutIdx, maxIdx);
  5358. if (ret == 0) {
  5359. /* Return the id/sum. */
  5360. *oid = dataASN[OBJECTIDASN_IDX_OID].data.oid.sum;
  5361. }
  5362. return ret;
  5363. #endif /* WOLFSSL_ASN_TEMPLATE */
  5364. }
  5365. #ifndef WOLFSSL_ASN_TEMPLATE
  5366. static int SkipObjectId(const byte* input, word32* inOutIdx, word32 maxIdx)
  5367. {
  5368. word32 idx = *inOutIdx;
  5369. int length;
  5370. int ret;
  5371. ret = GetASNObjectId(input, &idx, &length, maxIdx);
  5372. if (ret != 0)
  5373. return ret;
  5374. idx += (word32)length;
  5375. *inOutIdx = idx;
  5376. return 0;
  5377. }
  5378. #endif
  5379. #ifdef WOLFSSL_ASN_TEMPLATE
  5380. /* ASN.1 template for an algorithm identifier. */
  5381. static const ASNItem algoIdASN[] = {
  5382. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5383. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  5384. /* NULL */ { 1, ASN_TAG_NULL, 0, 0, 1 },
  5385. };
  5386. enum {
  5387. ALGOIDASN_IDX_SEQ = 0,
  5388. ALGOIDASN_IDX_OID,
  5389. ALGOIDASN_IDX_NULL
  5390. };
  5391. /* Number of items in ASN.1 template for an algorithm identifier. */
  5392. #define algoIdASN_Length (sizeof(algoIdASN) / sizeof(ASNItem))
  5393. #endif
  5394. /* Get the OID id/sum from the BER encoding of an algorithm identifier.
  5395. *
  5396. * NULL tag is skipped if present.
  5397. *
  5398. * @param [in] input Buffer holding BER encoded data.
  5399. * @param [in, out] inOutIdx On in, start of algorithm identifier.
  5400. * On out, start of ASN.1 item after algorithm id.
  5401. * @param [out] oid Id of OID in algorithm identifier data.
  5402. * @param [in] oidType Type of OID to expect.
  5403. * @param [in] maxIdx Maximum index of data in buffer.
  5404. * @return 0 on success.
  5405. * @return ASN_PARSE_E when encoding is invalid.
  5406. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  5407. */
  5408. int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
  5409. word32 oidType, word32 maxIdx)
  5410. {
  5411. #ifndef WOLFSSL_ASN_TEMPLATE
  5412. int length;
  5413. word32 idx = *inOutIdx;
  5414. int ret;
  5415. *oid = 0;
  5416. WOLFSSL_ENTER("GetAlgoId");
  5417. if (GetSequence(input, &idx, &length, maxIdx) < 0)
  5418. return ASN_PARSE_E;
  5419. if (GetObjectId(input, &idx, oid, oidType, maxIdx) < 0)
  5420. return ASN_OBJECT_ID_E;
  5421. /* could have NULL tag and 0 terminator, but may not */
  5422. if (idx < maxIdx) {
  5423. word32 localIdx = idx; /*use localIdx to not advance when checking tag*/
  5424. byte tag;
  5425. if (GetASNTag(input, &localIdx, &tag, maxIdx) == 0) {
  5426. if (tag == ASN_TAG_NULL) {
  5427. ret = GetASNNull(input, &idx, maxIdx);
  5428. if (ret != 0)
  5429. return ret;
  5430. }
  5431. }
  5432. }
  5433. *inOutIdx = idx;
  5434. return 0;
  5435. #else
  5436. DECL_ASNGETDATA(dataASN, algoIdASN_Length);
  5437. int ret = 0;
  5438. WOLFSSL_ENTER("GetAlgoId");
  5439. CALLOC_ASNGETDATA(dataASN, algoIdASN_Length, ret, NULL);
  5440. if (ret == 0) {
  5441. /* Set OID type expected. */
  5442. GetASN_OID(&dataASN[ALGOIDASN_IDX_OID], oidType);
  5443. /* Decode the algorithm identifier. */
  5444. ret = GetASN_Items(algoIdASN, dataASN, algoIdASN_Length, 0, input,
  5445. inOutIdx, maxIdx);
  5446. }
  5447. if (ret == 0) {
  5448. /* Return the OID id/sum. */
  5449. *oid = dataASN[ALGOIDASN_IDX_OID].data.oid.sum;
  5450. }
  5451. FREE_ASNGETDATA(dataASN, NULL);
  5452. return ret;
  5453. #endif /* WOLFSSL_ASN_TEMPLATE */
  5454. }
  5455. #ifndef NO_RSA
  5456. #ifdef WC_RSA_PSS
  5457. /* RFC 8017 - PKCS #1 has RSA PSS parameter ASN definition. */
  5458. /* Convert a hash OID to a hash type.
  5459. *
  5460. * @param [in] oid Hash OID.
  5461. * @param [out] type Hash type.
  5462. * @return 0 on success.
  5463. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5464. */
  5465. static int RsaPssHashOidToType(word32 oid, enum wc_HashType* type)
  5466. {
  5467. int ret = 0;
  5468. switch (oid) {
  5469. /* SHA-1 is missing as it is the default is not allowed to appear. */
  5470. #ifdef WOLFSSL_SHA224
  5471. case SHA224h:
  5472. *type = WC_HASH_TYPE_SHA224;
  5473. break;
  5474. #endif
  5475. #ifndef NO_SHA256
  5476. case SHA256h:
  5477. *type = WC_HASH_TYPE_SHA256;
  5478. break;
  5479. #endif
  5480. #ifdef WOLFSSL_SHA384
  5481. case SHA384h:
  5482. *type = WC_HASH_TYPE_SHA384;
  5483. break;
  5484. #endif
  5485. #ifdef WOLFSSL_SHA512
  5486. case SHA512h:
  5487. *type = WC_HASH_TYPE_SHA512;
  5488. break;
  5489. /* TODO: SHA512_224h */
  5490. /* TODO: SHA512_256h */
  5491. #endif
  5492. default:
  5493. ret = ASN_PARSE_E;
  5494. break;
  5495. }
  5496. return ret;
  5497. }
  5498. /* Convert a hash OID to a MGF1 type.
  5499. *
  5500. * @param [in] oid Hash OID.
  5501. * @param [out] mgf MGF type.
  5502. * @return 0 on success.
  5503. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5504. */
  5505. static int RsaPssHashOidToMgf1(word32 oid, int* mgf)
  5506. {
  5507. int ret = 0;
  5508. switch (oid) {
  5509. /* SHA-1 is missing as it is the default is not allowed to appear. */
  5510. #ifdef WOLFSSL_SHA224
  5511. case SHA224h:
  5512. *mgf = WC_MGF1SHA224;
  5513. break;
  5514. #endif
  5515. #ifndef NO_SHA256
  5516. case SHA256h:
  5517. *mgf = WC_MGF1SHA256;
  5518. break;
  5519. #endif
  5520. #ifdef WOLFSSL_SHA384
  5521. case SHA384h:
  5522. *mgf = WC_MGF1SHA384;
  5523. break;
  5524. #endif
  5525. #ifdef WOLFSSL_SHA512
  5526. case SHA512h:
  5527. *mgf = WC_MGF1SHA512;
  5528. break;
  5529. /* TODO: SHA512_224h */
  5530. /* TODO: SHA512_256h */
  5531. #endif
  5532. default:
  5533. ret = ASN_PARSE_E;
  5534. break;
  5535. }
  5536. return ret;
  5537. }
  5538. #ifndef NO_CERTS
  5539. /* Convert a hash OID to a fake signature OID.
  5540. *
  5541. * @param [in] oid Hash OID.
  5542. * @param [out] sigOid Signature OID to pass wto HashForSignature().
  5543. * @return 0 on success.
  5544. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5545. */
  5546. static int RsaPssHashOidToSigOid(word32 oid, word32* sigOid)
  5547. {
  5548. int ret = 0;
  5549. switch (oid) {
  5550. #ifndef NO_SHA
  5551. case WC_HASH_TYPE_SHA:
  5552. *sigOid = CTC_SHAwRSA;
  5553. break;
  5554. #endif
  5555. #ifdef WOLFSSL_SHA224
  5556. case WC_HASH_TYPE_SHA224:
  5557. *sigOid = CTC_SHA224wRSA;
  5558. break;
  5559. #endif
  5560. #ifndef NO_SHA256
  5561. case WC_HASH_TYPE_SHA256:
  5562. *sigOid = CTC_SHA256wRSA;
  5563. break;
  5564. #endif
  5565. #ifdef WOLFSSL_SHA384
  5566. case WC_HASH_TYPE_SHA384:
  5567. *sigOid = CTC_SHA384wRSA;
  5568. break;
  5569. #endif
  5570. #ifdef WOLFSSL_SHA512
  5571. case WC_HASH_TYPE_SHA512:
  5572. *sigOid = CTC_SHA512wRSA;
  5573. break;
  5574. #endif
  5575. /* TODO: SHA512_224h */
  5576. /* TODO: SHA512_256h */
  5577. /* Not supported by HashForSignature() */
  5578. default:
  5579. ret = ASN_PARSE_E;
  5580. break;
  5581. }
  5582. return ret;
  5583. }
  5584. #endif
  5585. #ifdef WOLFSSL_ASN_TEMPLATE
  5586. /* ASN tag for hashAlgorigthm. */
  5587. #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | 0)
  5588. /* ASN tag for maskGenAlgorithm. */
  5589. #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | 1)
  5590. /* ASN tag for saltLength. */
  5591. #define ASN_TAG_RSA_PSS_SALTLEN (ASN_CONTEXT_SPECIFIC | 2)
  5592. /* ASN tag for trailerField. */
  5593. #define ASN_TAG_RSA_PSS_TRAILER (ASN_CONTEXT_SPECIFIC | 3)
  5594. /* ASN.1 template for RSA PSS parameters. */
  5595. static const ASNItem rsaPssParamsASN[] = {
  5596. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5597. /* HASH */ { 1, ASN_TAG_RSA_PSS_HASH, 1, 1, 1 },
  5598. /* HASHSEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  5599. /* HASHOID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  5600. /* HASHNULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  5601. /* MGF */ { 1, ASN_TAG_RSA_PSS_MGF, 1, 1, 1 },
  5602. /* MGFSEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  5603. /* MGFOID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  5604. /* MGFPARAM */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  5605. /* MGFHOID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  5606. /* MGFHNULL */ { 4, ASN_TAG_NULL, 0, 0, 1 },
  5607. /* SALTLEN */ { 1, ASN_TAG_RSA_PSS_SALTLEN, 1, 1, 1 },
  5608. /* SALTLENINT */ { 2, ASN_INTEGER, 0, 0, 0 },
  5609. /* TRAILER */ { 1, ASN_TAG_RSA_PSS_TRAILER, 1, 1, 1 },
  5610. /* TRAILERINT */ { 2, ASN_INTEGER, 0, 0, 0 },
  5611. };
  5612. enum {
  5613. RSAPSSPARAMSASN_IDX_SEQ = 0,
  5614. RSAPSSPARAMSASN_IDX_HASH,
  5615. RSAPSSPARAMSASN_IDX_HASHSEQ,
  5616. RSAPSSPARAMSASN_IDX_HASHOID,
  5617. RSAPSSPARAMSASN_IDX_HASHNULL,
  5618. RSAPSSPARAMSASN_IDX_MGF,
  5619. RSAPSSPARAMSASN_IDX_MGFSEQ,
  5620. RSAPSSPARAMSASN_IDX_MGFOID,
  5621. RSAPSSPARAMSASN_IDX_MGFPARAM,
  5622. RSAPSSPARAMSASN_IDX_MGFHOID,
  5623. RSAPSSPARAMSASN_IDX_MGFHNULL,
  5624. RSAPSSPARAMSASN_IDX_SALTLEN,
  5625. RSAPSSPARAMSASN_IDX_SALTLENINT,
  5626. RSAPSSPARAMSASN_IDX_TRAILER,
  5627. RSAPSSPARAMSASN_IDX_TRAILERINT,
  5628. };
  5629. /* Number of items in ASN.1 template for an algorithm identifier. */
  5630. #define rsaPssParamsASN_Length (sizeof(rsaPssParamsASN) / sizeof(ASNItem))
  5631. #else
  5632. /* ASN tag for hashAlgorigthm. */
  5633. #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0)
  5634. /* ASN tag for maskGenAlgorithm. */
  5635. #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)
  5636. /* ASN tag for saltLength. */
  5637. #define ASN_TAG_RSA_PSS_SALTLEN (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)
  5638. /* ASN tag for trailerField. */
  5639. #define ASN_TAG_RSA_PSS_TRAILER (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)
  5640. #endif
  5641. /* Decode the RSA PSS parameters.
  5642. *
  5643. * @param [in] params Buffer holding BER encoded RSA PSS parameters.
  5644. * @param [in] sz Size of data in buffer in bytes.
  5645. * @param [out] hash Hash algorithm to use on message.
  5646. * @param [out] mgf MGF algorithm to use with PSS padding.
  5647. * @param [out] saltLen Length of salt in PSS padding.
  5648. * @return BAD_FUNC_ARG when the params is NULL.
  5649. * @return ASN_PARSE_E when the decoding fails.
  5650. * @return 0 on success.
  5651. */
  5652. static int DecodeRsaPssParams(const byte* params, word32 sz,
  5653. enum wc_HashType* hash, int* mgf, int* saltLen)
  5654. {
  5655. #ifndef WOLFSSL_ASN_TEMPLATE
  5656. int ret = 0;
  5657. word32 idx = 0;
  5658. int len = 0;
  5659. word32 oid = 0;
  5660. byte tag;
  5661. int length;
  5662. if (params == NULL) {
  5663. ret = BAD_FUNC_ARG;
  5664. }
  5665. if ((ret == 0) && (GetSequence_ex(params, &idx, &len, sz, 1) < 0)) {
  5666. ret = ASN_PARSE_E;
  5667. }
  5668. if (ret == 0) {
  5669. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_HASH)) {
  5670. /* Hash algorithm to use on message. */
  5671. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5672. ret = ASN_PARSE_E;
  5673. }
  5674. if (ret == 0) {
  5675. if (GetAlgoId(params, &idx, &oid, oidHashType, sz) < 0) {
  5676. ret = ASN_PARSE_E;
  5677. }
  5678. }
  5679. if (ret == 0) {
  5680. ret = RsaPssHashOidToType(oid, hash);
  5681. }
  5682. }
  5683. else {
  5684. /* Default hash algorithm. */
  5685. *hash = WC_HASH_TYPE_SHA;
  5686. }
  5687. }
  5688. if (ret == 0) {
  5689. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_MGF)) {
  5690. /* MGF and hash algorithm to use with padding. */
  5691. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5692. ret = ASN_PARSE_E;
  5693. }
  5694. if (ret == 0) {
  5695. if (GetAlgoId(params, &idx, &oid, oidIgnoreType, sz) < 0) {
  5696. ret = ASN_PARSE_E;
  5697. }
  5698. }
  5699. if ((ret == 0) && (oid != MGF1_OID)) {
  5700. ret = ASN_PARSE_E;
  5701. }
  5702. if (ret == 0) {
  5703. ret = GetAlgoId(params, &idx, &oid, oidHashType, sz);
  5704. if (ret == 0) {
  5705. ret = RsaPssHashOidToMgf1(oid, mgf);
  5706. }
  5707. }
  5708. }
  5709. else {
  5710. /* Default MGF/Hash algorithm. */
  5711. *mgf = WC_MGF1SHA1;
  5712. }
  5713. }
  5714. if (ret == 0) {
  5715. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_SALTLEN)) {
  5716. /* Salt length to use with padding. */
  5717. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5718. ret = ASN_PARSE_E;
  5719. }
  5720. if (ret == 0) {
  5721. ret = GetInteger16Bit(params, &idx, sz);
  5722. if (ret >= 0) {
  5723. *saltLen = ret;
  5724. ret = 0;
  5725. }
  5726. }
  5727. }
  5728. else {
  5729. /* Default salt length. */
  5730. *saltLen = 20;
  5731. }
  5732. }
  5733. if (ret == 0) {
  5734. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_TRAILER)) {
  5735. /* Unused - trialerField. */
  5736. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5737. ret = ASN_PARSE_E;
  5738. }
  5739. if (ret == 0) {
  5740. ret = GetInteger16Bit(params, &idx, sz);
  5741. if (ret > 0) {
  5742. ret = 0;
  5743. }
  5744. }
  5745. }
  5746. }
  5747. if ((ret == 0) && (idx != sz)) {
  5748. ret = ASN_PARSE_E;
  5749. }
  5750. return ret;
  5751. #else
  5752. DECL_ASNGETDATA(dataASN, rsaPssParamsASN_Length);
  5753. int ret = 0;
  5754. word16 sLen = 20;
  5755. if (params == NULL) {
  5756. ret = BAD_FUNC_ARG;
  5757. }
  5758. CALLOC_ASNGETDATA(dataASN, rsaPssParamsASN_Length, ret, NULL);
  5759. if (ret == 0) {
  5760. word32 inOutIdx = 0;
  5761. /* Default values. */
  5762. *hash = WC_HASH_TYPE_SHA;
  5763. *mgf = WC_MGF1SHA1;
  5764. /* Set OID type expected. */
  5765. GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_HASHOID], oidHashType);
  5766. GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_MGFHOID], oidHashType);
  5767. /* Place the salt length into 16-bit var sLen. */
  5768. GetASN_Int16Bit(&dataASN[RSAPSSPARAMSASN_IDX_SALTLENINT], &sLen);
  5769. /* Decode the algorithm identifier. */
  5770. ret = GetASN_Items(rsaPssParamsASN, dataASN, rsaPssParamsASN_Length, 1,
  5771. params, &inOutIdx, sz);
  5772. }
  5773. if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_HASHOID].tag != 0)) {
  5774. word32 oid = dataASN[RSAPSSPARAMSASN_IDX_HASHOID].data.oid.sum;
  5775. ret = RsaPssHashOidToType(oid, hash);
  5776. }
  5777. if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].tag != 0)) {
  5778. word32 oid = dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].data.oid.sum;
  5779. ret = RsaPssHashOidToMgf1(oid, mgf);
  5780. }
  5781. if (ret == 0) {
  5782. *saltLen = sLen;
  5783. }
  5784. FREE_ASNGETDATA(dataASN, NULL);
  5785. return ret;
  5786. #endif /* WOLFSSL_ASN_TEMPLATE */
  5787. }
  5788. #endif /* WC_RSA_PSS */
  5789. #ifndef HAVE_USER_RSA
  5790. #if defined(WOLFSSL_ASN_TEMPLATE) || (!defined(NO_CERTS) && \
  5791. (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  5792. defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)))
  5793. /* Byte offset of numbers in RSA key. */
  5794. size_t rsaIntOffset[] = {
  5795. OFFSETOF(RsaKey, n),
  5796. OFFSETOF(RsaKey, e),
  5797. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  5798. OFFSETOF(RsaKey, d),
  5799. OFFSETOF(RsaKey, p),
  5800. OFFSETOF(RsaKey, q),
  5801. #if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
  5802. OFFSETOF(RsaKey, dP),
  5803. OFFSETOF(RsaKey, dQ),
  5804. OFFSETOF(RsaKey, u)
  5805. #endif
  5806. #endif
  5807. };
  5808. /* Get a number from the RSA key based on an index.
  5809. *
  5810. * Order: { n, e, d, p, q, dP, dQ, u }
  5811. *
  5812. * Caller must ensure index is not invalid!
  5813. *
  5814. * @param [in] key RSA key object.
  5815. * @param [in] idx Index of number.
  5816. * @return A pointer to an mp_int when valid index.
  5817. * @return NULL when invalid index.
  5818. */
  5819. static mp_int* GetRsaInt(RsaKey* key, int idx)
  5820. {
  5821. /* Cast key to byte array to and use offset to get to mp_int field. */
  5822. return (mp_int*)(((byte*)key) + rsaIntOffset[idx]);
  5823. }
  5824. #endif
  5825. #ifdef WOLFSSL_ASN_TEMPLATE
  5826. /* ASN.1 template for an RSA private key.
  5827. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  5828. */
  5829. static const ASNItem rsaKeyASN[] = {
  5830. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5831. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  5832. /* Integers need to be in this specific order
  5833. * as asn code depends on this. */
  5834. /* N */ { 1, ASN_INTEGER, 0, 0, 0 },
  5835. /* E */ { 1, ASN_INTEGER, 0, 0, 0 },
  5836. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  5837. /* D */ { 1, ASN_INTEGER, 0, 0, 0 },
  5838. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  5839. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  5840. /* DP */ { 1, ASN_INTEGER, 0, 0, 0 },
  5841. /* DQ */ { 1, ASN_INTEGER, 0, 0, 0 },
  5842. /* U */ { 1, ASN_INTEGER, 0, 0, 0 },
  5843. /* otherPrimeInfos OtherPrimeInfos OPTIONAL
  5844. * v2 - multiprime */
  5845. #endif
  5846. };
  5847. enum {
  5848. RSAKEYASN_IDX_SEQ = 0,
  5849. RSAKEYASN_IDX_VER,
  5850. /* Integers need to be in this specific order
  5851. * as asn code depends on this. */
  5852. RSAKEYASN_IDX_N,
  5853. RSAKEYASN_IDX_E,
  5854. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  5855. RSAKEYASN_IDX_D,
  5856. RSAKEYASN_IDX_P,
  5857. RSAKEYASN_IDX_Q,
  5858. RSAKEYASN_IDX_DP,
  5859. RSAKEYASN_IDX_DQ,
  5860. RSAKEYASN_IDX_U,
  5861. #endif
  5862. WOLF_ENUM_DUMMY_LAST_ELEMENT(RSAKEYASN_IDX)
  5863. };
  5864. /* Number of items in ASN.1 template for an RSA private key. */
  5865. #define rsaKeyASN_Length (sizeof(rsaKeyASN) / sizeof(ASNItem))
  5866. #endif
  5867. /* Decode RSA private key.
  5868. *
  5869. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  5870. *
  5871. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  5872. * being extracted.
  5873. *
  5874. * @param [in] input Buffer holding BER encoded data.
  5875. * @param [in, out] inOutIdx On in, start of RSA private key.
  5876. * On out, start of ASN.1 item after RSA private key.
  5877. * @param [in, out] key RSA key object. May be NULL.
  5878. * @param [out] keySz Size of key in bytes. May be NULL.
  5879. * @param [in] inSz Number of bytes in buffer.
  5880. * @return 0 on success.
  5881. * @return BAD_FUNC_ARG when input or inOutIdx is NULL.
  5882. * @return BAD_FUNC_ARG when key and keySz are NULL.
  5883. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  5884. * is invalid.
  5885. * @return BUFFER_E when data in buffer is too small.
  5886. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  5887. * non-zero length.
  5888. * @return MP_INIT_E when the unable to initialize an mp_int.
  5889. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  5890. */
  5891. static int _RsaPrivateKeyDecode(const byte* input, word32* inOutIdx,
  5892. RsaKey* key, int* keySz, word32 inSz)
  5893. {
  5894. #ifndef WOLFSSL_ASN_TEMPLATE
  5895. int version, length;
  5896. word32 algId = 0;
  5897. if (inOutIdx == NULL || input == NULL || (key == NULL && keySz == NULL)) {
  5898. return BAD_FUNC_ARG;
  5899. }
  5900. /* if has pkcs8 header skip it */
  5901. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  5902. /* ignore error, did not have pkcs8 header */
  5903. }
  5904. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  5905. return ASN_PARSE_E;
  5906. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  5907. return ASN_PARSE_E;
  5908. if (key == NULL) {
  5909. int i;
  5910. /* Modulus */
  5911. if (GetASNInt(input, inOutIdx, keySz, inSz) < 0) {
  5912. return ASN_PARSE_E;
  5913. }
  5914. *inOutIdx += (word32)*keySz;
  5915. for (i = 1; i < RSA_INTS; i++) {
  5916. if (SkipInt(input, inOutIdx, inSz) < 0) {
  5917. return ASN_RSA_KEY_E;
  5918. }
  5919. }
  5920. }
  5921. else {
  5922. key->type = RSA_PRIVATE;
  5923. #ifdef WOLFSSL_CHECK_MEM_ZERO
  5924. mp_memzero_add("Decode RSA key d", &key->d);
  5925. mp_memzero_add("Decode RSA key p", &key->p);
  5926. mp_memzero_add("Decode RSA key q", &key->q);
  5927. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  5928. !defined(RSA_LOW_MEM)) && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5929. mp_memzero_add("Decode RSA key dP", &key->dP);
  5930. mp_memzero_add("Decode RSA key dQ", &key->dQ);
  5931. mp_memzero_add("Decode RSA key u", &key->u);
  5932. #endif
  5933. #endif
  5934. if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
  5935. GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
  5936. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  5937. GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
  5938. GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  5939. GetInt(&key->q, input, inOutIdx, inSz) < 0
  5940. #else
  5941. SkipInt(input, inOutIdx, inSz) < 0 ||
  5942. SkipInt(input, inOutIdx, inSz) < 0 ||
  5943. SkipInt(input, inOutIdx, inSz) < 0
  5944. #endif
  5945. ) {
  5946. return ASN_RSA_KEY_E;
  5947. }
  5948. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)) \
  5949. && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5950. if (GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
  5951. GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
  5952. GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  5953. #else
  5954. if (SkipInt(input, inOutIdx, inSz) < 0 ||
  5955. SkipInt(input, inOutIdx, inSz) < 0 ||
  5956. SkipInt(input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  5957. #endif
  5958. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  5959. if (wc_InitRsaHw(key) != 0) {
  5960. return BAD_STATE_E;
  5961. }
  5962. #endif
  5963. }
  5964. return 0;
  5965. #else
  5966. DECL_ASNGETDATA(dataASN, rsaKeyASN_Length);
  5967. int ret = 0;
  5968. byte version = (byte)-1;
  5969. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  5970. word32 algId = 0;
  5971. #endif
  5972. void* heap = NULL;
  5973. /* Check validity of parameters. */
  5974. if ((inOutIdx == NULL) || (input == NULL) || ((key == NULL) &&
  5975. (keySz == NULL))) {
  5976. ret = BAD_FUNC_ARG;
  5977. }
  5978. if ((ret == 0) && (key != NULL)) {
  5979. heap = key->heap;
  5980. }
  5981. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  5982. if (ret == 0) {
  5983. /* if has pkcs8 header skip it */
  5984. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  5985. /* ignore error, did not have pkcs8 header */
  5986. }
  5987. }
  5988. #endif
  5989. (void)heap;
  5990. CALLOC_ASNGETDATA(dataASN, rsaKeyASN_Length, ret, heap);
  5991. if (ret == 0) {
  5992. /* Register variable to hold version field. */
  5993. GetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], &version);
  5994. /* Setup data to store INTEGER data in mp_int's in RSA object. */
  5995. #if defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5996. #define RSA_ASN_INTS RSA_PUB_INTS
  5997. /* Not extracting all data from BER encoding. */
  5998. #define RSA_ASN_COMPLETE 0
  5999. #else
  6000. #define RSA_ASN_INTS RSA_INTS
  6001. /* Extracting all data from BER encoding. */
  6002. #define RSA_ASN_COMPLETE 1
  6003. #endif
  6004. if (key != NULL) {
  6005. int i;
  6006. /* Extract all public fields. */
  6007. for (i = 0; i < RSA_ASN_INTS; i++) {
  6008. GetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i],
  6009. GetRsaInt(key, i));
  6010. }
  6011. }
  6012. /* Parse BER encoding for RSA private key. */
  6013. ret = GetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length,
  6014. RSA_ASN_COMPLETE, input, inOutIdx, inSz);
  6015. }
  6016. /* Check version: 0 - two prime, 1 - multi-prime
  6017. * Multi-prime has optional sequence after coefficient for extra primes.
  6018. * If extra primes, parsing will fail as not all the buffer was used.
  6019. */
  6020. if ((ret == 0) && (version > PKCS1v1)) {
  6021. ret = ASN_PARSE_E;
  6022. }
  6023. if ((ret == 0) && (key != NULL)) {
  6024. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  6025. /* RSA key object has all private key values. */
  6026. key->type = RSA_PRIVATE;
  6027. #else
  6028. /* RSA key object has all public key values. */
  6029. key->type = RSA_PUBLIC;
  6030. #endif
  6031. #ifdef WOLFSSL_XILINX_CRYPT
  6032. if (wc_InitRsaHw(key) != 0)
  6033. ret = BAD_STATE_E;
  6034. #endif
  6035. }
  6036. else if (ret == 0) {
  6037. /* Not filling in key but do want key size. */
  6038. *keySz = (int)dataASN[(byte)RSAKEYASN_IDX_N].length;
  6039. /* Check whether first byte of data is 0x00 and drop it. */
  6040. if (input[(int)dataASN[RSAKEYASN_IDX_E].offset - *keySz] == 0) {
  6041. (*keySz)--;
  6042. }
  6043. }
  6044. FREE_ASNGETDATA(dataASN, heap);
  6045. return ret;
  6046. #endif /* WOLFSSL_ASN_TEMPLATE */
  6047. }
  6048. /* Decode RSA private key.
  6049. *
  6050. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  6051. *
  6052. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  6053. * being extracted.
  6054. *
  6055. * @param [in] input Buffer holding BER encoded data.
  6056. * @param [in, out] inOutIdx On in, start of RSA private key.
  6057. * On out, start of ASN.1 item after RSA private key.
  6058. * @param [in, out] key RSA key object.
  6059. * @param [in] inSz Number of bytes in buffer.
  6060. * @return 0 on success.
  6061. * @return BAD_FUNC_ARG when input, inOutIdx or key is NULL.
  6062. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6063. * is invalid.
  6064. * @return BUFFER_E when data in buffer is too small.
  6065. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6066. * non-zero length.
  6067. * @return MP_INIT_E when the unable to initialize an mp_int.
  6068. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  6069. */
  6070. int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  6071. word32 inSz)
  6072. {
  6073. if (key == NULL) {
  6074. return BAD_FUNC_ARG;
  6075. }
  6076. return _RsaPrivateKeyDecode(input, inOutIdx, key, NULL, inSz);
  6077. }
  6078. /* Valdidate RSA private key ASN.1 encoding.
  6079. *
  6080. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  6081. *
  6082. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  6083. * being extracted.
  6084. *
  6085. * @param [in] input Buffer holding BER encoded data.
  6086. * @param [in, out] inOutIdx On in, start of RSA private key.
  6087. * On out, start of ASN.1 item after RSA private key.
  6088. * @param [in] inSz Number of bytes in buffer.
  6089. * @return 0 on success.
  6090. * @return BAD_FUNC_ARG when input, inOutIdx or keySz is NULL.
  6091. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6092. * is invalid.
  6093. * @return BUFFER_E when data in buffer is too small.
  6094. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6095. * non-zero length.
  6096. * @return MP_INIT_E when the unable to initialize an mp_int.
  6097. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  6098. */
  6099. int wc_RsaPrivateKeyValidate(const byte* input, word32* inOutIdx, int* keySz,
  6100. word32 inSz)
  6101. {
  6102. return _RsaPrivateKeyDecode(input, inOutIdx, NULL, keySz, inSz);
  6103. }
  6104. #endif /* HAVE_USER_RSA */
  6105. #endif /* NO_RSA */
  6106. #ifdef WOLFSSL_ASN_TEMPLATE
  6107. /* ASN.1 template for a PKCS #8 key.
  6108. * Ignoring optional attributes and public key.
  6109. * PKCS #8: RFC 5958, 2 - PrivateKeyInfo
  6110. */
  6111. static const ASNItem pkcs8KeyASN[] = {
  6112. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  6113. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  6114. /* PKEY_ALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  6115. /* PKEY_ALGO_OID_KEY */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  6116. /* PKEY_ALGO_OID_CURVE */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  6117. /* PKEY_ALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  6118. #ifdef WC_RSA_PSS
  6119. /* PKEY_ALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  6120. #endif
  6121. /* PKEY_DATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  6122. /* attributes [0] Attributes OPTIONAL */
  6123. /* [[2: publicKey [1] PublicKey OPTIONAL ]] */
  6124. };
  6125. enum {
  6126. PKCS8KEYASN_IDX_SEQ = 0,
  6127. PKCS8KEYASN_IDX_VER,
  6128. PKCS8KEYASN_IDX_PKEY_ALGO_SEQ,
  6129. PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY,
  6130. PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE,
  6131. PKCS8KEYASN_IDX_PKEY_ALGO_NULL,
  6132. #ifdef WC_RSA_PSS
  6133. PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ,
  6134. #endif
  6135. PKCS8KEYASN_IDX_PKEY_DATA,
  6136. WOLF_ENUM_DUMMY_LAST_ELEMENT(PKCS8KEYASN_IDX)
  6137. };
  6138. /* Number of items in ASN.1 template for a PKCS #8 key. */
  6139. #define pkcs8KeyASN_Length (sizeof(pkcs8KeyASN) / sizeof(ASNItem))
  6140. #endif
  6141. /* Remove PKCS #8 header around an RSA, ECDSA, Ed25519, or Ed448.
  6142. *
  6143. * @param [in] input Buffer holding BER data.
  6144. * @param [in, out] inOutIdx On in, start of PKCS #8 encoding.
  6145. * On out, start of encoded key.
  6146. * @param [in] sz Size of data in buffer.
  6147. * @param [out] algId Key's algorithm id from PKCS #8 header.
  6148. * @return Length of key data on success.
  6149. * @return BAD_FUNC_ARG when input or inOutIdx is NULL.
  6150. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6151. * is invalid.
  6152. * @return BUFFER_E when data in buffer is too small.
  6153. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  6154. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6155. * non-zero length.
  6156. */
  6157. int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz,
  6158. word32* algId)
  6159. {
  6160. #ifndef WOLFSSL_ASN_TEMPLATE
  6161. word32 idx;
  6162. int version, length;
  6163. int ret;
  6164. byte tag;
  6165. if (input == NULL || inOutIdx == NULL)
  6166. return BAD_FUNC_ARG;
  6167. idx = *inOutIdx;
  6168. if (GetSequence(input, &idx, &length, sz) < 0)
  6169. return ASN_PARSE_E;
  6170. if (GetMyVersion(input, &idx, &version, sz) < 0)
  6171. return ASN_PARSE_E;
  6172. if (GetAlgoId(input, &idx, algId, oidKeyType, sz) < 0)
  6173. return ASN_PARSE_E;
  6174. if (GetASNTag(input, &idx, &tag, sz) < 0)
  6175. return ASN_PARSE_E;
  6176. idx = idx - 1; /* reset idx after finding tag */
  6177. #if defined(WC_RSA_PSS) && !defined(NO_RSA)
  6178. if (*algId == RSAPSSk && tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  6179. word32 seqIdx = idx;
  6180. int seqLen;
  6181. /* Not set when -1. */
  6182. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  6183. int mgf = -1;
  6184. int saltLen = 0;
  6185. if (GetSequence(input, &idx, &seqLen, sz) < 0) {
  6186. return ASN_PARSE_E;
  6187. }
  6188. /* Get the private key parameters. */
  6189. ret = DecodeRsaPssParams(input + seqIdx,
  6190. seqLen + idx - seqIdx, &hash, &mgf, &saltLen);
  6191. if (ret != 0) {
  6192. return ASN_PARSE_E;
  6193. }
  6194. /* TODO: store parameters so that usage can be checked. */
  6195. idx += seqLen;
  6196. }
  6197. #endif /* WC_RSA_PSS && !NO_RSA */
  6198. if (tag == ASN_OBJECT_ID) {
  6199. if (SkipObjectId(input, &idx, sz) < 0)
  6200. return ASN_PARSE_E;
  6201. }
  6202. ret = GetOctetString(input, &idx, &length, sz);
  6203. if (ret < 0) {
  6204. if (ret == BUFFER_E)
  6205. return ASN_PARSE_E;
  6206. /* Some private keys don't expect an octet string */
  6207. WOLFSSL_MSG("Couldn't find Octet string");
  6208. }
  6209. *inOutIdx = idx;
  6210. return length;
  6211. #else
  6212. DECL_ASNGETDATA(dataASN, pkcs8KeyASN_Length);
  6213. int ret = 0;
  6214. word32 oid = 9;
  6215. byte version;
  6216. word32 idx;
  6217. /* Check validity of parameters. */
  6218. if (input == NULL || inOutIdx == NULL) {
  6219. return BAD_FUNC_ARG;
  6220. }
  6221. idx = *inOutIdx;
  6222. CALLOC_ASNGETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  6223. if (ret == 0) {
  6224. /* Get version, check key type and curve type. */
  6225. GetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], &version);
  6226. GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], oidKeyType);
  6227. GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE], oidCurveType);
  6228. /* Parse data. */
  6229. ret = GetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, 1, input,
  6230. &idx, sz);
  6231. }
  6232. if (ret == 0) {
  6233. /* Key type OID. */
  6234. oid = dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY].data.oid.sum;
  6235. /* Version 1 includes an optional public key.
  6236. * If public key is included then the parsing will fail as it did not
  6237. * use all the data.
  6238. */
  6239. if (version > PKCS8v1) {
  6240. ret = ASN_PARSE_E;
  6241. }
  6242. }
  6243. if (ret == 0) {
  6244. switch (oid) {
  6245. #ifndef NO_RSA
  6246. case RSAk:
  6247. /* Must have NULL item but not OBJECT_ID item. */
  6248. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag == 0) ||
  6249. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6250. ret = ASN_PARSE_E;
  6251. }
  6252. break;
  6253. #ifdef WC_RSA_PSS
  6254. case RSAPSSk:
  6255. /* Must not have NULL item. */
  6256. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
  6257. ret = ASN_PARSE_E;
  6258. }
  6259. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].tag != 0) {
  6260. enum wc_HashType hash;
  6261. int mgf;
  6262. int saltLen;
  6263. const byte* params = GetASNItem_Addr(
  6264. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
  6265. word32 paramsSz = GetASNItem_Length(
  6266. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
  6267. /* Validate the private key parameters. */
  6268. ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf,
  6269. &saltLen);
  6270. if (ret != 0) {
  6271. return ASN_PARSE_E;
  6272. }
  6273. /* TODO: store parameters so that usage can be checked. */
  6274. }
  6275. break;
  6276. #endif
  6277. #endif
  6278. #ifdef HAVE_ECC
  6279. case ECDSAk:
  6280. /* Must not have NULL item. */
  6281. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
  6282. ret = ASN_PARSE_E;
  6283. }
  6284. break;
  6285. #endif
  6286. #ifdef HAVE_ED25519
  6287. case ED25519k:
  6288. /* Neither NULL item nor OBJECT_ID item allowed. */
  6289. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6290. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6291. ret = ASN_PARSE_E;
  6292. }
  6293. break;
  6294. #endif
  6295. #ifdef HAVE_CURVE25519
  6296. case X25519k:
  6297. /* Neither NULL item nor OBJECT_ID item allowed. */
  6298. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6299. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6300. ret = ASN_PARSE_E;
  6301. }
  6302. break;
  6303. #endif
  6304. #ifdef HAVE_ED448
  6305. case ED448k:
  6306. /* Neither NULL item nor OBJECT_ID item allowed. */
  6307. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6308. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6309. ret = ASN_PARSE_E;
  6310. }
  6311. break;
  6312. #endif
  6313. #ifdef HAVE_CURVE448
  6314. case X448k:
  6315. /* Neither NULL item nor OBJECT_ID item allowed. */
  6316. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6317. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6318. ret = ASN_PARSE_E;
  6319. }
  6320. break;
  6321. #endif
  6322. /* DSAk not supported. */
  6323. /* Falcon, Dilithium and Sphincs not supported. */
  6324. /* Ignore OID lookup failures. */
  6325. default:
  6326. break;
  6327. }
  6328. }
  6329. if (ret == 0) {
  6330. /* Return algorithm id of internal key. */
  6331. *algId = oid;
  6332. /* Return index to start of internal key. */
  6333. *inOutIdx = GetASNItem_DataIdx(dataASN[PKCS8KEYASN_IDX_PKEY_DATA], input);
  6334. /* Return value is length of internal key. */
  6335. ret = (int)dataASN[PKCS8KEYASN_IDX_PKEY_DATA].data.ref.length;
  6336. }
  6337. FREE_ASNGETDATA(dataASN, NULL);
  6338. return ret;
  6339. #endif
  6340. }
  6341. /* TODO: test case */
  6342. int ToTraditionalInline(const byte* input, word32* inOutIdx, word32 sz)
  6343. {
  6344. word32 oid;
  6345. return ToTraditionalInline_ex(input, inOutIdx, sz, &oid);
  6346. }
  6347. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6348. /* Remove PKCS8 header, move beginning of traditional to beginning of input */
  6349. int ToTraditional_ex(byte* input, word32 sz, word32* algId)
  6350. {
  6351. word32 inOutIdx = 0;
  6352. int length;
  6353. if (input == NULL)
  6354. return BAD_FUNC_ARG;
  6355. length = ToTraditionalInline_ex(input, &inOutIdx, sz, algId);
  6356. if (length < 0)
  6357. return length;
  6358. if ((word32)length + inOutIdx > sz)
  6359. return BUFFER_E;
  6360. XMEMMOVE(input, input + inOutIdx, (size_t)length);
  6361. return length;
  6362. }
  6363. int ToTraditional(byte* input, word32 sz)
  6364. {
  6365. word32 oid;
  6366. return ToTraditional_ex(input, sz, &oid);
  6367. }
  6368. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  6369. #if defined(HAVE_PKCS8)
  6370. int wc_GetPkcs8TraditionalOffset(byte* input, word32* inOutIdx, word32 sz)
  6371. {
  6372. int length;
  6373. word32 algId;
  6374. if (input == NULL || inOutIdx == NULL || (*inOutIdx > sz))
  6375. return BAD_FUNC_ARG;
  6376. length = ToTraditionalInline_ex(input, inOutIdx, sz, &algId);
  6377. return length;
  6378. }
  6379. int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz,
  6380. int algoID, const byte* curveOID, word32 oidSz)
  6381. {
  6382. #ifndef WOLFSSL_ASN_TEMPLATE
  6383. word32 keyIdx = 0;
  6384. word32 tmpSz = 0;
  6385. word32 sz;
  6386. word32 tmpAlgId = 0;
  6387. /* If out is NULL then return the max size needed
  6388. * + 2 for ASN_OBJECT_ID and ASN_OCTET_STRING tags */
  6389. if (out == NULL && outSz != NULL) {
  6390. *outSz = keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6391. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2;
  6392. if (curveOID != NULL)
  6393. *outSz += oidSz + MAX_LENGTH_SZ + 1;
  6394. WOLFSSL_MSG("Checking size of PKCS8");
  6395. return LENGTH_ONLY_E;
  6396. }
  6397. WOLFSSL_ENTER("wc_CreatePKCS8Key");
  6398. if (key == NULL || out == NULL || outSz == NULL) {
  6399. return BAD_FUNC_ARG;
  6400. }
  6401. /* check the buffer has enough room for largest possible size */
  6402. if (curveOID != NULL) {
  6403. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6404. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 3 + oidSz + MAX_LENGTH_SZ))
  6405. return BUFFER_E;
  6406. }
  6407. else {
  6408. oidSz = 0; /* with no curveOID oid size must be 0 */
  6409. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6410. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2))
  6411. return BUFFER_E;
  6412. }
  6413. /* sanity check: make sure the key doesn't already have a PKCS 8 header */
  6414. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  6415. (void)tmpAlgId;
  6416. return ASN_PARSE_E;
  6417. }
  6418. /* PrivateKeyInfo ::= SEQUENCE */
  6419. keyIdx = MAX_SEQ_SZ; /* save room for sequence */
  6420. /* version Version
  6421. * no header information just INTEGER */
  6422. sz = (word32)SetMyVersion(PKCS8v0, out + keyIdx, 0);
  6423. tmpSz += sz; keyIdx += sz;
  6424. /* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier */
  6425. sz = 0; /* set sz to 0 and get privateKey oid buffer size needed */
  6426. if (curveOID != NULL && oidSz > 0) {
  6427. byte buf[MAX_LENGTH_SZ];
  6428. sz = SetLength(oidSz, buf);
  6429. sz += 1; /* plus one for ASN object id */
  6430. }
  6431. sz = (word32)SetAlgoID(algoID, out + keyIdx, oidKeyType, (int)(oidSz + sz));
  6432. tmpSz += sz; keyIdx += sz;
  6433. /* privateKey PrivateKey *
  6434. * pkcs8 ecc uses slightly different format. Places curve oid in
  6435. * buffer */
  6436. if (curveOID != NULL && oidSz > 0) {
  6437. sz = (word32)SetObjectId((int)oidSz, out + keyIdx);
  6438. keyIdx += sz; tmpSz += sz;
  6439. XMEMCPY(out + keyIdx, curveOID, oidSz);
  6440. keyIdx += oidSz; tmpSz += oidSz;
  6441. }
  6442. sz = (word32)SetOctetString(keySz, out + keyIdx);
  6443. keyIdx += sz; tmpSz += sz;
  6444. XMEMCPY(out + keyIdx, key, keySz);
  6445. tmpSz += keySz;
  6446. /* attributes optional
  6447. * No attributes currently added */
  6448. /* rewind and add sequence */
  6449. sz = SetSequence(tmpSz, out);
  6450. XMEMMOVE(out + sz, out + MAX_SEQ_SZ, tmpSz);
  6451. *outSz = tmpSz + sz;
  6452. return (int)(tmpSz + sz);
  6453. #else
  6454. DECL_ASNSETDATA(dataASN, pkcs8KeyASN_Length);
  6455. int sz;
  6456. int ret = 0;
  6457. word32 keyIdx = 0;
  6458. word32 tmpAlgId = 0;
  6459. WOLFSSL_ENTER("wc_CreatePKCS8Key");
  6460. /* Check validity of parameters. */
  6461. if (out == NULL && outSz != NULL) {
  6462. }
  6463. else if (key == NULL || out == NULL || outSz == NULL) {
  6464. ret = BAD_FUNC_ARG;
  6465. }
  6466. /* Sanity check: make sure key doesn't have PKCS #8 header. */
  6467. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  6468. (void)tmpAlgId;
  6469. ret = ASN_PARSE_E;
  6470. }
  6471. CALLOC_ASNSETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  6472. if (ret == 0) {
  6473. /* Only support default PKCS #8 format - v0. */
  6474. SetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], PKCS8v0);
  6475. /* Set key OID that corresponds to key data. */
  6476. SetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], (word32)algoID,
  6477. oidKeyType);
  6478. if (curveOID != NULL && oidSz > 0) {
  6479. /* ECC key and curveOID set to write. */
  6480. SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE],
  6481. curveOID, oidSz);
  6482. }
  6483. else {
  6484. /* EC curve OID to encode. */
  6485. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].noOut = 1;
  6486. }
  6487. /* Only RSA keys have NULL tagged item after OID. */
  6488. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].noOut = (algoID != RSAk);
  6489. #ifdef WC_RSA_PSS
  6490. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].noOut = 1;
  6491. #endif
  6492. /* Set key data to encode. */
  6493. SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_DATA], key, keySz);
  6494. /* Get the size of the DER encoding. */
  6495. ret = SizeASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, &sz);
  6496. }
  6497. if (ret == 0) {
  6498. /* Always return the calculated size. */
  6499. *outSz = (word32)sz;
  6500. }
  6501. /* Check for buffer to encoded into. */
  6502. if ((ret == 0) && (out == NULL)) {
  6503. WOLFSSL_MSG("Checking size of PKCS8");
  6504. ret = LENGTH_ONLY_E;
  6505. }
  6506. if (ret == 0) {
  6507. /* Encode PKCS #8 key into buffer. */
  6508. SetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, out);
  6509. ret = sz;
  6510. }
  6511. FREE_ASNSETDATA(dataASN, NULL);
  6512. return ret;
  6513. #endif /* WOLFSSL_ASN_TEMPLATE */
  6514. }
  6515. #endif /* HAVE_PKCS8 */
  6516. #if defined(HAVE_PKCS12) || !defined(NO_CHECK_PRIVATE_KEY)
  6517. /* check that the private key is a pair for the public key
  6518. * return 1 (true) on match
  6519. * return 0 or negative value on failure/error
  6520. *
  6521. * privKey : buffer holding DER format private key
  6522. * privKeySz : size of private key buffer
  6523. * pubKey : buffer holding DER format public key
  6524. * pubKeySz : size of public key buffer
  6525. * ks : type of key */
  6526. int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz,
  6527. const byte* pubKey, word32 pubKeySz, enum Key_Sum ks)
  6528. {
  6529. int ret;
  6530. (void)privKeySz;
  6531. (void)pubKeySz;
  6532. (void)ks;
  6533. if (privKey == NULL || pubKey == NULL) {
  6534. return BAD_FUNC_ARG;
  6535. }
  6536. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  6537. /* test if RSA key */
  6538. if (ks == RSAk
  6539. #ifdef WC_RSA_PSS
  6540. || ks == RSAPSSk
  6541. #endif
  6542. ) {
  6543. #ifdef WOLFSSL_SMALL_STACK
  6544. RsaKey* a;
  6545. RsaKey* b = NULL;
  6546. #else
  6547. RsaKey a[1], b[1];
  6548. #endif
  6549. word32 keyIdx = 0;
  6550. #ifdef WOLFSSL_SMALL_STACK
  6551. a = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  6552. if (a == NULL)
  6553. return MEMORY_E;
  6554. b = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  6555. if (b == NULL) {
  6556. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6557. return MEMORY_E;
  6558. }
  6559. #endif
  6560. if ((ret = wc_InitRsaKey(a, NULL)) < 0) {
  6561. #ifdef WOLFSSL_SMALL_STACK
  6562. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6563. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6564. #endif
  6565. return ret;
  6566. }
  6567. if ((ret = wc_InitRsaKey(b, NULL)) < 0) {
  6568. wc_FreeRsaKey(a);
  6569. #ifdef WOLFSSL_SMALL_STACK
  6570. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6571. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6572. #endif
  6573. return ret;
  6574. }
  6575. if ((ret = wc_RsaPrivateKeyDecode(privKey, &keyIdx, a, privKeySz)) == 0) {
  6576. WOLFSSL_MSG("Checking RSA key pair");
  6577. keyIdx = 0; /* reset to 0 for parsing public key */
  6578. if ((ret = wc_RsaPublicKeyDecode(pubKey, &keyIdx, b,
  6579. pubKeySz)) == 0) {
  6580. /* limit for user RSA crypto because of RsaKey
  6581. * dereference. */
  6582. #if defined(HAVE_USER_RSA)
  6583. WOLFSSL_MSG("Cannot verify RSA pair with user RSA");
  6584. ret = 1; /* return first RSA cert as match */
  6585. #else
  6586. /* both keys extracted successfully now check n and e
  6587. * values are the same. This is dereferencing RsaKey */
  6588. if (mp_cmp(&(a->n), &(b->n)) != MP_EQ ||
  6589. mp_cmp(&(a->e), &(b->e)) != MP_EQ) {
  6590. ret = MP_CMP_E;
  6591. WOLFSSL_ERROR_VERBOSE(ret);
  6592. }
  6593. else
  6594. ret = 1;
  6595. #endif
  6596. }
  6597. else {
  6598. WOLFSSL_ERROR_VERBOSE(ret);
  6599. }
  6600. }
  6601. wc_FreeRsaKey(b);
  6602. wc_FreeRsaKey(a);
  6603. #ifdef WOLFSSL_SMALL_STACK
  6604. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6605. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6606. #endif
  6607. }
  6608. else
  6609. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  6610. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  6611. if (ks == ECDSAk) {
  6612. #ifdef WOLFSSL_SMALL_STACK
  6613. ecc_key* key_pair;
  6614. byte* privDer;
  6615. #else
  6616. ecc_key key_pair[1];
  6617. byte privDer[MAX_ECC_BYTES];
  6618. #endif
  6619. word32 privSz = MAX_ECC_BYTES;
  6620. word32 keyIdx = 0;
  6621. #ifdef WOLFSSL_SMALL_STACK
  6622. key_pair = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL, DYNAMIC_TYPE_ECC);
  6623. if (key_pair == NULL)
  6624. return MEMORY_E;
  6625. privDer = (byte*)XMALLOC(MAX_ECC_BYTES, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6626. if (privDer == NULL) {
  6627. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6628. return MEMORY_E;
  6629. }
  6630. #endif
  6631. if ((ret = wc_ecc_init(key_pair)) < 0) {
  6632. #ifdef WOLFSSL_SMALL_STACK
  6633. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6634. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6635. #endif
  6636. return ret;
  6637. }
  6638. if ((ret = wc_EccPrivateKeyDecode(privKey, &keyIdx, key_pair,
  6639. privKeySz)) == 0) {
  6640. WOLFSSL_MSG("Checking ECC key pair");
  6641. if ((ret = wc_ecc_export_private_only(key_pair, privDer, &privSz))
  6642. == 0) {
  6643. #ifdef WOLFSSL_CHECK_MEM_ZERO
  6644. wc_MemZero_Add("wc_CheckPrivateKey privDer", privDer, privSz);
  6645. #endif
  6646. wc_ecc_free(key_pair);
  6647. ret = wc_ecc_init(key_pair);
  6648. if (ret == 0) {
  6649. ret = wc_ecc_import_private_key(privDer,
  6650. privSz, pubKey,
  6651. pubKeySz, key_pair);
  6652. }
  6653. /* public and private extracted successfully now check if is
  6654. * a pair and also do sanity checks on key. wc_ecc_check_key
  6655. * checks that private * base generator equals pubkey */
  6656. if (ret == 0) {
  6657. if ((ret = wc_ecc_check_key(key_pair)) == 0) {
  6658. ret = 1;
  6659. }
  6660. else {
  6661. WOLFSSL_ERROR_VERBOSE(ret);
  6662. }
  6663. }
  6664. ForceZero(privDer, privSz);
  6665. }
  6666. }
  6667. else {
  6668. WOLFSSL_ERROR_VERBOSE(ret);
  6669. }
  6670. wc_ecc_free(key_pair);
  6671. #ifdef WOLFSSL_SMALL_STACK
  6672. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6673. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6674. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  6675. wc_MemZero_Check(privDer, MAX_ECC_BYTES);
  6676. #endif
  6677. }
  6678. else
  6679. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  6680. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  6681. if (ks == ED25519k) {
  6682. #ifdef WOLFSSL_SMALL_STACK
  6683. ed25519_key* key_pair;
  6684. #else
  6685. ed25519_key key_pair[1];
  6686. #endif
  6687. word32 keyIdx = 0;
  6688. #ifdef WOLFSSL_SMALL_STACK
  6689. key_pair = (ed25519_key*)XMALLOC(sizeof(ed25519_key), NULL,
  6690. DYNAMIC_TYPE_ED25519);
  6691. if (key_pair == NULL)
  6692. return MEMORY_E;
  6693. #endif
  6694. if ((ret = wc_ed25519_init(key_pair)) < 0) {
  6695. #ifdef WOLFSSL_SMALL_STACK
  6696. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  6697. #endif
  6698. return ret;
  6699. }
  6700. if ((ret = wc_Ed25519PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6701. privKeySz)) == 0) {
  6702. WOLFSSL_MSG("Checking ED25519 key pair");
  6703. keyIdx = 0;
  6704. if ((ret = wc_ed25519_import_public(pubKey, pubKeySz,
  6705. key_pair)) == 0) {
  6706. /* public and private extracted successfully no check if is
  6707. * a pair and also do sanity checks on key. wc_ecc_check_key
  6708. * checks that private * base generator equals pubkey */
  6709. if ((ret = wc_ed25519_check_key(key_pair)) == 0) {
  6710. ret = 1;
  6711. }
  6712. else {
  6713. WOLFSSL_ERROR_VERBOSE(ret);
  6714. }
  6715. }
  6716. }
  6717. else {
  6718. WOLFSSL_ERROR_VERBOSE(ret);
  6719. }
  6720. wc_ed25519_free(key_pair);
  6721. #ifdef WOLFSSL_SMALL_STACK
  6722. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  6723. #endif
  6724. }
  6725. else
  6726. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  6727. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  6728. if (ks == ED448k) {
  6729. #ifdef WOLFSSL_SMALL_STACK
  6730. ed448_key* key_pair = NULL;
  6731. #else
  6732. ed448_key key_pair[1];
  6733. #endif
  6734. word32 keyIdx = 0;
  6735. #ifdef WOLFSSL_SMALL_STACK
  6736. key_pair = (ed448_key*)XMALLOC(sizeof(ed448_key), NULL,
  6737. DYNAMIC_TYPE_ED448);
  6738. if (key_pair == NULL)
  6739. return MEMORY_E;
  6740. #endif
  6741. if ((ret = wc_ed448_init(key_pair)) < 0) {
  6742. #ifdef WOLFSSL_SMALL_STACK
  6743. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  6744. #endif
  6745. return ret;
  6746. }
  6747. if ((ret = wc_Ed448PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6748. privKeySz)) == 0) {
  6749. WOLFSSL_MSG("Checking ED448 key pair");
  6750. keyIdx = 0;
  6751. if ((ret = wc_ed448_import_public(pubKey, pubKeySz,
  6752. key_pair)) == 0) {
  6753. /* public and private extracted successfully no check if is
  6754. * a pair and also do sanity checks on key. wc_ecc_check_key
  6755. * checks that private * base generator equals pubkey */
  6756. if ((ret = wc_ed448_check_key(key_pair)) == 0) {
  6757. ret = 1;
  6758. }
  6759. else {
  6760. WOLFSSL_ERROR_VERBOSE(ret);
  6761. }
  6762. }
  6763. }
  6764. else {
  6765. WOLFSSL_ERROR_VERBOSE(ret);
  6766. }
  6767. wc_ed448_free(key_pair);
  6768. #ifdef WOLFSSL_SMALL_STACK
  6769. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  6770. #endif
  6771. }
  6772. else
  6773. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  6774. #if defined(HAVE_PQC)
  6775. #if defined(HAVE_FALCON)
  6776. if ((ks == FALCON_LEVEL1k) || (ks == FALCON_LEVEL5k)) {
  6777. #ifdef WOLFSSL_SMALL_STACK
  6778. falcon_key* key_pair = NULL;
  6779. #else
  6780. falcon_key key_pair[1];
  6781. #endif
  6782. word32 keyIdx = 0;
  6783. #ifdef WOLFSSL_SMALL_STACK
  6784. key_pair = (falcon_key*)XMALLOC(sizeof(falcon_key), NULL,
  6785. DYNAMIC_TYPE_FALCON);
  6786. if (key_pair == NULL)
  6787. return MEMORY_E;
  6788. #endif
  6789. ret = wc_falcon_init(key_pair);
  6790. if (ret < 0) {
  6791. #ifdef WOLFSSL_SMALL_STACK
  6792. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6793. #endif
  6794. return ret;
  6795. }
  6796. if (ks == FALCON_LEVEL1k) {
  6797. ret = wc_falcon_set_level(key_pair, 1);
  6798. }
  6799. else if (ks == FALCON_LEVEL5k) {
  6800. ret = wc_falcon_set_level(key_pair, 5);
  6801. }
  6802. if (ret < 0) {
  6803. #ifdef WOLFSSL_SMALL_STACK
  6804. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6805. #endif
  6806. return ret;
  6807. }
  6808. if ((ret = wc_Falcon_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6809. privKeySz)) == 0) {
  6810. WOLFSSL_MSG("Checking Falcon key pair");
  6811. keyIdx = 0;
  6812. if ((ret = wc_falcon_import_public(pubKey, pubKeySz,
  6813. key_pair)) == 0) {
  6814. /* Public and private extracted successfully. Sanity check. */
  6815. if ((ret = wc_falcon_check_key(key_pair)) == 0) {
  6816. ret = 1;
  6817. }
  6818. else {
  6819. WOLFSSL_ERROR_VERBOSE(ret);
  6820. }
  6821. }
  6822. }
  6823. else {
  6824. WOLFSSL_ERROR_VERBOSE(ret);
  6825. }
  6826. wc_falcon_free(key_pair);
  6827. #ifdef WOLFSSL_SMALL_STACK
  6828. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6829. #endif
  6830. }
  6831. else
  6832. #endif /* HAVE_FALCON */
  6833. #if defined(HAVE_DILITHIUM)
  6834. if ((ks == DILITHIUM_LEVEL2k) ||
  6835. (ks == DILITHIUM_LEVEL3k) ||
  6836. (ks == DILITHIUM_LEVEL5k)) {
  6837. #ifdef WOLFSSL_SMALL_STACK
  6838. dilithium_key* key_pair = NULL;
  6839. #else
  6840. dilithium_key key_pair[1];
  6841. #endif
  6842. word32 keyIdx = 0;
  6843. #ifdef WOLFSSL_SMALL_STACK
  6844. key_pair = (dilithium_key*)XMALLOC(sizeof(dilithium_key), NULL,
  6845. DYNAMIC_TYPE_DILITHIUM);
  6846. if (key_pair == NULL)
  6847. return MEMORY_E;
  6848. #endif
  6849. ret = wc_dilithium_init(key_pair);
  6850. if (ret < 0) {
  6851. #ifdef WOLFSSL_SMALL_STACK
  6852. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6853. #endif
  6854. return ret;
  6855. }
  6856. if (ks == DILITHIUM_LEVEL2k) {
  6857. ret = wc_dilithium_set_level(key_pair, 2);
  6858. }
  6859. else if (ks == DILITHIUM_LEVEL3k) {
  6860. ret = wc_dilithium_set_level(key_pair, 3);
  6861. }
  6862. else if (ks == DILITHIUM_LEVEL5k) {
  6863. ret = wc_dilithium_set_level(key_pair, 5);
  6864. }
  6865. if (ret < 0) {
  6866. #ifdef WOLFSSL_SMALL_STACK
  6867. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6868. #endif
  6869. return ret;
  6870. }
  6871. if ((ret = wc_Dilithium_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6872. privKeySz)) == 0) {
  6873. WOLFSSL_MSG("Checking Dilithium key pair");
  6874. keyIdx = 0;
  6875. if ((ret = wc_dilithium_import_public(pubKey, pubKeySz,
  6876. key_pair)) == 0) {
  6877. /* Public and private extracted successfully. Sanity check. */
  6878. if ((ret = wc_dilithium_check_key(key_pair)) == 0)
  6879. ret = 1;
  6880. }
  6881. }
  6882. wc_dilithium_free(key_pair);
  6883. #ifdef WOLFSSL_SMALL_STACK
  6884. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6885. #endif
  6886. }
  6887. else
  6888. #endif /* HAVE_DILITHIUM */
  6889. #if defined(HAVE_SPHINCS)
  6890. if ((ks == SPHINCS_FAST_LEVEL1k) ||
  6891. (ks == SPHINCS_FAST_LEVEL3k) ||
  6892. (ks == SPHINCS_FAST_LEVEL5k) ||
  6893. (ks == SPHINCS_SMALL_LEVEL1k) ||
  6894. (ks == SPHINCS_SMALL_LEVEL3k) ||
  6895. (ks == SPHINCS_SMALL_LEVEL5k)) {
  6896. #ifdef WOLFSSL_SMALL_STACK
  6897. sphincs_key* key_pair = NULL;
  6898. #else
  6899. sphincs_key key_pair[1];
  6900. #endif
  6901. word32 keyIdx = 0;
  6902. #ifdef WOLFSSL_SMALL_STACK
  6903. key_pair = (sphincs_key*)XMALLOC(sizeof(sphincs_key), NULL,
  6904. DYNAMIC_TYPE_SPHINCS);
  6905. if (key_pair == NULL)
  6906. return MEMORY_E;
  6907. #endif
  6908. ret = wc_sphincs_init(key_pair);
  6909. if (ret < 0) {
  6910. #ifdef WOLFSSL_SMALL_STACK
  6911. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6912. #endif
  6913. return ret;
  6914. }
  6915. if (ks == SPHINCS_FAST_LEVEL1k) {
  6916. ret = wc_sphincs_set_level_and_optim(key_pair, 1, FAST_VARIANT);
  6917. }
  6918. else if (ks == SPHINCS_FAST_LEVEL3k) {
  6919. ret = wc_sphincs_set_level_and_optim(key_pair, 3, FAST_VARIANT);
  6920. }
  6921. else if (ks == SPHINCS_FAST_LEVEL5k) {
  6922. ret = wc_sphincs_set_level_and_optim(key_pair, 5, FAST_VARIANT);
  6923. }
  6924. else if (ks == SPHINCS_SMALL_LEVEL1k) {
  6925. ret = wc_sphincs_set_level_and_optim(key_pair, 1, SMALL_VARIANT);
  6926. }
  6927. else if (ks == SPHINCS_SMALL_LEVEL3k) {
  6928. ret = wc_sphincs_set_level_and_optim(key_pair, 3, SMALL_VARIANT);
  6929. }
  6930. else if (ks == SPHINCS_SMALL_LEVEL5k) {
  6931. ret = wc_sphincs_set_level_and_optim(key_pair, 5, SMALL_VARIANT);
  6932. }
  6933. if (ret < 0) {
  6934. #ifdef WOLFSSL_SMALL_STACK
  6935. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6936. #endif
  6937. return ret;
  6938. }
  6939. if ((ret = wc_Sphincs_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6940. privKeySz)) == 0) {
  6941. WOLFSSL_MSG("Checking Sphincs key pair");
  6942. keyIdx = 0;
  6943. if ((ret = wc_sphincs_import_public(pubKey, pubKeySz,
  6944. key_pair)) == 0) {
  6945. /* Public and private extracted successfully. Sanity check. */
  6946. if ((ret = wc_sphincs_check_key(key_pair)) == 0)
  6947. ret = 1;
  6948. }
  6949. }
  6950. wc_sphincs_free(key_pair);
  6951. #ifdef WOLFSSL_SMALL_STACK
  6952. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6953. #endif
  6954. }
  6955. else
  6956. #endif /* HAVE_SPHINCS */
  6957. #endif /* HAVE_PQC */
  6958. {
  6959. ret = 0;
  6960. }
  6961. (void)ks;
  6962. return ret;
  6963. }
  6964. /* check that the private key is a pair for the public key in certificate
  6965. * return 1 (true) on match
  6966. * return 0 or negative value on failure/error
  6967. *
  6968. * key : buffer holding DER format key
  6969. * keySz : size of key buffer
  6970. * der : a initialized and parsed DecodedCert holding a certificate */
  6971. int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der)
  6972. {
  6973. if (key == NULL || der == NULL) {
  6974. return BAD_FUNC_ARG;
  6975. }
  6976. return wc_CheckPrivateKey(key, keySz, der->publicKey,
  6977. der->pubKeySize, (enum Key_Sum) der->keyOID);
  6978. }
  6979. #endif /* HAVE_PKCS12 || !NO_CHECK_PRIVATE_KEY */
  6980. #ifndef NO_PWDBASED
  6981. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6982. /* Check the PBE algorithm is supported and return wolfSSL id, version and block
  6983. * size of encryption algorithm.
  6984. *
  6985. * When PBES2, version is PKCS5v2, CheckAlgoV2() must be called to get id and
  6986. * blockSz based on encryption algorithm.
  6987. *
  6988. * @param [in] first First byte of OID to use in check.
  6989. * @param [in] second Second byte of OID to use in check.
  6990. * @param [out] id wolfSSL id for PBE algorithm.
  6991. * @param [out] version Version of PBE OID:
  6992. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  6993. * @param [out] blockSz Block size of encryption algorithm.
  6994. * @return 0 on success.
  6995. * @return ALGO_ID_E when OID not supported.
  6996. * @return ASN_INPUT_E when first byte is invalid.
  6997. */
  6998. static int CheckAlgo(int first, int second, int* id, int* version, int* blockSz)
  6999. {
  7000. int ret = 0;
  7001. (void)id;
  7002. (void)blockSz;
  7003. *version = -1;
  7004. /* pkcs-12 1 = pkcs-12PbeIds */
  7005. if (first == 1) {
  7006. /* PKCS #12: Appendix C */
  7007. switch (second) {
  7008. #if !defined(NO_SHA)
  7009. #ifndef NO_RC4
  7010. case PBE_SHA1_RC4_128:
  7011. *id = PBE_SHA1_RC4_128;
  7012. *version = PKCS12v1;
  7013. if (blockSz != NULL) {
  7014. *blockSz = 1;
  7015. }
  7016. break;
  7017. #endif
  7018. #ifndef NO_DES3
  7019. case PBE_SHA1_DES3:
  7020. *id = PBE_SHA1_DES3;
  7021. *version = PKCS12v1;
  7022. if (blockSz != NULL) {
  7023. *blockSz = DES_BLOCK_SIZE;
  7024. }
  7025. break;
  7026. #endif
  7027. #ifdef WC_RC2
  7028. case PBE_SHA1_40RC2_CBC:
  7029. *id = PBE_SHA1_40RC2_CBC;
  7030. *version = PKCS12v1;
  7031. if (blockSz != NULL) {
  7032. *blockSz = RC2_BLOCK_SIZE;
  7033. }
  7034. break;
  7035. #endif
  7036. #endif /* !NO_SHA */
  7037. default:
  7038. ret = ALGO_ID_E;
  7039. break;
  7040. }
  7041. }
  7042. else if (first != PKCS5) {
  7043. /* Bad OID. */
  7044. ret = ASN_INPUT_E;
  7045. }
  7046. /* PKCS #5 PBES2: Appendix A.4
  7047. * pkcs-5 13 = id-PBES2 */
  7048. else if (second == PBES2) {
  7049. *version = PKCS5v2;
  7050. /* Id and block size come from CheckAlgoV2() */
  7051. }
  7052. else {
  7053. /* PKCS #5 PBES1: Appendix A.3 */
  7054. /* see RFC 2898 for ids */
  7055. switch (second) {
  7056. #ifndef NO_DES3
  7057. #ifndef NO_MD5
  7058. case PBES1_MD5_DES:
  7059. *id = PBE_MD5_DES;
  7060. *version = PKCS5;
  7061. if (blockSz != NULL) {
  7062. *blockSz = DES_BLOCK_SIZE;
  7063. }
  7064. break;
  7065. #endif
  7066. #ifndef NO_SHA
  7067. case PBES1_SHA1_DES:
  7068. *id = PBE_SHA1_DES;
  7069. *version = PKCS5;
  7070. if (blockSz != NULL) {
  7071. *blockSz = DES_BLOCK_SIZE;
  7072. }
  7073. break;
  7074. #endif
  7075. #endif /* !NO_DES3 */
  7076. default:
  7077. ret = ALGO_ID_E;
  7078. break;
  7079. }
  7080. }
  7081. /* Return error code. */
  7082. return ret;
  7083. }
  7084. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7085. #ifdef HAVE_PKCS8
  7086. /* Check the encryption algorithm with PBES2 is supported and return block size
  7087. * and wolfSSL id for the PBE.
  7088. *
  7089. * @param [in] oid Encryption algorithm OID id.
  7090. * @param [out] id wolfSSL id for PBE algorithm.
  7091. * @param [out] version Version of PBE OID:
  7092. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  7093. * @return 0 on success.
  7094. * @return ALGO_ID_E when encryption algorithm is not supported with PBES2.
  7095. */
  7096. static int CheckAlgoV2(int oid, int* id, int* blockSz)
  7097. {
  7098. int ret = 0;
  7099. (void)id;
  7100. (void)blockSz;
  7101. switch (oid) {
  7102. #if !defined(NO_DES3) && !defined(NO_SHA)
  7103. case DESb:
  7104. *id = PBE_SHA1_DES;
  7105. if (blockSz != NULL) {
  7106. *blockSz = DES_BLOCK_SIZE;
  7107. }
  7108. break;
  7109. case DES3b:
  7110. *id = PBE_SHA1_DES3;
  7111. if (blockSz != NULL) {
  7112. *blockSz = DES_BLOCK_SIZE;
  7113. }
  7114. break;
  7115. #endif
  7116. #ifdef WOLFSSL_AES_256
  7117. case AES256CBCb:
  7118. *id = PBE_AES256_CBC;
  7119. if (blockSz != NULL) {
  7120. *blockSz = AES_BLOCK_SIZE;
  7121. }
  7122. break;
  7123. #endif
  7124. #ifdef WOLFSSL_AES_128
  7125. case AES128CBCb:
  7126. *id = PBE_AES128_CBC;
  7127. if (blockSz != NULL) {
  7128. *blockSz = AES_BLOCK_SIZE;
  7129. }
  7130. break;
  7131. #endif
  7132. default:
  7133. WOLFSSL_MSG("No PKCS v2 algo found");
  7134. ret = ALGO_ID_E;
  7135. break;
  7136. }
  7137. /* Return error code. */
  7138. return ret;
  7139. }
  7140. #endif /* HAVE_PKCS8 */
  7141. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7142. int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz,
  7143. int* algoID, void* heap)
  7144. {
  7145. word32 tmpIdx = 0;
  7146. if (key == NULL || algoID == NULL)
  7147. return BAD_FUNC_ARG;
  7148. *algoID = 0;
  7149. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  7150. {
  7151. RsaKey *rsa = (RsaKey *)XMALLOC(sizeof *rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7152. if (rsa == NULL)
  7153. return MEMORY_E;
  7154. wc_InitRsaKey(rsa, heap);
  7155. if (wc_RsaPrivateKeyDecode(key, &tmpIdx, rsa, keySz) == 0) {
  7156. *algoID = RSAk;
  7157. }
  7158. else {
  7159. WOLFSSL_MSG("Not RSA DER key");
  7160. }
  7161. wc_FreeRsaKey(rsa);
  7162. XFREE(rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7163. }
  7164. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  7165. #if defined(HAVE_ECC) && !defined(NO_ASN_CRYPT)
  7166. if (*algoID == 0) {
  7167. ecc_key *ecc = (ecc_key *)XMALLOC(sizeof *ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7168. if (ecc == NULL)
  7169. return MEMORY_E;
  7170. tmpIdx = 0;
  7171. wc_ecc_init_ex(ecc, heap, INVALID_DEVID);
  7172. if (wc_EccPrivateKeyDecode(key, &tmpIdx, ecc, keySz) == 0) {
  7173. *algoID = ECDSAk;
  7174. /* now find oid */
  7175. if (wc_ecc_get_oid(ecc->dp->oidSum, curveOID, oidSz) < 0) {
  7176. WOLFSSL_MSG("Error getting ECC curve OID");
  7177. wc_ecc_free(ecc);
  7178. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7179. return BAD_FUNC_ARG;
  7180. }
  7181. }
  7182. else {
  7183. WOLFSSL_MSG("Not ECC DER key either");
  7184. }
  7185. wc_ecc_free(ecc);
  7186. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7187. }
  7188. #endif /* HAVE_ECC && !NO_ASN_CRYPT */
  7189. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  7190. if (*algoID == 0) {
  7191. ed25519_key *ed25519 = (ed25519_key *)XMALLOC(sizeof *ed25519, heap,
  7192. DYNAMIC_TYPE_TMP_BUFFER);
  7193. if (ed25519 == NULL)
  7194. return MEMORY_E;
  7195. tmpIdx = 0;
  7196. if (wc_ed25519_init_ex(ed25519, heap, INVALID_DEVID) == 0) {
  7197. if (wc_Ed25519PrivateKeyDecode(key, &tmpIdx, ed25519, keySz) == 0) {
  7198. *algoID = ED25519k;
  7199. }
  7200. else {
  7201. WOLFSSL_MSG("Not ED25519 DER key");
  7202. }
  7203. wc_ed25519_free(ed25519);
  7204. }
  7205. else {
  7206. WOLFSSL_MSG("GetKeyOID wc_ed25519_init failed");
  7207. }
  7208. XFREE(ed25519, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7209. }
  7210. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  7211. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  7212. if (*algoID == 0) {
  7213. ed448_key *ed448 = (ed448_key *)XMALLOC(sizeof *ed448, heap,
  7214. DYNAMIC_TYPE_TMP_BUFFER);
  7215. if (ed448 == NULL)
  7216. return MEMORY_E;
  7217. tmpIdx = 0;
  7218. if (wc_ed448_init(ed448) == 0) {
  7219. if (wc_Ed448PrivateKeyDecode(key, &tmpIdx, ed448, keySz) == 0) {
  7220. *algoID = ED448k;
  7221. }
  7222. else {
  7223. WOLFSSL_MSG("Not ED448 DER key");
  7224. }
  7225. wc_ed448_free(ed448);
  7226. }
  7227. else {
  7228. WOLFSSL_MSG("GetKeyOID wc_ed448_init failed");
  7229. }
  7230. XFREE(ed448, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7231. }
  7232. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  7233. #if defined(HAVE_PQC)
  7234. #if defined(HAVE_FALCON)
  7235. if (*algoID == 0) {
  7236. falcon_key *falcon = (falcon_key *)XMALLOC(sizeof(*falcon), heap,
  7237. DYNAMIC_TYPE_TMP_BUFFER);
  7238. if (falcon == NULL)
  7239. return MEMORY_E;
  7240. if (wc_falcon_init(falcon) != 0) {
  7241. tmpIdx = 0;
  7242. if (wc_falcon_set_level(falcon, 1) == 0) {
  7243. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  7244. == 0) {
  7245. *algoID = FALCON_LEVEL1k;
  7246. }
  7247. else {
  7248. WOLFSSL_MSG("Not Falcon Level 1 DER key");
  7249. }
  7250. }
  7251. else if (wc_falcon_set_level(falcon, 5) == 0) {
  7252. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  7253. == 0) {
  7254. *algoID = FALCON_LEVEL5k;
  7255. }
  7256. else {
  7257. WOLFSSL_MSG("Not Falcon Level 5 DER key");
  7258. }
  7259. }
  7260. else {
  7261. WOLFSSL_MSG("GetKeyOID falcon initialization failed");
  7262. }
  7263. wc_falcon_free(falcon);
  7264. }
  7265. XFREE(falcon, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7266. }
  7267. #endif /* HAVE_FALCON */
  7268. #if defined(HAVE_DILITHIUM)
  7269. if (*algoID == 0) {
  7270. dilithium_key *dilithium = (dilithium_key *)XMALLOC(sizeof(*dilithium),
  7271. heap, DYNAMIC_TYPE_TMP_BUFFER);
  7272. if (dilithium == NULL)
  7273. return MEMORY_E;
  7274. if (wc_dilithium_init(dilithium) != 0) {
  7275. tmpIdx = 0;
  7276. if (wc_dilithium_set_level(dilithium, 2)
  7277. == 0) {
  7278. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7279. keySz) == 0) {
  7280. *algoID = DILITHIUM_LEVEL2k;
  7281. }
  7282. else {
  7283. WOLFSSL_MSG("Not Dilithium Level 2 DER key");
  7284. }
  7285. }
  7286. else if (wc_dilithium_set_level(dilithium, 3)
  7287. == 0) {
  7288. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7289. keySz) == 0) {
  7290. *algoID = DILITHIUM_LEVEL3k;
  7291. }
  7292. else {
  7293. WOLFSSL_MSG("Not Dilithium Level 3 DER key");
  7294. }
  7295. }
  7296. else if (wc_dilithium_set_level(dilithium, 5)
  7297. == 0) {
  7298. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7299. keySz) == 0) {
  7300. *algoID = DILITHIUM_LEVEL5k;
  7301. }
  7302. else {
  7303. WOLFSSL_MSG("Not Dilithium Level 5 DER key");
  7304. }
  7305. }
  7306. else {
  7307. WOLFSSL_MSG("GetKeyOID dilithium initialization failed");
  7308. }
  7309. wc_dilithium_free(dilithium);
  7310. }
  7311. XFREE(dilithium, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7312. }
  7313. #endif /* HAVE_DILITHIUM */
  7314. #if defined(HAVE_SPHINCS)
  7315. if (*algoID == 0) {
  7316. sphincs_key *sphincs = (sphincs_key *)XMALLOC(sizeof(*sphincs),
  7317. heap, DYNAMIC_TYPE_TMP_BUFFER);
  7318. if (sphincs == NULL)
  7319. return MEMORY_E;
  7320. if (wc_sphincs_init(sphincs) != 0) {
  7321. tmpIdx = 0;
  7322. if (wc_sphincs_set_level_and_optim(sphincs, 1, FAST_VARIANT)
  7323. == 0) {
  7324. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7325. keySz) == 0) {
  7326. *algoID = SPHINCS_FAST_LEVEL1k;
  7327. }
  7328. else {
  7329. WOLFSSL_MSG("Not Sphincs-fast Level 1 DER key");
  7330. }
  7331. }
  7332. else if (wc_sphincs_set_level_and_optim(sphincs, 3, FAST_VARIANT)
  7333. == 0) {
  7334. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7335. keySz) == 0) {
  7336. *algoID = SPHINCS_FAST_LEVEL3k;
  7337. }
  7338. else {
  7339. WOLFSSL_MSG("Not Sphincs-fast Level 3 DER key");
  7340. }
  7341. }
  7342. else if (wc_sphincs_set_level_and_optim(sphincs, 5, FAST_VARIANT)
  7343. == 0) {
  7344. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7345. keySz) == 0) {
  7346. *algoID = SPHINCS_FAST_LEVEL5k;
  7347. }
  7348. else {
  7349. WOLFSSL_MSG("Not Sphincs-fast Level 5 DER key");
  7350. }
  7351. }
  7352. else if (wc_sphincs_set_level_and_optim(sphincs, 1, SMALL_VARIANT)
  7353. == 0) {
  7354. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7355. keySz) == 0) {
  7356. *algoID = SPHINCS_SMALL_LEVEL1k;
  7357. }
  7358. else {
  7359. WOLFSSL_MSG("Not Sphincs-small Level 1 DER key");
  7360. }
  7361. }
  7362. else if (wc_sphincs_set_level_and_optim(sphincs, 3, SMALL_VARIANT)
  7363. == 0) {
  7364. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7365. keySz) == 0) {
  7366. *algoID = SPHINCS_SMALL_LEVEL3k;
  7367. }
  7368. else {
  7369. WOLFSSL_MSG("Not Sphincs-small Level 3 DER key");
  7370. }
  7371. }
  7372. else if (wc_sphincs_set_level_and_optim(sphincs, 5, SMALL_VARIANT)
  7373. == 0) {
  7374. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7375. keySz) == 0) {
  7376. *algoID = SPHINCS_SMALL_LEVEL5k;
  7377. }
  7378. else {
  7379. WOLFSSL_MSG("Not Sphincs-small Level 5 DER key");
  7380. }
  7381. }
  7382. else {
  7383. WOLFSSL_MSG("GetKeyOID sphincs initialization failed");
  7384. }
  7385. wc_sphincs_free(sphincs);
  7386. }
  7387. XFREE(sphincs, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7388. }
  7389. #endif /* HAVE_SPHINCS */
  7390. #endif /* HAVE_PQC */
  7391. /* if flag is not set then this is not a key that we understand. */
  7392. if (*algoID == 0) {
  7393. WOLFSSL_MSG("Bad key DER or compile options");
  7394. return BAD_FUNC_ARG;
  7395. }
  7396. (void)tmpIdx;
  7397. (void)curveOID;
  7398. (void)oidSz;
  7399. (void)keySz;
  7400. (void)heap;
  7401. return 1;
  7402. }
  7403. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7404. #ifdef WOLFSSL_ASN_TEMPLATE
  7405. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7406. /* ASN.1 template for PBES2 parameters.
  7407. * PKCS #5: RFC 8018, A.4 - PBES2-params without outer SEQUENCE
  7408. * A.2 - PBKDF2-params
  7409. * B.2 - Encryption schemes
  7410. * C - AlgorithmIdentifier
  7411. */
  7412. static const ASNItem pbes2ParamsASN[] = {
  7413. /* KDF_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7414. /* PBKDF2 */
  7415. /* KDF_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  7416. /* PBKDF2_PARAMS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7417. /* Salt */
  7418. /* PBKDF2_PARAMS_SALT */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  7419. /* Iteration count */
  7420. /* PBKDF2_PARAMS_ITER */ { 2, ASN_INTEGER, 0, 0, 0 },
  7421. /* Key length */
  7422. /* PBKDF2_PARAMS_KEYLEN */ { 2, ASN_INTEGER, 0, 0, 1 },
  7423. /* PRF - default is HMAC-SHA1 */
  7424. /* PBKDF2_PARAMS_PRF */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  7425. /* PBKDF2_PARAMS_PRF_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  7426. /* PBKDF2_PARAMS_PRF_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  7427. /* ENCS_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7428. /* Encryption algorithm */
  7429. /* ENCS_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  7430. /* IV for CBC */
  7431. /* ENCS_PARAMS */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  7432. };
  7433. enum {
  7434. PBES2PARAMSASN_IDX_KDF_SEQ = 0,
  7435. PBES2PARAMSASN_IDX_KDF_OID,
  7436. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SEQ,
  7437. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT,
  7438. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER,
  7439. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_KEYLEN,
  7440. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF,
  7441. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID,
  7442. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_NULL,
  7443. PBES2PARAMSASN_IDX_ENCS_SEQ,
  7444. PBES2PARAMSASN_IDX_ENCS_OID,
  7445. PBES2PARAMSASN_IDX_ENCS_PARAMS
  7446. };
  7447. /* Number of items in ASN.1 template for PBES2 parameters. */
  7448. #define pbes2ParamsASN_Length (sizeof(pbes2ParamsASN) / sizeof(ASNItem))
  7449. /* ASN.1 template for PBES1 parameters.
  7450. * PKCS #5: RFC 8018, A.3. - PBEParameter without outer SEQUENCE
  7451. */
  7452. static const ASNItem pbes1ParamsASN[] = {
  7453. /* Salt */
  7454. /* SALT */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  7455. /* Iteration count */
  7456. /* ITER */ { 0, ASN_INTEGER, 0, 0, 0 },
  7457. };
  7458. enum {
  7459. PBES1PARAMSASN_IDX_SALT = 0,
  7460. PBES1PARAMSASN_IDX_ITER
  7461. };
  7462. /* Number of items in ASN.1 template for PBES1 parameters. */
  7463. #define pbes1ParamsASN_Length (sizeof(pbes1ParamsASN) / sizeof(ASNItem))
  7464. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7465. #endif /* WOLFSSL_ASN_TEMPLATE */
  7466. #ifdef HAVE_PKCS8
  7467. /*
  7468. * Equivalent to calling TraditionalEnc with the same parameters but with
  7469. * encAlgId set to 0. This function must be kept alive because it's sometimes
  7470. * part of the API (WOLFSSL_ASN_API).
  7471. */
  7472. int UnTraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  7473. const char* password, int passwordSz, int vPKCS, int vAlgo,
  7474. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  7475. {
  7476. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz,
  7477. vPKCS, vAlgo, 0, salt, saltSz, itt, rng, heap);
  7478. }
  7479. static int GetAlgoV2(int encAlgId, const byte** oid, int *len, int* id,
  7480. int *blkSz)
  7481. {
  7482. int ret = 0;
  7483. switch (encAlgId) {
  7484. #if !defined(NO_DES3) && !defined(NO_SHA)
  7485. case DESb:
  7486. *len = sizeof(blkDesCbcOid);
  7487. *oid = blkDesCbcOid;
  7488. *id = PBE_SHA1_DES;
  7489. *blkSz = 8;
  7490. break;
  7491. case DES3b:
  7492. *len = sizeof(blkDes3CbcOid);
  7493. *oid = blkDes3CbcOid;
  7494. *id = PBE_SHA1_DES3;
  7495. *blkSz = 8;
  7496. break;
  7497. #endif
  7498. #if defined(WOLFSSL_AES_128) && defined(HAVE_AES_CBC)
  7499. case AES128CBCb:
  7500. *len = sizeof(blkAes128CbcOid);
  7501. *oid = blkAes128CbcOid;
  7502. *id = PBE_AES128_CBC;
  7503. *blkSz = 16;
  7504. break;
  7505. #endif
  7506. #if defined(WOLFSSL_AES_256) && defined(HAVE_AES_CBC)
  7507. case AES256CBCb:
  7508. *len = sizeof(blkAes256CbcOid);
  7509. *oid = blkAes256CbcOid;
  7510. *id = PBE_AES256_CBC;
  7511. *blkSz = 16;
  7512. break;
  7513. #endif
  7514. default:
  7515. (void)len;
  7516. (void)oid;
  7517. (void)id;
  7518. (void)blkSz;
  7519. ret = ALGO_ID_E;
  7520. }
  7521. return ret;
  7522. }
  7523. int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz,
  7524. const char* password, int passwordSz, int vPKCS, int pbeOid,
  7525. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  7526. void* heap)
  7527. {
  7528. #ifdef WOLFSSL_SMALL_STACK
  7529. byte* saltTmp = NULL;
  7530. #else
  7531. byte saltTmp[MAX_SALT_SIZE];
  7532. #endif
  7533. int genSalt = 0;
  7534. int ret = 0;
  7535. int version = 0;
  7536. int pbeId = 0;
  7537. int blockSz = 0;
  7538. const byte* encOid = NULL;
  7539. int encOidSz = 0;
  7540. word32 padSz = 0;
  7541. word32 innerLen = 0;
  7542. const byte* pbeOidBuf = NULL;
  7543. word32 pbeOidBufSz = 0;
  7544. word32 pbeLen = 0;
  7545. word32 kdfLen = 0;
  7546. word32 encLen = 0;
  7547. byte cbcIv[MAX_IV_SIZE];
  7548. word32 idx = 0;
  7549. word32 encIdx = 0;
  7550. (void)heap;
  7551. WOLFSSL_ENTER("wc_EncryptPKCS8Key");
  7552. if (key == NULL || outSz == NULL || password == NULL) {
  7553. ret = BAD_FUNC_ARG;
  7554. }
  7555. if (ret == 0) {
  7556. ret = CheckAlgo(vPKCS, pbeOid, &pbeId, &version, &blockSz);
  7557. }
  7558. if (ret == 0 && (salt == NULL || saltSz == 0)) {
  7559. genSalt = 1;
  7560. saltSz = 8;
  7561. }
  7562. if (ret == 0 && version == PKCS5v2) {
  7563. ret = GetAlgoV2(encAlgId, &encOid, &encOidSz, &pbeId, &blockSz);
  7564. }
  7565. if (ret == 0) {
  7566. padSz = (word32)((blockSz - ((int)keySz & (blockSz - 1))) &
  7567. (blockSz - 1));
  7568. /* inner = OCT salt INT itt */
  7569. innerLen = 2 + saltSz + 2 + ((itt < 256) ? 1 : ((itt < 65536) ? 2 : 3));
  7570. if (version != PKCS5v2) {
  7571. pbeOidBuf = OidFromId((word32)pbeId, oidPBEType, &pbeOidBufSz);
  7572. /* pbe = OBJ pbse1 SEQ [ inner ] */
  7573. pbeLen = 2 + pbeOidBufSz + 2 + innerLen;
  7574. }
  7575. else {
  7576. pbeOidBuf = pbes2;
  7577. pbeOidBufSz = sizeof(pbes2);
  7578. /* kdf = OBJ pbkdf2 [ SEQ innerLen ] */
  7579. kdfLen = 2 + sizeof(pbkdf2Oid) + 2 + innerLen;
  7580. /* enc = OBJ enc_alg OCT iv */
  7581. encLen = 2 + (word32)encOidSz + 2 + (word32)blockSz;
  7582. /* pbe = OBJ pbse2 SEQ [ SEQ [ kdf ] SEQ [ enc ] ] */
  7583. pbeLen = (word32)(2 + sizeof(pbes2) + 2 + 2 + (size_t)kdfLen + 2 +
  7584. (size_t)encLen);
  7585. ret = wc_RNG_GenerateBlock(rng, cbcIv, (word32)blockSz);
  7586. }
  7587. }
  7588. if (ret == 0) {
  7589. /* outerLen = length of PBE encoding + octet string data */
  7590. /* Plus 2 for tag and length for pbe */
  7591. word32 outerLen = 2 + pbeLen;
  7592. /* Octet string tag, length */
  7593. outerLen += 1 + SetLength(keySz + padSz, NULL);
  7594. /* Octet string bytes */
  7595. outerLen += keySz + padSz;
  7596. if (out == NULL) {
  7597. /* Sequence tag, length */
  7598. *outSz = 1 + SetLength(outerLen, NULL) + outerLen;
  7599. return LENGTH_ONLY_E;
  7600. }
  7601. SetOctetString(keySz + padSz, out);
  7602. idx += SetSequence(outerLen, out + idx);
  7603. encIdx = idx + outerLen - keySz - padSz;
  7604. /* Put Encrypted content in place. */
  7605. XMEMCPY(out + encIdx, key, keySz);
  7606. if (padSz > 0) {
  7607. XMEMSET(out + encIdx + keySz, (int)padSz, padSz);
  7608. keySz += padSz;
  7609. }
  7610. if (genSalt == 1) {
  7611. #ifdef WOLFSSL_SMALL_STACK
  7612. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7613. if (saltTmp == NULL) {
  7614. ret = MEMORY_E;
  7615. }
  7616. else
  7617. #endif
  7618. {
  7619. salt = saltTmp;
  7620. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  7621. WOLFSSL_MSG("Error generating random salt");
  7622. }
  7623. }
  7624. }
  7625. }
  7626. if (ret == 0) {
  7627. ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, pbeId,
  7628. out + encIdx, (int)keySz, version, cbcIv, 1, 0);
  7629. }
  7630. if (ret == 0) {
  7631. if (version != PKCS5v2) {
  7632. /* PBE algorithm */
  7633. idx += SetSequence(pbeLen, out + idx);
  7634. idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
  7635. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  7636. idx += pbeOidBufSz;
  7637. }
  7638. else {
  7639. /* PBES2 algorithm identifier */
  7640. idx += SetSequence(pbeLen, out + idx);
  7641. idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
  7642. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  7643. idx += pbeOidBufSz;
  7644. /* PBES2 Parameters: SEQ [ kdf ] SEQ [ enc ] */
  7645. idx += SetSequence(2 + kdfLen + 2 + encLen, out + idx);
  7646. /* KDF Algorithm Identifier */
  7647. idx += SetSequence(kdfLen, out + idx);
  7648. idx += (word32)SetObjectId((int)sizeof(pbkdf2Oid), out + idx);
  7649. XMEMCPY(out + idx, pbkdf2Oid, sizeof(pbkdf2Oid));
  7650. idx += sizeof(pbkdf2Oid);
  7651. }
  7652. idx += SetSequence(innerLen, out + idx);
  7653. idx += SetOctetString(saltSz, out + idx);
  7654. XMEMCPY(out + idx, salt, saltSz); idx += saltSz;
  7655. ret = SetShortInt(out, &idx, (word32)itt, *outSz);
  7656. if (ret > 0)
  7657. ret = 0;
  7658. }
  7659. if (ret == 0) {
  7660. if (version == PKCS5v2) {
  7661. /* Encryption Algorithm Identifier */
  7662. idx += SetSequence(encLen, out + idx);
  7663. idx += (word32)SetObjectId(encOidSz, out + idx);
  7664. XMEMCPY(out + idx, encOid, (size_t)encOidSz);
  7665. idx += (word32)encOidSz;
  7666. /* Encryption Algorithm Parameter: CBC IV */
  7667. idx += SetOctetString((word32)blockSz, out + idx);
  7668. XMEMCPY(out + idx, cbcIv, (size_t)blockSz);
  7669. idx += (word32)blockSz;
  7670. }
  7671. idx += SetOctetString(keySz, out + idx);
  7672. /* Default PRF - no need to write out OID */
  7673. idx += keySz;
  7674. ret = (int)idx;
  7675. }
  7676. #ifdef WOLFSSL_SMALL_STACK
  7677. if (saltTmp != NULL) {
  7678. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7679. }
  7680. #endif
  7681. WOLFSSL_LEAVE("wc_EncryptPKCS8Key", ret);
  7682. return ret;
  7683. }
  7684. int wc_DecryptPKCS8Key(byte* input, word32 sz, const char* password,
  7685. int passwordSz)
  7686. {
  7687. int ret;
  7688. int length;
  7689. word32 inOutIdx = 0;
  7690. if (input == NULL || password == NULL) {
  7691. return BAD_FUNC_ARG;
  7692. }
  7693. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  7694. ret = ASN_PARSE_E;
  7695. }
  7696. else {
  7697. ret = DecryptContent(input + inOutIdx, sz - inOutIdx, password,
  7698. passwordSz);
  7699. if (ret > 0) {
  7700. XMEMMOVE(input, input + inOutIdx, (size_t)ret);
  7701. }
  7702. }
  7703. if (ret > 0) {
  7704. /* DecryptContent will decrypt the data, but it will leave any padding
  7705. * bytes intact. This code calculates the length without the padding
  7706. * and we return that to the user. */
  7707. inOutIdx = 0;
  7708. if (GetSequence(input, &inOutIdx, &length, (word32)ret) < 0) {
  7709. ret = ASN_PARSE_E;
  7710. }
  7711. else {
  7712. ret = (int)inOutIdx + length;
  7713. }
  7714. }
  7715. return ret;
  7716. }
  7717. /* Takes an unencrypted, traditional DER-encoded key and converts it to a PKCS#8
  7718. * encrypted key. If out is not NULL, it will hold the encrypted key. If it's
  7719. * NULL, LENGTH_ONLY_E will be returned and outSz will have the required out
  7720. * buffer size. */
  7721. int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  7722. const char* password, int passwordSz, int vPKCS, int vAlgo,
  7723. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  7724. void* heap)
  7725. {
  7726. int ret = 0;
  7727. byte *pkcs8Key = NULL;
  7728. word32 pkcs8KeySz = 0;
  7729. int algId = 0;
  7730. const byte* curveOid = NULL;
  7731. word32 curveOidSz = 0;
  7732. if (ret == 0) {
  7733. /* check key type and get OID if ECC */
  7734. ret = wc_GetKeyOID(key, keySz, &curveOid, &curveOidSz, &algId, heap);
  7735. if (ret == 1)
  7736. ret = 0;
  7737. }
  7738. if (ret == 0) {
  7739. ret = wc_CreatePKCS8Key(NULL, &pkcs8KeySz, key, keySz, algId, curveOid,
  7740. curveOidSz);
  7741. if (ret == LENGTH_ONLY_E)
  7742. ret = 0;
  7743. }
  7744. if (ret == 0) {
  7745. pkcs8Key = (byte*)XMALLOC(pkcs8KeySz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7746. if (pkcs8Key == NULL)
  7747. ret = MEMORY_E;
  7748. }
  7749. if (ret == 0) {
  7750. ret = wc_CreatePKCS8Key(pkcs8Key, &pkcs8KeySz, key, keySz, algId,
  7751. curveOid, curveOidSz);
  7752. if (ret >= 0) {
  7753. pkcs8KeySz = (word32)ret;
  7754. ret = 0;
  7755. }
  7756. }
  7757. #ifdef WOLFSSL_CHECK_MEM_ZERO
  7758. if (ret == 0) {
  7759. wc_MemZero_Add("TraditionalEnc pkcs8Key", pkcs8Key, pkcs8KeySz);
  7760. }
  7761. #endif
  7762. if (ret == 0) {
  7763. ret = wc_EncryptPKCS8Key(pkcs8Key, pkcs8KeySz, out, outSz, password,
  7764. passwordSz, vPKCS, vAlgo, encAlgId, salt, saltSz, itt, rng, heap);
  7765. }
  7766. if (pkcs8Key != NULL) {
  7767. ForceZero(pkcs8Key, pkcs8KeySz);
  7768. XFREE(pkcs8Key, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7769. }
  7770. (void)rng;
  7771. return ret;
  7772. }
  7773. /* Same as TraditionalEnc, but in the public API. */
  7774. int wc_CreateEncryptedPKCS8Key(byte* key, word32 keySz, byte* out,
  7775. word32* outSz, const char* password, int passwordSz, int vPKCS,
  7776. int pbeOid, int encAlgId, byte* salt, word32 saltSz, int itt,
  7777. WC_RNG* rng, void* heap)
  7778. {
  7779. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz, vPKCS,
  7780. pbeOid, encAlgId, salt, saltSz, itt, rng, heap);
  7781. }
  7782. #ifdef WOLFSSL_ASN_TEMPLATE
  7783. /* ASN.1 template for PKCS #8/#7 encrypted key for decrypting
  7784. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  7785. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  7786. */
  7787. static const ASNItem pkcs8DecASN[] = {
  7788. /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7789. /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  7790. /* ENCALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  7791. /* PKCS #7 */
  7792. /* ENCCONTENT */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ENC_CONTENT,
  7793. 0, 0, 2 },
  7794. /* PKCS #8 */
  7795. /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
  7796. };
  7797. enum {
  7798. PKCS8DECASN_IDX_ENCALGO_SEQ = 0,
  7799. PKCS8DECASN_IDX_ENCALGO_OID,
  7800. PKCS8DECASN_IDX_ENCALGO_PARAMS,
  7801. PKCS8DECASN_IDX_ENCCONTENT,
  7802. PKCS8DECASN_IDX_ENCDATA
  7803. };
  7804. /* Number of items in ASN.1 template for PKCS #8/#7 encrypted key. */
  7805. #define pkcs8DecASN_Length (sizeof(pkcs8DecASN) / sizeof(ASNItem))
  7806. #endif
  7807. /* Decrypt data using PBE algorithm.
  7808. *
  7809. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  7810. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  7811. *
  7812. * Note: input buffer is overwritten with decrypted data!
  7813. *
  7814. * Salt is in KDF parameters and IV is PBE parameters when needed.
  7815. *
  7816. * @param [in] input Data to decrypt and unwrap.
  7817. * @param [in] sz Size of encrypted data.
  7818. * @param [in] password Password to derive encryption key with.
  7819. * @param [in] passwordSz Size of password in bytes.
  7820. * @return Length of decrypted data on success.
  7821. * @return MEMORY_E when dynamic memory allocation fails.
  7822. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  7823. * is invalid.
  7824. * @return BUFFER_E when data in buffer is too small.
  7825. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  7826. * @return Other when decryption fails.
  7827. */
  7828. int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz)
  7829. {
  7830. #ifndef WOLFSSL_ASN_TEMPLATE
  7831. word32 inOutIdx = 0, seqEnd, oid, shaOid = 0;
  7832. int ret = 0, first, second, length = 0, version, saltSz, id = 0;
  7833. int iterations = 0, keySz = 0;
  7834. #ifdef WOLFSSL_SMALL_STACK
  7835. byte* salt = NULL;
  7836. byte* cbcIv = NULL;
  7837. #else
  7838. byte salt[MAX_SALT_SIZE];
  7839. byte cbcIv[MAX_IV_SIZE];
  7840. #endif
  7841. byte tag;
  7842. if (passwordSz < 0) {
  7843. WOLFSSL_MSG("Bad password size");
  7844. return BAD_FUNC_ARG;
  7845. }
  7846. if (GetAlgoId(input, &inOutIdx, &oid, oidIgnoreType, sz) < 0) {
  7847. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7848. }
  7849. first = input[inOutIdx - 2]; /* PKCS version always 2nd to last byte */
  7850. second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
  7851. if (CheckAlgo(first, second, &id, &version, NULL) < 0) {
  7852. ERROR_OUT(ASN_INPUT_E, exit_dc); /* Algo ID error */
  7853. }
  7854. if (version == PKCS5v2) {
  7855. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  7856. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7857. }
  7858. if (GetAlgoId(input, &inOutIdx, &oid, oidKdfType, sz) < 0) {
  7859. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7860. }
  7861. if (oid != PBKDF2_OID) {
  7862. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7863. }
  7864. }
  7865. if (GetSequence(input, &inOutIdx, &length, sz) <= 0) {
  7866. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7867. }
  7868. /* Find the end of this SEQUENCE so we can check for the OPTIONAL and
  7869. * DEFAULT items. */
  7870. seqEnd = inOutIdx + (word32)length;
  7871. ret = GetOctetString(input, &inOutIdx, &saltSz, sz);
  7872. if (ret < 0)
  7873. goto exit_dc;
  7874. if (saltSz > MAX_SALT_SIZE) {
  7875. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7876. }
  7877. #ifdef WOLFSSL_SMALL_STACK
  7878. salt = (byte*)XMALLOC(MAX_SALT_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7879. if (salt == NULL) {
  7880. ERROR_OUT(MEMORY_E, exit_dc);
  7881. }
  7882. #endif
  7883. XMEMCPY(salt, &input[inOutIdx], (size_t)saltSz);
  7884. inOutIdx += (word32)saltSz;
  7885. if (GetShortInt(input, &inOutIdx, &iterations, sz) < 0) {
  7886. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7887. }
  7888. /* OPTIONAL key length */
  7889. if (seqEnd > inOutIdx) {
  7890. word32 localIdx = inOutIdx;
  7891. if (GetASNTag(input, &localIdx, &tag, sz) < 0) {
  7892. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7893. }
  7894. if (tag == ASN_INTEGER &&
  7895. GetShortInt(input, &inOutIdx, &keySz, sz) < 0) {
  7896. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7897. }
  7898. }
  7899. /* DEFAULT HMAC is SHA-1 */
  7900. if (seqEnd > inOutIdx) {
  7901. if (GetAlgoId(input, &inOutIdx, &oid, oidHmacType, sz) < 0) {
  7902. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7903. }
  7904. shaOid = oid;
  7905. }
  7906. #ifdef WOLFSSL_SMALL_STACK
  7907. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7908. if (cbcIv == NULL) {
  7909. ERROR_OUT(MEMORY_E, exit_dc);
  7910. }
  7911. #endif
  7912. if (version == PKCS5v2) {
  7913. /* get encryption algo */
  7914. if (GetAlgoId(input, &inOutIdx, &oid, oidBlkType, sz) < 0) {
  7915. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7916. }
  7917. if (CheckAlgoV2((int)oid, &id, NULL) < 0) {
  7918. ERROR_OUT(ASN_PARSE_E, exit_dc); /* PKCS v2 algo id error */
  7919. }
  7920. if (shaOid == 0)
  7921. shaOid = oid;
  7922. ret = GetOctetString(input, &inOutIdx, &length, sz);
  7923. if (ret < 0)
  7924. goto exit_dc;
  7925. if (length > MAX_IV_SIZE) {
  7926. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7927. }
  7928. XMEMCPY(cbcIv, &input[inOutIdx], (size_t)length);
  7929. inOutIdx += (word32)length;
  7930. }
  7931. if (GetASNTag(input, &inOutIdx, &tag, sz) < 0) {
  7932. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7933. }
  7934. if (tag != (ASN_CONTEXT_SPECIFIC | 0) && tag != ASN_OCTET_STRING) {
  7935. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7936. }
  7937. if (GetLength(input, &inOutIdx, &length, sz) < 0) {
  7938. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7939. }
  7940. ret = wc_CryptKey(password, passwordSz, salt, saltSz, iterations, id,
  7941. input + inOutIdx, length, version, cbcIv, 0, (int)shaOid);
  7942. exit_dc:
  7943. #ifdef WOLFSSL_SMALL_STACK
  7944. XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7945. XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7946. #endif
  7947. if (ret == 0) {
  7948. XMEMMOVE(input, input + inOutIdx, (size_t)length);
  7949. ret = length;
  7950. }
  7951. return ret;
  7952. #else
  7953. /* pbes2ParamsASN longer than pkcs8DecASN_Length/pbes1ParamsASN_Length. */
  7954. DECL_ASNGETDATA(dataASN, pbes2ParamsASN_Length);
  7955. int ret = 0;
  7956. int id = 0;
  7957. int version;
  7958. word32 idx = 0;
  7959. word32 pIdx = 0;
  7960. word32 iterations;
  7961. word32 keySz = 0;
  7962. word32 saltSz = 0;
  7963. word32 shaOid = 0;
  7964. byte* salt = NULL;
  7965. byte* key = NULL;
  7966. byte cbcIv[MAX_IV_SIZE];
  7967. byte* params = NULL;
  7968. WOLFSSL_ENTER("DecryptContent");
  7969. CALLOC_ASNGETDATA(dataASN, pbes2ParamsASN_Length, ret, NULL);
  7970. if (ret == 0) {
  7971. /* Check OID is a PBE Type */
  7972. GetASN_OID(&dataASN[PKCS8DECASN_IDX_ENCALGO_OID], oidPBEType);
  7973. ret = GetASN_Items(pkcs8DecASN, dataASN, pkcs8DecASN_Length, 0, input,
  7974. &idx, sz);
  7975. }
  7976. if (ret == 0) {
  7977. /* Check the PBE algorithm and get the version and id. */
  7978. idx = dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.length;
  7979. /* Second last byte: 1 (PKCS #12 PBE Id) or 5 (PKCS #5)
  7980. * Last byte: Alg or PBES2 */
  7981. ret = CheckAlgo(dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 2],
  7982. dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 1],
  7983. &id, &version, NULL);
  7984. }
  7985. if (ret == 0) {
  7986. /* Get the parameters data. */
  7987. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCALGO_PARAMS], &params, &sz);
  7988. /* Having a numbered choice means none or both will have errored out. */
  7989. if (dataASN[PKCS8DECASN_IDX_ENCCONTENT].tag != 0)
  7990. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCCONTENT], &key, &keySz);
  7991. else if (dataASN[PKCS8DECASN_IDX_ENCDATA].tag != 0)
  7992. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCDATA], &key, &keySz);
  7993. else
  7994. ret = ASN_RSA_KEY_E;
  7995. }
  7996. if (ret == 0) {
  7997. if (version != PKCS5v2) {
  7998. /* Initialize for PBES1 parameters and put iterations in var. */
  7999. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes1ParamsASN_Length);
  8000. GetASN_Int32Bit(&dataASN[PBES1PARAMSASN_IDX_ITER], &iterations);
  8001. /* Parse the PBES1 parameters. */
  8002. ret = GetASN_Items(pbes1ParamsASN, dataASN, pbes1ParamsASN_Length,
  8003. 0, params, &pIdx, sz);
  8004. if (ret == 0) {
  8005. /* Get the salt data. */
  8006. GetASN_GetRef(&dataASN[PBES1PARAMSASN_IDX_SALT], &salt, &saltSz);
  8007. }
  8008. }
  8009. else {
  8010. word32 ivSz = MAX_IV_SIZE;
  8011. /* Initialize for PBES2 parameters. Put iterations in var; match
  8012. * KDF, HMAC and cipher, and copy CBC into buffer. */
  8013. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes2ParamsASN_Length);
  8014. GetASN_ExpBuffer(&dataASN[PBES2PARAMSASN_IDX_KDF_OID], pbkdf2Oid, sizeof(pbkdf2Oid));
  8015. GetASN_Int32Bit(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER], &iterations);
  8016. GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID], oidHmacType);
  8017. GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_ENCS_OID], oidBlkType);
  8018. GetASN_Buffer(&dataASN[PBES2PARAMSASN_IDX_ENCS_PARAMS], cbcIv, &ivSz);
  8019. /* Parse the PBES2 parameters */
  8020. ret = GetASN_Items(pbes2ParamsASN, dataASN, pbes2ParamsASN_Length,
  8021. 0, params, &pIdx, sz);
  8022. if (ret == 0) {
  8023. /* Get the salt data. */
  8024. GetASN_GetRef(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT], &salt, &saltSz);
  8025. /* Get the digest and encryption algorithm id. */
  8026. shaOid = dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID].data.oid.sum; /* Default HMAC-SHA1 */
  8027. id = (int)dataASN[PBES2PARAMSASN_IDX_ENCS_OID].data.oid.sum;
  8028. /* Convert encryption algorithm to a PBE algorithm if needed. */
  8029. CheckAlgoV2(id, &id, NULL);
  8030. }
  8031. }
  8032. }
  8033. if (ret == 0) {
  8034. /* Decrypt the key. */
  8035. ret = wc_CryptKey(
  8036. password, passwordSz, salt, (int)saltSz, (int)iterations, id, key,
  8037. (int)keySz, version, cbcIv, 0, (int)shaOid);
  8038. }
  8039. if (ret == 0) {
  8040. /* Copy the decrypted key into the input (inline). */
  8041. XMEMMOVE(input, key, keySz);
  8042. ret = (int)keySz;
  8043. }
  8044. FREE_ASNGETDATA(dataASN, NULL);
  8045. return ret;
  8046. #endif
  8047. }
  8048. /* Decrypt data using PBE algorithm and get key from PKCS#8 wrapping.
  8049. *
  8050. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  8051. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo
  8052. *
  8053. * Note: input buffer is overwritten with decrypted key!
  8054. *
  8055. * Salt is in KDF parameters and IV is PBE parameters when needed.
  8056. *
  8057. * @param [in] input Data to decrypt and unwrap.
  8058. * @param [in] sz Size of encrypted data.
  8059. * @param [in] password Password to derive encryption key with.
  8060. * @param [in] passwordSz Size of password in bytes.
  8061. * @param [out] algId Key algorithm from PKCS#8 wrapper.
  8062. * @return Length of decrypted data on success.
  8063. * @return MEMORY_E when dynamic memory allocation fails.
  8064. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8065. * is invalid.
  8066. * @return BUFFER_E when data in buffer is too small.
  8067. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8068. * @return Other when decryption fails.
  8069. */
  8070. int ToTraditionalEnc(byte* input, word32 sz, const char* password,
  8071. int passwordSz, word32* algId)
  8072. {
  8073. int ret;
  8074. ret = wc_DecryptPKCS8Key(input, sz, password, passwordSz);
  8075. if (ret > 0) {
  8076. ret = ToTraditional_ex(input, (word32)ret, algId);
  8077. }
  8078. return ret;
  8079. }
  8080. #endif /* HAVE_PKCS8 */
  8081. #ifdef HAVE_PKCS12
  8082. #define PKCS8_MIN_BLOCK_SIZE 8
  8083. static int Pkcs8Pad(byte* buf, int sz, int blockSz)
  8084. {
  8085. int padSz;
  8086. /* calculate pad size */
  8087. padSz = blockSz - (sz & (blockSz - 1));
  8088. /* pad with padSz value */
  8089. if (buf) {
  8090. int i;
  8091. for (i = 0; i < padSz; i++) {
  8092. buf[sz+i] = (byte)(padSz & 0xFF);
  8093. }
  8094. }
  8095. /* return adjusted length */
  8096. return sz + padSz;
  8097. }
  8098. #ifdef WOLFSSL_ASN_TEMPLATE
  8099. /* ASN.1 template for PKCS #8 encrypted key with PBES1 parameters.
  8100. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  8101. * PKCS #5: RFC 8018, A.3 - PBEParameter
  8102. */
  8103. static const ASNItem p8EncPbes1ASN[] = {
  8104. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8105. /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8106. /* PBE algorithm */
  8107. /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8108. /* ENCALGO_PBEPARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8109. /* Salt */
  8110. /* ENCALGO_PBEPARAM_SALT */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  8111. /* Iteration Count */
  8112. /* ENCALGO_PBEPARAM_ITER */ { 3, ASN_INTEGER, 0, 0, 0 },
  8113. /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  8114. };
  8115. enum {
  8116. P8ENCPBES1ASN_IDX_SEQ = 0,
  8117. P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8118. P8ENCPBES1ASN_IDX_ENCALGO_OID,
  8119. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SEQ,
  8120. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT,
  8121. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER,
  8122. P8ENCPBES1ASN_IDX_ENCDATA
  8123. };
  8124. #define p8EncPbes1ASN_Length (sizeof(p8EncPbes1ASN) / sizeof(ASNItem))
  8125. #endif
  8126. /* Wrap a private key in PKCS#8 and encrypt.
  8127. *
  8128. * Used for PKCS#12 and PKCS#7.
  8129. * vPKCS is the version of PKCS to use.
  8130. * vAlgo is the algorithm version to use.
  8131. *
  8132. * When salt is NULL, a random number is generated.
  8133. *
  8134. * data returned is :
  8135. * [ seq - obj [ seq -salt,itt]] , construct with encrypted data
  8136. *
  8137. * @param [in] input Data to encrypt.
  8138. * @param [in] inputSz Length of data in bytes.
  8139. * @param [out] out Buffer to write wrapped encrypted data into.
  8140. * @param [out] outSz Length of encrypted data in bytes.
  8141. * @param [in] password Password used to create encryption key.
  8142. * @param [in] passwordSz Length of password in bytes.
  8143. * @param [in] vPKCS First byte used to determine PBE algorithm.
  8144. * @param [in] vAlgo Second byte used to determine PBE algorithm.
  8145. * @param [in] salt Salt to use with KDF.
  8146. * @param [in] saltSz Length of salt in bytes.
  8147. * @param [in] itt Number of iterations to use in KDF.
  8148. * @param [in] rng Random number generator to use to generate salt.
  8149. * @param [in] heap Dynamic memory allocator hint.
  8150. * @return The size of encrypted data on success
  8151. * @return LENGTH_ONLY_E when out is NULL and able to encode.
  8152. * @return ASN_PARSE_E when the salt size is too large.
  8153. * @return ASN_VERSION_E when attempting to use a PBES2 algorithm (use
  8154. * TraditionalEnc).
  8155. * @return MEMORY_E when dynamic memory allocation fails.
  8156. * @return Other when encryption or random number generation fails.
  8157. */
  8158. int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz,
  8159. const char* password, int passwordSz, int vPKCS, int vAlgo,
  8160. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  8161. {
  8162. #ifndef WOLFSSL_ASN_TEMPLATE
  8163. word32 sz;
  8164. word32 inOutIdx = 0;
  8165. word32 tmpIdx = 0;
  8166. word32 totalSz = 0;
  8167. word32 seqSz;
  8168. word32 innerSz;
  8169. int ret;
  8170. int version, id, blockSz = 0;
  8171. #ifdef WOLFSSL_SMALL_STACK
  8172. byte* saltTmp = NULL;
  8173. byte* cbcIv = NULL;
  8174. #else
  8175. byte saltTmp[MAX_SALT_SIZE];
  8176. byte cbcIv[MAX_IV_SIZE];
  8177. #endif
  8178. byte seq[MAX_SEQ_SZ];
  8179. byte shr[MAX_SHORT_SZ];
  8180. word32 maxShr = MAX_SHORT_SZ;
  8181. word32 algoSz;
  8182. const byte* algoName;
  8183. (void)heap;
  8184. WOLFSSL_ENTER("EncryptContent");
  8185. if (CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0)
  8186. return ASN_INPUT_E; /* Algo ID error */
  8187. if (version == PKCS5v2) {
  8188. WOLFSSL_MSG("PKCS#5 version 2 not supported yet");
  8189. return BAD_FUNC_ARG;
  8190. }
  8191. if (saltSz > MAX_SALT_SIZE)
  8192. return ASN_PARSE_E;
  8193. if (outSz == NULL) {
  8194. return BAD_FUNC_ARG;
  8195. }
  8196. /* calculate size */
  8197. /* size of constructed string at end */
  8198. sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8199. totalSz = ASN_TAG_SZ;
  8200. totalSz += SetLength(sz, seq);
  8201. totalSz += sz;
  8202. /* size of sequence holding object id and sub sequence of salt and itt */
  8203. algoName = OidFromId((word32)id, oidPBEType, &algoSz);
  8204. if (algoName == NULL) {
  8205. WOLFSSL_MSG("Unknown Algorithm");
  8206. return 0;
  8207. }
  8208. innerSz = (word32)SetObjectId((int)algoSz, seq);
  8209. innerSz += algoSz;
  8210. /* get subsequence of salt and itt */
  8211. if (salt == NULL || saltSz == 0) {
  8212. sz = 8;
  8213. }
  8214. else {
  8215. sz = saltSz;
  8216. }
  8217. seqSz = SetOctetString(sz, seq);
  8218. seqSz += sz;
  8219. tmpIdx = 0;
  8220. ret = SetShortInt(shr, &tmpIdx, (word32)itt, maxShr);
  8221. if (ret >= 0) {
  8222. seqSz += (word32)ret;
  8223. }
  8224. else {
  8225. return ret;
  8226. }
  8227. innerSz += seqSz + SetSequence(seqSz, seq);
  8228. totalSz += innerSz + SetSequence(innerSz, seq);
  8229. if (out == NULL) {
  8230. *outSz = totalSz;
  8231. return LENGTH_ONLY_E;
  8232. }
  8233. inOutIdx = 0;
  8234. if (totalSz > *outSz)
  8235. return BUFFER_E;
  8236. inOutIdx += SetSequence(innerSz, out + inOutIdx);
  8237. inOutIdx += (word32)SetObjectId((int)algoSz, out + inOutIdx);
  8238. XMEMCPY(out + inOutIdx, algoName, algoSz);
  8239. inOutIdx += algoSz;
  8240. inOutIdx += SetSequence(seqSz, out + inOutIdx);
  8241. /* create random salt if one not provided */
  8242. if (salt == NULL || saltSz == 0) {
  8243. saltSz = 8;
  8244. #ifdef WOLFSSL_SMALL_STACK
  8245. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8246. if (saltTmp == NULL)
  8247. return MEMORY_E;
  8248. #endif
  8249. salt = saltTmp;
  8250. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  8251. WOLFSSL_MSG("Error generating random salt");
  8252. #ifdef WOLFSSL_SMALL_STACK
  8253. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8254. #endif
  8255. return ret;
  8256. }
  8257. }
  8258. inOutIdx += SetOctetString(saltSz, out + inOutIdx);
  8259. if (saltSz + inOutIdx > *outSz) {
  8260. #ifdef WOLFSSL_SMALL_STACK
  8261. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8262. #endif
  8263. return BUFFER_E;
  8264. }
  8265. XMEMCPY(out + inOutIdx, salt, saltSz);
  8266. inOutIdx += saltSz;
  8267. /* place iteration setting in buffer */
  8268. ret = SetShortInt(out, &inOutIdx, (word32)itt, *outSz);
  8269. if (ret < 0) {
  8270. #ifdef WOLFSSL_SMALL_STACK
  8271. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8272. #endif
  8273. return ret;
  8274. }
  8275. if (inOutIdx + 1 > *outSz) {
  8276. #ifdef WOLFSSL_SMALL_STACK
  8277. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8278. #endif
  8279. return BUFFER_E;
  8280. }
  8281. out[inOutIdx++] = ASN_CONTEXT_SPECIFIC | 0;
  8282. /* get pad size and verify buffer room */
  8283. sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8284. if (sz + inOutIdx > *outSz) {
  8285. #ifdef WOLFSSL_SMALL_STACK
  8286. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8287. #endif
  8288. return BUFFER_E;
  8289. }
  8290. inOutIdx += SetLength(sz, out + inOutIdx);
  8291. /* copy input to output buffer and pad end */
  8292. XMEMCPY(out + inOutIdx, input, inputSz);
  8293. sz = (word32)Pkcs8Pad(out + inOutIdx, (int)inputSz, blockSz);
  8294. #ifdef WOLFSSL_SMALL_STACK
  8295. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8296. if (cbcIv == NULL) {
  8297. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8298. return MEMORY_E;
  8299. }
  8300. #endif
  8301. /* encrypt */
  8302. if ((ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
  8303. out + inOutIdx, (int)sz, version, cbcIv, 1, 0)) < 0) {
  8304. #ifdef WOLFSSL_SMALL_STACK
  8305. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8306. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8307. #endif
  8308. return ret; /* encrypt failure */
  8309. }
  8310. #ifdef WOLFSSL_SMALL_STACK
  8311. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8312. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8313. #endif
  8314. (void)rng;
  8315. return (int)(inOutIdx + sz);
  8316. #else
  8317. DECL_ASNSETDATA(dataASN, p8EncPbes1ASN_Length);
  8318. int ret = 0;
  8319. int sz = 0;
  8320. int version = 0;
  8321. int id = -1;
  8322. int blockSz = 0;
  8323. word32 pkcs8Sz = 0;
  8324. (void)heap;
  8325. WOLFSSL_ENTER("EncryptContent");
  8326. /* Must have a output size to return or check. */
  8327. if (outSz == NULL) {
  8328. ret = BAD_FUNC_ARG;
  8329. }
  8330. /* Check salt size is valid. */
  8331. if ((ret == 0) && (saltSz > MAX_SALT_SIZE)) {
  8332. ret = ASN_PARSE_E;
  8333. }
  8334. /* Get algorithm parameters for algorithm identifier. */
  8335. if ((ret == 0) && CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0) {
  8336. ret = ASN_INPUT_E;
  8337. }
  8338. /* Check PKCS #5 version - only PBSE1 parameters supported. */
  8339. if ((ret == 0) && (version == PKCS5v2)) {
  8340. ret = BAD_FUNC_ARG;
  8341. }
  8342. CALLOC_ASNSETDATA(dataASN, p8EncPbes1ASN_Length, ret, heap);
  8343. if (ret == 0) {
  8344. /* Setup data to go into encoding including PBE algorithm, salt,
  8345. * iteration count, and padded key length. */
  8346. SetASN_OID(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_OID], (word32)id,
  8347. oidPBEType);
  8348. if (salt == NULL || saltSz == 0) {
  8349. salt = NULL;
  8350. saltSz = PKCS5_SALT_SZ;
  8351. /* Salt generated into encoding below. */
  8352. }
  8353. SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT],
  8354. salt, saltSz);
  8355. SetASN_Int16Bit(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER],
  8356. (word16)itt);
  8357. pkcs8Sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8358. SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCDATA], NULL, pkcs8Sz);
  8359. /* Calculate size of encoding. */
  8360. ret = SizeASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8361. dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8362. (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
  8363. &sz);
  8364. }
  8365. /* Return size when no output buffer. */
  8366. if ((ret == 0) && (out == NULL)) {
  8367. *outSz = (word32)sz;
  8368. ret = LENGTH_ONLY_E;
  8369. }
  8370. /* Check output buffer is big enough for encoded data. */
  8371. if ((ret == 0) && (sz > (int)*outSz)) {
  8372. ret = BAD_FUNC_ARG;
  8373. }
  8374. if (ret == 0) {
  8375. /* Encode PKCS#8 key. */
  8376. SetASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8377. dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8378. (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
  8379. out);
  8380. if (salt == NULL) {
  8381. /* Generate salt into encoding. */
  8382. salt = (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT].
  8383. data.buffer.data;
  8384. ret = wc_RNG_GenerateBlock(rng, salt, saltSz);
  8385. }
  8386. }
  8387. if (ret == 0) {
  8388. byte cbcIv[MAX_IV_SIZE];
  8389. /* Store PKCS#8 key in output buffer. */
  8390. byte* pkcs8 =
  8391. (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCDATA].data.buffer.data;
  8392. XMEMCPY(pkcs8, input, inputSz);
  8393. Pkcs8Pad(pkcs8, (int)inputSz, blockSz);
  8394. /* Encrypt PKCS#8 key inline. */
  8395. ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
  8396. pkcs8, (int)pkcs8Sz, version, cbcIv, 1, 0);
  8397. }
  8398. if (ret == 0) {
  8399. /* Returning size on success. */
  8400. ret = sz;
  8401. }
  8402. FREE_ASNSETDATA(dataASN, heap);
  8403. return ret;
  8404. #endif /* WOLFSSL_ASN_TEMPLATE */
  8405. }
  8406. #endif /* HAVE_PKCS12 */
  8407. #endif /* NO_PWDBASED */
  8408. #ifndef NO_RSA
  8409. #ifndef HAVE_USER_RSA
  8410. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  8411. /* This function is to retrieve key position information in a cert.*
  8412. * The information will be used to call TSIP TLS-linked API for *
  8413. * certificate verification. */
  8414. static int RsaPublicKeyDecodeRawIndex(const byte* input, word32* inOutIdx,
  8415. word32 inSz, word32* key_n,
  8416. word32* key_n_len, word32* key_e,
  8417. word32* key_e_len)
  8418. {
  8419. int ret = 0;
  8420. int length = 0;
  8421. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8422. byte b;
  8423. #endif
  8424. if (input == NULL || inOutIdx == NULL)
  8425. return BAD_FUNC_ARG;
  8426. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8427. return ASN_PARSE_E;
  8428. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8429. if ((*inOutIdx + 1) > inSz)
  8430. return BUFFER_E;
  8431. b = input[*inOutIdx];
  8432. if (b != ASN_INTEGER) {
  8433. /* not from decoded cert, will have algo id, skip past */
  8434. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8435. return ASN_PARSE_E;
  8436. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  8437. return ASN_PARSE_E;
  8438. /* Option NULL ASN.1 tag */
  8439. if (*inOutIdx >= inSz) {
  8440. return BUFFER_E;
  8441. }
  8442. if (input[*inOutIdx] == ASN_TAG_NULL) {
  8443. ret = GetASNNull(input, inOutIdx, inSz);
  8444. if (ret != 0)
  8445. return ret;
  8446. }
  8447. /* TODO: support RSA PSS */
  8448. /* should have bit tag length and seq next */
  8449. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  8450. if (ret != 0)
  8451. return ret;
  8452. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8453. return ASN_PARSE_E;
  8454. }
  8455. #endif /* OPENSSL_EXTRA */
  8456. /* Get modulus */
  8457. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8458. *key_n += *inOutIdx;
  8459. if (ret < 0) {
  8460. return ASN_RSA_KEY_E;
  8461. }
  8462. if (key_n_len)
  8463. *key_n_len = length;
  8464. *inOutIdx += length;
  8465. /* Get exponent */
  8466. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8467. *key_e += *inOutIdx;
  8468. if (ret < 0) {
  8469. return ASN_RSA_KEY_E;
  8470. }
  8471. if (key_e_len)
  8472. *key_e_len = length;
  8473. return ret;
  8474. }
  8475. #endif /* WOLFSSL_RENESAS_TSIP */
  8476. #ifdef WOLFSSL_ASN_TEMPLATE
  8477. /* ASN.1 template for an RSA public key.
  8478. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8479. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8480. */
  8481. static const ASNItem rsaPublicKeyASN[] = {
  8482. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8483. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8484. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8485. /* ALGOID_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  8486. #ifdef WC_RSA_PSS
  8487. /* ALGOID_P_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  8488. #endif
  8489. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 1, 0 },
  8490. /* RSAPublicKey */
  8491. /* PUBKEY_RSA_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8492. /* PUBKEY_RSA_N */ { 3, ASN_INTEGER, 0, 0, 0 },
  8493. /* PUBKEY_RSA_E */ { 3, ASN_INTEGER, 0, 0, 0 },
  8494. };
  8495. enum {
  8496. RSAPUBLICKEYASN_IDX_SEQ = 0,
  8497. RSAPUBLICKEYASN_IDX_ALGOID_SEQ,
  8498. RSAPUBLICKEYASN_IDX_ALGOID_OID,
  8499. RSAPUBLICKEYASN_IDX_ALGOID_NULL,
  8500. #ifdef WC_RSA_PSS
  8501. RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ,
  8502. #endif
  8503. RSAPUBLICKEYASN_IDX_PUBKEY,
  8504. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ,
  8505. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N,
  8506. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E
  8507. };
  8508. /* Number of items in ASN.1 template for an RSA public key. */
  8509. #define rsaPublicKeyASN_Length (sizeof(rsaPublicKeyASN) / sizeof(ASNItem))
  8510. #endif
  8511. /* Decode RSA public key.
  8512. *
  8513. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8514. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8515. *
  8516. * @param [in] input Buffer holding BER encoded data.
  8517. * @param [in, out] inOutIdx On in, start of RSA public key.
  8518. * On out, start of ASN.1 item after RSA public key.
  8519. * @param [in] inSz Number of bytes in buffer.
  8520. * @param [out] n Pointer to modulus in buffer.
  8521. * @param [out] nSz Size of modulus in bytes.
  8522. * @param [out] e Pointer to exponent in buffer.
  8523. * @param [out] eSz Size of exponent in bytes.
  8524. * @return 0 on success.
  8525. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8526. * is invalid.
  8527. * @return BUFFER_E when data in buffer is too small.
  8528. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8529. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8530. * non-zero length.
  8531. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8532. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8533. */
  8534. int wc_RsaPublicKeyDecode_ex(const byte* input, word32* inOutIdx, word32 inSz,
  8535. const byte** n, word32* nSz, const byte** e, word32* eSz)
  8536. {
  8537. #ifndef WOLFSSL_ASN_TEMPLATE
  8538. int ret = 0;
  8539. int length = 0;
  8540. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8541. word32 localIdx;
  8542. byte tag;
  8543. #endif
  8544. if (input == NULL || inOutIdx == NULL)
  8545. return BAD_FUNC_ARG;
  8546. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8547. return ASN_PARSE_E;
  8548. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8549. localIdx = *inOutIdx;
  8550. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  8551. return BUFFER_E;
  8552. if (tag != ASN_INTEGER) {
  8553. /* not from decoded cert, will have algo id, skip past */
  8554. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8555. return ASN_PARSE_E;
  8556. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  8557. return ASN_PARSE_E;
  8558. /* Option NULL ASN.1 tag */
  8559. if (*inOutIdx >= inSz) {
  8560. return BUFFER_E;
  8561. }
  8562. localIdx = *inOutIdx;
  8563. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  8564. return ASN_PARSE_E;
  8565. if (tag == ASN_TAG_NULL) {
  8566. ret = GetASNNull(input, inOutIdx, inSz);
  8567. if (ret != 0)
  8568. return ret;
  8569. }
  8570. #ifdef WC_RSA_PSS
  8571. /* Skip RSA PSS parameters. */
  8572. else if (tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  8573. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8574. return ASN_PARSE_E;
  8575. *inOutIdx += length;
  8576. }
  8577. #endif
  8578. /* should have bit tag length and seq next */
  8579. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  8580. if (ret != 0)
  8581. return ret;
  8582. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8583. return ASN_PARSE_E;
  8584. }
  8585. #endif /* OPENSSL_EXTRA */
  8586. /* Get modulus */
  8587. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8588. if (ret < 0) {
  8589. return ASN_RSA_KEY_E;
  8590. }
  8591. if (nSz)
  8592. *nSz = (word32)length;
  8593. if (n)
  8594. *n = &input[*inOutIdx];
  8595. *inOutIdx += (word32)length;
  8596. /* Get exponent */
  8597. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8598. if (ret < 0) {
  8599. return ASN_RSA_KEY_E;
  8600. }
  8601. if (eSz)
  8602. *eSz = (word32)length;
  8603. if (e)
  8604. *e = &input[*inOutIdx];
  8605. *inOutIdx += (word32)length;
  8606. return ret;
  8607. #else
  8608. DECL_ASNGETDATA(dataASN, rsaPublicKeyASN_Length);
  8609. int ret = 0;
  8610. #ifdef WC_RSA_PSS
  8611. word32 oid = RSAk;
  8612. #endif
  8613. /* Check validity of parameters. */
  8614. if (input == NULL || inOutIdx == NULL) {
  8615. ret = BAD_FUNC_ARG;
  8616. }
  8617. CALLOC_ASNGETDATA(dataASN, rsaPublicKeyASN_Length, ret, NULL);
  8618. if (ret == 0) {
  8619. /* Try decoding PKCS #1 public key by ignoring rest of ASN.1. */
  8620. ret = GetASN_Items(&rsaPublicKeyASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8621. &dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8622. (int)(rsaPublicKeyASN_Length - RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ),
  8623. 0, input, inOutIdx, inSz);
  8624. if (ret != 0) {
  8625. /* Didn't work - try whole SubjectKeyInfo instead. */
  8626. #ifdef WC_RSA_PSS
  8627. /* Could be RSA or RSA PSS key. */
  8628. GetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], oidKeyType);
  8629. #else
  8630. /* Set the OID to expect. */
  8631. GetASN_ExpBuffer(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID],
  8632. keyRsaOid, sizeof(keyRsaOid));
  8633. #endif
  8634. /* Decode SubjectKeyInfo. */
  8635. ret = GetASN_Items(rsaPublicKeyASN, dataASN,
  8636. rsaPublicKeyASN_Length, 1, input, inOutIdx,
  8637. inSz);
  8638. }
  8639. }
  8640. #ifdef WC_RSA_PSS
  8641. if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].tag != 0)) {
  8642. /* Two possible OIDs supported - RSA and RSA PSS. */
  8643. oid = dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].data.oid.sum;
  8644. if ((oid != RSAk) && (oid != RSAPSSk)) {
  8645. ret = ASN_PARSE_E;
  8646. }
  8647. }
  8648. if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].tag != 0)) {
  8649. /* Can't have NULL and SEQ. */
  8650. if (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_NULL].tag != 0) {
  8651. ret = ASN_PARSE_E;
  8652. }
  8653. /* SEQ present only with RSA PSS. */
  8654. if ((ret == 0) && (oid != RSAPSSk)) {
  8655. ret = ASN_PARSE_E;
  8656. }
  8657. if (ret == 0) {
  8658. enum wc_HashType hash;
  8659. int mgf;
  8660. int saltLen;
  8661. const byte* params = GetASNItem_Addr(
  8662. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
  8663. word32 paramsSz = GetASNItem_Length(
  8664. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
  8665. /* Validate the private key parameters. */
  8666. ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf, &saltLen);
  8667. /* TODO: store parameters so that usage can be checked. */
  8668. }
  8669. }
  8670. #endif
  8671. if (ret == 0) {
  8672. /* Return the buffers and lengths asked for. */
  8673. if (n != NULL) {
  8674. *n = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.data;
  8675. }
  8676. if (nSz != NULL) {
  8677. *nSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.length;
  8678. }
  8679. if (e != NULL) {
  8680. *e = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.data;
  8681. }
  8682. if (eSz != NULL) {
  8683. *eSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.length;
  8684. }
  8685. }
  8686. FREE_ASNGETDATA(dataASN, NULL);
  8687. return ret;
  8688. #endif /* WOLFSSL_ASN_TEMPLATE */
  8689. }
  8690. /* Decode RSA public key.
  8691. *
  8692. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8693. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8694. *
  8695. * @param [in] input Buffer holding BER encoded data.
  8696. * @param [in, out] inOutIdx On in, start of RSA public key.
  8697. * On out, start of ASN.1 item after RSA public key.
  8698. * @param [in, out] key RSA key object.
  8699. * @param [in] inSz Number of bytes in buffer.
  8700. * @return 0 on success.
  8701. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8702. * is invalid.
  8703. * @return BUFFER_E when data in buffer is too small.
  8704. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8705. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8706. * non-zero length.
  8707. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8708. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8709. */
  8710. int wc_RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  8711. word32 inSz)
  8712. {
  8713. int ret;
  8714. const byte *n = NULL, *e = NULL;
  8715. word32 nSz = 0, eSz = 0;
  8716. if (key == NULL)
  8717. return BAD_FUNC_ARG;
  8718. ret = wc_RsaPublicKeyDecode_ex(input, inOutIdx, inSz, &n, &nSz, &e, &eSz);
  8719. if (ret == 0) {
  8720. ret = wc_RsaPublicKeyDecodeRaw(n, nSz, e, eSz, key);
  8721. }
  8722. return ret;
  8723. }
  8724. #endif /* HAVE_USER_RSA */
  8725. #endif /* !NO_RSA */
  8726. #ifndef NO_DH
  8727. #if defined(WOLFSSL_DH_EXTRA)
  8728. /*
  8729. * Decodes DH public key to fill specified DhKey.
  8730. *
  8731. * return 0 on success, negative on failure
  8732. */
  8733. int wc_DhPublicKeyDecode(const byte* input, word32* inOutIdx,
  8734. DhKey* key, word32 inSz)
  8735. {
  8736. int ret = 0;
  8737. int length;
  8738. word32 oid = 0;
  8739. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  8740. return BAD_FUNC_ARG;
  8741. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8742. return ASN_PARSE_E;
  8743. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8744. return ASN_PARSE_E;
  8745. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  8746. if (oid != DHk || ret < 0)
  8747. return ASN_DH_KEY_E;
  8748. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8749. return ASN_PARSE_E;
  8750. if (GetInt(&key->p, input, inOutIdx, inSz) < 0)
  8751. return ASN_DH_KEY_E;
  8752. if (GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8753. mp_clear(&key->p);
  8754. return ASN_DH_KEY_E;
  8755. }
  8756. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  8757. if (ret > 0) {
  8758. /* Found Bit String WOLFSSL_DH_EXTRA is required to access DhKey.pub */
  8759. if (GetInt(&key->pub, input, inOutIdx, inSz) < 0) {
  8760. mp_clear(&key->p);
  8761. mp_clear(&key->g);
  8762. return ASN_DH_KEY_E;
  8763. }
  8764. }
  8765. else {
  8766. mp_clear(&key->p);
  8767. mp_clear(&key->g);
  8768. return ASN_DH_KEY_E;
  8769. }
  8770. return 0;
  8771. }
  8772. #endif /* WOLFSSL_DH_EXTRA */
  8773. #ifdef WOLFSSL_ASN_TEMPLATE
  8774. /* ASN.1 template for DH key.
  8775. * PKCS #3, 9 - DHParameter.
  8776. * (Also in: RFC 2786, 3)
  8777. */
  8778. static const ASNItem dhParamASN[] = {
  8779. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8780. /* prime */
  8781. /* PRIME */ { 1, ASN_INTEGER, 0, 0, 0 },
  8782. /* base */
  8783. /* BASE */ { 1, ASN_INTEGER, 0, 0, 0 },
  8784. /* privateValueLength */
  8785. /* PRIVLEN */ { 1, ASN_INTEGER, 0, 0, 1 },
  8786. };
  8787. enum {
  8788. DHPARAMASN_IDX_SEQ = 0,
  8789. DHPARAMASN_IDX_PRIME,
  8790. DHPARAMASN_IDX_BASE,
  8791. DHPARAMASN_IDX_PRIVLEN
  8792. };
  8793. /* Number of items in ASN.1 template for DH key. */
  8794. #define dhParamASN_Length (sizeof(dhParamASN) / sizeof(ASNItem))
  8795. #ifdef WOLFSSL_DH_EXTRA
  8796. /* ASN.1 template for DH key wrapped in PKCS #8 or SubjectPublicKeyInfo.
  8797. * PKCS #8: RFC 5208, 5 - PrivateKeyInfo
  8798. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8799. * RFC 3279, 2.3.3 - DH in SubjectPublicKeyInfo
  8800. */
  8801. static const ASNItem dhKeyPkcs8ASN[] = {
  8802. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8803. /* VER */ { 1, ASN_INTEGER, 0, 0, 1 },
  8804. /* PKEYALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8805. /* PKEYALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8806. /* DHParameter */
  8807. /* PKEYALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8808. /* p */
  8809. /* PKEYALGO_PARAM_P */ { 3, ASN_INTEGER, 0, 0, 0 },
  8810. /* g */
  8811. /* PKEYALGO_PARAM_G */ { 3, ASN_INTEGER, 0, 0, 0 },
  8812. /* q - factor of p-1 */
  8813. /* PKEYALGO_PARAM_Q */ { 3, ASN_INTEGER, 0, 0, 1 },
  8814. /* j - subgroup factor */
  8815. /* PKEYALGO_PARAM_J */ { 3, ASN_INTEGER, 0, 0, 1 },
  8816. /* ValidationParms */
  8817. /* PKEYALGO_PARAM_VALID */ { 3, ASN_SEQUENCE, 0, 0, 1 },
  8818. /* PrivateKey - PKCS #8 */
  8819. /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 2 },
  8820. /* PKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
  8821. /* PublicKey - SubjectPublicKeyInfo. */
  8822. /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 2 },
  8823. /* PUBKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
  8824. };
  8825. enum {
  8826. DHKEYPKCS8ASN_IDX_SEQ = 0,
  8827. DHKEYPKCS8ASN_IDX_VER,
  8828. DHKEYPKCS8ASN_IDX_PKEYALGO_SEQ,
  8829. DHKEYPKCS8ASN_IDX_PKEYALGO_OID,
  8830. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_SEQ,
  8831. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P,
  8832. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G,
  8833. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q,
  8834. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J,
  8835. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID,
  8836. DHKEYPKCS8ASN_IDX_PKEY_STR,
  8837. DHKEYPKCS8ASN_IDX_PKEY_INT,
  8838. DHKEYPKCS8ASN_IDX_PUBKEY_STR,
  8839. DHKEYPKCS8ASN_IDX_PUBKEY_INT
  8840. };
  8841. #define dhKeyPkcs8ASN_Length (sizeof(dhKeyPkcs8ASN) / sizeof(ASNItem))
  8842. #endif
  8843. #endif
  8844. /* Decodes either PKCS#3 DH parameters or PKCS#8 DH key file (WOLFSSL_DH_EXTRA).
  8845. *
  8846. * See also wc_DhParamsLoad(). Loads directly into buffers rather than key
  8847. * object.
  8848. *
  8849. * @param [in] input BER/DER encoded data.
  8850. * @param [in, out] inOutIdx On in, start of DH key data.
  8851. * On out, end of DH key data.
  8852. * @param [in, out] key DH key object.
  8853. * @param [in] inSz Size of data in bytes.
  8854. * @return 0 on success.
  8855. * @return BAD_FUNC_ARG when input, inOutIDx or key is NULL.
  8856. * @return MEMORY_E when dynamic memory allocation fails.
  8857. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8858. * is invalid.
  8859. * @return BUFFER_E when data in buffer is too small.
  8860. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8861. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8862. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8863. * non-zero length.
  8864. * @return MP_INIT_E when the unable to initialize an mp_int.
  8865. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  8866. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8867. */
  8868. int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
  8869. {
  8870. #ifndef WOLFSSL_ASN_TEMPLATE
  8871. int ret = 0;
  8872. int length;
  8873. #ifdef WOLFSSL_DH_EXTRA
  8874. #if !defined(HAVE_FIPS) || \
  8875. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8876. word32 oid = 0, temp = 0;
  8877. #endif
  8878. #endif
  8879. WOLFSSL_ENTER("wc_DhKeyDecode");
  8880. if (inOutIdx == NULL)
  8881. return BAD_FUNC_ARG;
  8882. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8883. return ASN_PARSE_E;
  8884. #ifdef WOLFSSL_DH_EXTRA
  8885. #if !defined(HAVE_FIPS) || \
  8886. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8887. temp = *inOutIdx;
  8888. #endif
  8889. #endif
  8890. /* Assume input started after 1.2.840.113549.1.3.1 dhKeyAgreement */
  8891. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  8892. ret = ASN_DH_KEY_E;
  8893. }
  8894. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8895. mp_clear(&key->p);
  8896. ret = ASN_DH_KEY_E;
  8897. }
  8898. #ifdef WOLFSSL_DH_EXTRA
  8899. #if !defined(HAVE_FIPS) || \
  8900. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8901. /* If ASN_DH_KEY_E: Check if input started at beginning of key */
  8902. if (ret == ASN_DH_KEY_E) {
  8903. *inOutIdx = temp;
  8904. /* the version (0) - private only (for public skip) */
  8905. if (GetASNInt(input, inOutIdx, &length, inSz) == 0) {
  8906. *inOutIdx += (word32)length;
  8907. }
  8908. /* Size of dhKeyAgreement section */
  8909. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8910. return ASN_PARSE_E;
  8911. /* Check for dhKeyAgreement */
  8912. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  8913. if (oid != DHk || ret < 0)
  8914. return ASN_DH_KEY_E;
  8915. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8916. return ASN_PARSE_E;
  8917. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  8918. return ASN_DH_KEY_E;
  8919. }
  8920. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8921. mp_clear(&key->p);
  8922. return ASN_DH_KEY_E;
  8923. }
  8924. }
  8925. temp = *inOutIdx;
  8926. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  8927. if (ret > 0) {
  8928. /* Found Bit String */
  8929. if (GetInt(&key->pub, input, inOutIdx, inSz) == 0) {
  8930. WOLFSSL_MSG("Found Public Key");
  8931. ret = 0;
  8932. }
  8933. } else {
  8934. *inOutIdx = temp;
  8935. ret = (GetOctetString(input, inOutIdx, &length, inSz) >= 0);
  8936. if (ret > 0) {
  8937. /* Found Octet String */
  8938. if (GetInt(&key->priv, input, inOutIdx, inSz) == 0) {
  8939. WOLFSSL_MSG("Found Private Key");
  8940. /* Compute public */
  8941. ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
  8942. }
  8943. } else {
  8944. /* Don't use length from failed CheckBitString/GetOctetString */
  8945. *inOutIdx = temp;
  8946. ret = 0;
  8947. }
  8948. }
  8949. #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
  8950. #endif /* WOLFSSL_DH_EXTRA */
  8951. WOLFSSL_LEAVE("wc_DhKeyDecode", ret);
  8952. return ret;
  8953. #else
  8954. #ifdef WOLFSSL_DH_EXTRA
  8955. DECL_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length);
  8956. #else
  8957. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  8958. #endif
  8959. int ret = 0;
  8960. /* Check input parameters are valid. */
  8961. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  8962. ret = BAD_FUNC_ARG;
  8963. }
  8964. #ifdef WOLFSSL_DH_EXTRA
  8965. ALLOC_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length, ret, key->heap);
  8966. #else
  8967. ALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, key->heap);
  8968. #endif
  8969. if (ret == 0) {
  8970. /* Initialize data and set mp_ints to hold p and g. */
  8971. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhParamASN_Length);
  8972. GetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
  8973. GetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
  8974. /* Try simple PKCS #3 template. */
  8975. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  8976. inOutIdx, inSz);
  8977. #ifdef WOLFSSL_DH_EXTRA
  8978. if (ret != 0) {
  8979. mp_free(&key->p);
  8980. mp_free(&key->g);
  8981. /* Initialize data and set mp_ints to hold p, g, q, priv and pub. */
  8982. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhKeyPkcs8ASN_Length);
  8983. GetASN_ExpBuffer(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID],
  8984. keyDhOid, sizeof(keyDhOid));
  8985. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
  8986. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
  8987. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q], &key->q);
  8988. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
  8989. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
  8990. /* Try PKCS #8 wrapped template. */
  8991. ret = GetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, 1,
  8992. input, inOutIdx, inSz);
  8993. if (ret == 0) {
  8994. /* VERSION only present in PKCS #8 private key structure */
  8995. if ((dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].length != 0) &&
  8996. (dataASN[DHKEYPKCS8ASN_IDX_VER].length == 0)) {
  8997. ret = ASN_PARSE_E;
  8998. }
  8999. else if ((dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].length != 0) &&
  9000. (dataASN[DHKEYPKCS8ASN_IDX_VER].length != 0)) {
  9001. ret = ASN_PARSE_E;
  9002. }
  9003. }
  9004. if ((ret == 0) && mp_iszero(&key->pub)) {
  9005. ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
  9006. }
  9007. }
  9008. #endif
  9009. }
  9010. FREE_ASNGETDATA(dataASN, key->heap);
  9011. return ret;
  9012. #endif /* WOLFSSL_ASN_TEMPLATE */
  9013. }
  9014. #ifdef WOLFSSL_DH_EXTRA
  9015. /* Export DH Key (private or public) */
  9016. int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv)
  9017. {
  9018. #ifndef WOLFSSL_ASN_TEMPLATE
  9019. int ret, privSz = 0, pubSz = 0;
  9020. word32 keySz, idx, len, total;
  9021. if (key == NULL || outSz == NULL) {
  9022. return BAD_FUNC_ARG;
  9023. }
  9024. /* determine size */
  9025. if (exportPriv) {
  9026. /* octet string: priv */
  9027. privSz = SetASNIntMP(&key->priv, -1, NULL);
  9028. if (privSz < 0)
  9029. return privSz;
  9030. idx = 1 + SetLength((word32)privSz, NULL) +
  9031. (word32)privSz; /* +1 for ASN_OCTET_STRING */
  9032. }
  9033. else {
  9034. /* bit string: public */
  9035. pubSz = SetASNIntMP(&key->pub, -1, NULL);
  9036. if (pubSz < 0)
  9037. return pubSz;
  9038. idx = SetBitString((word32)pubSz, 0, NULL) + (word32)pubSz;
  9039. }
  9040. keySz = idx;
  9041. /* DH Parameters sequence with P and G */
  9042. total = 0;
  9043. ret = wc_DhParamsToDer(key, NULL, &total);
  9044. if (ret != LENGTH_ONLY_E)
  9045. return ret;
  9046. idx += total;
  9047. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  9048. idx += (word32)SetObjectId(sizeof(keyDhOid), NULL);
  9049. idx += (word32)sizeof(keyDhOid);
  9050. len = idx - keySz;
  9051. /* sequence - all but pub/priv */
  9052. idx += SetSequence(len, NULL);
  9053. if (exportPriv) {
  9054. /* version: 0 (ASN_INTEGER, 0x01, 0x00) */
  9055. idx += 3;
  9056. }
  9057. /* sequence */
  9058. total = idx + SetSequence(idx, NULL);
  9059. /* if no output, then just getting size */
  9060. if (output == NULL) {
  9061. *outSz = total;
  9062. return LENGTH_ONLY_E;
  9063. }
  9064. /* make sure output fits in buffer */
  9065. if (total > *outSz) {
  9066. return BUFFER_E;
  9067. }
  9068. total = idx;
  9069. /* sequence */
  9070. idx = SetSequence(total, output);
  9071. if (exportPriv) {
  9072. /* version: 0 */
  9073. idx += (word32)SetMyVersion(0, output + idx, 0);
  9074. }
  9075. /* sequence - all but pub/priv */
  9076. idx += SetSequence(len, output + idx);
  9077. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  9078. idx += (word32)SetObjectId(sizeof(keyDhOid), output + idx);
  9079. XMEMCPY(output + idx, keyDhOid, sizeof(keyDhOid));
  9080. idx += sizeof(keyDhOid);
  9081. /* DH Parameters sequence with P and G */
  9082. total = *outSz - idx;
  9083. ret = wc_DhParamsToDer(key, output + idx, &total);
  9084. if (ret < 0)
  9085. return ret;
  9086. idx += total;
  9087. /* octet string: priv */
  9088. if (exportPriv) {
  9089. idx += (word32)SetOctetString((word32)privSz, output + idx);
  9090. idx += (word32)SetASNIntMP(&key->priv, -1, output + idx);
  9091. }
  9092. else {
  9093. /* bit string: public */
  9094. idx += (word32)SetBitString((word32)pubSz, 0, output + idx);
  9095. idx += (word32)SetASNIntMP(&key->pub, -1, output + idx);
  9096. }
  9097. *outSz = idx;
  9098. return (int)idx;
  9099. #else
  9100. ASNSetData dataASN[dhKeyPkcs8ASN_Length];
  9101. int ret = 0;
  9102. int sz;
  9103. WOLFSSL_ENTER("wc_DhKeyToDer");
  9104. XMEMSET(dataASN, 0, sizeof(dataASN));
  9105. SetASN_Int8Bit(&dataASN[DHKEYPKCS8ASN_IDX_VER], 0);
  9106. SetASN_OID(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID], DHk, oidKeyType);
  9107. /* Set mp_int containing p and g. */
  9108. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
  9109. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
  9110. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q].noOut = 1;
  9111. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J].noOut = 1;
  9112. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID].noOut = 1;
  9113. if (exportPriv) {
  9114. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
  9115. dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_STR].noOut = 1;
  9116. dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].noOut = 1;
  9117. }
  9118. else {
  9119. dataASN[DHKEYPKCS8ASN_IDX_VER].noOut = 1;
  9120. dataASN[DHKEYPKCS8ASN_IDX_PKEY_STR].noOut = 1;
  9121. dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].noOut = 1;
  9122. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
  9123. }
  9124. /* Calculate the size of the DH parameters. */
  9125. ret = SizeASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, &sz);
  9126. if (output == NULL) {
  9127. *outSz = (word32)sz;
  9128. ret = LENGTH_ONLY_E;
  9129. }
  9130. /* Check buffer is big enough for encoding. */
  9131. if ((ret == 0) && ((int)*outSz < sz)) {
  9132. ret = BUFFER_E;
  9133. }
  9134. if (ret == 0) {
  9135. /* Encode the DH parameters into buffer. */
  9136. SetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, output);
  9137. /* Set the actual encoding size. */
  9138. *outSz = (word32)sz;
  9139. /* Return the actual encoding size. */
  9140. ret = sz;
  9141. }
  9142. return ret;
  9143. #endif
  9144. }
  9145. int wc_DhPubKeyToDer(DhKey* key, byte* out, word32* outSz)
  9146. {
  9147. return wc_DhKeyToDer(key, out, outSz, 0);
  9148. }
  9149. int wc_DhPrivKeyToDer(DhKey* key, byte* out, word32* outSz)
  9150. {
  9151. return wc_DhKeyToDer(key, out, outSz, 1);
  9152. }
  9153. /* Convert DH key parameters to DER format, write to output (outSz)
  9154. * If output is NULL then max expected size is set to outSz and LENGTH_ONLY_E is
  9155. * returned.
  9156. *
  9157. * Note : static function due to redefinition complications with DhKey and FIPS
  9158. * version 2 build.
  9159. *
  9160. * return bytes written on success */
  9161. int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz)
  9162. {
  9163. #ifndef WOLFSSL_ASN_TEMPLATE
  9164. int ret;
  9165. word32 idx, total;
  9166. if (key == NULL || outSz == NULL) {
  9167. return BAD_FUNC_ARG;
  9168. }
  9169. /* determine size */
  9170. /* integer - g */
  9171. ret = SetASNIntMP(&key->g, -1, NULL);
  9172. if (ret < 0)
  9173. return ret;
  9174. idx = (word32)ret;
  9175. /* integer - p */
  9176. ret = SetASNIntMP(&key->p, -1, NULL);
  9177. if (ret < 0)
  9178. return ret;
  9179. idx += (word32)ret;
  9180. total = idx;
  9181. /* sequence */
  9182. idx += SetSequence(idx, NULL);
  9183. if (output == NULL) {
  9184. *outSz = idx;
  9185. return LENGTH_ONLY_E;
  9186. }
  9187. /* make sure output fits in buffer */
  9188. if (idx > *outSz) {
  9189. return BUFFER_E;
  9190. }
  9191. /* write DH parameters */
  9192. /* sequence - for P and G only */
  9193. idx = SetSequence(total, output);
  9194. /* integer - p */
  9195. ret = SetASNIntMP(&key->p, -1, output + idx);
  9196. if (ret < 0)
  9197. return ret;
  9198. idx += (word32)ret;
  9199. /* integer - g */
  9200. ret = SetASNIntMP(&key->g, -1, output + idx);
  9201. if (ret < 0)
  9202. return ret;
  9203. idx += (word32)ret;
  9204. *outSz = idx;
  9205. return (int)idx;
  9206. #else
  9207. ASNSetData dataASN[dhParamASN_Length];
  9208. int ret = 0;
  9209. int sz = 0;
  9210. WOLFSSL_ENTER("wc_DhParamsToDer");
  9211. if (key == NULL || outSz == NULL) {
  9212. ret = BAD_FUNC_ARG;
  9213. }
  9214. if (ret == 0) {
  9215. XMEMSET(dataASN, 0, sizeof(dataASN));
  9216. /* Set mp_int containing p and g. */
  9217. SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
  9218. SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
  9219. /* privateValueLength not encoded. */
  9220. dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
  9221. /* Calculate the size of the DH parameters. */
  9222. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  9223. }
  9224. if ((ret == 0) && (output == NULL)) {
  9225. *outSz = (word32)sz;
  9226. ret = LENGTH_ONLY_E;
  9227. }
  9228. /* Check buffer is big enough for encoding. */
  9229. if ((ret == 0) && (*outSz < (word32)sz)) {
  9230. ret = BUFFER_E;
  9231. }
  9232. if (ret == 0) {
  9233. /* Encode the DH parameters into buffer. */
  9234. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, output);
  9235. /* Set the actual encoding size. */
  9236. *outSz = (word32)sz;
  9237. /* Return count of bytes written. */
  9238. ret = sz;
  9239. }
  9240. return ret;
  9241. #endif
  9242. }
  9243. #endif /* WOLFSSL_DH_EXTRA */
  9244. /* Decode DH parameters.
  9245. *
  9246. * PKCS #3, 9 - DHParameter.
  9247. * (Also in: RFC 2786, 3)
  9248. *
  9249. * @param [in] input Buffer holding BER encoded data.
  9250. * @param [in, out] inOutIdx On in, start of RSA public key.
  9251. * On out, start of ASN.1 item after RSA public key.
  9252. * @param [in] inSz Number of bytes in buffer.
  9253. * @param [in, out] p Buffer to hold prime.
  9254. * @param [out] pInOutSz On in, size of buffer to hold prime in bytes.
  9255. * On out, size of prime in bytes.
  9256. * @param [in, out] g Buffer to hold base.
  9257. * @param [out] gInOutSz On in, size of buffer to hold base in bytes.
  9258. * On out, size of base in bytes.
  9259. * @return 0 on success.
  9260. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9261. * is invalid.
  9262. * @return BUFFER_E when data in buffer is too small.
  9263. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  9264. */
  9265. int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
  9266. byte* g, word32* gInOutSz)
  9267. {
  9268. #ifndef WOLFSSL_ASN_TEMPLATE
  9269. word32 idx = 0;
  9270. int ret;
  9271. int length;
  9272. if (GetSequence(input, &idx, &length, inSz) <= 0)
  9273. return ASN_PARSE_E;
  9274. ret = GetASNInt(input, &idx, &length, inSz);
  9275. if (ret != 0)
  9276. return ret;
  9277. if (length <= (int)*pInOutSz) {
  9278. XMEMCPY(p, &input[idx], (size_t)length);
  9279. *pInOutSz = (word32)length;
  9280. }
  9281. else {
  9282. return BUFFER_E;
  9283. }
  9284. idx += (word32)length;
  9285. ret = GetASNInt(input, &idx, &length, inSz);
  9286. if (ret != 0)
  9287. return ret;
  9288. if (length <= (int)*gInOutSz) {
  9289. XMEMCPY(g, &input[idx], (size_t)length);
  9290. *gInOutSz = (word32)length;
  9291. }
  9292. else {
  9293. return BUFFER_E;
  9294. }
  9295. return 0;
  9296. #else
  9297. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  9298. word32 idx = 0;
  9299. int ret = 0;
  9300. /* Make sure pointers are valid before use. */
  9301. if ((input == NULL) || (p == NULL) || (pInOutSz == NULL) || (g == NULL) ||
  9302. (gInOutSz == NULL)) {
  9303. ret = BAD_FUNC_ARG;
  9304. }
  9305. CALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, NULL);
  9306. if (ret == 0) {
  9307. /* Set the buffers to copy p and g into. */
  9308. GetASN_Buffer(&dataASN[DHPARAMASN_IDX_PRIME], p, pInOutSz);
  9309. GetASN_Buffer(&dataASN[DHPARAMASN_IDX_BASE], g, gInOutSz);
  9310. /* Decode the DH Parameters. */
  9311. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  9312. &idx, inSz);
  9313. }
  9314. FREE_ASNGETDATA(dataASN, NULL);
  9315. return ret;
  9316. #endif /* WOLFSSL_ASN_TEMPLATE */
  9317. }
  9318. #endif /* !NO_DH */
  9319. #ifndef NO_DSA
  9320. static mp_int* GetDsaInt(DsaKey* key, int idx)
  9321. {
  9322. if (idx == 0)
  9323. return &key->p;
  9324. if (idx == 1)
  9325. return &key->q;
  9326. if (idx == 2)
  9327. return &key->g;
  9328. if (idx == 3)
  9329. return &key->y;
  9330. if (idx == 4)
  9331. return &key->x;
  9332. return NULL;
  9333. }
  9334. #ifdef WOLFSSL_ASN_TEMPLATE
  9335. /* ASN.1 template for DSA public and private keys.
  9336. * Public key: seq, p, q, g, y
  9337. * Private key: seq, version, p, q, g, y, x
  9338. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9339. */
  9340. static const ASNItem dsaKeyASN[] = {
  9341. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9342. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  9343. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  9344. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  9345. /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
  9346. /* Y */ { 1, ASN_INTEGER, 0, 0, 0 },
  9347. /* X */ { 1, ASN_INTEGER, 0, 0, 0 },
  9348. };
  9349. enum {
  9350. DSAKEYASN_IDX_SEQ = 0,
  9351. DSAKEYASN_IDX_VER,
  9352. DSAKEYASN_IDX_P,
  9353. DSAKEYASN_IDX_Q,
  9354. DSAKEYASN_IDX_G,
  9355. DSAKEYASN_IDX_Y,
  9356. DSAKEYASN_IDX_X
  9357. };
  9358. /* Number of items in ASN.1 template for DSA private key. */
  9359. #define dsaKeyASN_Length (sizeof(dsaKeyASN) / sizeof(ASNItem))
  9360. /* Number of items in ASN.1 template for DSA public key. */
  9361. #define dsaPublicKeyASN_Length ((sizeof(dsaKeyASN) / sizeof(ASNItem)) - 2)
  9362. /* ASN.1 template for PublicKeyInfo with DSA.
  9363. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  9364. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9365. */
  9366. static const ASNItem dsaPubKeyASN[] = {
  9367. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9368. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  9369. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  9370. /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  9371. /* p */
  9372. /* ALGOID_PARAMS_P */ { 3, ASN_INTEGER, 0, 0, 0 },
  9373. /* q */
  9374. /* ALGOID_PARAMS_Q */ { 3, ASN_INTEGER, 0, 0, 0 },
  9375. /* g */
  9376. /* ALGOID_PARAMS_G */ { 3, ASN_INTEGER, 0, 0, 0 },
  9377. /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 1 },
  9378. /* y */
  9379. /* PUBKEY_Y */ { 2, ASN_INTEGER, 0, 0, 0 },
  9380. };
  9381. enum {
  9382. DSAPUBKEYASN_IDX_SEQ = 0,
  9383. DSAPUBKEYASN_IDX_ALGOID_SEQ,
  9384. DSAPUBKEYASN_IDX_ALGOID_OID,
  9385. DSAPUBKEYASN_IDX_ALGOID_PARAMS,
  9386. DSAPUBKEYASN_IDX_ALGOID_PARAMS_P,
  9387. DSAPUBKEYASN_IDX_ALGOID_PARAMS_Q,
  9388. DSAPUBKEYASN_IDX_ALGOID_PARAMS_G,
  9389. DSAPUBKEYASN_IDX_PUBKEY_STR,
  9390. DSAPUBKEYASN_IDX_PUBKEY_Y
  9391. };
  9392. /* Number of items in ASN.1 template for PublicKeyInfo with DSA. */
  9393. #define dsaPubKeyASN_Length (sizeof(dsaPubKeyASN) / sizeof(ASNItem))
  9394. #endif /* WOLFSSL_ASN_TEMPLATE */
  9395. /* Decode DSA public key.
  9396. *
  9397. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  9398. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9399. *
  9400. * @param [in] input Buffer holding BER encoded data.
  9401. * @param [in, out] inOutIdx On in, start of DSA public key.
  9402. * On out, start of ASN.1 item after DSA public key.
  9403. * @param [in, out] key DSA key object.
  9404. * @param [in] inSz Number of bytes in buffer.
  9405. * @return 0 on success.
  9406. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9407. * is invalid.
  9408. * @return BUFFER_E when data in buffer is too small.
  9409. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  9410. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  9411. * non-zero length.
  9412. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  9413. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  9414. */
  9415. int wc_DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9416. word32 inSz)
  9417. {
  9418. #ifndef WOLFSSL_ASN_TEMPLATE
  9419. int length;
  9420. int ret = 0;
  9421. word32 oid;
  9422. word32 maxIdx;
  9423. if (input == NULL || inOutIdx == NULL || key == NULL)
  9424. return BAD_FUNC_ARG;
  9425. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9426. return ASN_PARSE_E;
  9427. maxIdx = (word32)(*inOutIdx + (word32)length);
  9428. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  9429. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  9430. GetInt(&key->g, input, inOutIdx, maxIdx) < 0 ||
  9431. GetInt(&key->y, input, inOutIdx, maxIdx) < 0 )
  9432. ret = ASN_DH_KEY_E;
  9433. if (ret != 0) {
  9434. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9435. return ASN_PARSE_E;
  9436. ret = GetObjectId(input, inOutIdx, &oid, oidIgnoreType, inSz);
  9437. if (ret != 0)
  9438. return ret;
  9439. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9440. return ASN_PARSE_E;
  9441. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  9442. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  9443. GetInt(&key->g, input, inOutIdx, inSz) < 0)
  9444. return ASN_DH_KEY_E;
  9445. if (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) < 0)
  9446. return ASN_PARSE_E;
  9447. if (GetInt(&key->y, input, inOutIdx, inSz) < 0 )
  9448. return ASN_DH_KEY_E;
  9449. ret = 0;
  9450. }
  9451. key->type = DSA_PUBLIC;
  9452. return ret;
  9453. #else
  9454. /* dsaPubKeyASN is longer than dsaPublicKeyASN. */
  9455. DECL_ASNGETDATA(dataASN, dsaPubKeyASN_Length);
  9456. int ret = 0;
  9457. /* Validated parameters. */
  9458. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  9459. ret = BAD_FUNC_ARG;
  9460. }
  9461. ALLOC_ASNGETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  9462. if (ret == 0) {
  9463. int i;
  9464. /* Clear dynamic data items. */
  9465. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPublicKeyASN_Length);
  9466. /* seq
  9467. * p, q, g, y
  9468. * Start DSA ints from DSAKEYASN_IDX_VER instead of DSAKEYASN_IDX_P */
  9469. for (i = 0; i < DSA_INTS - 1; i++)
  9470. GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i], GetDsaInt(key, i));
  9471. /* Parse as simple form. */
  9472. ret = GetASN_Items(dsaKeyASN, dataASN, dsaPublicKeyASN_Length, 0, input,
  9473. inOutIdx, inSz);
  9474. if (ret != 0) {
  9475. /* Clear dynamic data items. */
  9476. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPubKeyASN_Length);
  9477. /* Set DSA OID to expect. */
  9478. GetASN_ExpBuffer(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID],
  9479. keyDsaOid, sizeof(keyDsaOid));
  9480. /* p, q, g */
  9481. for (i = 0; i < DSA_INTS - 2; i++)
  9482. GetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
  9483. GetDsaInt(key, i));
  9484. /* y */
  9485. GetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
  9486. /* Parse as SubjectPublicKeyInfo. */
  9487. ret = GetASN_Items(dsaPubKeyASN, dataASN, dsaPubKeyASN_Length, 1,
  9488. input, inOutIdx, inSz);
  9489. }
  9490. }
  9491. if (ret == 0) {
  9492. /* Data parsed - set type of key parsed. */
  9493. key->type = DSA_PUBLIC;
  9494. }
  9495. FREE_ASNGETDATA(dataASN, key->heap);
  9496. return ret;
  9497. #endif
  9498. }
  9499. int wc_DsaParamsDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9500. word32 inSz)
  9501. {
  9502. int length;
  9503. word32 maxIdx;
  9504. if (input == NULL || inOutIdx == NULL || key == NULL)
  9505. return BAD_FUNC_ARG;
  9506. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9507. return ASN_PARSE_E;
  9508. maxIdx = (word32)(*inOutIdx + (word32)length);
  9509. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  9510. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  9511. GetInt(&key->g, input, inOutIdx, maxIdx) < 0)
  9512. return ASN_DH_KEY_E;
  9513. return 0;
  9514. }
  9515. #ifdef WOLFSSL_ASN_TEMPLATE
  9516. /* ASN.1 template for a DSA key holding private key in an OCTET_STRING. */
  9517. static const ASNItem dsaKeyOctASN[] = {
  9518. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9519. /* p */
  9520. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  9521. /* q */
  9522. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  9523. /* g */
  9524. /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
  9525. /* Private key */
  9526. /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  9527. /* x */
  9528. /* X */ { 2, ASN_INTEGER, 0, 0, 0 },
  9529. };
  9530. enum {
  9531. DSAKEYOCTASN_IDX_SEQ = 0,
  9532. DSAKEYOCTASN_IDX_P,
  9533. DSAKEYOCTASN_IDX_Q,
  9534. DSAKEYOCTASN_IDX_G,
  9535. DSAKEYOCTASN_IDX_PKEY_STR,
  9536. DSAKEYOCTASN_IDX_X
  9537. };
  9538. /* Number of items in ASN.1 template for a DSA key (OCTET_STRING version). */
  9539. #define dsaKeyOctASN_Length (sizeof(dsaKeyOctASN) / sizeof(ASNItem))
  9540. #endif
  9541. /* Decode DSA private key.
  9542. *
  9543. * @param [in] input Buffer holding BER encoded data.
  9544. * @param [in, out] inOutIdx On in, start of DSA public key.
  9545. * On out, start of ASN.1 item after DSA public key.
  9546. * @param [in, out] key DSA key object.
  9547. * @param [in] inSz Number of bytes in buffer.
  9548. * @return 0 on success.
  9549. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9550. * is invalid.
  9551. * @return BUFFER_E when data in buffer is too small.
  9552. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  9553. * non-zero length.
  9554. */
  9555. int wc_DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9556. word32 inSz)
  9557. {
  9558. #ifndef WOLFSSL_ASN_TEMPLATE
  9559. int length, version, ret = 0, temp = 0;
  9560. word32 algId = 0;
  9561. /* Sanity checks on input */
  9562. if (input == NULL || inOutIdx == NULL || key == NULL) {
  9563. return BAD_FUNC_ARG;
  9564. }
  9565. /* if has pkcs8 header skip it */
  9566. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  9567. /* ignore error, did not have pkcs8 header */
  9568. }
  9569. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9570. return ASN_PARSE_E;
  9571. temp = (int)*inOutIdx;
  9572. /* Default case expects a certificate with OctetString but no version ID */
  9573. ret = GetInt(&key->p, input, inOutIdx, inSz);
  9574. if (ret < 0) {
  9575. mp_clear(&key->p);
  9576. ret = ASN_PARSE_E;
  9577. }
  9578. else {
  9579. ret = GetInt(&key->q, input, inOutIdx, inSz);
  9580. if (ret < 0) {
  9581. mp_clear(&key->p);
  9582. mp_clear(&key->q);
  9583. ret = ASN_PARSE_E;
  9584. }
  9585. else {
  9586. ret = GetInt(&key->g, input, inOutIdx, inSz);
  9587. if (ret < 0) {
  9588. mp_clear(&key->p);
  9589. mp_clear(&key->q);
  9590. mp_clear(&key->g);
  9591. ret = ASN_PARSE_E;
  9592. }
  9593. else {
  9594. ret = GetOctetString(input, inOutIdx, &length, inSz);
  9595. if (ret < 0) {
  9596. mp_clear(&key->p);
  9597. mp_clear(&key->q);
  9598. mp_clear(&key->g);
  9599. ret = ASN_PARSE_E;
  9600. }
  9601. else {
  9602. ret = GetInt(&key->y, input, inOutIdx, inSz);
  9603. if (ret < 0) {
  9604. mp_clear(&key->p);
  9605. mp_clear(&key->q);
  9606. mp_clear(&key->g);
  9607. mp_clear(&key->y);
  9608. ret = ASN_PARSE_E;
  9609. }
  9610. }
  9611. }
  9612. }
  9613. }
  9614. /* An alternate pass if default certificate fails parsing */
  9615. if (ret == ASN_PARSE_E) {
  9616. *inOutIdx = (word32)temp;
  9617. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  9618. return ASN_PARSE_E;
  9619. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  9620. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  9621. GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
  9622. GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
  9623. GetInt(&key->x, input, inOutIdx, inSz) < 0 )
  9624. return ASN_DH_KEY_E;
  9625. }
  9626. key->type = DSA_PRIVATE;
  9627. return 0;
  9628. #else
  9629. /* dsaKeyASN is longer than dsaKeyOctASN. */
  9630. DECL_ASNGETDATA(dataASN, dsaKeyASN_Length);
  9631. int ret = 0;
  9632. byte version = 0;
  9633. /* Sanity checks on input */
  9634. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  9635. ret = BAD_FUNC_ARG;
  9636. }
  9637. CALLOC_ASNGETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  9638. if (ret == 0) {
  9639. int i;
  9640. /* Try dsaKeyOctASN */
  9641. /* Initialize key data and set mp_ints for params */
  9642. for (i = 0; i < DSA_INTS - 2; i++) {
  9643. GetASN_MP(&dataASN[(int)DSAKEYOCTASN_IDX_P + i], GetDsaInt(key, i));
  9644. }
  9645. /* and priv */
  9646. GetASN_MP(&dataASN[DSAKEYOCTASN_IDX_X], GetDsaInt(key, i));
  9647. /* Try simple form. */
  9648. ret = GetASN_Items(dsaKeyOctASN, dataASN, dsaKeyOctASN_Length, 1, input,
  9649. inOutIdx, inSz);
  9650. if (ret != 0) {
  9651. /* Try dsaKeyASN */
  9652. XMEMSET(dataASN, 0, sizeof(*dataASN) * dsaKeyASN_Length);
  9653. GetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], &version);
  9654. for (i = 0; i < DSA_INTS; i++) {
  9655. mp_int* n = GetDsaInt(key, i);
  9656. mp_clear(n);
  9657. GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], n);
  9658. }
  9659. /* Try simple OCTET_STRING form. */
  9660. ret = GetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, 1, input,
  9661. inOutIdx, inSz);
  9662. }
  9663. }
  9664. if (ret == 0) {
  9665. /* Set the contents to be a private key. */
  9666. key->type = DSA_PRIVATE;
  9667. }
  9668. FREE_ASNGETDATA(dataASN, key->heap);
  9669. return ret;
  9670. #endif
  9671. }
  9672. #ifndef WOLFSSL_ASN_TEMPLATE
  9673. /* Release Tmp DSA resources */
  9674. static WC_INLINE void FreeTmpDsas(byte** tmps, void* heap, int ints)
  9675. {
  9676. int i;
  9677. for (i = 0; i < ints; i++)
  9678. XFREE(tmps[i], heap, DYNAMIC_TYPE_DSA);
  9679. (void)heap;
  9680. }
  9681. #endif /* !WOLFSSL_ASN_TEMPLATE */
  9682. #if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \
  9683. defined(WOLFSSL_CERT_GEN))
  9684. /* Encode a DSA public key into buffer.
  9685. *
  9686. * @param [out] output Buffer to hold encoded data.
  9687. * @param [in] key DSA key object.
  9688. * @param [out] outLen Length of buffer.
  9689. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  9690. * @return Size of encoded data in bytes on success.
  9691. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  9692. * than a minimal size (5 bytes), or buffer size is smaller than
  9693. * encoding size.
  9694. * @return MEMORY_E when dynamic memory allocation fails.
  9695. */
  9696. int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header)
  9697. {
  9698. #ifndef WOLFSSL_ASN_TEMPLATE
  9699. /* p, g, q = DSA params, y = public exponent */
  9700. #ifdef WOLFSSL_SMALL_STACK
  9701. byte* p = NULL;
  9702. byte* g = NULL;
  9703. byte* q = NULL;
  9704. byte* y = NULL;
  9705. #else
  9706. byte p[MAX_DSA_INT_SZ];
  9707. byte g[MAX_DSA_INT_SZ];
  9708. byte q[MAX_DSA_INT_SZ];
  9709. byte y[MAX_DSA_INT_SZ];
  9710. #endif
  9711. byte innerSeq[MAX_SEQ_SZ];
  9712. byte outerSeq[MAX_SEQ_SZ];
  9713. byte bitString[1 + MAX_LENGTH_SZ + 1];
  9714. int pSz, gSz, qSz, ySz;
  9715. word32 idx, innerSeqSz, outerSeqSz, bitStringSz = 0;
  9716. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  9717. if (output == NULL || key == NULL || outLen < MAX_SEQ_SZ) {
  9718. return BAD_FUNC_ARG;
  9719. }
  9720. /* p */
  9721. #ifdef WOLFSSL_SMALL_STACK
  9722. p = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9723. if (p == NULL)
  9724. return MEMORY_E;
  9725. #endif
  9726. if ((pSz = SetASNIntMP(&key->p, MAX_DSA_INT_SZ, p)) < 0) {
  9727. WOLFSSL_MSG("SetASNIntMP Error with p");
  9728. #ifdef WOLFSSL_SMALL_STACK
  9729. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9730. #endif
  9731. return pSz;
  9732. }
  9733. /* q */
  9734. #ifdef WOLFSSL_SMALL_STACK
  9735. q = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9736. if (q == NULL)
  9737. return MEMORY_E;
  9738. #endif
  9739. if ((qSz = SetASNIntMP(&key->q, MAX_DSA_INT_SZ, q)) < 0) {
  9740. WOLFSSL_MSG("SetASNIntMP Error with q");
  9741. #ifdef WOLFSSL_SMALL_STACK
  9742. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9743. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9744. #endif
  9745. return qSz;
  9746. }
  9747. /* g */
  9748. #ifdef WOLFSSL_SMALL_STACK
  9749. g = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9750. if (g == NULL)
  9751. return MEMORY_E;
  9752. #endif
  9753. if ((gSz = SetASNIntMP(&key->g, MAX_DSA_INT_SZ, g)) < 0) {
  9754. WOLFSSL_MSG("SetASNIntMP Error with g");
  9755. #ifdef WOLFSSL_SMALL_STACK
  9756. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9757. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9758. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9759. #endif
  9760. return gSz;
  9761. }
  9762. /* y */
  9763. #ifdef WOLFSSL_SMALL_STACK
  9764. y = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9765. if (y == NULL)
  9766. return MEMORY_E;
  9767. #endif
  9768. if ((ySz = SetASNIntMP(&key->y, MAX_DSA_INT_SZ, y)) < 0) {
  9769. WOLFSSL_MSG("SetASNIntMP Error with y");
  9770. #ifdef WOLFSSL_SMALL_STACK
  9771. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9772. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9773. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9774. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9775. #endif
  9776. return ySz;
  9777. }
  9778. if (with_header) {
  9779. word32 algoSz;
  9780. #ifdef WOLFSSL_SMALL_STACK
  9781. byte* algo = NULL;
  9782. algo = (byte*)XMALLOC(MAX_ALGO_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9783. if (algo == NULL) {
  9784. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9785. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9786. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9787. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9788. return MEMORY_E;
  9789. }
  9790. #else
  9791. byte algo[MAX_ALGO_SZ];
  9792. #endif
  9793. innerSeqSz = SetSequence((word32)(pSz + qSz + gSz), innerSeq);
  9794. algoSz = SetAlgoID(DSAk, algo, oidKeyType, 0);
  9795. bitStringSz = SetBitString((word32)ySz, 0, bitString);
  9796. outerSeqSz = SetSequence(algoSz + innerSeqSz +
  9797. (word32)(pSz + qSz + gSz), outerSeq);
  9798. idx = SetSequence(algoSz + innerSeqSz + (word32)(pSz + qSz + gSz) +
  9799. bitStringSz + (word32)ySz + outerSeqSz, output);
  9800. /* check output size */
  9801. if ((idx + algoSz + bitStringSz + innerSeqSz +
  9802. (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen)
  9803. {
  9804. #ifdef WOLFSSL_SMALL_STACK
  9805. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9806. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9807. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9808. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9809. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9810. #endif
  9811. WOLFSSL_MSG("Error, output size smaller than outlen");
  9812. return BUFFER_E;
  9813. }
  9814. /* outerSeq */
  9815. XMEMCPY(output + idx, outerSeq, outerSeqSz);
  9816. idx += outerSeqSz;
  9817. /* algo */
  9818. XMEMCPY(output + idx, algo, algoSz);
  9819. idx += algoSz;
  9820. #ifdef WOLFSSL_SMALL_STACK
  9821. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9822. #endif
  9823. } else {
  9824. innerSeqSz = SetSequence((word32)(pSz + qSz + gSz + ySz), innerSeq);
  9825. /* check output size */
  9826. if ((innerSeqSz + (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen) {
  9827. #ifdef WOLFSSL_SMALL_STACK
  9828. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9829. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9830. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9831. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9832. #endif
  9833. WOLFSSL_MSG("Error, output size smaller than outlen");
  9834. return BUFFER_E;
  9835. }
  9836. idx = 0;
  9837. }
  9838. /* innerSeq */
  9839. XMEMCPY(output + idx, innerSeq, innerSeqSz);
  9840. idx += innerSeqSz;
  9841. /* p */
  9842. XMEMCPY(output + idx, p, (size_t)pSz);
  9843. idx += (word32)pSz;
  9844. /* q */
  9845. XMEMCPY(output + idx, q, (size_t)qSz);
  9846. idx += (word32)qSz;
  9847. /* g */
  9848. XMEMCPY(output + idx, g, (size_t)gSz);
  9849. idx += (word32)gSz;
  9850. /* bit string */
  9851. if (bitStringSz > 0) {
  9852. XMEMCPY(output + idx, bitString, bitStringSz);
  9853. idx += bitStringSz;
  9854. }
  9855. /* y */
  9856. XMEMCPY(output + idx, y, (size_t)ySz);
  9857. idx += (word32)ySz;
  9858. #ifdef WOLFSSL_SMALL_STACK
  9859. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9860. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9861. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9862. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9863. #endif
  9864. return (int)idx;
  9865. #else
  9866. DECL_ASNSETDATA(dataASN, dsaPubKeyASN_Length);
  9867. int ret = 0;
  9868. int i;
  9869. int sz = 0;
  9870. const ASNItem *data = NULL;
  9871. int count = 0;
  9872. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  9873. if ((output == NULL) || (key == NULL) || (outLen < MAX_SEQ_SZ)) {
  9874. ret = BAD_FUNC_ARG;
  9875. }
  9876. CALLOC_ASNSETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  9877. if (ret == 0) {
  9878. if (with_header) {
  9879. /* Using dsaPubKeyASN */
  9880. data = dsaPubKeyASN;
  9881. count = dsaPubKeyASN_Length;
  9882. /* Set the algorithm OID to write out. */
  9883. SetASN_OID(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID], DSAk, oidKeyType);
  9884. /* Set the mp_ints to encode - parameters and public value. */
  9885. for (i = 0; i < DSA_INTS - 2; i++) {
  9886. SetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
  9887. GetDsaInt(key, i));
  9888. }
  9889. SetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
  9890. }
  9891. else {
  9892. /* Using dsaKeyASN */
  9893. data = dsaKeyASN;
  9894. count = dsaPublicKeyASN_Length;
  9895. /* Set the mp_ints to encode - parameters and public value. */
  9896. for (i = 0; i < DSA_INTS - 1; i++) {
  9897. /* Move all DSA ints up one slot (ignore VERSION so now
  9898. * it means P) */
  9899. SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i],
  9900. GetDsaInt(key, i));
  9901. }
  9902. }
  9903. ret = SizeASN_Items(data, dataASN, count, &sz);
  9904. }
  9905. /* Check buffer is big enough for encoding. */
  9906. if ((ret == 0) && (sz > (int)outLen)) {
  9907. ret = BAD_FUNC_ARG;
  9908. }
  9909. /* Encode the DSA public key into output buffer. */
  9910. if (ret == 0) {
  9911. ret = SetASN_Items(data, dataASN, count, output);
  9912. }
  9913. FREE_ASNSETDATA(dataASN, key->heap);
  9914. return ret;
  9915. #endif /* WOLFSSL_ASN_TEMPLATE */
  9916. }
  9917. /* Encode a DSA public key into buffer.
  9918. *
  9919. * @param [out] output Buffer to hold encoded data.
  9920. * @param [in] key DSA key object.
  9921. * @param [out] outLen Length of buffer.
  9922. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  9923. * @return Size of encoded data in bytes on success.
  9924. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  9925. * than a minimal size (5 bytes), or buffer size is smaller than
  9926. * encoding size.
  9927. * @return MEMORY_E when dynamic memory allocation fails.
  9928. */
  9929. int wc_DsaKeyToPublicDer(DsaKey* key, byte* output, word32 inLen)
  9930. {
  9931. return wc_SetDsaPublicKey(output, key, (int)inLen, 1);
  9932. }
  9933. #endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */
  9934. static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen,
  9935. int ints, int includeVersion)
  9936. {
  9937. #ifndef WOLFSSL_ASN_TEMPLATE
  9938. word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen, j;
  9939. word32 sizes[DSA_INTS];
  9940. int i, ret = 0;
  9941. byte seq[MAX_SEQ_SZ];
  9942. byte ver[MAX_VERSION_SZ];
  9943. byte* tmps[DSA_INTS];
  9944. if (ints > DSA_INTS || inLen == NULL)
  9945. return BAD_FUNC_ARG;
  9946. XMEMSET(sizes, 0, sizeof(sizes));
  9947. for (i = 0; i < ints; i++)
  9948. tmps[i] = NULL;
  9949. /* write all big ints from key to DER tmps */
  9950. for (i = 0; i < ints; i++) {
  9951. int mpSz;
  9952. mp_int* keyInt = GetDsaInt(key, i);
  9953. word32 rawLen = (word32)mp_unsigned_bin_size(keyInt) + 1;
  9954. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  9955. DYNAMIC_TYPE_DSA);
  9956. if (tmps[i] == NULL) {
  9957. ret = MEMORY_E;
  9958. break;
  9959. }
  9960. mpSz = SetASNIntMP(keyInt, -1, tmps[i]);
  9961. if (mpSz < 0) {
  9962. ret = mpSz;
  9963. break;
  9964. }
  9965. sizes[i] = (word32)mpSz;
  9966. intTotalLen += (word32)mpSz;
  9967. }
  9968. if (ret != 0) {
  9969. FreeTmpDsas(tmps, key->heap, ints);
  9970. return ret;
  9971. }
  9972. /* make headers */
  9973. if (includeVersion)
  9974. verSz = (word32)SetMyVersion(0, ver, FALSE);
  9975. seqSz = SetSequence(verSz + intTotalLen, seq);
  9976. outLen = seqSz + verSz + intTotalLen;
  9977. *inLen = outLen;
  9978. if (output == NULL) {
  9979. FreeTmpDsas(tmps, key->heap, ints);
  9980. return LENGTH_ONLY_E;
  9981. }
  9982. if (outLen > *inLen) {
  9983. FreeTmpDsas(tmps, key->heap, ints);
  9984. return BAD_FUNC_ARG;
  9985. }
  9986. /* write to output */
  9987. XMEMCPY(output, seq, seqSz);
  9988. j = seqSz;
  9989. if (includeVersion) {
  9990. XMEMCPY(output + j, ver, verSz);
  9991. j += verSz;
  9992. }
  9993. for (i = 0; i < ints; i++) {
  9994. XMEMCPY(output + j, tmps[i], sizes[i]);
  9995. j += sizes[i];
  9996. }
  9997. FreeTmpDsas(tmps, key->heap, ints);
  9998. return (int)outLen;
  9999. #else
  10000. DECL_ASNSETDATA(dataASN, dsaKeyASN_Length);
  10001. int ret = 0;
  10002. int sz = 0;
  10003. (void)ints;
  10004. if ((key == NULL) || (inLen == NULL)) {
  10005. ret = BAD_FUNC_ARG;
  10006. }
  10007. if ((ret == 0) && (ints > DSA_INTS)) {
  10008. ret = BAD_FUNC_ARG;
  10009. }
  10010. CALLOC_ASNSETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  10011. if (ret == 0) {
  10012. int i;
  10013. if (includeVersion) {
  10014. /* Set the version. */
  10015. SetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], 0);
  10016. }
  10017. else {
  10018. dataASN[DSAKEYASN_IDX_VER].noOut = 1;
  10019. }
  10020. dataASN[DSAKEYASN_IDX_Y].noOut = mp_iszero(&key->y);
  10021. dataASN[DSAKEYASN_IDX_X].noOut = mp_iszero(&key->x);
  10022. /* Set the mp_ints to encode - params, public and private value. */
  10023. for (i = 0; i < DSA_INTS; i++) {
  10024. if (i < ints)
  10025. SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], GetDsaInt(key, i));
  10026. else
  10027. dataASN[(int)DSAKEYASN_IDX_P + i].noOut = 1;
  10028. }
  10029. /* Calculate size of the encoding. */
  10030. ret = SizeASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, &sz);
  10031. }
  10032. if ((ret == 0) && (output == NULL)) {
  10033. *inLen = (word32)sz;
  10034. ret = LENGTH_ONLY_E;
  10035. }
  10036. /* Check buffer is big enough for encoding. */
  10037. if ((ret == 0) && (sz > (int)*inLen)) {
  10038. ret = BAD_FUNC_ARG;
  10039. }
  10040. if (ret == 0) {
  10041. /* Encode the DSA private key into output buffer. */
  10042. SetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, output);
  10043. /* Return the size of the encoding. */
  10044. ret = sz;
  10045. }
  10046. FREE_ASNSETDATA(dataASN, key->heap);
  10047. return ret;
  10048. #endif /* WOLFSSL_ASN_TEMPLATE */
  10049. }
  10050. /* Encode a DSA private key into buffer.
  10051. *
  10052. * @param [in] key DSA key object.
  10053. * @param [out] output Buffer to hold encoded data.
  10054. * @param [out] inLen Length of buffer.
  10055. * @return Size of encoded data in bytes on success.
  10056. * @return BAD_FUNC_ARG when key or output is NULL, or key is not a private key
  10057. * or, buffer size is smaller than encoding size.
  10058. * @return MEMORY_E when dynamic memory allocation fails.
  10059. */
  10060. int wc_DsaKeyToDer(DsaKey* key, byte* output, word32 inLen)
  10061. {
  10062. if (!key || !output)
  10063. return BAD_FUNC_ARG;
  10064. if (key->type != DSA_PRIVATE)
  10065. return BAD_FUNC_ARG;
  10066. return DsaKeyIntsToDer(key, output, &inLen, DSA_INTS, 1);
  10067. }
  10068. /* Convert DsaKey parameters to DER format, write to output (inLen),
  10069. return bytes written. Version is excluded to be compatible with
  10070. OpenSSL d2i_DSAparams */
  10071. int wc_DsaKeyToParamsDer(DsaKey* key, byte* output, word32 inLen)
  10072. {
  10073. if (!key || !output)
  10074. return BAD_FUNC_ARG;
  10075. return DsaKeyIntsToDer(key, output, &inLen, DSA_PARAM_INTS, 0);
  10076. }
  10077. /* This version of the function allows output to be NULL. In that case, the
  10078. DsaKeyIntsToDer will return LENGTH_ONLY_E and the required output buffer
  10079. size will be pointed to by inLen. */
  10080. int wc_DsaKeyToParamsDer_ex(DsaKey* key, byte* output, word32* inLen)
  10081. {
  10082. if (!key || !inLen)
  10083. return BAD_FUNC_ARG;
  10084. return DsaKeyIntsToDer(key, output, inLen, DSA_PARAM_INTS, 0);
  10085. }
  10086. #endif /* NO_DSA */
  10087. #ifndef NO_CERTS
  10088. /* Initialize decoded certificate object with buffer of DER encoding.
  10089. *
  10090. * @param [in, out] cert Decoded certificate object.
  10091. * @param [in] source Buffer containing DER encoded certificate.
  10092. * @param [in] inSz Size of DER data in buffer in bytes.
  10093. * @param [in] heap Dynamic memory hint.
  10094. */
  10095. void InitDecodedCert(DecodedCert* cert,
  10096. const byte* source, word32 inSz, void* heap)
  10097. {
  10098. InitDecodedCert_ex(cert, source, inSz, heap, INVALID_DEVID);
  10099. }
  10100. /* Initialize decoded certificate object with buffer of DER encoding.
  10101. *
  10102. * @param [in, out] cert Decoded certificate object.
  10103. * @param [in] source Buffer containing DER encoded certificate.
  10104. * @param [in] inSz Size of DER data in buffer in bytes.
  10105. * @param [in] heap Dynamic memory hint.
  10106. * @param [in] devId Crypto callback ID to use.
  10107. */
  10108. void InitDecodedCert_ex(DecodedCert* cert,
  10109. const byte* source, word32 inSz, void* heap, int devId)
  10110. {
  10111. if (cert != NULL) {
  10112. XMEMSET(cert, 0, sizeof(DecodedCert));
  10113. cert->subjectCNEnc = CTC_UTF8;
  10114. cert->issuer[0] = '\0';
  10115. cert->subject[0] = '\0';
  10116. cert->source = source; /* don't own */
  10117. cert->maxIdx = inSz; /* can't go over this index */
  10118. cert->heap = heap;
  10119. cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
  10120. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10121. #ifdef WOLFSSL_CERT_NAME_ALL
  10122. cert->subjectNEnc = CTC_UTF8;
  10123. cert->subjectIEnc = CTC_UTF8;
  10124. cert->subjectDNQEnc = CTC_UTF8;
  10125. cert->subjectGNEnc = CTC_UTF8;
  10126. #endif
  10127. cert->subjectSNEnc = CTC_UTF8;
  10128. cert->subjectCEnc = CTC_PRINTABLE;
  10129. cert->subjectLEnc = CTC_UTF8;
  10130. cert->subjectSTEnc = CTC_UTF8;
  10131. cert->subjectOEnc = CTC_UTF8;
  10132. cert->subjectOUEnc = CTC_UTF8;
  10133. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  10134. cert->issuerSNEnc = CTC_UTF8;
  10135. cert->issuerCEnc = CTC_PRINTABLE;
  10136. cert->issuerLEnc = CTC_UTF8;
  10137. cert->issuerSTEnc = CTC_UTF8;
  10138. cert->issuerOEnc = CTC_UTF8;
  10139. cert->issuerOUEnc = CTC_UTF8;
  10140. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  10141. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  10142. InitSignatureCtx(&cert->sigCtx, heap, devId);
  10143. }
  10144. }
  10145. void wc_InitDecodedCert(DecodedCert* cert, const byte* source, word32 inSz,
  10146. void* heap)
  10147. {
  10148. InitDecodedCert(cert, source, inSz, heap);
  10149. }
  10150. /* Free the alternative names object.
  10151. *
  10152. * Frees each linked list items and its name.
  10153. *
  10154. * @param [in, out] altNames Alternative names.
  10155. * @param [in] heap Dynamic memory hint.
  10156. */
  10157. void FreeAltNames(DNS_entry* altNames, void* heap)
  10158. {
  10159. (void)heap;
  10160. while (altNames) {
  10161. DNS_entry* tmp = altNames->next;
  10162. XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
  10163. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  10164. XFREE(altNames->ipString, heap, DYNAMIC_TYPE_ALTNAME);
  10165. #endif
  10166. XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME);
  10167. altNames = tmp;
  10168. }
  10169. }
  10170. /* malloc and initialize a new alt name structure */
  10171. DNS_entry* AltNameNew(void* heap)
  10172. {
  10173. DNS_entry* ret;
  10174. ret = (DNS_entry*)XMALLOC(sizeof(DNS_entry), heap, DYNAMIC_TYPE_ALTNAME);
  10175. if (ret != NULL) {
  10176. XMEMSET(ret, 0, sizeof(DNS_entry));
  10177. }
  10178. (void)heap;
  10179. return ret;
  10180. }
  10181. #ifndef IGNORE_NAME_CONSTRAINTS
  10182. /* Free the subtree names object.
  10183. *
  10184. * Frees each linked list items and its name.
  10185. *
  10186. * @param [in, out] names Subtree names.
  10187. * @param [in] heap Dynamic memory hint.
  10188. */
  10189. void FreeNameSubtrees(Base_entry* names, void* heap)
  10190. {
  10191. (void)heap;
  10192. while (names) {
  10193. Base_entry* tmp = names->next;
  10194. XFREE(names->name, heap, DYNAMIC_TYPE_ALTNAME);
  10195. XFREE(names, heap, DYNAMIC_TYPE_ALTNAME);
  10196. names = tmp;
  10197. }
  10198. }
  10199. #endif /* IGNORE_NAME_CONSTRAINTS */
  10200. /* Free the decoded cert object's dynamic data.
  10201. *
  10202. * @param [in, out] cert Decoded certificate object.
  10203. */
  10204. void FreeDecodedCert(DecodedCert* cert)
  10205. {
  10206. if (cert == NULL)
  10207. return;
  10208. if (cert->subjectCNStored == 1) {
  10209. XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
  10210. }
  10211. if (cert->pubKeyStored == 1) {
  10212. XFREE((void*)cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  10213. }
  10214. if (cert->weOwnAltNames && cert->altNames)
  10215. FreeAltNames(cert->altNames, cert->heap);
  10216. #ifndef IGNORE_NAME_CONSTRAINTS
  10217. if (cert->altEmailNames)
  10218. FreeAltNames(cert->altEmailNames, cert->heap);
  10219. if (cert->altDirNames)
  10220. FreeAltNames(cert->altDirNames, cert->heap);
  10221. if (cert->permittedNames)
  10222. FreeNameSubtrees(cert->permittedNames, cert->heap);
  10223. if (cert->excludedNames)
  10224. FreeNameSubtrees(cert->excludedNames, cert->heap);
  10225. #endif /* IGNORE_NAME_CONSTRAINTS */
  10226. #ifdef WOLFSSL_SEP
  10227. XFREE(cert->deviceType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10228. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10229. XFREE(cert->hwSerialNum, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10230. #endif /* WOLFSSL_SEP */
  10231. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10232. if (cert->issuerName != NULL)
  10233. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->issuerName);
  10234. if (cert->subjectName != NULL)
  10235. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->subjectName);
  10236. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  10237. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10238. if (cert->sce_tsip_encRsaKeyIdx != NULL)
  10239. XFREE(cert->sce_tsip_encRsaKeyIdx, cert->heap, DYNAMIC_TYPE_RSA);
  10240. #endif
  10241. FreeSignatureCtx(&cert->sigCtx);
  10242. }
  10243. void wc_FreeDecodedCert(DecodedCert* cert)
  10244. {
  10245. FreeDecodedCert(cert);
  10246. }
  10247. #ifndef WOLFSSL_ASN_TEMPLATE
  10248. static int GetCertHeader(DecodedCert* cert)
  10249. {
  10250. int ret = 0, len;
  10251. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  10252. return ASN_PARSE_E;
  10253. /* Reset the max index for the size indicated in the outer wrapper. */
  10254. cert->maxIdx = (word32)len + cert->srcIdx;
  10255. cert->certBegin = cert->srcIdx;
  10256. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  10257. return ASN_PARSE_E;
  10258. cert->sigIndex = (word32)len + cert->srcIdx;
  10259. if (cert->sigIndex > cert->maxIdx)
  10260. return ASN_PARSE_E;
  10261. if (GetExplicitVersion(cert->source, &cert->srcIdx, &cert->version,
  10262. cert->sigIndex) < 0)
  10263. return ASN_PARSE_E;
  10264. if (wc_GetSerialNumber(cert->source, &cert->srcIdx, cert->serial,
  10265. &cert->serialSz, cert->sigIndex) < 0)
  10266. return ASN_PARSE_E;
  10267. return ret;
  10268. }
  10269. #endif
  10270. #if defined(HAVE_ED25519) || defined(HAVE_ED448) || (defined(HAVE_PQC) && \
  10271. defined(HAVE_LIBOQS))
  10272. /* Store the key data under the BIT_STRING in dynamically allocated data.
  10273. *
  10274. * @param [in, out] cert Certificate object.
  10275. * @param [in] source Buffer containing encoded key.
  10276. * @param [in, out] srcIdx On in, start of key data.
  10277. * On out, start of element after key data.
  10278. * @param [in] maxIdx Maximum index of certificate data.
  10279. */
  10280. static int StoreKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10281. word32 maxIdx)
  10282. {
  10283. int ret;
  10284. int length;
  10285. byte* publicKey;
  10286. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10287. if (ret == 0) {
  10288. #ifdef HAVE_OCSP
  10289. ret = CalcHashId(source + *srcIdx, (word32)length,
  10290. cert->subjectKeyHash);
  10291. }
  10292. if (ret == 0) {
  10293. #endif
  10294. publicKey = (byte*)XMALLOC((size_t)length, cert->heap,
  10295. DYNAMIC_TYPE_PUBLIC_KEY);
  10296. if (publicKey == NULL) {
  10297. ret = MEMORY_E;
  10298. }
  10299. else {
  10300. XMEMCPY(publicKey, &source[*srcIdx], (size_t)length);
  10301. cert->publicKey = publicKey;
  10302. cert->pubKeyStored = 1;
  10303. cert->pubKeySize = (word32)length;
  10304. *srcIdx += (word32)length;
  10305. }
  10306. }
  10307. return ret;
  10308. }
  10309. #endif /* HAVE_ED25519 || HAVE_ED448 */
  10310. #endif
  10311. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  10312. static int SetCurve(ecc_key* key, byte* output, size_t outSz)
  10313. {
  10314. #ifdef HAVE_OID_ENCODING
  10315. int ret;
  10316. #endif
  10317. int idx;
  10318. word32 oidSz = 0;
  10319. /* validate key */
  10320. if (key == NULL || key->dp == NULL) {
  10321. return BAD_FUNC_ARG;
  10322. }
  10323. #ifdef HAVE_OID_ENCODING
  10324. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, NULL, &oidSz);
  10325. if (ret != 0) {
  10326. return ret;
  10327. }
  10328. #else
  10329. oidSz = key->dp->oidSz;
  10330. #endif
  10331. idx = SetObjectId((int)oidSz, output);
  10332. /* length only */
  10333. if (output == NULL) {
  10334. return idx + (int)oidSz;
  10335. }
  10336. /* verify output buffer has room */
  10337. if (oidSz > outSz)
  10338. return BUFFER_E;
  10339. #ifdef HAVE_OID_ENCODING
  10340. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, output+idx, &oidSz);
  10341. if (ret != 0) {
  10342. return ret;
  10343. }
  10344. #else
  10345. XMEMCPY(output+idx, key->dp->oid, oidSz);
  10346. #endif
  10347. idx += (int)oidSz;
  10348. return idx;
  10349. }
  10350. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  10351. #ifdef HAVE_ECC
  10352. #ifdef WOLFSSL_ASN_TEMPLATE
  10353. /* ASN.1 template for ECC public key (SubjectPublicKeyInfo).
  10354. * RFC 5480, 2 - Subject Public Key Information Fields
  10355. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  10356. * X9.62 ECC point format.
  10357. * See ASN.1 template 'eccSpecifiedASN' for specifiedCurve.
  10358. */
  10359. static const ASNItem eccPublicKeyASN[] = {
  10360. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  10361. /* AlgorithmIdentifier */
  10362. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  10363. /* algorithm */
  10364. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  10365. /* namedCurve */
  10366. /* ALGOID_CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  10367. /* specifiedCurve - explicit parameters */
  10368. /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  10369. /* Public Key */
  10370. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  10371. };
  10372. enum {
  10373. ECCPUBLICKEYASN_IDX_SEQ = 0,
  10374. ECCPUBLICKEYASN_IDX_ALGOID_SEQ,
  10375. ECCPUBLICKEYASN_IDX_ALGOID_OID,
  10376. ECCPUBLICKEYASN_IDX_ALGOID_CURVEID,
  10377. ECCPUBLICKEYASN_IDX_ALGOID_PARAMS,
  10378. ECCPUBLICKEYASN_IDX_PUBKEY
  10379. };
  10380. /* Number of items in ASN.1 template for ECC public key. */
  10381. #define eccPublicKeyASN_Length (sizeof(eccPublicKeyASN) / sizeof(ASNItem))
  10382. #endif /* WOLFSSL_ASN_TEMPLATE */
  10383. #endif /* HAVE_ECC */
  10384. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  10385. /* Encode public ECC key in DER format.
  10386. *
  10387. * RFC 5480, 2 - Subject Public Key Information Fields
  10388. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  10389. * X9.62 ECC point format.
  10390. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  10391. *
  10392. * @param [out] output Buffer to put encoded data in.
  10393. * @param [in] key ECC key object.
  10394. * @param [in] outLen Size of buffer in bytes.
  10395. * @param [in] with_header Whether to use SubjectPublicKeyInfo format.
  10396. * @return Size of encoded data in bytes on success.
  10397. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  10398. * @return MEMORY_E when dynamic memory allocation failed.
  10399. */
  10400. static int SetEccPublicKey(byte* output, ecc_key* key, int outLen,
  10401. int with_header, int comp)
  10402. {
  10403. #ifndef WOLFSSL_ASN_TEMPLATE
  10404. int ret;
  10405. word32 idx = 0, curveSz, algoSz, pubSz, bitStringSz;
  10406. byte bitString[1 + MAX_LENGTH_SZ + 1]; /* 6 */
  10407. byte algo[MAX_ALGO_SZ]; /* 20 */
  10408. /* public size */
  10409. pubSz = key->dp ? (word32)key->dp->size : MAX_ECC_BYTES;
  10410. if (comp)
  10411. pubSz = 1 + pubSz;
  10412. else
  10413. pubSz = 1 + 2 * pubSz;
  10414. /* check for buffer overflow */
  10415. if (output != NULL && pubSz > (word32)outLen) {
  10416. return BUFFER_E;
  10417. }
  10418. /* headers */
  10419. if (with_header) {
  10420. ret = SetCurve(key, NULL, 0);
  10421. if (ret <= 0) {
  10422. return ret;
  10423. }
  10424. curveSz = (word32)ret;
  10425. ret = 0;
  10426. /* calculate size */
  10427. algoSz = SetAlgoID(ECDSAk, algo, oidKeyType, (int)curveSz);
  10428. bitStringSz = SetBitString(pubSz, 0, bitString);
  10429. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz, NULL);
  10430. /* check for buffer overflow */
  10431. if (output != NULL &&
  10432. curveSz + algoSz + bitStringSz + idx + pubSz > (word32)outLen) {
  10433. return BUFFER_E;
  10434. }
  10435. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz,
  10436. output);
  10437. /* algo */
  10438. if (output)
  10439. XMEMCPY(output + idx, algo, algoSz);
  10440. idx += algoSz;
  10441. /* curve */
  10442. if (output)
  10443. (void)SetCurve(key, output + idx, curveSz);
  10444. idx += curveSz;
  10445. /* bit string */
  10446. if (output)
  10447. XMEMCPY(output + idx, bitString, bitStringSz);
  10448. idx += bitStringSz;
  10449. }
  10450. /* pub */
  10451. if (output) {
  10452. PRIVATE_KEY_UNLOCK();
  10453. ret = wc_ecc_export_x963_ex(key, output + idx, &pubSz, comp);
  10454. PRIVATE_KEY_LOCK();
  10455. if (ret != 0) {
  10456. return ret;
  10457. }
  10458. }
  10459. idx += pubSz;
  10460. return (int)idx;
  10461. #else
  10462. word32 pubSz = 0;
  10463. int sz = 0;
  10464. int ret = 0;
  10465. int curveIdSz = 0;
  10466. byte* curveOid = NULL;
  10467. /* Check key validity. */
  10468. if ((key == NULL) || (key->dp == NULL)) {
  10469. ret = BAD_FUNC_ARG;
  10470. }
  10471. if (ret == 0) {
  10472. /* Calculate the size of the encoded public point. */
  10473. PRIVATE_KEY_UNLOCK();
  10474. #if defined(HAVE_COMP_KEY) && defined(HAVE_FIPS) && \
  10475. defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  10476. /* in earlier versions of FIPS the get length functionality is not
  10477. * available with compressed keys */
  10478. pubSz = key->dp ? key->dp->size : MAX_ECC_BYTES;
  10479. if (comp)
  10480. pubSz = 1 + pubSz;
  10481. else
  10482. pubSz = 1 + 2 * pubSz;
  10483. ret = LENGTH_ONLY_E;
  10484. #else
  10485. ret = wc_ecc_export_x963_ex(key, NULL, &pubSz, comp);
  10486. #endif
  10487. PRIVATE_KEY_LOCK();
  10488. /* LENGTH_ONLY_E on success. */
  10489. if (ret == LENGTH_ONLY_E) {
  10490. ret = 0;
  10491. }
  10492. }
  10493. if ((ret == 0) && with_header) {
  10494. /* Including SubjectPublicKeyInfo header. */
  10495. DECL_ASNSETDATA(dataASN, eccPublicKeyASN_Length);
  10496. CALLOC_ASNSETDATA(dataASN, eccPublicKeyASN_Length, ret, key->heap);
  10497. /* Get the length of the named curve OID to put into the encoding. */
  10498. curveIdSz = SetCurve(key, NULL, 0);
  10499. if (curveIdSz < 0) {
  10500. ret = curveIdSz;
  10501. }
  10502. if (ret == 0) {
  10503. /* Set the key type OID. */
  10504. SetASN_OID(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], ECDSAk,
  10505. oidKeyType);
  10506. /* Set the curve OID. */
  10507. SetASN_ReplaceBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID],
  10508. NULL, (word32)curveIdSz);
  10509. /* Don't try to write out explicit parameters. */
  10510. dataASN[ECCPUBLICKEYASN_IDX_ALGOID_PARAMS].noOut = 1;
  10511. /* Set size of public point to ensure space is made for it. */
  10512. SetASN_Buffer(&dataASN[ECCPUBLICKEYASN_IDX_PUBKEY], NULL, pubSz);
  10513. /* Calculate size of ECC public key. */
  10514. ret = SizeASN_Items(eccPublicKeyASN, dataASN,
  10515. eccPublicKeyASN_Length, &sz);
  10516. }
  10517. /* Check buffer, if passed in, is big enough for encoded data. */
  10518. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  10519. ret = BUFFER_E;
  10520. }
  10521. if ((ret == 0) && (output != NULL)) {
  10522. /* Encode ECC public key. */
  10523. SetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length,
  10524. output);
  10525. /* Skip to where public point is to be encoded. */
  10526. output += sz - (int)pubSz;
  10527. /* Cache the location to place the name curve OID. */
  10528. curveOid = (byte*)
  10529. dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID].data.buffer.data;
  10530. }
  10531. FREE_ASNSETDATA(dataASN, key->heap);
  10532. }
  10533. else if ((ret == 0) && (output != NULL) && (pubSz > (word32)outLen)) {
  10534. ret = BUFFER_E;
  10535. }
  10536. else {
  10537. /* Total size is the public point size. */
  10538. sz = (int)pubSz;
  10539. }
  10540. if ((ret == 0) && (output != NULL)) {
  10541. /* Put named curve OID data into encoding. */
  10542. curveIdSz = SetCurve(key, curveOid, (size_t)curveIdSz);
  10543. if (curveIdSz < 0) {
  10544. ret = curveIdSz;
  10545. }
  10546. }
  10547. if ((ret == 0) && (output != NULL)) {
  10548. /* Encode public point. */
  10549. PRIVATE_KEY_UNLOCK();
  10550. ret = wc_ecc_export_x963_ex(key, output, &pubSz, comp);
  10551. PRIVATE_KEY_LOCK();
  10552. }
  10553. if (ret == 0) {
  10554. /* Return the size of the encoding. */
  10555. ret = sz;
  10556. }
  10557. return ret;
  10558. #endif
  10559. }
  10560. /* Encode the public part of an ECC key in a DER.
  10561. *
  10562. * Pass NULL for output to get the size of the encoding.
  10563. *
  10564. * @param [in] key ECC key object.
  10565. * @param [out] output Buffer to hold DER encoding.
  10566. * @param [in] inLen Size of buffer in bytes.
  10567. * @param [in] with_AlgCurve Whether to use SubjectPublicKeyInfo format.
  10568. * @return Size of encoded data in bytes on success.
  10569. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  10570. * @return MEMORY_E when dynamic memory allocation failed.
  10571. */
  10572. WOLFSSL_ABI
  10573. int wc_EccPublicKeyToDer(ecc_key* key, byte* output, word32 inLen,
  10574. int with_AlgCurve)
  10575. {
  10576. return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, 0);
  10577. }
  10578. int wc_EccPublicKeyToDer_ex(ecc_key* key, byte* output, word32 inLen,
  10579. int with_AlgCurve, int comp)
  10580. {
  10581. return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, comp);
  10582. }
  10583. int wc_EccPublicKeyDerSize(ecc_key* key, int with_AlgCurve)
  10584. {
  10585. return SetEccPublicKey(NULL, key, 0, with_AlgCurve, 0);
  10586. }
  10587. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  10588. #ifdef WOLFSSL_ASN_TEMPLATE
  10589. #if defined(WC_ENABLE_ASYM_KEY_EXPORT) || defined(WC_ENABLE_ASYM_KEY_IMPORT)
  10590. /* ASN.1 template for Ed25519 and Ed448 public key (SubkectPublicKeyInfo).
  10591. * RFC 8410, 4 - Subject Public Key Fields
  10592. */
  10593. static const ASNItem edPubKeyASN[] = {
  10594. /* SubjectPublicKeyInfo */
  10595. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  10596. /* AlgorithmIdentifier */
  10597. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  10598. /* Ed25519/Ed448 OID */
  10599. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  10600. /* Public key stream */
  10601. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  10602. };
  10603. enum {
  10604. EDPUBKEYASN_IDX_SEQ = 0,
  10605. EDPUBKEYASN_IDX_ALGOID_SEQ,
  10606. EDPUBKEYASN_IDX_ALGOID_OID,
  10607. EDPUBKEYASN_IDX_PUBKEY
  10608. };
  10609. /* Number of items in ASN.1 template for Ed25519 and Ed448 public key. */
  10610. #define edPubKeyASN_Length (sizeof(edPubKeyASN) / sizeof(ASNItem))
  10611. #endif /* WC_ENABLE_ASYM_KEY_EXPORT || WC_ENABLE_ASYM_KEY_IMPORT */
  10612. #endif /* WOLFSSL_ASN_TEMPLATE */
  10613. #ifdef WC_ENABLE_ASYM_KEY_EXPORT
  10614. /* Build ASN.1 formatted public key based on RFC 8410
  10615. *
  10616. * Pass NULL for output to get the size of the encoding.
  10617. *
  10618. * @param [in] pubKey public key buffer
  10619. * @param [in] pubKeyLen public key buffer length
  10620. * @param [out] output Buffer to put encoded data in (optional)
  10621. * @param [in] outLen Size of buffer in bytes
  10622. * @param [in] keyType is "enum Key_Sum" like ED25519k
  10623. * @param [in] withHeader Whether to include SubjectPublicKeyInfo around key.
  10624. * @return Size of encoded data in bytes on success
  10625. * @return BAD_FUNC_ARG when key is NULL.
  10626. * @return MEMORY_E when dynamic memory allocation failed.
  10627. */
  10628. int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen,
  10629. byte* output, word32 outLen, int keyType, int withHeader)
  10630. {
  10631. int ret = 0;
  10632. #ifndef WOLFSSL_ASN_TEMPLATE
  10633. word32 idx = 0;
  10634. word32 seqDataSz = 0;
  10635. word32 sz;
  10636. #else
  10637. int sz = 0;
  10638. DECL_ASNSETDATA(dataASN, edPubKeyASN_Length);
  10639. #endif
  10640. if (pubKey == NULL) {
  10641. return BAD_FUNC_ARG;
  10642. }
  10643. #ifndef WOLFSSL_ASN_TEMPLATE
  10644. /* calculate size */
  10645. if (withHeader) {
  10646. word32 algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
  10647. word32 bitStringSz = SetBitString(pubKeyLen, 0, NULL);
  10648. seqDataSz = algoSz + bitStringSz + pubKeyLen;
  10649. sz = SetSequence(seqDataSz, NULL) + seqDataSz;
  10650. }
  10651. else {
  10652. sz = pubKeyLen;
  10653. }
  10654. /* checkout output size */
  10655. if (output != NULL && sz > outLen) {
  10656. ret = BUFFER_E;
  10657. }
  10658. /* headers */
  10659. if (ret == 0 && output != NULL && withHeader) {
  10660. /* sequence */
  10661. idx = SetSequence(seqDataSz, output);
  10662. /* algo */
  10663. idx += SetAlgoID(keyType, output + idx, oidKeyType, 0);
  10664. /* bit string */
  10665. idx += SetBitString(pubKeyLen, 0, output + idx);
  10666. }
  10667. if (ret == 0 && output != NULL) {
  10668. /* pub */
  10669. XMEMCPY(output + idx, pubKey, pubKeyLen);
  10670. idx += pubKeyLen;
  10671. sz = idx;
  10672. }
  10673. if (ret == 0) {
  10674. ret = (int)sz;
  10675. }
  10676. #else
  10677. if (withHeader) {
  10678. CALLOC_ASNSETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
  10679. if (ret == 0) {
  10680. /* Set the OID. */
  10681. SetASN_OID(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], (word32)keyType,
  10682. oidKeyType);
  10683. /* Leave space for public point. */
  10684. SetASN_Buffer(&dataASN[EDPUBKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
  10685. /* Calculate size of public key encoding. */
  10686. ret = SizeASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, &sz);
  10687. }
  10688. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  10689. ret = BUFFER_E;
  10690. }
  10691. if ((ret == 0) && (output != NULL)) {
  10692. /* Encode public key. */
  10693. SetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, output);
  10694. /* Set location to encode public point. */
  10695. output = (byte*)dataASN[EDPUBKEYASN_IDX_PUBKEY].data.buffer.data;
  10696. }
  10697. FREE_ASNSETDATA(dataASN, NULL);
  10698. }
  10699. else if ((output != NULL) && (pubKeyLen > outLen)) {
  10700. ret = BUFFER_E;
  10701. }
  10702. else if (ret == 0) {
  10703. sz = (int)pubKeyLen;
  10704. }
  10705. if ((ret == 0) && (output != NULL)) {
  10706. /* Put public key into space provided. */
  10707. XMEMCPY(output, pubKey, pubKeyLen);
  10708. }
  10709. if (ret == 0) {
  10710. ret = sz;
  10711. }
  10712. #endif /* WOLFSSL_ASN_TEMPLATE */
  10713. return ret;
  10714. }
  10715. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  10716. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  10717. /* Encode the public part of an Ed25519 key in DER.
  10718. *
  10719. * Pass NULL for output to get the size of the encoding.
  10720. *
  10721. * @param [in] key Ed25519 key object.
  10722. * @param [out] output Buffer to put encoded data in.
  10723. * @param [in] outLen Size of buffer in bytes.
  10724. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  10725. * @return Size of encoded data in bytes on success.
  10726. * @return BAD_FUNC_ARG when key is NULL.
  10727. * @return MEMORY_E when dynamic memory allocation failed.
  10728. */
  10729. int wc_Ed25519PublicKeyToDer(ed25519_key* key, byte* output, word32 inLen,
  10730. int withAlg)
  10731. {
  10732. int ret;
  10733. byte pubKey[ED25519_PUB_KEY_SIZE];
  10734. word32 pubKeyLen = (word32)sizeof(pubKey);
  10735. if (key == NULL) {
  10736. return BAD_FUNC_ARG;
  10737. }
  10738. ret = wc_ed25519_export_public(key, pubKey, &pubKeyLen);
  10739. if (ret == 0) {
  10740. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  10741. ED25519k, withAlg);
  10742. }
  10743. return ret;
  10744. }
  10745. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  10746. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  10747. /* Encode the public part of an Ed448 key in DER.
  10748. *
  10749. * Pass NULL for output to get the size of the encoding.
  10750. *
  10751. * @param [in] key Ed448 key object.
  10752. * @param [out] output Buffer to put encoded data in.
  10753. * @param [in] outLen Size of buffer in bytes.
  10754. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  10755. * @return Size of encoded data in bytes on success.
  10756. * @return BAD_FUNC_ARG when key is NULL.
  10757. * @return MEMORY_E when dynamic memory allocation failed.
  10758. */
  10759. int wc_Ed448PublicKeyToDer(ed448_key* key, byte* output, word32 inLen,
  10760. int withAlg)
  10761. {
  10762. int ret;
  10763. byte pubKey[ED448_PUB_KEY_SIZE];
  10764. word32 pubKeyLen = (word32)sizeof(pubKey);
  10765. if (key == NULL) {
  10766. return BAD_FUNC_ARG;
  10767. }
  10768. ret = wc_ed448_export_public(key, pubKey, &pubKeyLen);
  10769. if (ret == 0) {
  10770. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  10771. ED448k, withAlg);
  10772. }
  10773. return ret;
  10774. }
  10775. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  10776. #if !defined(NO_RSA) && !defined(NO_CERTS)
  10777. #ifdef WOLFSSL_ASN_TEMPLATE
  10778. /* ASN.1 template for header before RSA key in certificate. */
  10779. static const ASNItem rsaCertKeyASN[] = {
  10780. /* STR */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  10781. /* SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  10782. };
  10783. enum {
  10784. RSACERTKEYASN_IDX_STR = 0,
  10785. RSACERTKEYASN_IDX_SEQ
  10786. };
  10787. /* Number of items in ASN.1 template for header before RSA key in cert. */
  10788. #define rsaCertKeyASN_Length (sizeof(rsaCertKeyASN) / sizeof(ASNItem))
  10789. #endif
  10790. /* Store RSA key pointer and length in certificate object.
  10791. *
  10792. * @param [in, out] cert Certificate object.
  10793. * @param [in] source Buffer containing encoded key.
  10794. * @param [in, out] srcIdx On in, start of RSA key data.
  10795. * On out, start of element after RSA key data.
  10796. * @param [in] maxIdx Maximum index of key data.
  10797. * @return 0 on success.
  10798. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10799. * is invalid.
  10800. * @return BUFFER_E when data in buffer is too small.
  10801. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10802. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10803. * non-zero length.
  10804. */
  10805. static int StoreRsaKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10806. word32 maxIdx)
  10807. {
  10808. #ifndef WOLFSSL_ASN_TEMPLATE
  10809. int length;
  10810. int pubLen;
  10811. word32 pubIdx;
  10812. if (CheckBitString(source, srcIdx, &pubLen, maxIdx, 1, NULL) != 0)
  10813. return ASN_PARSE_E;
  10814. pubIdx = *srcIdx;
  10815. if (GetSequence(source, srcIdx, &length, pubIdx + (word32)pubLen) < 0)
  10816. return ASN_PARSE_E;
  10817. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10818. cert->sigCtx.CertAtt.pubkey_n_start =
  10819. cert->sigCtx.CertAtt.pubkey_e_start = pubIdx;
  10820. #endif
  10821. cert->pubKeySize = (word32)pubLen;
  10822. cert->publicKey = source + pubIdx;
  10823. #ifdef WOLFSSL_MAXQ10XX_TLS
  10824. cert->publicKeyIndex = pubIdx;
  10825. #endif
  10826. *srcIdx += (word32)length;
  10827. #ifdef HAVE_OCSP
  10828. return CalcHashId(cert->publicKey, cert->pubKeySize, cert->subjectKeyHash);
  10829. #else
  10830. return 0;
  10831. #endif
  10832. #else
  10833. ASNGetData dataASN[rsaCertKeyASN_Length];
  10834. int ret;
  10835. /* No dynamic data. */
  10836. XMEMSET(dataASN, 0, sizeof(dataASN));
  10837. /* Decode the header before the key data. */
  10838. ret = GetASN_Items(rsaCertKeyASN, dataASN, rsaCertKeyASN_Length, 1, source,
  10839. srcIdx, maxIdx);
  10840. if (ret == 0) {
  10841. /* Store the pointer and length in certificate object starting at
  10842. * SEQUENCE. */
  10843. GetASN_GetConstRef(&dataASN[RSACERTKEYASN_IDX_STR],
  10844. &cert->publicKey, &cert->pubKeySize);
  10845. #ifdef WOLFSSL_MAXQ10XX_TLS
  10846. cert->publicKeyIndex = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
  10847. #endif
  10848. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10849. /* Start of SEQUENCE. */
  10850. cert->sigCtx.CertAtt.pubkey_n_start =
  10851. cert->sigCtx.CertAtt.pubkey_e_start = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
  10852. #endif
  10853. #ifdef HAVE_OCSP
  10854. /* Calculate the hash of the public key for OCSP. */
  10855. ret = CalcHashId(cert->publicKey, cert->pubKeySize,
  10856. cert->subjectKeyHash);
  10857. #endif
  10858. }
  10859. return ret;
  10860. #endif /* WOLFSSL_ASN_TEMPLATE */
  10861. }
  10862. #endif /* !NO_RSA && !NO_CERTS */
  10863. #if defined(HAVE_ECC) && !defined(NO_CERTS)
  10864. #ifdef WOLFSSL_ASN_TEMPLATE
  10865. /* ASN.1 template for header before ECC key in certificate. */
  10866. static const ASNItem eccCertKeyASN[] = {
  10867. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 2 },
  10868. /* Algo parameters */
  10869. /* PARAMS */ { 1, ASN_SEQUENCE, 1, 0, 2 },
  10870. /* Subject public key */
  10871. /* SUBJPUBKEY */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  10872. };
  10873. enum {
  10874. ECCCERTKEYASN_IDX_OID = 0,
  10875. ECCCERTKEYASN_IDX_PARAMS,
  10876. ECCCERTKEYASN_IDX_SUBJPUBKEY
  10877. };
  10878. /* Number of items in ASN.1 template for header before ECC key in cert. */
  10879. #define eccCertKeyASN_Length (sizeof(eccCertKeyASN) / sizeof(ASNItem))
  10880. #endif /* WOLFSSL_ASN_TEMPLATE */
  10881. /* Store public ECC key in certificate object.
  10882. *
  10883. * Parse parameters and store public key data.
  10884. *
  10885. * @param [in, out] cert Certificate object.
  10886. * @param [in] source Buffer containing encoded key.
  10887. * @param [in, out] srcIdx On in, start of ECC key data.
  10888. * On out, start of element after ECC key data.
  10889. * @param [in] maxIdx Maximum index of key data.
  10890. * @param [in] pubKey Buffer holding encoded public key.
  10891. * @param [in] pubKeyLen Length of encoded public key in bytes.
  10892. * @return 0 on success.
  10893. * @return BAD_FUNC_ARG when pubKey is NULL.
  10894. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10895. * is invalid.
  10896. * @return BUFFER_E when data in buffer is too small.
  10897. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  10898. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10899. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10900. * non-zero length.
  10901. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  10902. */
  10903. static int StoreEccKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10904. word32 maxIdx, const byte* pubKey, word32 pubKeyLen)
  10905. {
  10906. #ifndef WOLFSSL_ASN_TEMPLATE
  10907. int ret;
  10908. word32 localIdx;
  10909. byte* publicKey;
  10910. byte tag;
  10911. int length;
  10912. if (pubKey == NULL) {
  10913. return BAD_FUNC_ARG;
  10914. }
  10915. localIdx = *srcIdx;
  10916. if (GetASNTag(source, &localIdx, &tag, maxIdx) < 0)
  10917. return ASN_PARSE_E;
  10918. if (tag != (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  10919. if (GetObjectId(source, srcIdx, &cert->pkCurveOID, oidCurveType,
  10920. maxIdx) < 0)
  10921. return ASN_PARSE_E;
  10922. if ((ret = CheckCurve(cert->pkCurveOID)) < 0)
  10923. return ECC_CURVE_OID_E;
  10924. #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  10925. cert->sigCtx.CertAtt.curve_id = ret;
  10926. #else
  10927. (void)ret;
  10928. #endif
  10929. /* key header */
  10930. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10931. if (ret != 0)
  10932. return ret;
  10933. #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  10934. cert->sigCtx.CertAtt.pubkey_n_start =
  10935. cert->sigCtx.CertAtt.pubkey_e_start = (*srcIdx + 1);
  10936. cert->sigCtx.CertAtt.pubkey_n_len = ((length - 1) >> 1);
  10937. cert->sigCtx.CertAtt.pubkey_e_start +=
  10938. cert->sigCtx.CertAtt.pubkey_n_len;
  10939. cert->sigCtx.CertAtt.pubkey_e_len =
  10940. cert->sigCtx.CertAtt.pubkey_n_len;
  10941. #endif
  10942. #ifdef WOLFSSL_MAXQ10XX_TLS
  10943. cert->publicKeyIndex = *srcIdx + 1;
  10944. #endif
  10945. #ifdef HAVE_OCSP
  10946. ret = CalcHashId(source + *srcIdx, (word32)length,
  10947. cert->subjectKeyHash);
  10948. if (ret != 0)
  10949. return ret;
  10950. #endif
  10951. *srcIdx += (word32)length;
  10952. }
  10953. publicKey = (byte*)XMALLOC(pubKeyLen, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  10954. if (publicKey == NULL)
  10955. return MEMORY_E;
  10956. XMEMCPY(publicKey, pubKey, pubKeyLen);
  10957. cert->publicKey = publicKey;
  10958. cert->pubKeyStored = 1;
  10959. cert->pubKeySize = pubKeyLen;
  10960. return 0;
  10961. #else
  10962. int ret = 0;
  10963. DECL_ASNGETDATA(dataASN, eccCertKeyASN_Length);
  10964. byte* publicKey;
  10965. /* Validate parameters. */
  10966. if (pubKey == NULL) {
  10967. ret = BAD_FUNC_ARG;
  10968. }
  10969. /* Clear dynamic data and check OID is a curve. */
  10970. CALLOC_ASNGETDATA(dataASN, eccCertKeyASN_Length, ret, cert->heap);
  10971. if (ret == 0) {
  10972. GetASN_OID(&dataASN[ECCCERTKEYASN_IDX_OID], oidCurveType);
  10973. /* Parse ECC public key header. */
  10974. ret = GetASN_Items(eccCertKeyASN, dataASN, eccCertKeyASN_Length, 1,
  10975. source, srcIdx, maxIdx);
  10976. }
  10977. if (ret == 0) {
  10978. if (dataASN[ECCCERTKEYASN_IDX_OID].tag != 0) {
  10979. /* Store curve OID. */
  10980. cert->pkCurveOID = dataASN[ECCCERTKEYASN_IDX_OID].data.oid.sum;
  10981. }
  10982. /* Ignore explicit parameters. */
  10983. #ifdef WOLFSSL_MAXQ10XX_TLS
  10984. cert->publicKeyIndex =
  10985. GetASNItem_DataIdx(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY], source)
  10986. + 1;
  10987. #endif
  10988. #ifdef HAVE_OCSP
  10989. /* Calculate the hash of the subject public key for OCSP. */
  10990. ret = CalcHashId(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.data,
  10991. dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.length,
  10992. cert->subjectKeyHash);
  10993. }
  10994. if (ret == 0) {
  10995. #endif
  10996. /* Store public key data length. */
  10997. cert->pubKeySize = pubKeyLen;
  10998. /* Must allocated space for key.
  10999. * Don't memcpy into constant pointer so use temp. */
  11000. publicKey = (byte*)XMALLOC(cert->pubKeySize, cert->heap,
  11001. DYNAMIC_TYPE_PUBLIC_KEY);
  11002. if (publicKey == NULL) {
  11003. ret = MEMORY_E;
  11004. }
  11005. else {
  11006. /* Copy in whole public key and store pointer. */
  11007. XMEMCPY(publicKey, pubKey, cert->pubKeySize);
  11008. cert->publicKey = publicKey;
  11009. /* Indicate publicKey needs to be freed. */
  11010. cert->pubKeyStored = 1;
  11011. }
  11012. }
  11013. FREE_ASNGETDATA(dataASN, cert->heap);
  11014. return ret;
  11015. #endif /* WOLFSSL_ASN_TEMPLATE */
  11016. }
  11017. #endif /* HAVE_ECC && !NO_CERTS */
  11018. #ifndef NO_CERTS
  11019. #if !defined(NO_DSA)
  11020. #ifdef WOLFSSL_ASN_TEMPLATE
  11021. /* ASN.1 template for DSA key in certificate.
  11022. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  11023. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  11024. */
  11025. static const ASNItem dsaCertKeyASN[] = {
  11026. /* 0 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  11027. /* 1 */ { 2, ASN_INTEGER, 0, 0, 0 },
  11028. /* 2 */ { 2, ASN_INTEGER, 0, 0, 0 },
  11029. /* 3 */ { 2, ASN_INTEGER, 0, 0, 0 },
  11030. /* 4 */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  11031. /* 5 */ { 1, ASN_INTEGER, 0, 0, 0 },
  11032. };
  11033. /* Number of items in ASN.1 template for DSA key in certificate. */
  11034. #define dsaCertKeyASN_Length (sizeof(dsaCertKeyASN) / sizeof(ASNItem))
  11035. #endif /* WOLFSSL_ASN_TEMPLATE */
  11036. /* Parse DSA parameters to ensure valid.
  11037. *
  11038. * @param [in] source Buffer containing encoded key.
  11039. * @param [in, out] srcIdx On in, start of DSA key data.
  11040. * On out, start of element after DSA key data.
  11041. * @param [in] maxIdx Maximum index of key data.
  11042. * @param [in] heap Dynamic memory hint.
  11043. * @return 0 on success.
  11044. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  11045. * is invalid.
  11046. * @return BUFFER_E when data in buffer is too small.
  11047. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  11048. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  11049. * non-zero length.
  11050. */
  11051. static int ParseDsaKey(const byte* source, word32* srcIdx, word32 maxIdx,
  11052. void* heap)
  11053. {
  11054. #ifndef WOLFSSL_ASN_TEMPLATE
  11055. int ret;
  11056. int length;
  11057. (void)heap;
  11058. ret = GetSequence(source, srcIdx, &length, maxIdx);
  11059. if (ret < 0)
  11060. return ret;
  11061. ret = SkipInt(source, srcIdx, maxIdx);
  11062. if (ret != 0)
  11063. return ret;
  11064. ret = SkipInt(source, srcIdx, maxIdx);
  11065. if (ret != 0)
  11066. return ret;
  11067. ret = SkipInt(source, srcIdx, maxIdx);
  11068. if (ret != 0)
  11069. return ret;
  11070. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  11071. if (ret != 0)
  11072. return ret;
  11073. ret = GetASNInt(source, srcIdx, &length, maxIdx);
  11074. if (ret != 0)
  11075. return ASN_PARSE_E;
  11076. *srcIdx += (word32)length;
  11077. return 0;
  11078. #else
  11079. DECL_ASNGETDATA(dataASN, dsaCertKeyASN_Length);
  11080. int ret = 0;
  11081. (void)heap;
  11082. CALLOC_ASNGETDATA(dataASN, dsaCertKeyASN_Length, ret, heap);
  11083. if (ret == 0) {
  11084. /* Parse the DSA key data to ensure valid. */
  11085. ret = GetASN_Items(dsaCertKeyASN, dataASN, dsaCertKeyASN_Length, 1,
  11086. source, srcIdx, maxIdx);
  11087. }
  11088. FREE_ASNGETDATA(dataASN, heap);
  11089. return ret;
  11090. #endif /* WOLFSSL_ASN_TEMPLATE */
  11091. }
  11092. #endif /* !NO_DSA */
  11093. /* Decode the SubjectPublicKeyInfo block in a certificate.
  11094. *
  11095. * Stores the public key in fields of the certificate object.
  11096. * Validates the BER/DER items and does not store in a key object.
  11097. *
  11098. * @param [in, out] cert Decoded certificate object.
  11099. * @param [in] source BER/DER encoded SubjectPublicKeyInfo block.
  11100. * @param [in, out] inOutIdx On in, start of public key.
  11101. * On out, start of ASN.1 item after public key.
  11102. * @param [in] maxIdx Maximum index of key data.
  11103. * @return 0 on success.
  11104. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  11105. * is invalid.
  11106. * @return BUFFER_E when data in buffer is too small.
  11107. */
  11108. static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx,
  11109. word32 maxIdx)
  11110. {
  11111. word32 srcIdx = *inOutIdx;
  11112. #if defined(HAVE_ECC) || !defined(NO_DSA)
  11113. int pubLen;
  11114. #endif
  11115. #if defined(HAVE_ECC) || !defined(NO_DSA)
  11116. int pubIdx = (int)srcIdx;
  11117. #endif
  11118. int ret = 0;
  11119. int length;
  11120. /* Validate parameters. */
  11121. if (source == NULL) {
  11122. return ASN_PARSE_E;
  11123. }
  11124. #ifndef WOLFSSL_ASN_TEMPLATE
  11125. if (GetSequence(source, &srcIdx, &length, maxIdx) < 0)
  11126. #else
  11127. /* Get SEQUENCE and expect all data to be accounted for. */
  11128. if (GetASN_Sequence(source, &srcIdx, &length, maxIdx, 1) != 0)
  11129. #endif
  11130. {
  11131. return ASN_PARSE_E;
  11132. }
  11133. #if defined(HAVE_ECC) || !defined(NO_DSA)
  11134. pubLen = (int)srcIdx - pubIdx + length;
  11135. #endif
  11136. maxIdx = srcIdx + (word32)length;
  11137. /* Decode the algorithm identifier for the key. */
  11138. if (GetAlgoId(source, &srcIdx, &cert->keyOID, oidKeyType, maxIdx) < 0) {
  11139. return ASN_PARSE_E;
  11140. }
  11141. (void)length;
  11142. /* Parse each type of public key. */
  11143. switch (cert->keyOID) {
  11144. #ifndef NO_RSA
  11145. #ifdef WC_RSA_PSS
  11146. case RSAPSSk:
  11147. if (srcIdx != maxIdx &&
  11148. source[srcIdx] == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  11149. word32 seqIdx = srcIdx;
  11150. int seqLen;
  11151. /* Not set when -1. */
  11152. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  11153. int mgf = -1;
  11154. int saltLen = 0;
  11155. /* Defaults for sig algorithm parameters. */
  11156. enum wc_HashType sigHash = WC_HASH_TYPE_SHA;
  11157. int sigMgf = WC_MGF1SHA1;
  11158. int sigSaltLen = 20;
  11159. if (GetSequence(source, &srcIdx, &seqLen, maxIdx) < 0) {
  11160. return ASN_PARSE_E;
  11161. }
  11162. /* Get the pubic key parameters. */
  11163. ret = DecodeRsaPssParams(source + seqIdx,
  11164. (word32)seqLen + srcIdx - seqIdx, &hash, &mgf, &saltLen);
  11165. if (ret != 0) {
  11166. return ASN_PARSE_E;
  11167. }
  11168. /* Get the signature parameters. */
  11169. ret = DecodeRsaPssParams(source + cert->sigParamsIndex,
  11170. cert->sigParamsLength, &sigHash, &sigMgf, &sigSaltLen);
  11171. if (ret != 0) {
  11172. return ASN_PARSE_E;
  11173. }
  11174. /* Validated signature params match public key params. */
  11175. if (hash != WC_HASH_TYPE_NONE && hash != sigHash) {
  11176. WOLFSSL_MSG("RSA PSS: hash not matching signature hash");
  11177. return ASN_PARSE_E;
  11178. }
  11179. if (mgf != -1 && mgf != sigMgf) {
  11180. WOLFSSL_MSG("RSA PSS: MGF not matching signature MGF");
  11181. return ASN_PARSE_E;
  11182. }
  11183. if (saltLen > sigSaltLen) {
  11184. WOLFSSL_MSG("RSA PSS: sig salt length too small");
  11185. return ASN_PARSE_E;
  11186. }
  11187. srcIdx += (word32)seqLen;
  11188. }
  11189. FALL_THROUGH;
  11190. #endif /* WC_RSA_PSS */
  11191. case RSAk:
  11192. ret = StoreRsaKey(cert, source, &srcIdx, maxIdx);
  11193. break;
  11194. #endif /* NO_RSA */
  11195. #ifdef HAVE_ECC
  11196. case ECDSAk:
  11197. ret = StoreEccKey(cert, source, &srcIdx, maxIdx, source + pubIdx,
  11198. (word32)pubLen);
  11199. break;
  11200. #endif /* HAVE_ECC */
  11201. #ifdef HAVE_ED25519
  11202. case ED25519k:
  11203. cert->pkCurveOID = ED25519k;
  11204. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11205. break;
  11206. #endif /* HAVE_ED25519 */
  11207. #ifdef HAVE_ED448
  11208. case ED448k:
  11209. cert->pkCurveOID = ED448k;
  11210. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11211. break;
  11212. #endif /* HAVE_ED448 */
  11213. #if defined(HAVE_PQC) && defined(HAVE_LIBOQS)
  11214. #ifdef HAVE_FALCON
  11215. case FALCON_LEVEL1k:
  11216. cert->pkCurveOID = FALCON_LEVEL1k;
  11217. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11218. break;
  11219. case FALCON_LEVEL5k:
  11220. cert->pkCurveOID = FALCON_LEVEL5k;
  11221. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11222. break;
  11223. #endif /* HAVE_FALCON */
  11224. #ifdef HAVE_DILITHIUM
  11225. case DILITHIUM_LEVEL2k:
  11226. cert->pkCurveOID = DILITHIUM_LEVEL2k;
  11227. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11228. break;
  11229. case DILITHIUM_LEVEL3k:
  11230. cert->pkCurveOID = DILITHIUM_LEVEL3k;
  11231. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11232. break;
  11233. case DILITHIUM_LEVEL5k:
  11234. cert->pkCurveOID = DILITHIUM_LEVEL5k;
  11235. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11236. break;
  11237. #endif /* HAVE_DILITHIUM */
  11238. #ifdef HAVE_SPHINCS
  11239. case SPHINCS_FAST_LEVEL1k:
  11240. cert->pkCurveOID = SPHINCS_FAST_LEVEL1k;
  11241. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11242. break;
  11243. case SPHINCS_FAST_LEVEL3k:
  11244. cert->pkCurveOID = SPHINCS_FAST_LEVEL3k;
  11245. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11246. break;
  11247. case SPHINCS_FAST_LEVEL5k:
  11248. cert->pkCurveOID = SPHINCS_FAST_LEVEL5k;
  11249. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11250. break;
  11251. case SPHINCS_SMALL_LEVEL1k:
  11252. cert->pkCurveOID = SPHINCS_SMALL_LEVEL1k;
  11253. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11254. break;
  11255. case SPHINCS_SMALL_LEVEL3k:
  11256. cert->pkCurveOID = SPHINCS_SMALL_LEVEL3k;
  11257. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11258. break;
  11259. case SPHINCS_SMALL_LEVEL5k:
  11260. cert->pkCurveOID = SPHINCS_SMALL_LEVEL5k;
  11261. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11262. break;
  11263. #endif /* HAVE_SPHINCS */
  11264. #endif /* HAVE_PQC */
  11265. #ifndef NO_DSA
  11266. case DSAk:
  11267. cert->publicKey = source + pubIdx;
  11268. cert->pubKeySize = (word32)pubLen;
  11269. ret = ParseDsaKey(source, &srcIdx, maxIdx, cert->heap);
  11270. break;
  11271. #endif /* NO_DSA */
  11272. default:
  11273. WOLFSSL_MSG("Unknown or not compiled in key OID");
  11274. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  11275. ret = ASN_UNKNOWN_OID_E;
  11276. }
  11277. /* Return index after public key. */
  11278. *inOutIdx = srcIdx;
  11279. /* Return error code. */
  11280. return ret;
  11281. }
  11282. #endif
  11283. /* Calculate hash of the id using the SHA-1 or SHA-256.
  11284. *
  11285. * @param [in] data Data to hash.
  11286. * @param [in] len Length of data to hash.
  11287. * @param [out] hash Buffer to hold hash.
  11288. * @return 0 on success.
  11289. * @return MEMORY_E when dynamic memory allocation fails.
  11290. */
  11291. int CalcHashId(const byte* data, word32 len, byte* hash)
  11292. {
  11293. int ret;
  11294. #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
  11295. ret = wc_Sha256Hash(data, len, hash);
  11296. #elif !defined(NO_SHA)
  11297. ret = wc_ShaHash(data, len, hash);
  11298. #else
  11299. ret = NOT_COMPILED_IN;
  11300. (void)data;
  11301. (void)len;
  11302. (void)hash;
  11303. #endif
  11304. return ret;
  11305. }
  11306. #ifndef NO_CERTS
  11307. /* Get the hash of the id using the SHA-1 or SHA-256.
  11308. *
  11309. * If the id is not the length of the hash, then hash it.
  11310. *
  11311. * @param [in] id Id to get hash for.
  11312. * @param [in] len Length of id in bytes.
  11313. * @param [out] hash Buffer to hold hash.
  11314. * @return 0 on success.
  11315. * @return MEMORY_E when dynamic memory allocation fails.
  11316. */
  11317. static int GetHashId(const byte* id, int length, byte* hash)
  11318. {
  11319. int ret;
  11320. if (length == KEYID_SIZE) {
  11321. XMEMCPY(hash, id, (size_t)length);
  11322. ret = 0;
  11323. }
  11324. else {
  11325. ret = CalcHashId(id, (word32)length, hash);
  11326. }
  11327. return ret;
  11328. }
  11329. #endif /* !NO_CERTS */
  11330. #ifdef WOLFSSL_ASN_TEMPLATE
  11331. /* Id for email address. */
  11332. #define ASN_EMAIL 0x100
  11333. /* Id for domain component. */
  11334. #define ASN_DC 0x102
  11335. /* Id for jurisdiction country. */
  11336. #define ASN_JURIS_C 0x203
  11337. /* Id for jurisdiction state. */
  11338. #define ASN_JURIS_ST 0x202
  11339. /* Set the string for a name component into the subject name. */
  11340. #define SetCertNameSubject(cert, id, val) \
  11341. *((char**)(((byte *)(cert)) + certNameSubject[(id) - 3].data)) = (val)
  11342. /* Set the string length for a name component into the subject name. */
  11343. #define SetCertNameSubjectLen(cert, id, val) \
  11344. *((int*)(((byte *)(cert)) + certNameSubject[(id) - 3].len)) = (int)(val)
  11345. /* Set the encoding for a name component into the subject name. */
  11346. #define SetCertNameSubjectEnc(cert, id, val) \
  11347. *((byte*)(((byte *)(cert)) + certNameSubject[(id) - 3].enc)) = (val)
  11348. /* Get the string of a name component from the subject name. */
  11349. #define GetCertNameSubjectStr(id) \
  11350. (certNameSubject[(id) - 3].str)
  11351. /* Get the string length of a name component from the subject name. */
  11352. #define GetCertNameSubjectStrLen(id) \
  11353. (certNameSubject[(id) - 3].strLen)
  11354. /* Get the NID of a name component from the subject name. */
  11355. #define GetCertNameSubjectNID(id) \
  11356. (certNameSubject[(id) - 3].nid)
  11357. #define ValidCertNameSubject(id) \
  11358. (((id) - 3) >= 0 && ((id) - 3) < certNameSubjectSz && \
  11359. (certNameSubject[(id) - 3].strLen > 0))
  11360. /* Mapping of certificate name component to useful information. */
  11361. typedef struct CertNameData {
  11362. /* Type string of name component. */
  11363. const char* str;
  11364. /* Length of type string of name component. */
  11365. byte strLen;
  11366. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11367. /* Offset of data in subject name component. */
  11368. size_t data;
  11369. /* Offset of length in subject name component. */
  11370. size_t len;
  11371. /* Offset of encoding in subject name component. */
  11372. size_t enc;
  11373. #endif
  11374. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11375. /* NID of type for subject name component. */
  11376. int nid;
  11377. #endif
  11378. } CertNameData;
  11379. /* List of data for common name components. */
  11380. static const CertNameData certNameSubject[] = {
  11381. /* Common Name */
  11382. {
  11383. "/CN=", 4,
  11384. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11385. OFFSETOF(DecodedCert, subjectCN),
  11386. OFFSETOF(DecodedCert, subjectCNLen),
  11387. OFFSETOF(DecodedCert, subjectCNEnc),
  11388. #endif
  11389. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11390. NID_commonName
  11391. #endif
  11392. },
  11393. /* Surname */
  11394. {
  11395. "/SN=", 4,
  11396. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11397. OFFSETOF(DecodedCert, subjectSN),
  11398. OFFSETOF(DecodedCert, subjectSNLen),
  11399. OFFSETOF(DecodedCert, subjectSNEnc),
  11400. #endif
  11401. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11402. NID_surname
  11403. #endif
  11404. },
  11405. /* Serial Number */
  11406. {
  11407. "/serialNumber=", 14,
  11408. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11409. OFFSETOF(DecodedCert, subjectSND),
  11410. OFFSETOF(DecodedCert, subjectSNDLen),
  11411. OFFSETOF(DecodedCert, subjectSNDEnc),
  11412. #endif
  11413. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11414. NID_serialNumber
  11415. #endif
  11416. },
  11417. /* Country Name */
  11418. {
  11419. "/C=", 3,
  11420. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11421. OFFSETOF(DecodedCert, subjectC),
  11422. OFFSETOF(DecodedCert, subjectCLen),
  11423. OFFSETOF(DecodedCert, subjectCEnc),
  11424. #endif
  11425. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11426. NID_countryName
  11427. #endif
  11428. },
  11429. /* Locality Name */
  11430. {
  11431. "/L=", 3,
  11432. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11433. OFFSETOF(DecodedCert, subjectL),
  11434. OFFSETOF(DecodedCert, subjectLLen),
  11435. OFFSETOF(DecodedCert, subjectLEnc),
  11436. #endif
  11437. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11438. NID_localityName
  11439. #endif
  11440. },
  11441. /* State Name */
  11442. {
  11443. "/ST=", 4,
  11444. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11445. OFFSETOF(DecodedCert, subjectST),
  11446. OFFSETOF(DecodedCert, subjectSTLen),
  11447. OFFSETOF(DecodedCert, subjectSTEnc),
  11448. #endif
  11449. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11450. NID_stateOrProvinceName
  11451. #endif
  11452. },
  11453. /* Street Address */
  11454. {
  11455. "/street=", 8,
  11456. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11457. OFFSETOF(DecodedCert, subjectStreet),
  11458. OFFSETOF(DecodedCert, subjectStreetLen),
  11459. OFFSETOF(DecodedCert, subjectStreetEnc),
  11460. #endif
  11461. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11462. NID_streetAddress
  11463. #endif
  11464. },
  11465. /* Organization Name */
  11466. {
  11467. "/O=", 3,
  11468. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11469. OFFSETOF(DecodedCert, subjectO),
  11470. OFFSETOF(DecodedCert, subjectOLen),
  11471. OFFSETOF(DecodedCert, subjectOEnc),
  11472. #endif
  11473. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11474. NID_organizationName
  11475. #endif
  11476. },
  11477. /* Organization Unit Name */
  11478. {
  11479. "/OU=", 4,
  11480. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11481. OFFSETOF(DecodedCert, subjectOU),
  11482. OFFSETOF(DecodedCert, subjectOULen),
  11483. OFFSETOF(DecodedCert, subjectOUEnc),
  11484. #endif
  11485. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11486. NID_organizationalUnitName
  11487. #endif
  11488. },
  11489. /* Title */
  11490. {
  11491. NULL, 0,
  11492. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11493. 0,
  11494. 0,
  11495. 0,
  11496. #endif
  11497. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11498. 0,
  11499. #endif
  11500. },
  11501. /* Undefined */
  11502. {
  11503. NULL, 0,
  11504. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11505. 0,
  11506. 0,
  11507. 0,
  11508. #endif
  11509. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11510. 0,
  11511. #endif
  11512. },
  11513. /* Undefined */
  11514. {
  11515. NULL, 0,
  11516. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11517. 0,
  11518. 0,
  11519. 0,
  11520. #endif
  11521. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11522. 0,
  11523. #endif
  11524. },
  11525. /* Business Category */
  11526. {
  11527. "/businessCategory=", 18,
  11528. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11529. OFFSETOF(DecodedCert, subjectBC),
  11530. OFFSETOF(DecodedCert, subjectBCLen),
  11531. OFFSETOF(DecodedCert, subjectBCEnc),
  11532. #endif
  11533. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11534. NID_businessCategory
  11535. #endif
  11536. },
  11537. /* Undefined */
  11538. {
  11539. NULL, 0,
  11540. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11541. 0,
  11542. 0,
  11543. 0,
  11544. #endif
  11545. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11546. 0,
  11547. #endif
  11548. },
  11549. /* Postal Code */
  11550. {
  11551. "/postalCode=", 12,
  11552. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11553. OFFSETOF(DecodedCert, subjectPC),
  11554. OFFSETOF(DecodedCert, subjectPCLen),
  11555. OFFSETOF(DecodedCert, subjectPCEnc),
  11556. #endif
  11557. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11558. NID_postalCode
  11559. #endif
  11560. },
  11561. /* User Id */
  11562. {
  11563. "/userid=", 8,
  11564. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11565. OFFSETOF(DecodedCert, subjectUID),
  11566. OFFSETOF(DecodedCert, subjectUIDLen),
  11567. OFFSETOF(DecodedCert, subjectUIDEnc),
  11568. #endif
  11569. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11570. NID_userId
  11571. #endif
  11572. },
  11573. #ifdef WOLFSSL_CERT_NAME_ALL
  11574. /* Name, id 41 */
  11575. {
  11576. "/N=", 3,
  11577. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11578. OFFSETOF(DecodedCert, subjectN),
  11579. OFFSETOF(DecodedCert, subjectNLen),
  11580. OFFSETOF(DecodedCert, subjectNEnc),
  11581. #endif
  11582. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11583. NID_name
  11584. #endif
  11585. },
  11586. /* Given Name, id 42 */
  11587. {
  11588. "/GN=", 4,
  11589. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11590. OFFSETOF(DecodedCert, subjectGN),
  11591. OFFSETOF(DecodedCert, subjectGNLen),
  11592. OFFSETOF(DecodedCert, subjectGNEnc),
  11593. #endif
  11594. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11595. NID_givenName
  11596. #endif
  11597. },
  11598. /* initials, id 43 */
  11599. {
  11600. "/initials=", 10,
  11601. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11602. OFFSETOF(DecodedCert, subjectI),
  11603. OFFSETOF(DecodedCert, subjectILen),
  11604. OFFSETOF(DecodedCert, subjectIEnc),
  11605. #endif
  11606. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11607. NID_initials
  11608. #endif
  11609. },
  11610. /* DN Qualifier Name, id 46 */
  11611. {
  11612. "/dnQualifier=", 13,
  11613. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11614. OFFSETOF(DecodedCert, subjectDNQ),
  11615. OFFSETOF(DecodedCert, subjectDNQLen),
  11616. OFFSETOF(DecodedCert, subjectDNQEnc),
  11617. #endif
  11618. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11619. NID_dnQualifier
  11620. #endif
  11621. },
  11622. #endif /* WOLFSSL_CERT_NAME_ALL */
  11623. };
  11624. static const int certNameSubjectSz =
  11625. (int) (sizeof(certNameSubject) / sizeof(CertNameData));
  11626. /* ASN.1 template for an RDN.
  11627. * X.509: RFC 5280, 4.1.2.4 - RelativeDistinguishedName
  11628. */
  11629. static const ASNItem rdnASN[] = {
  11630. /* SET */ { 1, ASN_SET, 1, 1, 0 },
  11631. /* AttributeTypeAndValue */
  11632. /* ATTR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  11633. /* AttributeType */
  11634. /* ATTR_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  11635. /* AttributeValue: Choice of tags - rdnChoice. */
  11636. /* ATTR_VAL */ { 3, 0, 0, 0, 0 },
  11637. };
  11638. enum {
  11639. RDNASN_IDX_SET = 0,
  11640. RDNASN_IDX_ATTR_SEQ,
  11641. RDNASN_IDX_ATTR_TYPE,
  11642. RDNASN_IDX_ATTR_VAL
  11643. };
  11644. /* Number of items in ASN.1 template for an RDN. */
  11645. #define rdnASN_Length (sizeof(rdnASN) / sizeof(ASNItem))
  11646. /* Supported types of encodings (tags) for RDN strings.
  11647. * X.509: RFC 5280, 4.1.2.4 - DirectoryString
  11648. * (IA5 String not listed in RFC but required for alternative types)
  11649. */
  11650. static const byte rdnChoice[] = {
  11651. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, ASN_T61STRING,
  11652. ASN_UNIVERSALSTRING, ASN_BMPSTRING, 0
  11653. };
  11654. #endif
  11655. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  11656. /* used to set the human readable string for the IP address with a ASN_IP_TYPE
  11657. * DNS entry
  11658. * return 0 on success
  11659. */
  11660. static int GenerateDNSEntryIPString(DNS_entry* entry, void* heap)
  11661. {
  11662. int ret = 0;
  11663. int nameSz;
  11664. char tmpName[WOLFSSL_MAX_IPSTR] = {0};
  11665. char* ip;
  11666. if (entry == NULL || entry->type != ASN_IP_TYPE) {
  11667. return BAD_FUNC_ARG;
  11668. }
  11669. if (entry->len != WOLFSSL_IP4_ADDR_LEN &&
  11670. entry->len != WOLFSSL_IP6_ADDR_LEN) {
  11671. WOLFSSL_MSG("Unexpected IP size");
  11672. return BAD_FUNC_ARG;
  11673. }
  11674. ip = entry->name;
  11675. /* store IP addresses as a string */
  11676. if (entry->len == WOLFSSL_IP4_ADDR_LEN) {
  11677. if (XSNPRINTF(tmpName, sizeof(tmpName), "%u.%u.%u.%u", 0xFFU & ip[0],
  11678. 0xFFU & ip[1], 0xFFU & ip[2], 0xFFU & ip[3])
  11679. >= (int)sizeof(tmpName))
  11680. {
  11681. WOLFSSL_MSG("IP buffer overrun");
  11682. return BUFFER_E;
  11683. }
  11684. }
  11685. if (entry->len == WOLFSSL_IP6_ADDR_LEN) {
  11686. int i;
  11687. for (i = 0; i < 8; i++) {
  11688. if (XSNPRINTF(tmpName + i * 5, sizeof(tmpName) - i * 5,
  11689. "%02X%02X%s", 0xFF & ip[2 * i], 0xFF & ip[2 * i + 1],
  11690. (i < 7) ? ":" : "")
  11691. >= (int)sizeof(tmpName))
  11692. {
  11693. WOLFSSL_MSG("IPv6 buffer overrun");
  11694. return BUFFER_E;
  11695. }
  11696. }
  11697. }
  11698. nameSz = (int)XSTRLEN(tmpName);
  11699. entry->ipString = (char*)XMALLOC(nameSz + 1, heap, DYNAMIC_TYPE_ALTNAME);
  11700. if (entry->ipString == NULL) {
  11701. ret = MEMORY_E;
  11702. }
  11703. if (ret == 0) {
  11704. XMEMCPY(entry->ipString, tmpName, nameSz);
  11705. entry->ipString[nameSz] = '\0';
  11706. }
  11707. (void)heap;
  11708. return ret;
  11709. }
  11710. #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  11711. #ifdef WOLFSSL_ASN_TEMPLATE
  11712. #if defined(WOLFSSL_CERT_GEN) || !defined(NO_CERTS)
  11713. /* Adds a DNS entry to a list of DNS entries
  11714. *
  11715. * @param [in, out] lst Linked list of DNS name entries.
  11716. * @param [in] entry Entry to add to the list
  11717. * @return 0 on success.
  11718. */
  11719. static int AddDNSEntryToList(DNS_entry** lst, DNS_entry* entry)
  11720. {
  11721. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  11722. entry->next = NULL;
  11723. if (*lst == NULL) {
  11724. /* First on list */
  11725. *lst = entry;
  11726. }
  11727. else {
  11728. DNS_entry* temp = *lst;
  11729. /* Find end */
  11730. for (; (temp->next != NULL); temp = temp->next);
  11731. /* Add to end */
  11732. temp->next = entry;
  11733. }
  11734. #else
  11735. /* Prepend entry to linked list. */
  11736. entry->next = *lst;
  11737. *lst = entry;
  11738. #endif
  11739. return 0;
  11740. }
  11741. /* Allocate a DNS entry and set the fields.
  11742. *
  11743. * @param [in] cert Certificate object.
  11744. * @param [in] str DNS name string.
  11745. * @param [in] strLen Length of DNS name string.
  11746. * @param [in] type Type of DNS name string.
  11747. * @param [in, out] entries Linked list of DNS name entries.
  11748. * @return 0 on success.
  11749. * @return MEMORY_E when dynamic memory allocation fails.
  11750. */
  11751. static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen,
  11752. int type, DNS_entry** entries)
  11753. {
  11754. DNS_entry* dnsEntry;
  11755. int ret = 0;
  11756. /* Only used for heap. */
  11757. (void)cert;
  11758. /* TODO: consider one malloc. */
  11759. /* Allocate DNS Entry object. */
  11760. dnsEntry = AltNameNew(cert->heap);
  11761. if (dnsEntry == NULL) {
  11762. ret = MEMORY_E;
  11763. }
  11764. if (ret == 0) {
  11765. /* Allocate DNS Entry name - length of string plus 1 for NUL. */
  11766. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  11767. DYNAMIC_TYPE_ALTNAME);
  11768. if (dnsEntry->name == NULL) {
  11769. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11770. ret = MEMORY_E;
  11771. }
  11772. }
  11773. if (ret == 0) {
  11774. /* Set tag type, name length, name and NUL terminate name. */
  11775. dnsEntry->type = type;
  11776. dnsEntry->len = strLen;
  11777. XMEMCPY(dnsEntry->name, str, (size_t)strLen);
  11778. dnsEntry->name[strLen] = '\0';
  11779. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  11780. /* store IP addresses as a string */
  11781. if (type == ASN_IP_TYPE) {
  11782. if ((ret = GenerateDNSEntryIPString(dnsEntry, cert->heap)) != 0) {
  11783. XFREE(dnsEntry->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11784. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11785. }
  11786. }
  11787. }
  11788. if (ret == 0) {
  11789. #endif
  11790. ret = AddDNSEntryToList(entries, dnsEntry);
  11791. }
  11792. return ret;
  11793. }
  11794. #endif
  11795. /* Set the details of a subject name component into a certificate.
  11796. *
  11797. * @param [in, out] cert Certificate object.
  11798. * @param [in] id Id of component.
  11799. * @param [in] str String for component.
  11800. * @param [in] strLen Length of string.
  11801. * @param [in] tag BER tag representing encoding of string.
  11802. * @return 0 on success, negative values on failure.
  11803. */
  11804. static int SetSubject(DecodedCert* cert, int id, byte* str, int strLen,
  11805. byte tag)
  11806. {
  11807. int ret = 0;
  11808. /* Put string and encoding into certificate. */
  11809. if (id == ASN_COMMON_NAME) {
  11810. cert->subjectCN = (char *)str;
  11811. cert->subjectCNLen = (int)strLen;
  11812. cert->subjectCNEnc = (char)tag;
  11813. }
  11814. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11815. else if (id > ASN_COMMON_NAME && id <= ASN_USER_ID) {
  11816. /* Use table and offsets to put data into appropriate fields. */
  11817. SetCertNameSubject(cert, id, (char*)str);
  11818. SetCertNameSubjectLen(cert, id, strLen);
  11819. SetCertNameSubjectEnc(cert, id, tag);
  11820. }
  11821. #endif
  11822. #if !defined(IGNORE_NAME_CONSTRAINTS) || \
  11823. defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11824. else if (id == ASN_EMAIL) {
  11825. cert->subjectEmail = (char*)str;
  11826. cert->subjectEmailLen = strLen;
  11827. }
  11828. #endif
  11829. #ifdef WOLFSSL_CERT_EXT
  11830. /* TODO: consider mapping id to an index and using SetCertNameSubect*(). */
  11831. else if (id == ASN_JURIS_C) {
  11832. cert->subjectJC = (char*)str;
  11833. cert->subjectJCLen = strLen;
  11834. cert->subjectJCEnc = (char)tag;
  11835. }
  11836. else if (id == ASN_JURIS_ST) {
  11837. cert->subjectJS = (char*)str;
  11838. cert->subjectJSLen = strLen;
  11839. cert->subjectJSEnc = (char)tag;
  11840. }
  11841. #endif
  11842. return ret;
  11843. }
  11844. /* Get a RelativeDistinguishedName from the encoding and put in certificate.
  11845. *
  11846. * @param [in, out] cert Certificate object.
  11847. * @param [in, out] full Full name string. ([/<type>=<value>]*)
  11848. * @param [in, out] idx Index int full name to place next component.
  11849. * @param [in, out] nid NID of component type.
  11850. * @param [in] isSubject Whether this data is for a subject name.
  11851. * @param [in] dataASN Decoded data of RDN. Expected rdnASN type.
  11852. * @return 0 on success.
  11853. * @return MEMORY_E when dynamic memory allocation fails.
  11854. * @return ASN_PARSE_E when type not supported.
  11855. */
  11856. static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid,
  11857. int isSubject, ASNGetData* dataASN)
  11858. {
  11859. int ret = 0;
  11860. const char* typeStr = NULL;
  11861. byte typeStrLen = 0;
  11862. byte* oid;
  11863. word32 oidSz;
  11864. int id = 0;
  11865. (void)nid;
  11866. /* Get name type OID from data items. */
  11867. GetASN_OIDData(&dataASN[RDNASN_IDX_ATTR_TYPE], &oid, &oidSz);
  11868. /* v1 name types */
  11869. if ((oidSz == 3) && (oid[0] == 0x55) && (oid[1] == 0x04)) {
  11870. id = oid[2];
  11871. /* Check range of supported ids in table. */
  11872. if (ValidCertNameSubject(id)) {
  11873. /* Get the type string, length and NID from table. */
  11874. typeStr = GetCertNameSubjectStr(id);
  11875. typeStrLen = GetCertNameSubjectStrLen(id);
  11876. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11877. *nid = GetCertNameSubjectNID(id);
  11878. #endif
  11879. }
  11880. }
  11881. else if (oidSz == sizeof(attrEmailOid) && XMEMCMP(oid, attrEmailOid, oidSz) == 0) {
  11882. /* Set the email id, type string, length and NID. */
  11883. id = ASN_EMAIL;
  11884. typeStr = WOLFSSL_EMAIL_ADDR;
  11885. typeStrLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  11886. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11887. *nid = NID_emailAddress;
  11888. #endif
  11889. }
  11890. else if (oidSz == sizeof(uidOid) && XMEMCMP(oid, uidOid, oidSz) == 0) {
  11891. /* Set the user id, type string, length and NID. */
  11892. id = ASN_USER_ID;
  11893. typeStr = WOLFSSL_USER_ID;
  11894. typeStrLen = sizeof(WOLFSSL_USER_ID) - 1;
  11895. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11896. *nid = NID_userId;
  11897. #endif
  11898. }
  11899. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz) == 0) {
  11900. /* Set the domain component, type string, length and NID. */
  11901. id = ASN_DC;
  11902. typeStr = WOLFSSL_DOMAIN_COMPONENT;
  11903. typeStrLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  11904. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11905. *nid = NID_domainComponent;
  11906. #endif
  11907. }
  11908. else if (oidSz == sizeof(fvrtDrk) && XMEMCMP(oid, fvrtDrk, oidSz) == 0) {
  11909. /* Set the favourite drink, type string, length and NID. */
  11910. id = ASN_FAVOURITE_DRINK;
  11911. typeStr = WOLFSSL_FAVOURITE_DRINK;
  11912. typeStrLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
  11913. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11914. *nid = NID_favouriteDrink;
  11915. #endif
  11916. }
  11917. /* Other OIDs that start with the same values. */
  11918. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz-1) == 0) {
  11919. WOLFSSL_MSG("Unknown pilot attribute type");
  11920. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  11921. ret = ASN_PARSE_E;
  11922. }
  11923. else if (oidSz == ASN_JOI_PREFIX_SZ + 1 &&
  11924. XMEMCMP(oid, ASN_JOI_PREFIX, ASN_JOI_PREFIX_SZ) == 0) {
  11925. /* Set the jurisdiction id. */
  11926. id = 0x200 + oid[ASN_JOI_PREFIX_SZ];
  11927. /* Set the jurisdiction type string, length and NID if known. */
  11928. if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_C) {
  11929. typeStr = WOLFSSL_JOI_C;
  11930. typeStrLen = sizeof(WOLFSSL_JOI_C) - 1;
  11931. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11932. *nid = NID_jurisdictionCountryName;
  11933. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  11934. }
  11935. else if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_ST) {
  11936. typeStr = WOLFSSL_JOI_ST;
  11937. typeStrLen = sizeof(WOLFSSL_JOI_ST) - 1;
  11938. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11939. *nid = NID_jurisdictionStateOrProvinceName;
  11940. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  11941. }
  11942. else {
  11943. WOLFSSL_MSG("Unknown Jurisdiction, skipping");
  11944. }
  11945. }
  11946. if ((ret == 0) && (typeStr != NULL)) {
  11947. /* OID type to store for subject name and add to full string. */
  11948. byte* str;
  11949. word32 strLen;
  11950. byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
  11951. /* Get the string reference and length. */
  11952. GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
  11953. if (isSubject) {
  11954. /* Store subject field components. */
  11955. ret = SetSubject(cert, id, str, (int)strLen, tag);
  11956. }
  11957. if (ret == 0) {
  11958. /* Check there is space for this in the full name string and
  11959. * terminating NUL character. */
  11960. if ((typeStrLen + strLen) < (word32)(WC_ASN_NAME_MAX - *idx))
  11961. {
  11962. /* Add RDN to full string. */
  11963. XMEMCPY(&full[*idx], typeStr, typeStrLen);
  11964. *idx += typeStrLen;
  11965. XMEMCPY(&full[*idx], str, strLen);
  11966. *idx += strLen;
  11967. }
  11968. else {
  11969. WOLFSSL_MSG("ASN Name too big, skipping");
  11970. }
  11971. }
  11972. }
  11973. return ret;
  11974. }
  11975. #endif /* WOLFSSL_ASN_TEMPLATE */
  11976. /* Get a certificate name into the certificate object.
  11977. *
  11978. * @param [in, out] cert Decoded certificate object.
  11979. * @param [out] full Buffer to hold full name as a string.
  11980. * @param [out] hash Buffer to hold hash of name.
  11981. * @param [in] nameType ISSUER or SUBJECT.
  11982. * @param [in] input Buffer holding certificate name.
  11983. * @param [in, out] inOutIdx On in, start of certificate name.
  11984. * On out, start of ASN.1 item after cert name.
  11985. * @param [in] maxIdx Index of next item after certificate name.
  11986. * @return 0 on success.
  11987. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  11988. * is invalid.
  11989. * @return BUFFER_E when data in buffer is too small.
  11990. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  11991. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  11992. * @return MEMORY_E when dynamic memory allocation fails.
  11993. */
  11994. static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType,
  11995. const byte* input, word32* inOutIdx, word32 maxIdx)
  11996. {
  11997. #ifndef WOLFSSL_ASN_TEMPLATE
  11998. int length; /* length of all distinguished names */
  11999. int dummy;
  12000. int ret;
  12001. word32 idx;
  12002. word32 srcIdx = *inOutIdx;
  12003. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12004. !defined(WOLFCRYPT_ONLY)
  12005. WOLFSSL_X509_NAME* dName = NULL;
  12006. #endif
  12007. WOLFSSL_MSG("Getting Cert Name");
  12008. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  12009. * calculated over the entire DER encoding of the Name field, including
  12010. * the tag and length. */
  12011. if (CalcHashId(input + *inOutIdx, maxIdx - *inOutIdx, hash) != 0)
  12012. return ASN_PARSE_E;
  12013. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12014. !defined(WOLFCRYPT_ONLY)
  12015. dName = wolfSSL_X509_NAME_new_ex(cert->heap);
  12016. if (dName == NULL) {
  12017. return MEMORY_E;
  12018. }
  12019. #endif /* OPENSSL_EXTRA */
  12020. if (GetSequence(input, &srcIdx, &length, maxIdx) < 0) {
  12021. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12022. !defined(WOLFCRYPT_ONLY)
  12023. wolfSSL_X509_NAME_free(dName);
  12024. #endif /* OPENSSL_EXTRA */
  12025. return ASN_PARSE_E;
  12026. }
  12027. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  12028. /* store pointer to raw issuer */
  12029. if (nameType == ISSUER) {
  12030. cert->issuerRaw = &input[srcIdx];
  12031. cert->issuerRawLen = length;
  12032. }
  12033. #endif
  12034. #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
  12035. if (nameType == SUBJECT) {
  12036. cert->subjectRaw = &input[srcIdx];
  12037. cert->subjectRawLen = length;
  12038. }
  12039. #endif
  12040. length += (int)srcIdx;
  12041. idx = 0;
  12042. while (srcIdx < (word32)length) {
  12043. byte b = 0;
  12044. byte joint[3];
  12045. byte tooBig = FALSE;
  12046. int oidSz;
  12047. const char* copy = NULL;
  12048. int copyLen = 0;
  12049. int strLen = 0;
  12050. byte id = 0;
  12051. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  12052. && !defined(WOLFCRYPT_ONLY)
  12053. int nid = NID_undef;
  12054. int enc;
  12055. #endif /* OPENSSL_EXTRA */
  12056. if (GetSet(input, &srcIdx, &dummy, maxIdx) < 0) {
  12057. WOLFSSL_MSG("Cert name lacks set header, trying sequence");
  12058. }
  12059. if (GetSequence(input, &srcIdx, &dummy, maxIdx) <= 0) {
  12060. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12061. !defined(WOLFCRYPT_ONLY)
  12062. wolfSSL_X509_NAME_free(dName);
  12063. #endif /* OPENSSL_EXTRA */
  12064. return ASN_PARSE_E;
  12065. }
  12066. ret = GetASNObjectId(input, &srcIdx, &oidSz, maxIdx);
  12067. if (ret != 0) {
  12068. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12069. !defined(WOLFCRYPT_ONLY)
  12070. wolfSSL_X509_NAME_free(dName);
  12071. #endif /* OPENSSL_EXTRA */
  12072. return ret;
  12073. }
  12074. /* make sure there is room for joint */
  12075. if ((srcIdx + sizeof(joint)) > (word32)maxIdx) {
  12076. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12077. !defined(WOLFCRYPT_ONLY)
  12078. wolfSSL_X509_NAME_free(dName);
  12079. #endif /* OPENSSL_EXTRA */
  12080. return ASN_PARSE_E;
  12081. }
  12082. XMEMCPY(joint, &input[srcIdx], sizeof(joint));
  12083. /* v1 name types */
  12084. if (joint[0] == 0x55 && joint[1] == 0x04) {
  12085. srcIdx += 3;
  12086. id = joint[2];
  12087. if (GetHeader(input, &b, &srcIdx, &strLen, maxIdx, 1) < 0) {
  12088. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12089. !defined(WOLFCRYPT_ONLY)
  12090. wolfSSL_X509_NAME_free(dName);
  12091. #endif /* OPENSSL_EXTRA */
  12092. return ASN_PARSE_E;
  12093. }
  12094. if (id == ASN_COMMON_NAME) {
  12095. if (nameType == SUBJECT) {
  12096. cert->subjectCN = (char *)&input[srcIdx];
  12097. cert->subjectCNLen = strLen;
  12098. cert->subjectCNEnc = (char)b;
  12099. }
  12100. #if (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)) && \
  12101. defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12102. else if (nameType == ISSUER) {
  12103. cert->issuerCN = (char*)&input[srcIdx];
  12104. cert->issuerCNLen = strLen;
  12105. cert->issuerCNEnc = (char)b;
  12106. }
  12107. #endif
  12108. copy = WOLFSSL_COMMON_NAME;
  12109. copyLen = sizeof(WOLFSSL_COMMON_NAME) - 1;
  12110. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  12111. && !defined(WOLFCRYPT_ONLY)
  12112. nid = NID_commonName;
  12113. #endif /* OPENSSL_EXTRA */
  12114. }
  12115. #ifdef WOLFSSL_CERT_NAME_ALL
  12116. else if (id == ASN_NAME) {
  12117. copy = WOLFSSL_NAME;
  12118. copyLen = sizeof(WOLFSSL_NAME) - 1;
  12119. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12120. if (nameType == SUBJECT) {
  12121. cert->subjectN = (char*)&input[srcIdx];
  12122. cert->subjectNLen = strLen;
  12123. cert->subjectNEnc = b;
  12124. }
  12125. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12126. #if (defined(OPENSSL_EXTRA) || \
  12127. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12128. && !defined(WOLFCRYPT_ONLY)
  12129. nid = NID_name;
  12130. #endif /* OPENSSL_EXTRA */
  12131. }
  12132. else if (id == ASN_INITIALS) {
  12133. copy = WOLFSSL_INITIALS;
  12134. copyLen = sizeof(WOLFSSL_INITIALS) - 1;
  12135. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12136. if (nameType == SUBJECT) {
  12137. cert->subjectI = (char*)&input[srcIdx];
  12138. cert->subjectILen = strLen;
  12139. cert->subjectIEnc = b;
  12140. }
  12141. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12142. #if (defined(OPENSSL_EXTRA) || \
  12143. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12144. && !defined(WOLFCRYPT_ONLY)
  12145. nid = NID_initials;
  12146. #endif /* OPENSSL_EXTRA */
  12147. }
  12148. else if (id == ASN_GIVEN_NAME) {
  12149. copy = WOLFSSL_GIVEN_NAME;
  12150. copyLen = sizeof(WOLFSSL_GIVEN_NAME) - 1;
  12151. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12152. if (nameType == SUBJECT) {
  12153. cert->subjectGN = (char*)&input[srcIdx];
  12154. cert->subjectGNLen = strLen;
  12155. cert->subjectGNEnc = b;
  12156. }
  12157. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12158. #if (defined(OPENSSL_EXTRA) || \
  12159. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12160. && !defined(WOLFCRYPT_ONLY)
  12161. nid = NID_givenName;
  12162. #endif /* OPENSSL_EXTRA */
  12163. }
  12164. else if (id == ASN_DNQUALIFIER) {
  12165. copy = WOLFSSL_DNQUALIFIER;
  12166. copyLen = sizeof(WOLFSSL_DNQUALIFIER) - 1;
  12167. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12168. if (nameType == SUBJECT) {
  12169. cert->subjectDNQ = (char*)&input[srcIdx];
  12170. cert->subjectDNQLen = strLen;
  12171. cert->subjectDNQEnc = b;
  12172. }
  12173. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12174. #if (defined(OPENSSL_EXTRA) || \
  12175. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12176. && !defined(WOLFCRYPT_ONLY)
  12177. nid = NID_dnQualifier;
  12178. #endif /* OPENSSL_EXTRA */
  12179. }
  12180. #endif /* WOLFSSL_CERT_NAME_ALL */
  12181. else if (id == ASN_SUR_NAME) {
  12182. copy = WOLFSSL_SUR_NAME;
  12183. copyLen = sizeof(WOLFSSL_SUR_NAME) - 1;
  12184. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12185. if (nameType == SUBJECT) {
  12186. cert->subjectSN = (char*)&input[srcIdx];
  12187. cert->subjectSNLen = strLen;
  12188. cert->subjectSNEnc = (char)b;
  12189. }
  12190. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12191. else if (nameType == ISSUER) {
  12192. cert->issuerSN = (char*)&input[srcIdx];
  12193. cert->issuerSNLen = strLen;
  12194. cert->issuerSNEnc = (char)b;
  12195. }
  12196. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12197. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12198. #if (defined(OPENSSL_EXTRA) || \
  12199. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12200. && !defined(WOLFCRYPT_ONLY)
  12201. nid = NID_surname;
  12202. #endif /* OPENSSL_EXTRA */
  12203. }
  12204. else if (id == ASN_COUNTRY_NAME) {
  12205. copy = WOLFSSL_COUNTRY_NAME;
  12206. copyLen = sizeof(WOLFSSL_COUNTRY_NAME) - 1;
  12207. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12208. if (nameType == SUBJECT) {
  12209. cert->subjectC = (char*)&input[srcIdx];
  12210. cert->subjectCLen = strLen;
  12211. cert->subjectCEnc = (char)b;
  12212. }
  12213. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12214. else if (nameType == ISSUER) {
  12215. cert->issuerC = (char*)&input[srcIdx];
  12216. cert->issuerCLen = strLen;
  12217. cert->issuerCEnc = (char)b;
  12218. }
  12219. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12220. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12221. #if (defined(OPENSSL_EXTRA) || \
  12222. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12223. && !defined(WOLFCRYPT_ONLY)
  12224. nid = NID_countryName;
  12225. #endif /* OPENSSL_EXTRA */
  12226. }
  12227. else if (id == ASN_LOCALITY_NAME) {
  12228. copy = WOLFSSL_LOCALITY_NAME;
  12229. copyLen = sizeof(WOLFSSL_LOCALITY_NAME) - 1;
  12230. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12231. if (nameType == SUBJECT) {
  12232. cert->subjectL = (char*)&input[srcIdx];
  12233. cert->subjectLLen = strLen;
  12234. cert->subjectLEnc = (char)b;
  12235. }
  12236. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12237. else if (nameType == ISSUER) {
  12238. cert->issuerL = (char*)&input[srcIdx];
  12239. cert->issuerLLen = strLen;
  12240. cert->issuerLEnc = (char)b;
  12241. }
  12242. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12243. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12244. #if (defined(OPENSSL_EXTRA) || \
  12245. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12246. && !defined(WOLFCRYPT_ONLY)
  12247. nid = NID_localityName;
  12248. #endif /* OPENSSL_EXTRA */
  12249. }
  12250. else if (id == ASN_STATE_NAME) {
  12251. copy = WOLFSSL_STATE_NAME;
  12252. copyLen = sizeof(WOLFSSL_STATE_NAME) - 1;
  12253. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12254. if (nameType == SUBJECT) {
  12255. cert->subjectST = (char*)&input[srcIdx];
  12256. cert->subjectSTLen = strLen;
  12257. cert->subjectSTEnc = (char)b;
  12258. }
  12259. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12260. else if (nameType == ISSUER) {
  12261. cert->issuerST = (char*)&input[srcIdx];
  12262. cert->issuerSTLen = strLen;
  12263. cert->issuerSTEnc = (char)b;
  12264. }
  12265. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12266. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
  12267. #if (defined(OPENSSL_EXTRA) || \
  12268. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12269. && !defined(WOLFCRYPT_ONLY)
  12270. nid = NID_stateOrProvinceName;
  12271. #endif /* OPENSSL_EXTRA */
  12272. }
  12273. else if (id == ASN_ORG_NAME) {
  12274. copy = WOLFSSL_ORG_NAME;
  12275. copyLen = sizeof(WOLFSSL_ORG_NAME) - 1;
  12276. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12277. if (nameType == SUBJECT) {
  12278. cert->subjectO = (char*)&input[srcIdx];
  12279. cert->subjectOLen = strLen;
  12280. cert->subjectOEnc = (char)b;
  12281. }
  12282. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12283. else if (nameType == ISSUER) {
  12284. cert->issuerO = (char*)&input[srcIdx];
  12285. cert->issuerOLen = strLen;
  12286. cert->issuerOEnc = (char)b;
  12287. }
  12288. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12289. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12290. #if (defined(OPENSSL_EXTRA) || \
  12291. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12292. && !defined(WOLFCRYPT_ONLY)
  12293. nid = NID_organizationName;
  12294. #endif /* OPENSSL_EXTRA */
  12295. }
  12296. else if (id == ASN_ORGUNIT_NAME) {
  12297. copy = WOLFSSL_ORGUNIT_NAME;
  12298. copyLen = sizeof(WOLFSSL_ORGUNIT_NAME) - 1;
  12299. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12300. if (nameType == SUBJECT) {
  12301. cert->subjectOU = (char*)&input[srcIdx];
  12302. cert->subjectOULen = strLen;
  12303. cert->subjectOUEnc = (char)b;
  12304. }
  12305. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12306. else if (nameType == ISSUER) {
  12307. cert->issuerOU = (char*)&input[srcIdx];
  12308. cert->issuerOULen = strLen;
  12309. cert->issuerOUEnc = (char)b;
  12310. }
  12311. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12312. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12313. #if (defined(OPENSSL_EXTRA) || \
  12314. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12315. && !defined(WOLFCRYPT_ONLY)
  12316. nid = NID_organizationalUnitName;
  12317. #endif /* OPENSSL_EXTRA */
  12318. }
  12319. else if (id == ASN_SERIAL_NUMBER) {
  12320. copy = WOLFSSL_SERIAL_NUMBER;
  12321. copyLen = sizeof(WOLFSSL_SERIAL_NUMBER) - 1;
  12322. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12323. if (nameType == SUBJECT) {
  12324. cert->subjectSND = (char*)&input[srcIdx];
  12325. cert->subjectSNDLen = strLen;
  12326. cert->subjectSNDEnc = (char)b;
  12327. }
  12328. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12329. else if (nameType == ISSUER) {
  12330. cert->issuerSND = (char*)&input[srcIdx];
  12331. cert->issuerSNDLen = strLen;
  12332. cert->issuerSNDEnc = (char)b;
  12333. }
  12334. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12335. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12336. #if (defined(OPENSSL_EXTRA) || \
  12337. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12338. && !defined(WOLFCRYPT_ONLY)
  12339. nid = NID_serialNumber;
  12340. #endif /* OPENSSL_EXTRA */
  12341. }
  12342. else if (id == ASN_USER_ID) {
  12343. copy = WOLFSSL_USER_ID;
  12344. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  12345. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12346. if (nameType == SUBJECT) {
  12347. cert->subjectUID = (char*)&input[srcIdx];
  12348. cert->subjectUIDLen = strLen;
  12349. cert->subjectUIDEnc = (char)b;
  12350. }
  12351. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12352. #if (defined(OPENSSL_EXTRA) || \
  12353. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12354. && !defined(WOLFCRYPT_ONLY)
  12355. nid = NID_userId;
  12356. #endif /* OPENSSL_EXTRA */
  12357. }
  12358. #ifdef WOLFSSL_CERT_EXT
  12359. else if (id == ASN_STREET_ADDR) {
  12360. copy = WOLFSSL_STREET_ADDR_NAME;
  12361. copyLen = sizeof(WOLFSSL_STREET_ADDR_NAME) - 1;
  12362. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12363. if (nameType == SUBJECT) {
  12364. cert->subjectStreet = (char*)&input[srcIdx];
  12365. cert->subjectStreetLen = strLen;
  12366. cert->subjectStreetEnc = (char)b;
  12367. }
  12368. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12369. #if (defined(OPENSSL_EXTRA) || \
  12370. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12371. && !defined(WOLFCRYPT_ONLY)
  12372. nid = NID_streetAddress;
  12373. #endif /* OPENSSL_EXTRA */
  12374. }
  12375. else if (id == ASN_BUS_CAT) {
  12376. copy = WOLFSSL_BUS_CAT;
  12377. copyLen = sizeof(WOLFSSL_BUS_CAT) - 1;
  12378. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12379. if (nameType == SUBJECT) {
  12380. cert->subjectBC = (char*)&input[srcIdx];
  12381. cert->subjectBCLen = strLen;
  12382. cert->subjectBCEnc = (char)b;
  12383. }
  12384. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12385. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  12386. && !defined(WOLFCRYPT_ONLY)
  12387. nid = NID_businessCategory;
  12388. #endif /* OPENSSL_EXTRA */
  12389. }
  12390. else if (id == ASN_POSTAL_CODE) {
  12391. copy = WOLFSSL_POSTAL_NAME;
  12392. copyLen = sizeof(WOLFSSL_POSTAL_NAME) - 1;
  12393. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12394. if (nameType == SUBJECT) {
  12395. cert->subjectPC = (char*)&input[srcIdx];
  12396. cert->subjectPCLen = strLen;
  12397. cert->subjectPCEnc = (char)b;
  12398. }
  12399. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
  12400. #if (defined(OPENSSL_EXTRA) || \
  12401. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12402. && !defined(WOLFCRYPT_ONLY)
  12403. nid = NID_postalCode;
  12404. #endif /* OPENSSL_EXTRA */
  12405. }
  12406. #endif /* WOLFSSL_CERT_EXT */
  12407. }
  12408. #ifdef WOLFSSL_CERT_EXT
  12409. else if ((srcIdx + ASN_JOI_PREFIX_SZ + 2 <= (word32)maxIdx) &&
  12410. (0 == XMEMCMP(&input[srcIdx], ASN_JOI_PREFIX,
  12411. ASN_JOI_PREFIX_SZ)) &&
  12412. ((input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_C) ||
  12413. (input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_ST)))
  12414. {
  12415. srcIdx += ASN_JOI_PREFIX_SZ;
  12416. id = input[srcIdx++];
  12417. b = input[srcIdx++]; /* encoding */
  12418. if (GetLength(input, &srcIdx, &strLen,
  12419. maxIdx) < 0) {
  12420. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12421. !defined(WOLFCRYPT_ONLY)
  12422. wolfSSL_X509_NAME_free(dName);
  12423. #endif /* OPENSSL_EXTRA */
  12424. return ASN_PARSE_E;
  12425. }
  12426. /* Check for jurisdiction of incorporation country name */
  12427. if (id == ASN_JOI_C) {
  12428. copy = WOLFSSL_JOI_C;
  12429. copyLen = sizeof(WOLFSSL_JOI_C) - 1;
  12430. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12431. if (nameType == SUBJECT) {
  12432. cert->subjectJC = (char*)&input[srcIdx];
  12433. cert->subjectJCLen = strLen;
  12434. cert->subjectJCEnc = (char)b;
  12435. }
  12436. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12437. #if (defined(OPENSSL_EXTRA) || \
  12438. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12439. && !defined(WOLFCRYPT_ONLY)
  12440. nid = NID_jurisdictionCountryName;
  12441. #endif /* OPENSSL_EXTRA */
  12442. }
  12443. /* Check for jurisdiction of incorporation state name */
  12444. else if (id == ASN_JOI_ST) {
  12445. copy = WOLFSSL_JOI_ST;
  12446. copyLen = sizeof(WOLFSSL_JOI_ST) - 1;
  12447. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12448. if (nameType == SUBJECT) {
  12449. cert->subjectJS = (char*)&input[srcIdx];
  12450. cert->subjectJSLen = strLen;
  12451. cert->subjectJSEnc = (char)b;
  12452. }
  12453. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12454. #if (defined(OPENSSL_EXTRA) || \
  12455. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12456. && !defined(WOLFCRYPT_ONLY)
  12457. nid = NID_jurisdictionStateOrProvinceName;
  12458. #endif /* OPENSSL_EXTRA */
  12459. }
  12460. if ((strLen + copyLen) > (int)(WC_ASN_NAME_MAX - idx)) {
  12461. WOLFSSL_MSG("ASN Name too big, skipping");
  12462. tooBig = TRUE;
  12463. }
  12464. }
  12465. #endif /* WOLFSSL_CERT_EXT */
  12466. else {
  12467. /* skip */
  12468. byte email = FALSE;
  12469. byte pilot = FALSE;
  12470. if (joint[0] == 0x2a && joint[1] == 0x86) { /* email id hdr 42.134.* */
  12471. id = ASN_EMAIL_NAME;
  12472. email = TRUE;
  12473. }
  12474. if (joint[0] == 0x9 && joint[1] == 0x92) { /* uid id hdr 9.146.* */
  12475. /* last value of OID is the type of pilot attribute */
  12476. id = input[srcIdx + (word32)oidSz - 1];
  12477. if (id == 0x01)
  12478. id = ASN_USER_ID;
  12479. pilot = TRUE;
  12480. }
  12481. srcIdx += (word32)oidSz + 1;
  12482. if (GetLength(input, &srcIdx, &strLen, maxIdx) < 0) {
  12483. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12484. !defined(WOLFCRYPT_ONLY)
  12485. wolfSSL_X509_NAME_free(dName);
  12486. #endif /* OPENSSL_EXTRA */
  12487. return ASN_PARSE_E;
  12488. }
  12489. if (strLen > (int)(WC_ASN_NAME_MAX - idx)) {
  12490. WOLFSSL_MSG("ASN name too big, skipping");
  12491. tooBig = TRUE;
  12492. }
  12493. if (email) {
  12494. copyLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  12495. if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx)) {
  12496. WOLFSSL_MSG("ASN name too big, skipping");
  12497. tooBig = TRUE;
  12498. }
  12499. else {
  12500. copy = WOLFSSL_EMAIL_ADDR;
  12501. }
  12502. #if !defined(IGNORE_NAME_CONSTRAINTS) || \
  12503. defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12504. if (nameType == SUBJECT) {
  12505. cert->subjectEmail = (char*)&input[srcIdx];
  12506. cert->subjectEmailLen = strLen;
  12507. }
  12508. #if defined(WOLFSSL_HAVE_ISSUER_NAMES) && \
  12509. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
  12510. else if (nameType == ISSUER) {
  12511. cert->issuerEmail = (char*)&input[srcIdx];
  12512. cert->issuerEmailLen = strLen;
  12513. }
  12514. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12515. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12516. #if (defined(OPENSSL_EXTRA) || \
  12517. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12518. && !defined(WOLFCRYPT_ONLY)
  12519. nid = NID_emailAddress;
  12520. #endif /* OPENSSL_EXTRA */
  12521. }
  12522. if (pilot) {
  12523. switch (id) {
  12524. case ASN_USER_ID:
  12525. copy = WOLFSSL_USER_ID;
  12526. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  12527. #if (defined(OPENSSL_EXTRA) || \
  12528. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12529. && !defined(WOLFCRYPT_ONLY)
  12530. nid = NID_userId;
  12531. #endif /* OPENSSL_EXTRA */
  12532. break;
  12533. case ASN_DOMAIN_COMPONENT:
  12534. copy = WOLFSSL_DOMAIN_COMPONENT;
  12535. copyLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  12536. #if (defined(OPENSSL_EXTRA) || \
  12537. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12538. && !defined(WOLFCRYPT_ONLY)
  12539. nid = NID_domainComponent;
  12540. #endif /* OPENSSL_EXTRA */
  12541. break;
  12542. case ASN_FAVOURITE_DRINK:
  12543. copy = WOLFSSL_FAVOURITE_DRINK;
  12544. copyLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
  12545. #if (defined(OPENSSL_EXTRA) || \
  12546. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12547. && !defined(WOLFCRYPT_ONLY)
  12548. nid = NID_favouriteDrink;
  12549. #endif /* OPENSSL_EXTRA */
  12550. break;
  12551. default:
  12552. WOLFSSL_MSG("Unknown pilot attribute type");
  12553. #if (defined(OPENSSL_EXTRA) || \
  12554. defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12555. !defined(WOLFCRYPT_ONLY)
  12556. wolfSSL_X509_NAME_free(dName);
  12557. #endif /* OPENSSL_EXTRA */
  12558. return ASN_PARSE_E;
  12559. }
  12560. }
  12561. }
  12562. if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx))
  12563. {
  12564. WOLFSSL_MSG("ASN Name too big, skipping");
  12565. tooBig = TRUE;
  12566. }
  12567. if ((copy != NULL) && !tooBig) {
  12568. XMEMCPY(&full[idx], copy, (size_t)copyLen);
  12569. idx += (word32)copyLen;
  12570. XMEMCPY(&full[idx], &input[srcIdx], (size_t)strLen);
  12571. idx += (word32)strLen;
  12572. }
  12573. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12574. !defined(WOLFCRYPT_ONLY)
  12575. switch (b) {
  12576. case CTC_UTF8:
  12577. enc = MBSTRING_UTF8;
  12578. break;
  12579. case CTC_PRINTABLE:
  12580. enc = V_ASN1_PRINTABLESTRING;
  12581. break;
  12582. default:
  12583. WOLFSSL_MSG("Unknown encoding type, using UTF8 by default");
  12584. enc = MBSTRING_UTF8;
  12585. }
  12586. if (nid != NID_undef) {
  12587. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc,
  12588. &input[srcIdx], strLen, -1, -1) !=
  12589. WOLFSSL_SUCCESS) {
  12590. wolfSSL_X509_NAME_free(dName);
  12591. return ASN_PARSE_E;
  12592. }
  12593. }
  12594. #endif /* OPENSSL_EXTRA */
  12595. srcIdx += (word32)strLen;
  12596. }
  12597. full[idx++] = 0;
  12598. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12599. !defined(WOLFCRYPT_ONLY)
  12600. if (nameType == ISSUER) {
  12601. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)) && \
  12602. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  12603. dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX);
  12604. XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
  12605. #endif
  12606. cert->issuerName = dName;
  12607. }
  12608. else {
  12609. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  12610. dName->rawLen = min(cert->subjectRawLen, WC_ASN_NAME_MAX);
  12611. XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
  12612. #endif
  12613. cert->subjectName = dName;
  12614. }
  12615. #endif
  12616. *inOutIdx = srcIdx;
  12617. return 0;
  12618. #else
  12619. DECL_ASNGETDATA(dataASN, rdnASN_Length);
  12620. int ret = 0;
  12621. word32 idx = 0;
  12622. int len;
  12623. word32 srcIdx = *inOutIdx;
  12624. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12625. WOLFSSL_X509_NAME* dName = NULL;
  12626. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12627. WOLFSSL_MSG("Getting Cert Name");
  12628. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  12629. * calculated over the entire DER encoding of the Name field, including
  12630. * the tag and length. */
  12631. if (CalcHashId(input + srcIdx, maxIdx - srcIdx, hash) != 0) {
  12632. ret = ASN_PARSE_E;
  12633. }
  12634. CALLOC_ASNGETDATA(dataASN, rdnASN_Length, ret, cert->heap);
  12635. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12636. if (ret == 0) {
  12637. /* Create an X509_NAME to hold data for OpenSSL compatibility APIs. */
  12638. dName = wolfSSL_X509_NAME_new_ex(cert->heap);
  12639. if (dName == NULL) {
  12640. ret = MEMORY_E;
  12641. }
  12642. }
  12643. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12644. if (ret == 0) {
  12645. /* Expecting a SEQUENCE using up all data. */
  12646. ret = GetASN_Sequence(input, &srcIdx, &len, maxIdx, 1);
  12647. }
  12648. if (ret == 0) {
  12649. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  12650. /* Store pointer and length to raw issuer. */
  12651. if (nameType == ISSUER) {
  12652. cert->issuerRaw = &input[srcIdx];
  12653. cert->issuerRawLen = len;
  12654. }
  12655. #endif
  12656. #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
  12657. /* Store pointer and length to raw subject. */
  12658. if (nameType == SUBJECT) {
  12659. cert->subjectRaw = &input[srcIdx];
  12660. cert->subjectRawLen = len;
  12661. }
  12662. #endif
  12663. /* Process all RDNs in name. */
  12664. while ((ret == 0) && (srcIdx < maxIdx)) {
  12665. int nid = 0;
  12666. /* Initialize for data and setup RDN choice. */
  12667. GetASN_Choice(&dataASN[RDNASN_IDX_ATTR_VAL], rdnChoice);
  12668. /* Ignore type OID as too many to store in table. */
  12669. GetASN_OID(&dataASN[RDNASN_IDX_ATTR_TYPE], oidIgnoreType);
  12670. /* Parse RDN. */
  12671. ret = GetASN_Items(rdnASN, dataASN, rdnASN_Length, 1, input,
  12672. &srcIdx, maxIdx);
  12673. if (ret == 0) {
  12674. /* Put RDN data into certificate. */
  12675. ret = GetRDN(cert, full, &idx, &nid, nameType == SUBJECT,
  12676. dataASN);
  12677. }
  12678. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12679. /* TODO: push this back up to ssl.c
  12680. * (do parsing for WOLFSSL_X509_NAME on demand) */
  12681. if (ret == 0) {
  12682. int enc;
  12683. byte* str;
  12684. word32 strLen;
  12685. byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
  12686. /* Get string reference. */
  12687. GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
  12688. /* Convert BER tag to a OpenSSL type. */
  12689. switch (tag) {
  12690. case CTC_UTF8:
  12691. enc = MBSTRING_UTF8;
  12692. break;
  12693. case CTC_PRINTABLE:
  12694. enc = V_ASN1_PRINTABLESTRING;
  12695. break;
  12696. default:
  12697. WOLFSSL_MSG("Unknown encoding type, default UTF8");
  12698. enc = MBSTRING_UTF8;
  12699. }
  12700. if (nid != 0) {
  12701. /* Add an entry to the X509_NAME. */
  12702. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc, str,
  12703. strLen, -1, -1) != WOLFSSL_SUCCESS) {
  12704. ret = ASN_PARSE_E;
  12705. }
  12706. }
  12707. }
  12708. #endif
  12709. }
  12710. }
  12711. if (ret == 0) {
  12712. /* Terminate string. */
  12713. full[idx] = 0;
  12714. /* Return index into encoding after name. */
  12715. *inOutIdx = srcIdx;
  12716. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12717. /* Store X509_NAME in certificate. */
  12718. if (nameType == ISSUER) {
  12719. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  12720. defined(HAVE_LIGHTY)) && \
  12721. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  12722. dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX);
  12723. XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
  12724. #endif
  12725. cert->issuerName = dName;
  12726. }
  12727. else {
  12728. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  12729. dName->rawLen = min(cert->subjectRawLen, WC_ASN_NAME_MAX);
  12730. XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
  12731. #endif
  12732. cert->subjectName = dName;
  12733. }
  12734. }
  12735. else {
  12736. /* Dispose of unused X509_NAME. */
  12737. wolfSSL_X509_NAME_free(dName);
  12738. #endif
  12739. }
  12740. FREE_ASNGETDATA(dataASN, cert->heap);
  12741. return ret;
  12742. #endif /* WOLFSSL_ASN_TEMPLATE */
  12743. }
  12744. #ifdef WOLFSSL_ASN_TEMPLATE
  12745. /* ASN.1 template for certificate name. */
  12746. static const ASNItem certNameASN[] = {
  12747. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  12748. /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  12749. };
  12750. enum {
  12751. CERTNAMEASN_IDX_OID = 0,
  12752. CERTNAMEASN_IDX_NAME
  12753. };
  12754. /* Number of items in ASN.1 template for certificate name. */
  12755. #define certNameASN_Length (sizeof(certNameASN) / sizeof(ASNItem))
  12756. #endif
  12757. /* Get a certificate name into the certificate object.
  12758. *
  12759. * Either the issuer or subject name.
  12760. *
  12761. * @param [in, out] cert Decoded certificate object.
  12762. * @param [in] nameType Type of name being decoded: ISSUER or SUBJECT.
  12763. * @param [in] maxIdx Index of next item after certificate name.
  12764. * @return 0 on success.
  12765. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12766. * is invalid.
  12767. * @return BUFFER_E when data in buffer is too small.
  12768. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  12769. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  12770. * @return MEMORY_E when dynamic memory allocation fails.
  12771. */
  12772. int GetName(DecodedCert* cert, int nameType, int maxIdx)
  12773. {
  12774. #ifndef WOLFSSL_ASN_TEMPLATE
  12775. char* full;
  12776. byte* hash;
  12777. int length;
  12778. word32 localIdx;
  12779. byte tag;
  12780. WOLFSSL_MSG("Getting Name");
  12781. if (nameType == ISSUER) {
  12782. full = cert->issuer;
  12783. hash = cert->issuerHash;
  12784. }
  12785. else {
  12786. full = cert->subject;
  12787. hash = cert->subjectHash;
  12788. }
  12789. if (cert->srcIdx >= (word32)maxIdx) {
  12790. return BUFFER_E;
  12791. }
  12792. localIdx = cert->srcIdx;
  12793. if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
  12794. return ASN_PARSE_E;
  12795. }
  12796. if (tag == ASN_OBJECT_ID) {
  12797. WOLFSSL_MSG("Trying optional prefix...");
  12798. if (SkipObjectId(cert->source, &cert->srcIdx, (word32)maxIdx) < 0)
  12799. return ASN_PARSE_E;
  12800. WOLFSSL_MSG("Got optional prefix");
  12801. }
  12802. localIdx = cert->srcIdx;
  12803. if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
  12804. return ASN_PARSE_E;
  12805. }
  12806. localIdx = cert->srcIdx + 1;
  12807. if (GetLength(cert->source, &localIdx, &length, (word32)maxIdx) < 0) {
  12808. return ASN_PARSE_E;
  12809. }
  12810. length += (int)(localIdx - cert->srcIdx);
  12811. return GetCertName(cert, full, hash, nameType, cert->source, &cert->srcIdx,
  12812. cert->srcIdx + (word32)length);
  12813. #else
  12814. ASNGetData dataASN[certNameASN_Length];
  12815. word32 idx = cert->srcIdx;
  12816. int ret = 0;
  12817. WOLFSSL_MSG("Getting Name");
  12818. XMEMSET(dataASN, 0, sizeof(dataASN));
  12819. /* Initialize for data and don't check optional prefix OID. */
  12820. GetASN_OID(&dataASN[CERTNAMEASN_IDX_OID], oidIgnoreType);
  12821. ret = GetASN_Items(certNameASN, dataASN, certNameASN_Length, 0,
  12822. cert->source, &idx, (word32)maxIdx);
  12823. if (ret == 0) {
  12824. char* full;
  12825. byte* hash;
  12826. /* Store offset of SEQUENCE that is start of name. */
  12827. cert->srcIdx = dataASN[CERTNAMEASN_IDX_NAME].offset;
  12828. /* Get fields to fill in based on name type. */
  12829. if (nameType == ISSUER) {
  12830. full = cert->issuer;
  12831. hash = cert->issuerHash;
  12832. }
  12833. else {
  12834. full = cert->subject;
  12835. hash = cert->subjectHash;
  12836. }
  12837. /* Parse certificate name. */
  12838. ret = GetCertName(cert, full, hash, nameType, cert->source,
  12839. &cert->srcIdx, idx);
  12840. }
  12841. return ret;
  12842. #endif
  12843. }
  12844. #ifndef NO_ASN_TIME
  12845. /* two byte date/time, add to value */
  12846. static WC_INLINE int GetTime(int* value, const byte* date, int* idx)
  12847. {
  12848. int i = *idx;
  12849. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  12850. date[i+1] > 0x39) {
  12851. return ASN_PARSE_E;
  12852. }
  12853. *value += (int)btoi(date[i++]) * 10;
  12854. *value += (int)btoi(date[i++]);
  12855. *idx = i;
  12856. return 0;
  12857. }
  12858. #ifdef WOLFSSL_LINUXKM
  12859. static WC_INLINE int GetTime_Long(long* value, const byte* date, int* idx)
  12860. {
  12861. int i = *idx;
  12862. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  12863. date[i+1] > 0x39) {
  12864. return ASN_PARSE_E;
  12865. }
  12866. *value += (long)btoi(date[i++]) * 10;
  12867. *value += (long)btoi(date[i++]);
  12868. *idx = i;
  12869. return 0;
  12870. }
  12871. #endif
  12872. int ExtractDate(const unsigned char* date, unsigned char format,
  12873. struct tm* certTime, int* idx)
  12874. {
  12875. XMEMSET(certTime, 0, sizeof(struct tm));
  12876. if (format == ASN_UTC_TIME) {
  12877. if (btoi(date[*idx]) >= 5)
  12878. certTime->tm_year = 1900;
  12879. else
  12880. certTime->tm_year = 2000;
  12881. }
  12882. else { /* format == GENERALIZED_TIME */
  12883. #ifdef WOLFSSL_LINUXKM
  12884. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  12885. #else
  12886. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  12887. #endif
  12888. certTime->tm_year *= 100;
  12889. }
  12890. #ifdef AVR
  12891. /* Extract the time from the struct tm and adjust tm_year, tm_mon */
  12892. /* AVR libc stores these as uint8_t instead of int */
  12893. /* AVR time_t also offsets from midnight 1 Jan 2000 */
  12894. int tm_year = certTime->tm_year - 2000;
  12895. int tm_mon = certTime->tm_mon - 1;
  12896. int tm_mday = certTime->tm_mday;
  12897. int tm_hour = certTime->tm_hour;
  12898. int tm_min = certTime->tm_min;
  12899. int tm_sec = certTime->tm_sec;
  12900. #ifdef WOLFSSL_LINUXKM
  12901. if (GetTime_Long(&tm_year, date, idx) != 0) return 0;
  12902. #else
  12903. if (GetTime(&tm_year, date, idx) != 0) return 0;
  12904. #endif
  12905. if (GetTime(&tm_mon , date, idx) != 0) return 0;
  12906. if (GetTime(&tm_mday, date, idx) != 0) return 0;
  12907. if (GetTime(&tm_hour, date, idx) != 0) return 0;
  12908. if (GetTime(&tm_min , date, idx) != 0) return 0;
  12909. if (GetTime(&tm_sec , date, idx) != 0) return 0;
  12910. /* Re-populate certTime with computed values */
  12911. certTime->tm_year = tm_year;
  12912. certTime->tm_mon = tm_mon;
  12913. certTime->tm_mday = tm_mday;
  12914. certTime->tm_hour = tm_hour;
  12915. certTime->tm_min = tm_min;
  12916. certTime->tm_sec = tm_sec;
  12917. #else
  12918. /* adjust tm_year, tm_mon */
  12919. #ifdef WOLFSSL_LINUXKM
  12920. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  12921. #else
  12922. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  12923. #endif
  12924. certTime->tm_year -= 1900;
  12925. if (GetTime(&certTime->tm_mon , date, idx) != 0) return 0;
  12926. certTime->tm_mon -= 1;
  12927. if (GetTime(&certTime->tm_mday, date, idx) != 0) return 0;
  12928. if (GetTime(&certTime->tm_hour, date, idx) != 0) return 0;
  12929. if (GetTime(&certTime->tm_min , date, idx) != 0) return 0;
  12930. if (GetTime(&certTime->tm_sec , date, idx) != 0) return 0;
  12931. #endif
  12932. return 1;
  12933. }
  12934. #if defined(OPENSSL_ALL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
  12935. defined(OPENSSL_EXTRA) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  12936. int GetTimeString(byte* date, int format, char* buf, int len)
  12937. {
  12938. struct tm t;
  12939. int idx = 0;
  12940. if (!ExtractDate(date, (unsigned char)format, &t, &idx)) {
  12941. return 0;
  12942. }
  12943. if (date[idx] != 'Z') {
  12944. WOLFSSL_MSG("UTCtime, not Zulu") ;
  12945. return 0;
  12946. }
  12947. /* place month in buffer */
  12948. buf[0] = '\0';
  12949. switch(t.tm_mon) {
  12950. case 0: XSTRNCAT(buf, "Jan ", 5); break;
  12951. case 1: XSTRNCAT(buf, "Feb ", 5); break;
  12952. case 2: XSTRNCAT(buf, "Mar ", 5); break;
  12953. case 3: XSTRNCAT(buf, "Apr ", 5); break;
  12954. case 4: XSTRNCAT(buf, "May ", 5); break;
  12955. case 5: XSTRNCAT(buf, "Jun ", 5); break;
  12956. case 6: XSTRNCAT(buf, "Jul ", 5); break;
  12957. case 7: XSTRNCAT(buf, "Aug ", 5); break;
  12958. case 8: XSTRNCAT(buf, "Sep ", 5); break;
  12959. case 9: XSTRNCAT(buf, "Oct ", 5); break;
  12960. case 10: XSTRNCAT(buf, "Nov ", 5); break;
  12961. case 11: XSTRNCAT(buf, "Dec ", 5); break;
  12962. default:
  12963. return 0;
  12964. }
  12965. idx = 4; /* use idx now for char buffer */
  12966. if (XSNPRINTF(buf + idx, len - idx, "%2d %02d:%02d:%02d %d GMT",
  12967. t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, (int)t.tm_year + 1900)
  12968. >= len - idx)
  12969. {
  12970. WOLFSSL_MSG("buffer overrun in GetTimeString");
  12971. return 0;
  12972. }
  12973. return 1;
  12974. }
  12975. #endif /* OPENSSL_ALL || WOLFSSL_MYSQL_COMPATIBLE || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
  12976. #if !defined(NO_ASN_TIME) && !defined(USER_TIME) && \
  12977. !defined(TIME_OVERRIDES) && (defined(OPENSSL_EXTRA) || defined(HAVE_PKCS7))
  12978. /* Set current time string, either UTC or GeneralizedTime.
  12979. * (void*) tm should be a pointer to time_t, output is placed in buf.
  12980. *
  12981. * Return time string length placed in buf on success, negative on error */
  12982. int GetAsnTimeString(void* currTime, byte* buf, word32 len)
  12983. {
  12984. byte* data_ptr = buf;
  12985. byte uf_time[ASN_GENERALIZED_TIME_SIZE];
  12986. int data_len = 0;
  12987. WOLFSSL_ENTER("GetAsnTimeString");
  12988. if (buf == NULL || len == 0)
  12989. return BAD_FUNC_ARG;
  12990. XMEMSET(uf_time, 0, sizeof(uf_time));
  12991. /* GetFormattedTime returns length with null terminator */
  12992. data_len = GetFormattedTime(currTime, uf_time, (word32)sizeof(uf_time));
  12993. if (data_len <= 0) {
  12994. return ASN_TIME_E;
  12995. }
  12996. /* ensure room to add 2 bytes (ASN type and length) before proceeding */
  12997. else if (len < (word32)data_len + 2) {
  12998. return BUFFER_E;
  12999. }
  13000. if (data_len == ASN_UTC_TIME_SIZE-1) {
  13001. /* increment data_len for ASN length byte after adding the data_ptr */
  13002. *data_ptr = (byte)ASN_UTC_TIME; data_ptr++; data_len++;
  13003. /* -1 below excludes null terminator */
  13004. *data_ptr = (byte)ASN_UTC_TIME_SIZE - 1; data_ptr++; data_len++;
  13005. XMEMCPY(data_ptr, (byte *)uf_time, ASN_UTC_TIME_SIZE - 1);
  13006. data_ptr += ASN_UTC_TIME_SIZE - 1;
  13007. }
  13008. else if (data_len == ASN_GENERALIZED_TIME_SIZE-1) {
  13009. /* increment data_len for ASN length byte after adding the data_ptr */
  13010. *data_ptr = (byte)ASN_GENERALIZED_TIME; data_ptr++; data_len++;
  13011. /* -1 below excludes null terminator */
  13012. *data_ptr = (byte)ASN_GENERALIZED_TIME_SIZE - 1; data_ptr++; data_len++;
  13013. XMEMCPY(data_ptr, (byte*)uf_time, ASN_GENERALIZED_TIME_SIZE - 1);
  13014. data_ptr += ASN_GENERALIZED_TIME_SIZE - 1;
  13015. }
  13016. else {
  13017. WOLFSSL_MSG("Invalid time size returned");
  13018. return ASN_TIME_E;
  13019. }
  13020. /* append null terminator */
  13021. *data_ptr = 0;
  13022. /* return length without null terminator */
  13023. return data_len;
  13024. }
  13025. /* return just the time string as either UTC or Generalized Time*/
  13026. int GetFormattedTime(void* currTime, byte* buf, word32 len)
  13027. {
  13028. struct tm* ts = NULL;
  13029. struct tm* tmpTime = NULL;
  13030. int year, mon, day, hour, mini, sec;
  13031. int ret;
  13032. #if defined(NEED_TMP_TIME)
  13033. struct tm tmpTimeStorage;
  13034. tmpTime = &tmpTimeStorage;
  13035. #endif
  13036. /* Needed in case XGMTIME does not use the tmpTime argument. */
  13037. (void)tmpTime;
  13038. WOLFSSL_ENTER("GetFormattedTime");
  13039. if (buf == NULL || len == 0)
  13040. return BAD_FUNC_ARG;
  13041. ts = (struct tm *)XGMTIME((time_t*)currTime, tmpTime);
  13042. if (ts == NULL) {
  13043. WOLFSSL_MSG("failed to get time data.");
  13044. return ASN_TIME_E;
  13045. }
  13046. /* Note ASN_UTC_TIME_SIZE and ASN_GENERALIZED_TIME_SIZE include space for
  13047. * the null terminator. ASN encoded values leave off the terminator. */
  13048. if (ts->tm_year >= 50 && ts->tm_year < 150) {
  13049. /* UTC Time */
  13050. if (ts->tm_year >= 50 && ts->tm_year < 100) {
  13051. year = ts->tm_year;
  13052. }
  13053. else {
  13054. year = ts->tm_year - 100;
  13055. }
  13056. mon = ts->tm_mon + 1;
  13057. day = ts->tm_mday;
  13058. hour = ts->tm_hour;
  13059. mini = ts->tm_min;
  13060. sec = ts->tm_sec;
  13061. #if defined(WOLF_C89)
  13062. if (len < ASN_UTC_TIME_SIZE) {
  13063. WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
  13064. return BUFFER_E;
  13065. }
  13066. ret = XSPRINTF((char*)buf,
  13067. "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
  13068. hour, mini, sec);
  13069. #else
  13070. ret = XSNPRINTF((char*)buf, len,
  13071. "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
  13072. hour, mini, sec);
  13073. #endif
  13074. }
  13075. else {
  13076. /* GeneralizedTime */
  13077. year = ts->tm_year + 1900;
  13078. mon = ts->tm_mon + 1;
  13079. day = ts->tm_mday;
  13080. hour = ts->tm_hour;
  13081. mini = ts->tm_min;
  13082. sec = ts->tm_sec;
  13083. #if defined(WOLF_C89)
  13084. if (len < ASN_GENERALIZED_TIME_SIZE) {
  13085. WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
  13086. return BUFFER_E;
  13087. }
  13088. ret = XSPRINTF((char*)buf,
  13089. "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
  13090. hour, mini, sec);
  13091. #else
  13092. ret = XSNPRINTF((char*)buf, len,
  13093. "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
  13094. hour, mini, sec);
  13095. #endif
  13096. }
  13097. return ret;
  13098. }
  13099. #endif /* !NO_ASN_TIME && !USER_TIME && !TIME_OVERRIDES &&
  13100. * (OPENSSL_EXTRA || HAVE_PKCS7) */
  13101. #if defined(USE_WOLF_VALIDDATE)
  13102. /* to the second */
  13103. int DateGreaterThan(const struct tm* a, const struct tm* b)
  13104. {
  13105. if (a->tm_year > b->tm_year)
  13106. return 1;
  13107. if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
  13108. return 1;
  13109. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13110. a->tm_mday > b->tm_mday)
  13111. return 1;
  13112. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13113. a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
  13114. return 1;
  13115. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13116. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  13117. a->tm_min > b->tm_min)
  13118. return 1;
  13119. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13120. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  13121. a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
  13122. return 1;
  13123. return 0; /* false */
  13124. }
  13125. static WC_INLINE int DateLessThan(const struct tm* a, const struct tm* b)
  13126. {
  13127. return DateGreaterThan(b,a);
  13128. }
  13129. /* like atoi but only use first byte */
  13130. /* Make sure before and after dates are valid */
  13131. int wc_ValidateDate(const byte* date, byte format, int dateType)
  13132. {
  13133. time_t ltime;
  13134. struct tm certTime;
  13135. struct tm* localTime;
  13136. struct tm* tmpTime;
  13137. int i = 0;
  13138. int timeDiff = 0;
  13139. int diffHH = 0, diffMM = 0;
  13140. #if defined(NEED_TMP_TIME)
  13141. struct tm tmpTimeStorage;
  13142. tmpTime = &tmpTimeStorage;
  13143. #else
  13144. tmpTime = NULL;
  13145. #endif
  13146. (void)tmpTime;
  13147. ltime = wc_Time(0);
  13148. if (sizeof(ltime) == sizeof(word32) && (int)ltime < 0){
  13149. /* A negative response here could be due to a 32-bit time_t
  13150. * where the year is 2038 or later. */
  13151. WOLFSSL_MSG("wc_Time failed to return a valid value");
  13152. return 0;
  13153. }
  13154. #ifdef WOLFSSL_BEFORE_DATE_CLOCK_SKEW
  13155. if (dateType == BEFORE) {
  13156. WOLFSSL_MSG("Skewing local time for before date check");
  13157. ltime += WOLFSSL_BEFORE_DATE_CLOCK_SKEW;
  13158. }
  13159. #endif
  13160. #ifdef WOLFSSL_AFTER_DATE_CLOCK_SKEW
  13161. if (dateType == AFTER) {
  13162. WOLFSSL_MSG("Skewing local time for after date check");
  13163. ltime -= WOLFSSL_AFTER_DATE_CLOCK_SKEW;
  13164. }
  13165. #endif
  13166. if (!ExtractDate(date, format, &certTime, &i)) {
  13167. WOLFSSL_MSG("Error extracting the date");
  13168. return 0;
  13169. }
  13170. if ((date[i] == '+') || (date[i] == '-')) {
  13171. int diffSign;
  13172. WOLFSSL_MSG("Using time differential, not Zulu") ;
  13173. diffSign = date[i++] == '+' ? 1 : -1 ;
  13174. if (GetTime(&diffHH, date, &i) != 0)
  13175. return 0;
  13176. if (GetTime(&diffMM, date, &i) != 0)
  13177. return 0;
  13178. timeDiff = diffSign * (diffHH*60 + diffMM) * 60 ;
  13179. } else if (date[i] != 'Z') {
  13180. WOLFSSL_MSG("UTCtime, neither Zulu or time differential") ;
  13181. return 0;
  13182. }
  13183. ltime -= (time_t)timeDiff;
  13184. localTime = XGMTIME(&ltime, tmpTime);
  13185. if (localTime == NULL) {
  13186. WOLFSSL_MSG("XGMTIME failed");
  13187. return 0;
  13188. }
  13189. if (dateType == BEFORE) {
  13190. if (DateLessThan(localTime, &certTime)) {
  13191. WOLFSSL_MSG("Date BEFORE check failed");
  13192. return 0;
  13193. }
  13194. }
  13195. else { /* dateType == AFTER */
  13196. if (DateGreaterThan(localTime, &certTime)) {
  13197. WOLFSSL_MSG("Date AFTER check failed");
  13198. return 0;
  13199. }
  13200. }
  13201. return 1;
  13202. }
  13203. #endif /* USE_WOLF_VALIDDATE */
  13204. int wc_GetTime(void* timePtr, word32 timeSize)
  13205. {
  13206. time_t* ltime = (time_t*)timePtr;
  13207. if (timePtr == NULL) {
  13208. return BAD_FUNC_ARG;
  13209. }
  13210. if ((word32)sizeof(time_t) > timeSize) {
  13211. return BUFFER_E;
  13212. }
  13213. *ltime = wc_Time(0);
  13214. return 0;
  13215. }
  13216. #ifdef TIME_OVERRIDES
  13217. #ifndef HAVE_TIME_T_TYPE
  13218. typedef long time_t;
  13219. #endif
  13220. extern time_t XTIME(time_t* t);
  13221. #endif
  13222. static wc_time_cb timeFunc = NULL;
  13223. int wc_SetTimeCb(wc_time_cb f)
  13224. {
  13225. timeFunc = f;
  13226. return 0;
  13227. }
  13228. time_t wc_Time(time_t* t)
  13229. {
  13230. if (timeFunc != NULL) {
  13231. return timeFunc(t);
  13232. }
  13233. return XTIME(t);
  13234. }
  13235. #endif /* !NO_ASN_TIME */
  13236. #ifdef WOLFSSL_ASN_TEMPLATE
  13237. /* TODO: use a CHOICE instead of two items? */
  13238. /* ASN.1 template for a date - either UTC or Generalized Time. */
  13239. static const ASNItem dateASN[] = {
  13240. /* UTC */ { 0, ASN_UTC_TIME, 0, 0, 2 },
  13241. /* GT */ { 0, ASN_GENERALIZED_TIME, 0, 0, 2 },
  13242. };
  13243. enum {
  13244. DATEASN_IDX_UTC = 0,
  13245. DATEASN_IDX_GT
  13246. };
  13247. /* Number of items in ASN.1 template for a date. */
  13248. #define dateASN_Length (sizeof(dateASN) / sizeof(ASNItem))
  13249. #endif /* WOLFSSL_ASN_TEMPLATE */
  13250. /* Get date buffer, format and length. Returns 0=success or error */
  13251. /* Decode a DateInfo - choice of UTC TIME or GENERALIZED TIME.
  13252. *
  13253. * @param [in] source Buffer containing encoded date.
  13254. * @param [in, out] idx On in, the index of the date.
  13255. * On out, index after date.
  13256. * @param [out] pDate Pointer into buffer of data bytes.
  13257. * @param [out] pFormat Format of date - BER/DER tag.
  13258. * @param [out] pLength Length of date bytes.
  13259. * @param [in] maxIdx Index of next item after date.
  13260. * @return 0 on success.
  13261. * @return BAD_FUNC_ARG when source or idx is NULL.
  13262. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13263. * is invalid.
  13264. * @return BUFFER_E when data in buffer is too small.
  13265. */
  13266. static int GetDateInfo(const byte* source, word32* idx, const byte** pDate,
  13267. byte* pFormat, int* pLength, word32 maxIdx)
  13268. {
  13269. #ifndef WOLFSSL_ASN_TEMPLATE
  13270. int length;
  13271. byte format;
  13272. if (source == NULL || idx == NULL)
  13273. return BAD_FUNC_ARG;
  13274. /* get ASN format header */
  13275. if (*idx+1 > maxIdx)
  13276. return BUFFER_E;
  13277. format = source[*idx];
  13278. *idx += 1;
  13279. if (format != ASN_UTC_TIME && format != ASN_GENERALIZED_TIME) {
  13280. WOLFSSL_ERROR_VERBOSE(ASN_TIME_E);
  13281. return ASN_TIME_E;
  13282. }
  13283. /* get length */
  13284. if (GetLength(source, idx, &length, maxIdx) < 0)
  13285. return ASN_PARSE_E;
  13286. if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
  13287. return ASN_DATE_SZ_E;
  13288. /* return format, date and length */
  13289. if (pFormat)
  13290. *pFormat = format;
  13291. if (pDate)
  13292. *pDate = &source[*idx];
  13293. if (pLength)
  13294. *pLength = length;
  13295. *idx += (word32)length;
  13296. return 0;
  13297. #else
  13298. ASNGetData dataASN[dateASN_Length];
  13299. int ret = 0;
  13300. if ((source == NULL) || (idx == NULL)) {
  13301. ret = BAD_FUNC_ARG;
  13302. }
  13303. if (ret == 0) {
  13304. /* Initialize data. */
  13305. XMEMSET(dataASN, 0, sizeof(dataASN));
  13306. /* Parse date. */
  13307. ret = GetASN_Items(dateASN, dataASN, dateASN_Length, 0, source, idx,
  13308. maxIdx);
  13309. }
  13310. if (ret == 0) {
  13311. /* Determine which tag was seen. */
  13312. int i = (dataASN[DATEASN_IDX_UTC].tag != 0) ? DATEASN_IDX_UTC
  13313. : DATEASN_IDX_GT;
  13314. /* Return data from seen item. */
  13315. if (pFormat != NULL) {
  13316. *pFormat = dataASN[i].tag;
  13317. }
  13318. if (pDate != NULL) {
  13319. *pDate = dataASN[i].data.ref.data;
  13320. }
  13321. if (pLength != NULL) {
  13322. *pLength = (int)dataASN[i].data.ref.length;
  13323. }
  13324. }
  13325. return ret;
  13326. #endif
  13327. }
  13328. #if !defined(NO_CERTS) && !defined(WOLFSSL_ASN_TEMPLATE)
  13329. static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx)
  13330. {
  13331. int ret, length;
  13332. const byte *datePtr = NULL;
  13333. byte date[MAX_DATE_SIZE];
  13334. byte format;
  13335. word32 startIdx = 0;
  13336. if (dateType == BEFORE)
  13337. cert->beforeDate = &cert->source[cert->srcIdx];
  13338. else
  13339. cert->afterDate = &cert->source[cert->srcIdx];
  13340. startIdx = cert->srcIdx;
  13341. ret = GetDateInfo(cert->source, &cert->srcIdx, &datePtr, &format,
  13342. &length, (word32)maxIdx);
  13343. if (ret < 0)
  13344. return ret;
  13345. XMEMSET(date, 0, MAX_DATE_SIZE);
  13346. XMEMCPY(date, datePtr, (size_t)length);
  13347. if (dateType == BEFORE)
  13348. cert->beforeDateLen = (int)(cert->srcIdx - startIdx);
  13349. else
  13350. cert->afterDateLen = (int)(cert->srcIdx - startIdx);
  13351. #ifndef NO_ASN_TIME_CHECK
  13352. if (verify != NO_VERIFY && verify != VERIFY_SKIP_DATE &&
  13353. !XVALIDATE_DATE(date, format, dateType)) {
  13354. if (dateType == BEFORE) {
  13355. WOLFSSL_ERROR_VERBOSE(ASN_BEFORE_DATE_E);
  13356. return ASN_BEFORE_DATE_E;
  13357. }
  13358. else {
  13359. WOLFSSL_ERROR_VERBOSE(ASN_AFTER_DATE_E);
  13360. return ASN_AFTER_DATE_E;
  13361. }
  13362. }
  13363. #else
  13364. (void)verify;
  13365. #endif
  13366. return 0;
  13367. }
  13368. static int GetValidity(DecodedCert* cert, int verify, int maxIdx)
  13369. {
  13370. int length;
  13371. int badDate = 0;
  13372. if (GetSequence(cert->source, &cert->srcIdx, &length, (word32)maxIdx) < 0)
  13373. return ASN_PARSE_E;
  13374. maxIdx = (int)cert->srcIdx + length;
  13375. if (GetDate(cert, BEFORE, verify, maxIdx) < 0)
  13376. badDate = ASN_BEFORE_DATE_E; /* continue parsing */
  13377. if (GetDate(cert, AFTER, verify, maxIdx) < 0)
  13378. return ASN_AFTER_DATE_E;
  13379. if (badDate != 0)
  13380. return badDate;
  13381. return 0;
  13382. }
  13383. #endif /* !NO_CERTS && !WOLFSSL_ASN_TEMPLATE */
  13384. int wc_GetDateInfo(const byte* certDate, int certDateSz, const byte** date,
  13385. byte* format, int* length)
  13386. {
  13387. int ret;
  13388. word32 idx = 0;
  13389. ret = GetDateInfo(certDate, &idx, date, format, length, (word32)certDateSz);
  13390. return ret;
  13391. }
  13392. #ifndef NO_ASN_TIME
  13393. int wc_GetDateAsCalendarTime(const byte* date, int length, byte format,
  13394. struct tm* timearg)
  13395. {
  13396. int idx = 0;
  13397. (void)length;
  13398. if (!ExtractDate(date, format, timearg, &idx))
  13399. return ASN_TIME_E;
  13400. return 0;
  13401. }
  13402. #if defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_ALT_NAMES)
  13403. int wc_GetCertDates(Cert* cert, struct tm* before, struct tm* after)
  13404. {
  13405. int ret = 0;
  13406. const byte* date;
  13407. byte format;
  13408. int length;
  13409. if (cert == NULL)
  13410. return BAD_FUNC_ARG;
  13411. if (before && cert->beforeDateSz > 0) {
  13412. ret = wc_GetDateInfo(cert->beforeDate, cert->beforeDateSz, &date,
  13413. &format, &length);
  13414. if (ret == 0)
  13415. ret = wc_GetDateAsCalendarTime(date, length, format, before);
  13416. }
  13417. if (after && cert->afterDateSz > 0) {
  13418. ret = wc_GetDateInfo(cert->afterDate, cert->afterDateSz, &date,
  13419. &format, &length);
  13420. if (ret == 0)
  13421. ret = wc_GetDateAsCalendarTime(date, length, format, after);
  13422. }
  13423. return ret;
  13424. }
  13425. #endif /* WOLFSSL_CERT_GEN && WOLFSSL_ALT_NAMES */
  13426. #endif /* !NO_ASN_TIME */
  13427. #if !defined(WOLFSSL_ASN_TEMPLATE) && !defined(NO_CERTS)
  13428. static int GetSigAlg(DecodedCert* cert, word32* sigOid, word32 maxIdx)
  13429. {
  13430. int length;
  13431. word32 endSeqIdx;
  13432. if (GetSequence(cert->source, &cert->srcIdx, &length, maxIdx) < 0)
  13433. return ASN_PARSE_E;
  13434. endSeqIdx = cert->srcIdx + (word32)length;
  13435. if (GetObjectId(cert->source, &cert->srcIdx, sigOid, oidSigType,
  13436. maxIdx) < 0) {
  13437. return ASN_OBJECT_ID_E;
  13438. }
  13439. if (cert->srcIdx != endSeqIdx) {
  13440. #ifdef WC_RSA_PSS
  13441. if (*sigOid == CTC_RSASSAPSS) {
  13442. cert->sigParamsIndex = cert->srcIdx;
  13443. cert->sigParamsLength = endSeqIdx - cert->srcIdx;
  13444. }
  13445. else
  13446. #endif
  13447. /* Only allowed a ASN NULL header with zero length. */
  13448. if (endSeqIdx - cert->srcIdx != 2)
  13449. return ASN_PARSE_E;
  13450. else {
  13451. byte tag;
  13452. if (GetASNTag(cert->source, &cert->srcIdx, &tag, endSeqIdx) != 0)
  13453. return ASN_PARSE_E;
  13454. if (tag != ASN_TAG_NULL)
  13455. return ASN_PARSE_E;
  13456. }
  13457. }
  13458. cert->srcIdx = endSeqIdx;
  13459. return 0;
  13460. }
  13461. #endif
  13462. #ifndef NO_CERTS
  13463. #ifdef WOLFSSL_ASN_TEMPLATE
  13464. /* TODO: move code around to not require this. */
  13465. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  13466. int* badDateRet, int stopAtPubKey,
  13467. int stopAfterPubKey);
  13468. #endif
  13469. /* Parse the certificate up to the X.509 public key.
  13470. *
  13471. * If cert data is invalid then badDate get set to error value.
  13472. *
  13473. * @param [in, out] cert Decoded certificate object.
  13474. * @param [in] verify Whether to verify dates.
  13475. * @param [out] badDate Error code when verify dates.
  13476. * @return 0 on success.
  13477. * @return BAD_FUNC_ARG when cert or badDate is NULL.
  13478. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  13479. * @return ASN_DATE_SZ_E when time data is not supported.
  13480. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13481. * is invalid.
  13482. * @return BUFFER_E when data in buffer is too small.
  13483. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  13484. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  13485. */
  13486. int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate)
  13487. {
  13488. #ifndef WOLFSSL_ASN_TEMPLATE
  13489. int ret;
  13490. if (cert == NULL || badDate == NULL)
  13491. return BAD_FUNC_ARG;
  13492. *badDate = 0;
  13493. if ( (ret = GetCertHeader(cert)) < 0)
  13494. return ret;
  13495. WOLFSSL_MSG("Got Cert Header");
  13496. #ifdef WOLFSSL_CERT_REQ
  13497. if (!cert->isCSR) {
  13498. #endif
  13499. /* Using the sigIndex as the upper bound because that's where the
  13500. * actual certificate data ends. */
  13501. if ((ret = GetSigAlg(cert, &cert->signatureOID, cert->sigIndex)) < 0)
  13502. return ret;
  13503. WOLFSSL_MSG("Got Algo ID");
  13504. if ( (ret = GetName(cert, ISSUER, (int)cert->sigIndex)) < 0)
  13505. return ret;
  13506. if ( (ret = GetValidity(cert, verify, (int)cert->sigIndex)) < 0)
  13507. *badDate = ret;
  13508. #ifdef WOLFSSL_CERT_REQ
  13509. }
  13510. #endif
  13511. if ( (ret = GetName(cert, SUBJECT, (int)cert->sigIndex)) < 0)
  13512. return ret;
  13513. WOLFSSL_MSG("Got Subject Name");
  13514. return ret;
  13515. #else
  13516. /* Use common decode routine and stop at public key. */
  13517. int ret;
  13518. *badDate = 0;
  13519. ret = DecodeCertInternal(cert, verify, NULL, badDate, 1, 0);
  13520. if (ret >= 0) {
  13521. /* Store current index: public key. */
  13522. cert->srcIdx = (word32)ret;
  13523. }
  13524. return ret;
  13525. #endif /* WOLFSSL_ASN_TEMPLATE */
  13526. }
  13527. /* Parse the certificate up to and including X.509 public key.
  13528. *
  13529. * @param [in, out] cert Decoded certificate object.
  13530. * @param [in] verify Whether to verify dates.
  13531. * @return 0 on success.
  13532. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  13533. * @return ASN_DATE_SZ_E when time data is not supported.
  13534. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  13535. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  13536. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13537. * is invalid.
  13538. * @return BUFFER_E when data in buffer is too small.
  13539. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  13540. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  13541. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  13542. */
  13543. int DecodeToKey(DecodedCert* cert, int verify)
  13544. {
  13545. #ifndef WOLFSSL_ASN_TEMPLATE
  13546. int badDate = 0;
  13547. int ret;
  13548. if ( (ret = wc_GetPubX509(cert, verify, &badDate)) < 0)
  13549. return ret;
  13550. /* Determine if self signed */
  13551. #ifdef WOLFSSL_CERT_REQ
  13552. if (cert->isCSR)
  13553. cert->selfSigned = 1;
  13554. else
  13555. #endif
  13556. {
  13557. cert->selfSigned = XMEMCMP(cert->issuerHash,
  13558. cert->subjectHash,
  13559. KEYID_SIZE) == 0 ? 1 : 0;
  13560. }
  13561. ret = GetCertKey(cert, cert->source, &cert->srcIdx, cert->maxIdx);
  13562. if (ret != 0)
  13563. return ret;
  13564. WOLFSSL_MSG("Got Key");
  13565. if (badDate != 0)
  13566. return badDate;
  13567. return ret;
  13568. #else
  13569. int ret;
  13570. int badDate = 0;
  13571. /* Call internal version and stop after public key. */
  13572. ret = DecodeCertInternal(cert, verify, NULL, &badDate, 0, 1);
  13573. /* Always return date errors. */
  13574. if (ret == 0) {
  13575. ret = badDate;
  13576. }
  13577. return ret;
  13578. #endif /* WOLFSSL_ASN_TEMPLATE */
  13579. }
  13580. #if !defined(WOLFSSL_ASN_TEMPLATE)
  13581. static int GetSignature(DecodedCert* cert)
  13582. {
  13583. int length;
  13584. int ret;
  13585. ret = CheckBitString(cert->source, &cert->srcIdx, &length, cert->maxIdx, 1,
  13586. NULL);
  13587. if (ret != 0)
  13588. return ret;
  13589. cert->sigLength = (word32)length;
  13590. cert->signature = &cert->source[cert->srcIdx];
  13591. cert->srcIdx += cert->sigLength;
  13592. if (cert->srcIdx != cert->maxIdx)
  13593. return ASN_PARSE_E;
  13594. return 0;
  13595. }
  13596. #endif /* !WOLFSSL_ASN_TEMPLATE */
  13597. #endif /* !NO_CERTS */
  13598. #ifndef WOLFSSL_ASN_TEMPLATE
  13599. static word32 SetOctetString8Bit(word32 len, byte* output)
  13600. {
  13601. output[0] = ASN_OCTET_STRING;
  13602. output[1] = (byte)len;
  13603. return 2;
  13604. }
  13605. static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
  13606. {
  13607. word32 idx = SetOctetString8Bit(digSz, output);
  13608. XMEMCPY(&output[idx], digest, digSz);
  13609. return idx + digSz;
  13610. }
  13611. #endif
  13612. /* Encode a length for DER.
  13613. *
  13614. * @param [in] length Value to encode.
  13615. * @param [out] output Buffer to encode into.
  13616. * @return Number of bytes encoded.
  13617. */
  13618. word32 SetLength(word32 length, byte* output)
  13619. {
  13620. /* Start encoding at start of buffer. */
  13621. word32 i = 0;
  13622. if (length < ASN_LONG_LENGTH) {
  13623. /* Only one byte needed to encode. */
  13624. if (output) {
  13625. /* Write out length value. */
  13626. output[i] = (byte)length;
  13627. }
  13628. /* Skip over length. */
  13629. i++;
  13630. }
  13631. else {
  13632. /* Calculate the number of bytes required to encode value. */
  13633. byte j = (byte)BytePrecision(length);
  13634. if (output) {
  13635. /* Encode count byte. */
  13636. output[i] = (byte)(j | ASN_LONG_LENGTH);
  13637. }
  13638. /* Skip over count byte. */
  13639. i++;
  13640. /* Encode value as a big-endian byte array. */
  13641. for (; j > 0; --j) {
  13642. if (output) {
  13643. /* Encode next most-significant byte. */
  13644. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  13645. }
  13646. /* Skip over byte. */
  13647. i++;
  13648. }
  13649. }
  13650. /* Return number of bytes in encoded length. */
  13651. return i;
  13652. }
  13653. /* Encode a DER header - type/tag and length.
  13654. *
  13655. * @param [in] tag DER tag of ASN.1 item.
  13656. * @param [in] len Length of data in ASN.1 item.
  13657. * @param [out] output Buffer to encode into.
  13658. * @return Number of bytes encoded.
  13659. */
  13660. static word32 SetHeader(byte tag, word32 len, byte* output)
  13661. {
  13662. if (output) {
  13663. /* Encode tag first. */
  13664. output[0] = tag;
  13665. }
  13666. /* Encode the length. */
  13667. return SetLength(len, output ? output + ASN_TAG_SZ : NULL) + ASN_TAG_SZ;
  13668. }
  13669. /* Encode a SEQUENCE header in DER.
  13670. *
  13671. * @param [in] len Length of data in SEQUENCE.
  13672. * @param [out] output Buffer to encode into.
  13673. * @return Number of bytes encoded.
  13674. */
  13675. word32 SetSequence(word32 len, byte* output)
  13676. {
  13677. return SetHeader(ASN_SEQUENCE | ASN_CONSTRUCTED, len, output);
  13678. }
  13679. /* Encode an OCTET STRING header in DER.
  13680. *
  13681. * @param [in] len Length of data in OCTET STRING.
  13682. * @param [out] output Buffer to encode into.
  13683. * @return Number of bytes encoded.
  13684. */
  13685. word32 SetOctetString(word32 len, byte* output)
  13686. {
  13687. return SetHeader(ASN_OCTET_STRING, len, output);
  13688. }
  13689. /* Encode a SET header in DER.
  13690. *
  13691. * @param [in] len Length of data in SET.
  13692. * @param [out] output Buffer to encode into.
  13693. * @return Number of bytes encoded.
  13694. */
  13695. word32 SetSet(word32 len, byte* output)
  13696. {
  13697. return SetHeader(ASN_SET | ASN_CONSTRUCTED, len, output);
  13698. }
  13699. /* Encode an implicit context specific header in DER.
  13700. *
  13701. * Implicit means that it is constructed only if the included ASN.1 item is.
  13702. *
  13703. * @param [in] tag Tag for the implicit ASN.1 item.
  13704. * @param [in] number Context specific number.
  13705. * @param [in] len Length of data in SET.
  13706. * @param [out] output Buffer to encode into.
  13707. * @return Number of bytes encoded.
  13708. */
  13709. word32 SetImplicit(byte tag, byte number, word32 len, byte* output)
  13710. {
  13711. tag = (byte)(((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0)
  13712. | ASN_CONTEXT_SPECIFIC | number);
  13713. return SetHeader(tag, len, output);
  13714. }
  13715. /* Encode an explicit context specific header in DER.
  13716. *
  13717. * Explicit means that there will be an ASN.1 item underneath.
  13718. *
  13719. * @param [in] number Context specific number.
  13720. * @param [in] len Length of data in SET.
  13721. * @param [out] output Buffer to encode into.
  13722. * @return Number of bytes encoded.
  13723. */
  13724. word32 SetExplicit(byte number, word32 len, byte* output)
  13725. {
  13726. return SetHeader((byte)(ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | number),
  13727. len, output);
  13728. }
  13729. #if defined(OPENSSL_EXTRA)
  13730. /* Encode an Othername into DER.
  13731. *
  13732. * @param [in] name Pointer to the WOLFSSL_ASN1_OTHERNAME to be encoded.
  13733. * @param [out] output Buffer to encode into. If NULL, don't encode.
  13734. * @return Number of bytes encoded or WOLFSSL_FAILURE if name parameter is bad.
  13735. */
  13736. word32 SetOthername(void *name, byte *output)
  13737. {
  13738. WOLFSSL_ASN1_OTHERNAME *nm = (WOLFSSL_ASN1_OTHERNAME *)name;
  13739. char *nameStr = NULL;
  13740. int nameSz = 0;
  13741. word32 len = 0;
  13742. if ((nm == NULL) || (nm->value == NULL)) {
  13743. WOLFSSL_MSG("otherName value is NULL");
  13744. return WOLFSSL_FAILURE;
  13745. }
  13746. nameStr = nm->value->value.utf8string->data;
  13747. nameSz = nm->value->value.utf8string->length;
  13748. len = nm->type_id->objSz +
  13749. SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2, NULL) +
  13750. SetHeader(CTC_UTF8, nameSz, NULL) + nameSz;
  13751. if (output != NULL) {
  13752. /* otherName OID */
  13753. XMEMCPY(output, nm->type_id->obj, nm->type_id->objSz);
  13754. output += nm->type_id->objSz;
  13755. output += SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2,
  13756. output);
  13757. output += SetHeader(CTC_UTF8, nameSz, output);
  13758. XMEMCPY(output, nameStr, nameSz);
  13759. }
  13760. return len;
  13761. }
  13762. #endif /* OPENSSL_EXTRA */
  13763. #ifdef HAVE_ECC
  13764. /* Determines whether the signature algorithm is using ECDSA.
  13765. *
  13766. * @param [in] algoOID Signature algorithm identifier.
  13767. * @return 1 when algorithm is using ECDSA.
  13768. * @return 0 otherwise.
  13769. */
  13770. static WC_INLINE int IsSigAlgoECDSA(word32 algoOID)
  13771. {
  13772. /* ECDSA sigAlgo must not have ASN1 NULL parameters */
  13773. if (algoOID == CTC_SHAwECDSA || algoOID == CTC_SHA256wECDSA ||
  13774. algoOID == CTC_SHA384wECDSA || algoOID == CTC_SHA512wECDSA) {
  13775. return 1;
  13776. }
  13777. return 0;
  13778. }
  13779. #endif
  13780. /* Determines if OID is for an EC signing algorithm including ECDSA and EdDSA
  13781. * and post-quantum algorithms.
  13782. *
  13783. * @param [in] algoOID Algorithm OID.
  13784. * @return 1 when is EC signing algorithm.
  13785. * @return 0 otherwise.
  13786. */
  13787. static WC_INLINE int IsSigAlgoECC(word32 algoOID)
  13788. {
  13789. (void)algoOID;
  13790. return (0
  13791. #ifdef HAVE_ECC
  13792. || IsSigAlgoECDSA(algoOID)
  13793. #endif
  13794. #ifdef HAVE_ED25519
  13795. || (algoOID == ED25519k)
  13796. #endif
  13797. #ifdef HAVE_CURVE25519
  13798. || (algoOID == X25519k)
  13799. #endif
  13800. #ifdef HAVE_ED448
  13801. || (algoOID == ED448k)
  13802. #endif
  13803. #ifdef HAVE_CURVE448
  13804. || (algoOID == X448k)
  13805. #endif
  13806. #ifdef HAVE_PQC
  13807. #ifdef HAVE_FACON
  13808. || (algoOID == FALCON_LEVEL1k)
  13809. || (algoOID == FALCON_LEVEL5k)
  13810. #endif
  13811. #ifdef HAVE_DILITHIUM
  13812. || (algoOID == DILITHIUM_LEVEL2k)
  13813. || (algoOID == DILITHIUM_LEVEL3k)
  13814. || (algoOID == DILITHIUM_LEVEL5k)
  13815. #endif
  13816. #ifdef HAVE_SPHINCS
  13817. || (algoOID == SPHINCS_FAST_LEVEL1k)
  13818. || (algoOID == SPHINCS_FAST_LEVEL3k)
  13819. || (algoOID == SPHINCS_FAST_LEVEL5k)
  13820. || (algoOID == SPHINCS_SMALL_LEVEL1k)
  13821. || (algoOID == SPHINCS_SMALL_LEVEL3k)
  13822. || (algoOID == SPHINCS_SMALL_LEVEL5k)
  13823. #endif
  13824. #endif /* HAVE_PQC */
  13825. );
  13826. }
  13827. /* Encode an algorithm identifier.
  13828. *
  13829. * [algoOID, type] is unique.
  13830. *
  13831. * @param [in] algoOID Algorithm identifier.
  13832. * @param [out] output Buffer to hold encoding.
  13833. * @param [in] type Type of OID being encoded.
  13834. * @param [in] curveSz Add extra space for curve data.
  13835. * @return Encoded data size on success.
  13836. * @return 0 when dynamic memory allocation fails.
  13837. */
  13838. word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz)
  13839. {
  13840. #ifndef WOLFSSL_ASN_TEMPLATE
  13841. word32 tagSz, idSz, seqSz, algoSz = 0;
  13842. const byte* algoName = 0;
  13843. byte ID_Length[1 + MAX_LENGTH_SZ];
  13844. byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
  13845. word32 length = 0;
  13846. tagSz = (type == oidHashType ||
  13847. (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
  13848. (type == oidKeyType && algoOID == RSAk)) ? 2U : 0U;
  13849. algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
  13850. if (algoName == NULL) {
  13851. WOLFSSL_MSG("Unknown Algorithm");
  13852. return 0;
  13853. }
  13854. idSz = (word32)SetObjectId((int)algoSz, ID_Length);
  13855. seqSz = SetSequence(idSz + algoSz + tagSz + (word32)curveSz, seqArray);
  13856. /* Copy only algo to output for DSA keys */
  13857. if (algoOID == DSAk && output) {
  13858. XMEMCPY(output, ID_Length, idSz);
  13859. XMEMCPY(output + idSz, algoName, algoSz);
  13860. if (tagSz == 2)
  13861. SetASNNull(&output[seqSz + idSz + algoSz]);
  13862. }
  13863. else if (output) {
  13864. XMEMCPY(output, seqArray, seqSz);
  13865. XMEMCPY(output + seqSz, ID_Length, idSz);
  13866. XMEMCPY(output + seqSz + idSz, algoName, algoSz);
  13867. if (tagSz == 2)
  13868. SetASNNull(&output[seqSz + idSz + algoSz]);
  13869. }
  13870. if (algoOID == DSAk)
  13871. length = idSz + algoSz + tagSz;
  13872. else
  13873. length = seqSz + idSz + algoSz + tagSz;
  13874. return length;
  13875. #else
  13876. DECL_ASNSETDATA(dataASN, algoIdASN_Length);
  13877. int ret = 0;
  13878. const byte* algoName = 0;
  13879. word32 algoSz = 0;
  13880. CALLOC_ASNSETDATA(dataASN, algoIdASN_Length, ret, NULL);
  13881. algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
  13882. if (algoName == NULL) {
  13883. WOLFSSL_MSG("Unknown Algorithm");
  13884. }
  13885. else {
  13886. int sz;
  13887. int o = 0;
  13888. /* Set the OID and OID type to encode. */
  13889. SetASN_OID(&dataASN[ALGOIDASN_IDX_OID], (word32)algoOID, (word32)type);
  13890. /* Hashes, signatures not ECC and keys not RSA output NULL tag. */
  13891. if (!(type == oidHashType ||
  13892. (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
  13893. (type == oidKeyType && algoOID == RSAk))) {
  13894. /* Don't put out NULL DER item. */
  13895. dataASN[ALGOIDASN_IDX_NULL].noOut = 1;
  13896. }
  13897. if (algoOID == DSAk) {
  13898. /* Don't include SEQUENCE for DSA keys. */
  13899. o = 1;
  13900. }
  13901. else if (curveSz > 0) {
  13902. /* Don't put out NULL DER item. */
  13903. dataASN[ALGOIDASN_IDX_NULL].noOut = 0;
  13904. /* Include space for extra data of length curveSz.
  13905. * Subtract 1 for sequence and 1 for length encoding. */
  13906. SetASN_Buffer(&dataASN[ALGOIDASN_IDX_NULL], NULL,
  13907. (word32)curveSz - 2);
  13908. }
  13909. /* Calculate size of encoding. */
  13910. ret = SizeASN_Items(algoIdASN + o, dataASN + o,
  13911. (int)algoIdASN_Length - (int)o, &sz);
  13912. if (ret == 0 && output != NULL) {
  13913. /* Encode into buffer. */
  13914. SetASN_Items(algoIdASN + o, dataASN + o,
  13915. (int)algoIdASN_Length - (int)o, output);
  13916. if (curveSz > 0) {
  13917. /* Return size excluding curve data. */
  13918. sz = (int)(dataASN[o].offset -
  13919. dataASN[ALGOIDASN_IDX_NULL].offset);
  13920. }
  13921. }
  13922. if (ret == 0) {
  13923. /* Return encoded size. */
  13924. ret = sz;
  13925. }
  13926. else {
  13927. /* Unsigned return type so 0 indicates error. */
  13928. ret = 0;
  13929. }
  13930. }
  13931. FREE_ASNSETDATA(dataASN, NULL);
  13932. return (word32)ret;
  13933. #endif /* WOLFSSL_ASN_TEMPLATE */
  13934. }
  13935. #ifdef WOLFSSL_ASN_TEMPLATE
  13936. /* Always encode PKCS#1 v1.5 RSA signature and compare to encoded data. */
  13937. /* ASN.1 template for DigestInfo for a PKCS#1 v1.5 RSA signature.
  13938. * PKCS#1 v2.2: RFC 8017, A.2.4 - DigestInfo
  13939. */
  13940. static const ASNItem digestInfoASN[] = {
  13941. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  13942. /* digestAlgorithm */
  13943. /* DIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  13944. /* DIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  13945. /* DIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  13946. /* digest */
  13947. /* DIGEST */ { 1, ASN_OCTET_STRING, 0, 0, 0 }
  13948. };
  13949. enum {
  13950. DIGESTINFOASN_IDX_SEQ = 0,
  13951. DIGESTINFOASN_IDX_DIGALGO_SEQ,
  13952. DIGESTINFOASN_IDX_DIGALGO_OID,
  13953. DIGESTINFOASN_IDX_DIGALGO_NULL,
  13954. DIGESTINFOASN_IDX_DIGEST
  13955. };
  13956. /* Number of items in ASN.1 template for DigestInfo for RSA. */
  13957. #define digestInfoASN_Length (sizeof(digestInfoASN) / sizeof(ASNItem))
  13958. #endif
  13959. /* Encode signature.
  13960. *
  13961. * @param [out] out Buffer to hold encoding.
  13962. * @param [in] digest Buffer holding digest.
  13963. * @param [in] digSz Length of digest in bytes.
  13964. * @return Encoded data size on success.
  13965. * @return 0 when dynamic memory allocation fails.
  13966. */
  13967. word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz,
  13968. int hashOID)
  13969. {
  13970. #ifndef WOLFSSL_ASN_TEMPLATE
  13971. byte digArray[MAX_ENCODED_DIG_SZ];
  13972. byte algoArray[MAX_ALGO_SZ];
  13973. byte seqArray[MAX_SEQ_SZ];
  13974. word32 encDigSz, algoSz, seqSz;
  13975. encDigSz = SetDigest(digest, digSz, digArray);
  13976. algoSz = SetAlgoID(hashOID, algoArray, oidHashType, 0);
  13977. seqSz = SetSequence(encDigSz + algoSz, seqArray);
  13978. XMEMCPY(out, seqArray, seqSz);
  13979. XMEMCPY(out + seqSz, algoArray, algoSz);
  13980. XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
  13981. return encDigSz + algoSz + seqSz;
  13982. #else
  13983. DECL_ASNSETDATA(dataASN, digestInfoASN_Length);
  13984. int ret = 0;
  13985. int sz;
  13986. unsigned char dgst[WC_MAX_DIGEST_SIZE];
  13987. CALLOC_ASNSETDATA(dataASN, digestInfoASN_Length, ret, NULL);
  13988. if (ret == 0) {
  13989. /* Set hash OID and type. */
  13990. SetASN_OID(&dataASN[DIGESTINFOASN_IDX_DIGALGO_OID], (word32)hashOID,
  13991. oidHashType);
  13992. /* Set digest. */
  13993. if (digest == out) {
  13994. XMEMCPY(dgst, digest, digSz);
  13995. digest = dgst;
  13996. }
  13997. SetASN_Buffer(&dataASN[DIGESTINFOASN_IDX_DIGEST], digest, digSz);
  13998. /* Calculate size of encoding. */
  13999. ret = SizeASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, &sz);
  14000. }
  14001. if (ret == 0) {
  14002. /* Encode PKCS#1 v1.5 RSA signature. */
  14003. SetASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, out);
  14004. ret = sz;
  14005. }
  14006. else {
  14007. /* Unsigned return type so 0 indicates error. */
  14008. ret = 0;
  14009. }
  14010. FREE_ASNSETDATA(dataASN, NULL);
  14011. return (word32)ret;
  14012. #endif
  14013. }
  14014. #ifndef NO_CERTS
  14015. int wc_GetCTC_HashOID(int type)
  14016. {
  14017. int ret;
  14018. enum wc_HashType hType;
  14019. hType = wc_HashTypeConvert(type);
  14020. ret = wc_HashGetOID(hType);
  14021. if (ret < 0) {
  14022. ret = 0; /* backwards compatibility */
  14023. }
  14024. return ret;
  14025. }
  14026. /* Initialize a signature context object.
  14027. *
  14028. * Object used for signing and verifying a certificate signature.
  14029. *
  14030. * @param [in, out] sigCtx Signature context object.
  14031. * @param [in] heap Dynamic memory hint.
  14032. * @param [in] devId Hardware device identifier.
  14033. */
  14034. void InitSignatureCtx(SignatureCtx* sigCtx, void* heap, int devId)
  14035. {
  14036. if (sigCtx) {
  14037. XMEMSET(sigCtx, 0, sizeof(SignatureCtx));
  14038. sigCtx->devId = devId;
  14039. sigCtx->heap = heap;
  14040. }
  14041. }
  14042. /* Free dynamic data in a signature context object.
  14043. *
  14044. * @param [in, out] sigCtx Signature context object.
  14045. */
  14046. void FreeSignatureCtx(SignatureCtx* sigCtx)
  14047. {
  14048. if (sigCtx == NULL)
  14049. return;
  14050. if (sigCtx->digest) {
  14051. XFREE(sigCtx->digest, sigCtx->heap, DYNAMIC_TYPE_DIGEST);
  14052. sigCtx->digest = NULL;
  14053. }
  14054. #if !(defined(NO_RSA) && defined(NO_DSA))
  14055. if (sigCtx->sigCpy) {
  14056. XFREE(sigCtx->sigCpy, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  14057. sigCtx->sigCpy = NULL;
  14058. }
  14059. #endif
  14060. #ifndef NO_ASN_CRYPT
  14061. if (sigCtx->key.ptr) {
  14062. switch (sigCtx->keyOID) {
  14063. #ifndef NO_RSA
  14064. #ifdef WC_RSA_PSS
  14065. case RSAPSSk:
  14066. #endif
  14067. case RSAk:
  14068. wc_FreeRsaKey(sigCtx->key.rsa);
  14069. XFREE(sigCtx->key.rsa, sigCtx->heap, DYNAMIC_TYPE_RSA);
  14070. sigCtx->key.rsa = NULL;
  14071. break;
  14072. #endif /* !NO_RSA */
  14073. #ifndef NO_DSA
  14074. case DSAk:
  14075. wc_FreeDsaKey(sigCtx->key.dsa);
  14076. XFREE(sigCtx->key.dsa, sigCtx->heap, DYNAMIC_TYPE_DSA);
  14077. sigCtx->key.dsa = NULL;
  14078. break;
  14079. #endif
  14080. #ifdef HAVE_ECC
  14081. case ECDSAk:
  14082. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14083. defined(WC_ASYNC_ENABLE_ECC)
  14084. if (sigCtx->key.ecc->nb_ctx != NULL) {
  14085. XFREE(sigCtx->key.ecc->nb_ctx, sigCtx->heap,
  14086. DYNAMIC_TYPE_TMP_BUFFER);
  14087. }
  14088. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14089. WC_ASYNC_ENABLE_ECC */
  14090. wc_ecc_free(sigCtx->key.ecc);
  14091. XFREE(sigCtx->key.ecc, sigCtx->heap, DYNAMIC_TYPE_ECC);
  14092. sigCtx->key.ecc = NULL;
  14093. break;
  14094. #endif /* HAVE_ECC */
  14095. #ifdef HAVE_ED25519
  14096. case ED25519k:
  14097. wc_ed25519_free(sigCtx->key.ed25519);
  14098. XFREE(sigCtx->key.ed25519, sigCtx->heap, DYNAMIC_TYPE_ED25519);
  14099. sigCtx->key.ed25519 = NULL;
  14100. break;
  14101. #endif /* HAVE_ED25519 */
  14102. #ifdef HAVE_ED448
  14103. case ED448k:
  14104. wc_ed448_free(sigCtx->key.ed448);
  14105. XFREE(sigCtx->key.ed448, sigCtx->heap, DYNAMIC_TYPE_ED448);
  14106. sigCtx->key.ed448 = NULL;
  14107. break;
  14108. #endif /* HAVE_ED448 */
  14109. #if defined(HAVE_PQC)
  14110. #if defined(HAVE_FALCON)
  14111. case FALCON_LEVEL1k:
  14112. case FALCON_LEVEL5k:
  14113. wc_falcon_free(sigCtx->key.falcon);
  14114. XFREE(sigCtx->key.falcon, sigCtx->heap,
  14115. DYNAMIC_TYPE_FALCON);
  14116. sigCtx->key.falcon = NULL;
  14117. break;
  14118. #endif /* HAVE_FALCON */
  14119. #if defined(HAVE_DILITHIUM)
  14120. case DILITHIUM_LEVEL2k:
  14121. case DILITHIUM_LEVEL3k:
  14122. case DILITHIUM_LEVEL5k:
  14123. wc_dilithium_free(sigCtx->key.dilithium);
  14124. XFREE(sigCtx->key.dilithium, sigCtx->heap,
  14125. DYNAMIC_TYPE_DILITHIUM);
  14126. sigCtx->key.dilithium = NULL;
  14127. break;
  14128. #endif /* HAVE_DILITHIUM */
  14129. #if defined(HAVE_SPHINCS)
  14130. case SPHINCS_FAST_LEVEL1k:
  14131. case SPHINCS_FAST_LEVEL3k:
  14132. case SPHINCS_FAST_LEVEL5k:
  14133. case SPHINCS_SMALL_LEVEL1k:
  14134. case SPHINCS_SMALL_LEVEL3k:
  14135. case SPHINCS_SMALL_LEVEL5k:
  14136. wc_sphincs_free(sigCtx->key.sphincs);
  14137. XFREE(sigCtx->key.sphincs, sigCtx->heap,
  14138. DYNAMIC_TYPE_SPHINCS);
  14139. sigCtx->key.sphincs = NULL;
  14140. break;
  14141. #endif /* HAVE_SPHINCS */
  14142. #endif /* HAVE_PQC */
  14143. default:
  14144. break;
  14145. } /* switch (keyOID) */
  14146. sigCtx->key.ptr = NULL;
  14147. }
  14148. #endif
  14149. /* reset state, we are done */
  14150. sigCtx->state = SIG_STATE_BEGIN;
  14151. }
  14152. #if !defined(NO_ASN_CRYPT) && !defined(NO_HASH_WRAPPER)
  14153. static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID,
  14154. byte* digest, int* typeH, int* digestSz, int verify)
  14155. {
  14156. int ret = 0;
  14157. switch (sigOID) {
  14158. #if defined(WOLFSSL_MD2)
  14159. case CTC_MD2wRSA:
  14160. if (!verify) {
  14161. ret = HASH_TYPE_E;
  14162. WOLFSSL_MSG("MD2 not supported for signing");
  14163. }
  14164. else if ((ret = wc_Md2Hash(buf, bufSz, digest)) == 0) {
  14165. *typeH = MD2h;
  14166. *digestSz = MD2_DIGEST_SIZE;
  14167. }
  14168. break;
  14169. #endif
  14170. #ifndef NO_MD5
  14171. case CTC_MD5wRSA:
  14172. if ((ret = wc_Md5Hash(buf, bufSz, digest)) == 0) {
  14173. *typeH = MD5h;
  14174. *digestSz = WC_MD5_DIGEST_SIZE;
  14175. }
  14176. break;
  14177. #endif
  14178. #ifndef NO_SHA
  14179. case CTC_SHAwRSA:
  14180. case CTC_SHAwDSA:
  14181. case CTC_SHAwECDSA:
  14182. if ((ret = wc_ShaHash(buf, bufSz, digest)) == 0) {
  14183. *typeH = SHAh;
  14184. *digestSz = WC_SHA_DIGEST_SIZE;
  14185. }
  14186. break;
  14187. #endif
  14188. #ifdef WOLFSSL_SHA224
  14189. case CTC_SHA224wRSA:
  14190. case CTC_SHA224wECDSA:
  14191. if ((ret = wc_Sha224Hash(buf, bufSz, digest)) == 0) {
  14192. *typeH = SHA224h;
  14193. *digestSz = WC_SHA224_DIGEST_SIZE;
  14194. }
  14195. break;
  14196. #endif
  14197. #ifndef NO_SHA256
  14198. case CTC_SHA256wRSA:
  14199. case CTC_SHA256wECDSA:
  14200. case CTC_SHA256wDSA:
  14201. if ((ret = wc_Sha256Hash(buf, bufSz, digest)) == 0) {
  14202. *typeH = SHA256h;
  14203. *digestSz = WC_SHA256_DIGEST_SIZE;
  14204. }
  14205. break;
  14206. #endif
  14207. #ifdef WOLFSSL_SHA384
  14208. case CTC_SHA384wRSA:
  14209. case CTC_SHA384wECDSA:
  14210. if ((ret = wc_Sha384Hash(buf, bufSz, digest)) == 0) {
  14211. *typeH = SHA384h;
  14212. *digestSz = WC_SHA384_DIGEST_SIZE;
  14213. }
  14214. break;
  14215. #endif
  14216. #ifdef WOLFSSL_SHA512
  14217. case CTC_SHA512wRSA:
  14218. case CTC_SHA512wECDSA:
  14219. if ((ret = wc_Sha512Hash(buf, bufSz, digest)) == 0) {
  14220. *typeH = SHA512h;
  14221. *digestSz = WC_SHA512_DIGEST_SIZE;
  14222. }
  14223. break;
  14224. #endif
  14225. #ifdef WOLFSSL_SHA3
  14226. #ifndef WOLFSSL_NOSHA3_224
  14227. case CTC_SHA3_224wRSA:
  14228. case CTC_SHA3_224wECDSA:
  14229. if ((ret = wc_Sha3_224Hash(buf, bufSz, digest)) == 0) {
  14230. *typeH = SHA3_224h;
  14231. *digestSz = WC_SHA3_224_DIGEST_SIZE;
  14232. }
  14233. break;
  14234. #endif
  14235. #ifndef WOLFSSL_NOSHA3_256
  14236. case CTC_SHA3_256wRSA:
  14237. case CTC_SHA3_256wECDSA:
  14238. if ((ret = wc_Sha3_256Hash(buf, bufSz, digest)) == 0) {
  14239. *typeH = SHA3_256h;
  14240. *digestSz = WC_SHA3_256_DIGEST_SIZE;
  14241. }
  14242. break;
  14243. #endif
  14244. #ifndef WOLFSSL_NOSHA3_384
  14245. case CTC_SHA3_384wRSA:
  14246. case CTC_SHA3_384wECDSA:
  14247. if ((ret = wc_Sha3_384Hash(buf, bufSz, digest)) == 0) {
  14248. *typeH = SHA3_384h;
  14249. *digestSz = WC_SHA3_384_DIGEST_SIZE;
  14250. }
  14251. break;
  14252. #endif
  14253. #ifndef WOLFSSL_NOSHA3_512
  14254. case CTC_SHA3_512wRSA:
  14255. case CTC_SHA3_512wECDSA:
  14256. if ((ret = wc_Sha3_512Hash(buf, bufSz, digest)) == 0) {
  14257. *typeH = SHA3_512h;
  14258. *digestSz = WC_SHA3_512_DIGEST_SIZE;
  14259. }
  14260. break;
  14261. #endif
  14262. #endif
  14263. #ifdef HAVE_ED25519
  14264. case CTC_ED25519:
  14265. /* Hashes done in signing operation.
  14266. * Two dependent hashes with prefixes performed.
  14267. */
  14268. break;
  14269. #endif
  14270. #ifdef HAVE_ED448
  14271. case CTC_ED448:
  14272. /* Hashes done in signing operation.
  14273. * Two dependent hashes with prefixes performed.
  14274. */
  14275. break;
  14276. #endif
  14277. #ifdef HAVE_PQC
  14278. #ifdef HAVE_FALCON
  14279. case CTC_FALCON_LEVEL1:
  14280. case CTC_FALCON_LEVEL5:
  14281. /* Hashes done in signing operation. */
  14282. break;
  14283. #endif
  14284. #ifdef HAVE_DILITHIUM
  14285. case CTC_DILITHIUM_LEVEL2:
  14286. case CTC_DILITHIUM_LEVEL3:
  14287. case CTC_DILITHIUM_LEVEL5:
  14288. /* Hashes done in signing operation. */
  14289. break;
  14290. #endif
  14291. #ifdef HAVE_SPHINCS
  14292. case CTC_SPHINCS_FAST_LEVEL1:
  14293. case CTC_SPHINCS_FAST_LEVEL3:
  14294. case CTC_SPHINCS_FAST_LEVEL5:
  14295. case CTC_SPHINCS_SMALL_LEVEL1:
  14296. case CTC_SPHINCS_SMALL_LEVEL3:
  14297. case CTC_SPHINCS_SMALL_LEVEL5:
  14298. /* Hashes done in signing operation. */
  14299. break;
  14300. #endif
  14301. #endif /* HAVE_PQC */
  14302. default:
  14303. ret = HASH_TYPE_E;
  14304. WOLFSSL_MSG("Hash for Signature has unsupported type");
  14305. }
  14306. (void)buf;
  14307. (void)bufSz;
  14308. (void)sigOID;
  14309. (void)digest;
  14310. (void)digestSz;
  14311. (void)typeH;
  14312. (void)verify;
  14313. return ret;
  14314. }
  14315. #endif /* !NO_ASN_CRYPT && !NO_HASH_WRAPPER */
  14316. /* Return codes: 0=Success, Negative (see error-crypt.h), ASN_SIG_CONFIRM_E */
  14317. static int ConfirmSignature(SignatureCtx* sigCtx,
  14318. const byte* buf, word32 bufSz,
  14319. const byte* key, word32 keySz, word32 keyOID,
  14320. const byte* sig, word32 sigSz, word32 sigOID,
  14321. const byte* sigParams, word32 sigParamsSz,
  14322. byte* rsaKeyIdx)
  14323. {
  14324. int ret = 0;
  14325. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  14326. CertAttribute* certatt = NULL;
  14327. #endif
  14328. if (sigCtx == NULL || buf == NULL || bufSz == 0 || key == NULL ||
  14329. keySz == 0 || sig == NULL || sigSz == 0) {
  14330. return BAD_FUNC_ARG;
  14331. }
  14332. (void)key;
  14333. (void)keySz;
  14334. (void)sig;
  14335. (void)sigSz;
  14336. (void)sigParams;
  14337. (void)sigParamsSz;
  14338. WOLFSSL_ENTER("ConfirmSignature");
  14339. #if !defined(WOLFSSL_RENESAS_TSIP_TLS) && !defined(WOLFSSL_RENESAS_SCEPROTECT)
  14340. (void)rsaKeyIdx;
  14341. #else
  14342. #if !defined(NO_RSA) || defined(HAVE_ECC)
  14343. certatt = (CertAttribute*)&sigCtx->CertAtt;
  14344. #endif
  14345. if (certatt) {
  14346. certatt->keyIndex = rsaKeyIdx;
  14347. certatt->cert = buf;
  14348. certatt->certSz = bufSz;
  14349. }
  14350. #endif
  14351. #ifndef NO_ASN_CRYPT
  14352. switch (sigCtx->state) {
  14353. case SIG_STATE_BEGIN:
  14354. {
  14355. sigCtx->keyOID = keyOID; /* must set early for cleanup */
  14356. sigCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, sigCtx->heap,
  14357. DYNAMIC_TYPE_DIGEST);
  14358. if (sigCtx->digest == NULL) {
  14359. ERROR_OUT(MEMORY_E, exit_cs);
  14360. }
  14361. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  14362. /* RSA PSS Defaults */
  14363. sigCtx->hash = WC_HASH_TYPE_SHA;
  14364. sigCtx->mgf = WC_MGF1SHA1;
  14365. sigCtx->saltLen = 20;
  14366. #endif
  14367. sigCtx->state = SIG_STATE_HASH;
  14368. } /* SIG_STATE_BEGIN */
  14369. FALL_THROUGH;
  14370. case SIG_STATE_HASH:
  14371. {
  14372. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  14373. if (sigOID == RSAPSSk) {
  14374. word32 fakeSigOID = 0;
  14375. ret = DecodeRsaPssParams(sigParams, sigParamsSz, &sigCtx->hash,
  14376. &sigCtx->mgf, &sigCtx->saltLen);
  14377. if (ret != 0) {
  14378. goto exit_cs;
  14379. }
  14380. ret = RsaPssHashOidToSigOid(sigCtx->hash, &fakeSigOID);
  14381. if (ret != 0) {
  14382. goto exit_cs;
  14383. }
  14384. /* Decode parameters. */
  14385. ret = HashForSignature(buf, bufSz, fakeSigOID, sigCtx->digest,
  14386. &sigCtx->typeH, &sigCtx->digestSz, 1);
  14387. if (ret != 0) {
  14388. goto exit_cs;
  14389. }
  14390. }
  14391. else
  14392. #endif
  14393. {
  14394. ret = HashForSignature(buf, bufSz, sigOID, sigCtx->digest,
  14395. &sigCtx->typeH, &sigCtx->digestSz, 1);
  14396. if (ret != 0) {
  14397. goto exit_cs;
  14398. }
  14399. }
  14400. sigCtx->state = SIG_STATE_KEY;
  14401. } /* SIG_STATE_HASH */
  14402. FALL_THROUGH;
  14403. case SIG_STATE_KEY:
  14404. {
  14405. switch (keyOID) {
  14406. #ifndef NO_RSA
  14407. #ifdef WC_RSA_PSS
  14408. case RSAPSSk:
  14409. #endif
  14410. case RSAk:
  14411. {
  14412. word32 idx = 0;
  14413. sigCtx->key.rsa = (RsaKey*)XMALLOC(sizeof(RsaKey),
  14414. sigCtx->heap, DYNAMIC_TYPE_RSA);
  14415. if (sigCtx->key.rsa == NULL) {
  14416. ERROR_OUT(MEMORY_E, exit_cs);
  14417. }
  14418. if ((ret = wc_InitRsaKey_ex(sigCtx->key.rsa, sigCtx->heap,
  14419. sigCtx->devId)) != 0) {
  14420. goto exit_cs;
  14421. }
  14422. sigCtx->sigCpy = (byte*)XMALLOC(sigSz, sigCtx->heap,
  14423. DYNAMIC_TYPE_SIGNATURE);
  14424. if (sigCtx->sigCpy == NULL) {
  14425. ERROR_OUT(MEMORY_E, exit_cs);
  14426. }
  14427. if (sigSz > MAX_ENCODED_SIG_SZ) {
  14428. WOLFSSL_MSG("Verify Signature is too big");
  14429. ERROR_OUT(BUFFER_E, exit_cs);
  14430. }
  14431. if ((ret = wc_RsaPublicKeyDecode(key, &idx, sigCtx->key.rsa,
  14432. keySz)) != 0) {
  14433. WOLFSSL_MSG("ASN Key decode error RSA");
  14434. WOLFSSL_ERROR_VERBOSE(ret);
  14435. goto exit_cs;
  14436. }
  14437. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  14438. sigCtx->out = NULL;
  14439. #ifdef WOLFSSL_ASYNC_CRYPT
  14440. sigCtx->asyncDev = &sigCtx->key.rsa->asyncDev;
  14441. #endif
  14442. break;
  14443. }
  14444. #endif /* !NO_RSA */
  14445. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  14446. case DSAk:
  14447. {
  14448. word32 idx = 0;
  14449. if (sigSz < DSA_MIN_SIG_SIZE) {
  14450. WOLFSSL_MSG("Verify Signature is too small");
  14451. ERROR_OUT(BUFFER_E, exit_cs);
  14452. }
  14453. sigCtx->key.dsa = (DsaKey*)XMALLOC(sizeof(DsaKey),
  14454. sigCtx->heap, DYNAMIC_TYPE_DSA);
  14455. if (sigCtx->key.dsa == NULL) {
  14456. ERROR_OUT(MEMORY_E, exit_cs);
  14457. }
  14458. if ((ret = wc_InitDsaKey_h(sigCtx->key.dsa, sigCtx->heap)) != 0) {
  14459. WOLFSSL_MSG("wc_InitDsaKey_h error");
  14460. goto exit_cs;
  14461. }
  14462. sigCtx->sigCpy = (byte*)XMALLOC(sigSz,
  14463. sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  14464. if (sigCtx->sigCpy == NULL) {
  14465. ERROR_OUT(MEMORY_E, exit_cs);
  14466. }
  14467. if ((ret = wc_DsaPublicKeyDecode(key, &idx, sigCtx->key.dsa,
  14468. keySz)) != 0) {
  14469. WOLFSSL_MSG("ASN Key decode error DSA");
  14470. WOLFSSL_ERROR_VERBOSE(ret);
  14471. goto exit_cs;
  14472. }
  14473. if (sigSz != DSA_160_SIG_SIZE &&
  14474. sigSz != DSA_256_SIG_SIZE) {
  14475. /* Try to parse it as the contents of a bitstring */
  14476. #ifdef WOLFSSL_SMALL_STACK
  14477. mp_int* r;
  14478. mp_int* s;
  14479. #else
  14480. mp_int r[1];
  14481. mp_int s[1];
  14482. #endif
  14483. int rSz;
  14484. int sSz;
  14485. #ifdef WOLFSSL_SMALL_STACK
  14486. r = (mp_int*)XMALLOC(sizeof(*r), sigCtx->heap,
  14487. DYNAMIC_TYPE_TMP_BUFFER);
  14488. if (r == NULL) {
  14489. ERROR_OUT(MEMORY_E, exit_cs);
  14490. }
  14491. s = (mp_int*)XMALLOC(sizeof(*s), sigCtx->heap,
  14492. DYNAMIC_TYPE_TMP_BUFFER);
  14493. if (s == NULL) {
  14494. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14495. ERROR_OUT(MEMORY_E, exit_cs);
  14496. }
  14497. #endif
  14498. if ((ret = mp_init_multi(r, s, NULL, NULL, NULL, NULL)) != MP_OKAY) {
  14499. goto exit_cs;
  14500. }
  14501. idx = 0;
  14502. if (DecodeECC_DSA_Sig(sig + idx, sigSz - idx, r, s)
  14503. != 0) {
  14504. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14505. "incorrect format");
  14506. mp_free(r);
  14507. mp_free(s);
  14508. #ifdef WOLFSSL_SMALL_STACK
  14509. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14510. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14511. #endif
  14512. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14513. }
  14514. rSz = mp_unsigned_bin_size(r);
  14515. sSz = mp_unsigned_bin_size(s);
  14516. if (rSz + sSz > (int)sigSz) {
  14517. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14518. "incorrect format");
  14519. mp_free(r);
  14520. mp_free(s);
  14521. #ifdef WOLFSSL_SMALL_STACK
  14522. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14523. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14524. #endif
  14525. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14526. }
  14527. if (mp_to_unsigned_bin(r, sigCtx->sigCpy) != MP_OKAY ||
  14528. mp_to_unsigned_bin(s,
  14529. sigCtx->sigCpy + rSz) != MP_OKAY) {
  14530. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14531. "incorrect format");
  14532. mp_free(r);
  14533. mp_free(s);
  14534. #ifdef WOLFSSL_SMALL_STACK
  14535. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14536. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14537. #endif
  14538. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14539. }
  14540. mp_free(r);
  14541. mp_free(s);
  14542. #ifdef WOLFSSL_SMALL_STACK
  14543. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14544. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14545. #endif
  14546. }
  14547. else {
  14548. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  14549. }
  14550. break;
  14551. }
  14552. #endif /* !NO_DSA && !HAVE_SELFTEST */
  14553. #ifdef HAVE_ECC
  14554. case ECDSAk:
  14555. {
  14556. word32 idx = 0;
  14557. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14558. defined(WC_ASYNC_ENABLE_ECC)
  14559. ecc_nb_ctx_t* nbCtx;
  14560. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14561. WC_ASYNC_ENABLE_ECC */
  14562. sigCtx->verify = 0;
  14563. sigCtx->key.ecc = (ecc_key*)XMALLOC(sizeof(ecc_key),
  14564. sigCtx->heap, DYNAMIC_TYPE_ECC);
  14565. if (sigCtx->key.ecc == NULL) {
  14566. ERROR_OUT(MEMORY_E, exit_cs);
  14567. }
  14568. if ((ret = wc_ecc_init_ex(sigCtx->key.ecc, sigCtx->heap,
  14569. sigCtx->devId)) < 0) {
  14570. goto exit_cs;
  14571. }
  14572. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14573. defined(WC_ASYNC_ENABLE_ECC)
  14574. nbCtx = (ecc_nb_ctx_t*)XMALLOC(sizeof(ecc_nb_ctx_t),
  14575. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14576. if (nbCtx == NULL) {
  14577. ERROR_OUT(MEMORY_E, exit_cs);
  14578. }
  14579. else {
  14580. ret = wc_ecc_set_nonblock(sigCtx->key.ecc, nbCtx);
  14581. if (ret != 0) {
  14582. goto exit_cs;
  14583. }
  14584. }
  14585. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14586. WC_ASYNC_ENABLE_ECC */
  14587. ret = wc_EccPublicKeyDecode(key, &idx, sigCtx->key.ecc,
  14588. keySz);
  14589. if (ret < 0) {
  14590. WOLFSSL_MSG("ASN Key import error ECC");
  14591. WOLFSSL_ERROR_VERBOSE(ret);
  14592. goto exit_cs;
  14593. }
  14594. #ifdef WOLFSSL_ASYNC_CRYPT
  14595. sigCtx->asyncDev = &sigCtx->key.ecc->asyncDev;
  14596. #endif
  14597. break;
  14598. }
  14599. #endif /* HAVE_ECC */
  14600. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  14601. case ED25519k:
  14602. {
  14603. sigCtx->verify = 0;
  14604. sigCtx->key.ed25519 = (ed25519_key*)XMALLOC(
  14605. sizeof(ed25519_key), sigCtx->heap,
  14606. DYNAMIC_TYPE_ED25519);
  14607. if (sigCtx->key.ed25519 == NULL) {
  14608. ERROR_OUT(MEMORY_E, exit_cs);
  14609. }
  14610. if ((ret = wc_ed25519_init_ex(sigCtx->key.ed25519,
  14611. sigCtx->heap, sigCtx->devId)) < 0) {
  14612. goto exit_cs;
  14613. }
  14614. if ((ret = wc_ed25519_import_public(key, keySz,
  14615. sigCtx->key.ed25519)) < 0) {
  14616. WOLFSSL_MSG("ASN Key import error ED25519");
  14617. WOLFSSL_ERROR_VERBOSE(ret);
  14618. goto exit_cs;
  14619. }
  14620. #ifdef WOLFSSL_ASYNC_CRYPT
  14621. sigCtx->asyncDev = &sigCtx->key.ed25519->asyncDev;
  14622. #endif
  14623. break;
  14624. }
  14625. #endif
  14626. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  14627. case ED448k:
  14628. {
  14629. sigCtx->verify = 0;
  14630. sigCtx->key.ed448 = (ed448_key*)XMALLOC(
  14631. sizeof(ed448_key), sigCtx->heap,
  14632. DYNAMIC_TYPE_ED448);
  14633. if (sigCtx->key.ed448 == NULL) {
  14634. ERROR_OUT(MEMORY_E, exit_cs);
  14635. }
  14636. if ((ret = wc_ed448_init(sigCtx->key.ed448)) < 0) {
  14637. goto exit_cs;
  14638. }
  14639. if ((ret = wc_ed448_import_public(key, keySz,
  14640. sigCtx->key.ed448)) < 0) {
  14641. WOLFSSL_MSG("ASN Key import error ED448");
  14642. WOLFSSL_ERROR_VERBOSE(ret);
  14643. goto exit_cs;
  14644. }
  14645. #ifdef WOLFSSL_ASYNC_CRYPT
  14646. sigCtx->asyncDev = &sigCtx->key.ed448->asyncDev;
  14647. #endif
  14648. break;
  14649. }
  14650. #endif
  14651. #if defined(HAVE_PQC)
  14652. #if defined(HAVE_FALCON)
  14653. case FALCON_LEVEL1k:
  14654. {
  14655. sigCtx->verify = 0;
  14656. sigCtx->key.falcon =
  14657. (falcon_key*)XMALLOC(sizeof(falcon_key),
  14658. sigCtx->heap,
  14659. DYNAMIC_TYPE_FALCON);
  14660. if (sigCtx->key.falcon == NULL) {
  14661. ERROR_OUT(MEMORY_E, exit_cs);
  14662. }
  14663. if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
  14664. goto exit_cs;
  14665. }
  14666. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 1))
  14667. < 0) {
  14668. goto exit_cs;
  14669. }
  14670. if ((ret = wc_falcon_import_public(key, keySz,
  14671. sigCtx->key.falcon)) < 0) {
  14672. WOLFSSL_MSG("ASN Key import error Falcon Level 1");
  14673. WOLFSSL_ERROR_VERBOSE(ret);
  14674. goto exit_cs;
  14675. }
  14676. break;
  14677. }
  14678. case FALCON_LEVEL5k:
  14679. {
  14680. sigCtx->verify = 0;
  14681. sigCtx->key.falcon =
  14682. (falcon_key*)XMALLOC(sizeof(falcon_key),
  14683. sigCtx->heap,
  14684. DYNAMIC_TYPE_FALCON);
  14685. if (sigCtx->key.falcon == NULL) {
  14686. ERROR_OUT(MEMORY_E, exit_cs);
  14687. }
  14688. if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
  14689. goto exit_cs;
  14690. }
  14691. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 5))
  14692. < 0) {
  14693. goto exit_cs;
  14694. }
  14695. if ((ret = wc_falcon_import_public(key, keySz,
  14696. sigCtx->key.falcon)) < 0) {
  14697. WOLFSSL_MSG("ASN Key import error Falcon Level 5");
  14698. WOLFSSL_ERROR_VERBOSE(ret);
  14699. goto exit_cs;
  14700. }
  14701. break;
  14702. }
  14703. #endif /* HAVE_FALCON */
  14704. #if defined(HAVE_DILITHIUM)
  14705. case DILITHIUM_LEVEL2k:
  14706. {
  14707. sigCtx->verify = 0;
  14708. sigCtx->key.dilithium =
  14709. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14710. sigCtx->heap,
  14711. DYNAMIC_TYPE_DILITHIUM);
  14712. if (sigCtx->key.dilithium == NULL) {
  14713. ERROR_OUT(MEMORY_E, exit_cs);
  14714. }
  14715. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14716. goto exit_cs;
  14717. }
  14718. if ((ret = wc_dilithium_set_level(
  14719. sigCtx->key.dilithium, 2))
  14720. < 0) {
  14721. goto exit_cs;
  14722. }
  14723. if ((ret = wc_dilithium_import_public(key, keySz,
  14724. sigCtx->key.dilithium)) < 0) {
  14725. WOLFSSL_MSG("ASN Key import error Dilithium Level 2");
  14726. goto exit_cs;
  14727. }
  14728. break;
  14729. }
  14730. case DILITHIUM_LEVEL3k:
  14731. {
  14732. sigCtx->verify = 0;
  14733. sigCtx->key.dilithium =
  14734. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14735. sigCtx->heap,
  14736. DYNAMIC_TYPE_DILITHIUM);
  14737. if (sigCtx->key.dilithium == NULL) {
  14738. ERROR_OUT(MEMORY_E, exit_cs);
  14739. }
  14740. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14741. goto exit_cs;
  14742. }
  14743. if ((ret = wc_dilithium_set_level(
  14744. sigCtx->key.dilithium, 3))
  14745. < 0) {
  14746. goto exit_cs;
  14747. }
  14748. if ((ret = wc_dilithium_import_public(key, keySz,
  14749. sigCtx->key.dilithium)) < 0) {
  14750. WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
  14751. goto exit_cs;
  14752. }
  14753. break;
  14754. }
  14755. case DILITHIUM_LEVEL5k:
  14756. {
  14757. sigCtx->verify = 0;
  14758. sigCtx->key.dilithium =
  14759. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14760. sigCtx->heap,
  14761. DYNAMIC_TYPE_DILITHIUM);
  14762. if (sigCtx->key.dilithium == NULL) {
  14763. ERROR_OUT(MEMORY_E, exit_cs);
  14764. }
  14765. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14766. goto exit_cs;
  14767. }
  14768. if ((ret = wc_dilithium_set_level(
  14769. sigCtx->key.dilithium, 5))
  14770. < 0) {
  14771. goto exit_cs;
  14772. }
  14773. if ((ret = wc_dilithium_import_public(key, keySz,
  14774. sigCtx->key.dilithium)) < 0) {
  14775. WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
  14776. goto exit_cs;
  14777. }
  14778. break;
  14779. }
  14780. #endif /* HAVE_DILITHIUM */
  14781. #if defined(HAVE_SPHINCS)
  14782. case SPHINCS_FAST_LEVEL1k:
  14783. {
  14784. sigCtx->verify = 0;
  14785. sigCtx->key.sphincs =
  14786. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14787. sigCtx->heap,
  14788. DYNAMIC_TYPE_SPHINCS);
  14789. if (sigCtx->key.sphincs == NULL) {
  14790. ERROR_OUT(MEMORY_E, exit_cs);
  14791. }
  14792. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14793. goto exit_cs;
  14794. }
  14795. if ((ret = wc_sphincs_set_level_and_optim(
  14796. sigCtx->key.sphincs, 1, FAST_VARIANT))
  14797. < 0) {
  14798. goto exit_cs;
  14799. }
  14800. if ((ret = wc_sphincs_import_public(key, keySz,
  14801. sigCtx->key.sphincs)) < 0) {
  14802. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
  14803. goto exit_cs;
  14804. }
  14805. break;
  14806. }
  14807. case SPHINCS_FAST_LEVEL3k:
  14808. {
  14809. sigCtx->verify = 0;
  14810. sigCtx->key.sphincs =
  14811. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14812. sigCtx->heap,
  14813. DYNAMIC_TYPE_SPHINCS);
  14814. if (sigCtx->key.sphincs == NULL) {
  14815. ERROR_OUT(MEMORY_E, exit_cs);
  14816. }
  14817. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14818. goto exit_cs;
  14819. }
  14820. if ((ret = wc_sphincs_set_level_and_optim(
  14821. sigCtx->key.sphincs, 3, FAST_VARIANT))
  14822. < 0) {
  14823. goto exit_cs;
  14824. }
  14825. if ((ret = wc_sphincs_import_public(key, keySz,
  14826. sigCtx->key.sphincs)) < 0) {
  14827. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
  14828. goto exit_cs;
  14829. }
  14830. break;
  14831. }
  14832. case SPHINCS_FAST_LEVEL5k:
  14833. {
  14834. sigCtx->verify = 0;
  14835. sigCtx->key.sphincs =
  14836. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14837. sigCtx->heap,
  14838. DYNAMIC_TYPE_SPHINCS);
  14839. if (sigCtx->key.sphincs == NULL) {
  14840. ERROR_OUT(MEMORY_E, exit_cs);
  14841. }
  14842. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14843. goto exit_cs;
  14844. }
  14845. if ((ret = wc_sphincs_set_level_and_optim(
  14846. sigCtx->key.sphincs, 5, FAST_VARIANT))
  14847. < 0) {
  14848. goto exit_cs;
  14849. }
  14850. if ((ret = wc_sphincs_import_public(key, keySz,
  14851. sigCtx->key.sphincs)) < 0) {
  14852. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
  14853. goto exit_cs;
  14854. }
  14855. break;
  14856. }
  14857. case SPHINCS_SMALL_LEVEL1k:
  14858. {
  14859. sigCtx->verify = 0;
  14860. sigCtx->key.sphincs =
  14861. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14862. sigCtx->heap,
  14863. DYNAMIC_TYPE_SPHINCS);
  14864. if (sigCtx->key.sphincs == NULL) {
  14865. ERROR_OUT(MEMORY_E, exit_cs);
  14866. }
  14867. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14868. goto exit_cs;
  14869. }
  14870. if ((ret = wc_sphincs_set_level_and_optim(
  14871. sigCtx->key.sphincs, 1, SMALL_VARIANT))
  14872. < 0) {
  14873. goto exit_cs;
  14874. }
  14875. if ((ret = wc_sphincs_import_public(key, keySz,
  14876. sigCtx->key.sphincs)) < 0) {
  14877. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
  14878. goto exit_cs;
  14879. }
  14880. break;
  14881. }
  14882. case SPHINCS_SMALL_LEVEL3k:
  14883. {
  14884. sigCtx->verify = 0;
  14885. sigCtx->key.sphincs =
  14886. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14887. sigCtx->heap,
  14888. DYNAMIC_TYPE_SPHINCS);
  14889. if (sigCtx->key.sphincs == NULL) {
  14890. ERROR_OUT(MEMORY_E, exit_cs);
  14891. }
  14892. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14893. goto exit_cs;
  14894. }
  14895. if ((ret = wc_sphincs_set_level_and_optim(
  14896. sigCtx->key.sphincs, 3, SMALL_VARIANT))
  14897. < 0) {
  14898. goto exit_cs;
  14899. }
  14900. if ((ret = wc_sphincs_import_public(key, keySz,
  14901. sigCtx->key.sphincs)) < 0) {
  14902. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
  14903. goto exit_cs;
  14904. }
  14905. break;
  14906. }
  14907. case SPHINCS_SMALL_LEVEL5k:
  14908. {
  14909. sigCtx->verify = 0;
  14910. sigCtx->key.sphincs =
  14911. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14912. sigCtx->heap,
  14913. DYNAMIC_TYPE_SPHINCS);
  14914. if (sigCtx->key.sphincs == NULL) {
  14915. ERROR_OUT(MEMORY_E, exit_cs);
  14916. }
  14917. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14918. goto exit_cs;
  14919. }
  14920. if ((ret = wc_sphincs_set_level_and_optim(
  14921. sigCtx->key.sphincs, 5, SMALL_VARIANT))
  14922. < 0) {
  14923. goto exit_cs;
  14924. }
  14925. if ((ret = wc_sphincs_import_public(key, keySz,
  14926. sigCtx->key.sphincs)) < 0) {
  14927. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
  14928. goto exit_cs;
  14929. }
  14930. break;
  14931. }
  14932. #endif /* HAVE_SPHINCS */
  14933. #endif /* HAVE_PQC */
  14934. default:
  14935. WOLFSSL_MSG("Verify Key type unknown");
  14936. ret = ASN_UNKNOWN_OID_E;
  14937. WOLFSSL_ERROR_VERBOSE(ret);
  14938. break;
  14939. } /* switch (keyOID) */
  14940. if (ret != 0) {
  14941. goto exit_cs;
  14942. }
  14943. sigCtx->state = SIG_STATE_DO;
  14944. #ifdef WOLFSSL_ASYNC_CRYPT
  14945. if (sigCtx->devId != INVALID_DEVID && sigCtx->asyncDev && sigCtx->asyncCtx) {
  14946. /* make sure event is initialized */
  14947. WOLF_EVENT* event = &sigCtx->asyncDev->event;
  14948. ret = wolfAsync_EventInit(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL,
  14949. sigCtx->asyncCtx, WC_ASYNC_FLAG_CALL_AGAIN);
  14950. }
  14951. #endif
  14952. } /* SIG_STATE_KEY */
  14953. FALL_THROUGH;
  14954. case SIG_STATE_DO:
  14955. {
  14956. switch (keyOID) {
  14957. #ifndef NO_RSA
  14958. case RSAk:
  14959. #ifdef WC_RSA_PSS
  14960. case RSAPSSk:
  14961. if (sigOID == RSAPSSk) {
  14962. /* TODO: pkCbRsaPss - RSA PSS callback. */
  14963. ret = wc_RsaPSS_VerifyInline_ex(sigCtx->sigCpy, sigSz,
  14964. &sigCtx->out, sigCtx->hash, sigCtx->mgf,
  14965. sigCtx->saltLen, sigCtx->key.rsa);
  14966. }
  14967. else
  14968. #endif
  14969. {
  14970. #if defined(HAVE_PK_CALLBACKS)
  14971. if (sigCtx->pkCbRsa) {
  14972. ret = sigCtx->pkCbRsa(
  14973. sigCtx->sigCpy, sigSz, &sigCtx->out,
  14974. key, keySz,
  14975. sigCtx->pkCtxRsa);
  14976. }
  14977. #if !defined(WOLFSSL_RENESAS_SCEPROTECT) && \
  14978. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  14979. else
  14980. #else
  14981. if (!sigCtx->pkCbRsa || ret == CRYPTOCB_UNAVAILABLE)
  14982. #endif /* WOLFSSL_RENESAS_SCEPROTECT */
  14983. #endif /* HAVE_PK_CALLBACKS */
  14984. {
  14985. ret = wc_RsaSSL_VerifyInline(sigCtx->sigCpy, sigSz,
  14986. &sigCtx->out, sigCtx->key.rsa);
  14987. }
  14988. }
  14989. break;
  14990. #endif /* !NO_RSA */
  14991. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  14992. case DSAk:
  14993. {
  14994. ret = wc_DsaVerify(sigCtx->digest, sigCtx->sigCpy,
  14995. sigCtx->key.dsa, &sigCtx->verify);
  14996. break;
  14997. }
  14998. #endif /* !NO_DSA && !HAVE_SELFTEST */
  14999. #if defined(HAVE_ECC) && defined(HAVE_ECC_VERIFY)
  15000. case ECDSAk:
  15001. {
  15002. #if defined(HAVE_PK_CALLBACKS)
  15003. if (sigCtx->pkCbEcc) {
  15004. ret = sigCtx->pkCbEcc(
  15005. sig, sigSz,
  15006. sigCtx->digest, (unsigned int)sigCtx->digestSz,
  15007. key, keySz, &sigCtx->verify,
  15008. sigCtx->pkCtxEcc);
  15009. }
  15010. #if !defined(WOLFSSL_RENESAS_SCEPROTECT) && \
  15011. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  15012. else
  15013. #else
  15014. if (!sigCtx->pkCbEcc || ret == CRYPTOCB_UNAVAILABLE)
  15015. #endif /* WOLFSSL_RENESAS_SCEPROTECT */
  15016. #endif /* HAVE_PK_CALLBACKS */
  15017. {
  15018. ret = wc_ecc_verify_hash(sig, sigSz, sigCtx->digest,
  15019. (word32)sigCtx->digestSz, &sigCtx->verify,
  15020. sigCtx->key.ecc);
  15021. }
  15022. break;
  15023. }
  15024. #endif /* HAVE_ECC */
  15025. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_VERIFY)
  15026. case ED25519k:
  15027. {
  15028. ret = wc_ed25519_verify_msg(sig, sigSz, buf, bufSz,
  15029. &sigCtx->verify, sigCtx->key.ed25519);
  15030. break;
  15031. }
  15032. #endif
  15033. #if defined(HAVE_ED448) && defined(HAVE_ED448_VERIFY)
  15034. case ED448k:
  15035. {
  15036. ret = wc_ed448_verify_msg(sig, sigSz, buf, bufSz,
  15037. &sigCtx->verify, sigCtx->key.ed448,
  15038. NULL, 0);
  15039. break;
  15040. }
  15041. #endif
  15042. #if defined(HAVE_PQC)
  15043. #if defined(HAVE_FALCON)
  15044. case FALCON_LEVEL1k:
  15045. case FALCON_LEVEL5k:
  15046. {
  15047. ret = wc_falcon_verify_msg(sig, sigSz, buf, bufSz,
  15048. &sigCtx->verify,
  15049. sigCtx->key.falcon);
  15050. break;
  15051. }
  15052. #endif /* HAVE_FALCON */
  15053. #if defined(HAVE_DILITHIUM)
  15054. case DILITHIUM_LEVEL2k:
  15055. case DILITHIUM_LEVEL3k:
  15056. case DILITHIUM_LEVEL5k:
  15057. {
  15058. ret = wc_dilithium_verify_msg(sig, sigSz, buf, bufSz,
  15059. &sigCtx->verify,
  15060. sigCtx->key.dilithium);
  15061. break;
  15062. }
  15063. #endif /* HAVE_DILITHIUM */
  15064. #if defined(HAVE_SPHINCS)
  15065. case SPHINCS_FAST_LEVEL1k:
  15066. case SPHINCS_FAST_LEVEL3k:
  15067. case SPHINCS_FAST_LEVEL5k:
  15068. case SPHINCS_SMALL_LEVEL1k:
  15069. case SPHINCS_SMALL_LEVEL3k:
  15070. case SPHINCS_SMALL_LEVEL5k:
  15071. {
  15072. ret = wc_sphincs_verify_msg(sig, sigSz, buf, bufSz,
  15073. &sigCtx->verify,
  15074. sigCtx->key.sphincs);
  15075. break;
  15076. }
  15077. #endif /* HAVE_SPHINCS */
  15078. #endif /* HAVE_PQC */
  15079. default:
  15080. break;
  15081. } /* switch (keyOID) */
  15082. #ifdef WOLFSSL_ASYNC_CRYPT
  15083. if (ret == WC_PENDING_E) {
  15084. goto exit_cs;
  15085. }
  15086. #endif
  15087. if (ret < 0) {
  15088. /* treat all errors as ASN_SIG_CONFIRM_E */
  15089. ret = ASN_SIG_CONFIRM_E;
  15090. WOLFSSL_ERROR_VERBOSE(ret);
  15091. goto exit_cs;
  15092. }
  15093. sigCtx->state = SIG_STATE_CHECK;
  15094. } /* SIG_STATE_DO */
  15095. FALL_THROUGH;
  15096. case SIG_STATE_CHECK:
  15097. {
  15098. switch (keyOID) {
  15099. #ifndef NO_RSA
  15100. case RSAk:
  15101. #ifdef WC_RSA_PSS
  15102. case RSAPSSk:
  15103. if (sigOID == RSAPSSk) {
  15104. #if (defined(HAVE_SELFTEST) && \
  15105. (!defined(HAVE_SELFTEST_VERSION) || \
  15106. (HAVE_SELFTEST_VERSION < 2))) || \
  15107. (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  15108. (HAVE_FIPS_VERSION < 2))
  15109. ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
  15110. sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
  15111. sigCtx->saltLen);
  15112. #elif (defined(HAVE_SELFTEST) && \
  15113. (HAVE_SELFTEST_VERSION == 2)) || \
  15114. (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  15115. (HAVE_FIPS_VERSION == 2))
  15116. ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
  15117. sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
  15118. sigCtx->saltLen, 0);
  15119. #else
  15120. ret = wc_RsaPSS_CheckPadding_ex2(sigCtx->digest,
  15121. (word32)sigCtx->digestSz, sigCtx->out, (word32)ret, sigCtx->hash,
  15122. sigCtx->saltLen, wc_RsaEncryptSize(sigCtx->key.rsa) * 8,
  15123. sigCtx->heap);
  15124. #endif
  15125. break;
  15126. }
  15127. else
  15128. #endif
  15129. {
  15130. int encodedSigSz, verifySz;
  15131. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || \
  15132. defined(WOLFSSL_RENESAS_SCEPROTECT)
  15133. if (sigCtx->CertAtt.verifyByTSIP_SCE == 1) break;
  15134. #endif
  15135. #ifdef WOLFSSL_SMALL_STACK
  15136. byte* encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  15137. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15138. if (encodedSig == NULL) {
  15139. ERROR_OUT(MEMORY_E, exit_cs);
  15140. }
  15141. #else
  15142. byte encodedSig[MAX_ENCODED_SIG_SZ];
  15143. #endif
  15144. verifySz = ret;
  15145. /* make sure we're right justified */
  15146. encodedSigSz = (int)wc_EncodeSignature(encodedSig,
  15147. sigCtx->digest, (word32)sigCtx->digestSz,
  15148. sigCtx->typeH);
  15149. if (encodedSigSz == verifySz && sigCtx->out != NULL &&
  15150. XMEMCMP(sigCtx->out, encodedSig,
  15151. (size_t)encodedSigSz) == 0) {
  15152. ret = 0;
  15153. }
  15154. else {
  15155. WOLFSSL_MSG("RSA SSL verify match encode error");
  15156. ret = ASN_SIG_CONFIRM_E;
  15157. WOLFSSL_ERROR_VERBOSE(ret);
  15158. }
  15159. #ifdef WOLFSSL_SMALL_STACK
  15160. XFREE(encodedSig, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15161. #endif
  15162. break;
  15163. }
  15164. #endif /* NO_RSA */
  15165. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  15166. case DSAk:
  15167. {
  15168. if (sigCtx->verify == 1) {
  15169. ret = 0;
  15170. }
  15171. else {
  15172. WOLFSSL_MSG("DSA Verify didn't match");
  15173. ret = ASN_SIG_CONFIRM_E;
  15174. WOLFSSL_ERROR_VERBOSE(ret);
  15175. }
  15176. break;
  15177. }
  15178. #endif /* !NO_DSA && !HAVE_SELFTEST */
  15179. #ifdef HAVE_ECC
  15180. case ECDSAk:
  15181. {
  15182. if (sigCtx->verify == 1) {
  15183. ret = 0;
  15184. }
  15185. else {
  15186. WOLFSSL_MSG("ECC Verify didn't match");
  15187. ret = ASN_SIG_CONFIRM_E;
  15188. WOLFSSL_ERROR_VERBOSE(ret);
  15189. }
  15190. break;
  15191. }
  15192. #endif /* HAVE_ECC */
  15193. #ifdef HAVE_ED25519
  15194. case ED25519k:
  15195. {
  15196. if (sigCtx->verify == 1) {
  15197. ret = 0;
  15198. }
  15199. else {
  15200. WOLFSSL_MSG("ED25519 Verify didn't match");
  15201. ret = ASN_SIG_CONFIRM_E;
  15202. WOLFSSL_ERROR_VERBOSE(ret);
  15203. }
  15204. break;
  15205. }
  15206. #endif /* HAVE_ED25519 */
  15207. #ifdef HAVE_ED448
  15208. case ED448k:
  15209. {
  15210. if (sigCtx->verify == 1) {
  15211. ret = 0;
  15212. }
  15213. else {
  15214. WOLFSSL_MSG("ED448 Verify didn't match");
  15215. ret = ASN_SIG_CONFIRM_E;
  15216. WOLFSSL_ERROR_VERBOSE(ret);
  15217. }
  15218. break;
  15219. }
  15220. #endif /* HAVE_ED448 */
  15221. #ifdef HAVE_PQC
  15222. #ifdef HAVE_FALCON
  15223. case FALCON_LEVEL1k:
  15224. {
  15225. if (sigCtx->verify == 1) {
  15226. ret = 0;
  15227. }
  15228. else {
  15229. WOLFSSL_MSG("FALCON_LEVEL1 Verify didn't match");
  15230. ret = ASN_SIG_CONFIRM_E;
  15231. WOLFSSL_ERROR_VERBOSE(ret);
  15232. }
  15233. break;
  15234. }
  15235. case FALCON_LEVEL5k:
  15236. {
  15237. if (sigCtx->verify == 1) {
  15238. ret = 0;
  15239. }
  15240. else {
  15241. WOLFSSL_MSG("FALCON_LEVEL5 Verify didn't match");
  15242. ret = ASN_SIG_CONFIRM_E;
  15243. WOLFSSL_ERROR_VERBOSE(ret);
  15244. }
  15245. break;
  15246. }
  15247. #endif /* HAVE_FALCON */
  15248. #ifdef HAVE_DILITHIUM
  15249. case DILITHIUM_LEVEL2k:
  15250. {
  15251. if (sigCtx->verify == 1) {
  15252. ret = 0;
  15253. }
  15254. else {
  15255. WOLFSSL_MSG("DILITHIUM_LEVEL2 Verify didn't match");
  15256. ret = ASN_SIG_CONFIRM_E;
  15257. }
  15258. break;
  15259. }
  15260. case DILITHIUM_LEVEL3k:
  15261. {
  15262. if (sigCtx->verify == 1) {
  15263. ret = 0;
  15264. }
  15265. else {
  15266. WOLFSSL_MSG("DILITHIUM_LEVEL3 Verify didn't match");
  15267. ret = ASN_SIG_CONFIRM_E;
  15268. }
  15269. break;
  15270. }
  15271. case DILITHIUM_LEVEL5k:
  15272. {
  15273. if (sigCtx->verify == 1) {
  15274. ret = 0;
  15275. }
  15276. else {
  15277. WOLFSSL_MSG("DILITHIUM_LEVEL5 Verify didn't match");
  15278. ret = ASN_SIG_CONFIRM_E;
  15279. }
  15280. break;
  15281. }
  15282. #endif /* HAVE_DILITHIUM */
  15283. #ifdef HAVE_SPHINCS
  15284. case SPHINCS_FAST_LEVEL1k:
  15285. {
  15286. if (sigCtx->verify == 1) {
  15287. ret = 0;
  15288. }
  15289. else {
  15290. WOLFSSL_MSG("SPHINCS_FAST_LEVEL1 Verify didn't match");
  15291. ret = ASN_SIG_CONFIRM_E;
  15292. }
  15293. break;
  15294. }
  15295. case SPHINCS_FAST_LEVEL3k:
  15296. {
  15297. if (sigCtx->verify == 1) {
  15298. ret = 0;
  15299. }
  15300. else {
  15301. WOLFSSL_MSG("SPHINCS_FAST_LEVEL3 Verify didn't match");
  15302. ret = ASN_SIG_CONFIRM_E;
  15303. }
  15304. break;
  15305. }
  15306. case SPHINCS_FAST_LEVEL5k:
  15307. {
  15308. if (sigCtx->verify == 1) {
  15309. ret = 0;
  15310. }
  15311. else {
  15312. WOLFSSL_MSG("SPHINCS_FAST_LEVEL5 Verify didn't match");
  15313. ret = ASN_SIG_CONFIRM_E;
  15314. }
  15315. break;
  15316. }
  15317. case SPHINCS_SMALL_LEVEL1k:
  15318. {
  15319. if (sigCtx->verify == 1) {
  15320. ret = 0;
  15321. }
  15322. else {
  15323. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL1 Verify didn't match");
  15324. ret = ASN_SIG_CONFIRM_E;
  15325. }
  15326. break;
  15327. }
  15328. case SPHINCS_SMALL_LEVEL3k:
  15329. {
  15330. if (sigCtx->verify == 1) {
  15331. ret = 0;
  15332. }
  15333. else {
  15334. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL3 Verify didn't match");
  15335. ret = ASN_SIG_CONFIRM_E;
  15336. }
  15337. break;
  15338. }
  15339. case SPHINCS_SMALL_LEVEL5k:
  15340. {
  15341. if (sigCtx->verify == 1) {
  15342. ret = 0;
  15343. }
  15344. else {
  15345. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL5 Verify didn't match");
  15346. ret = ASN_SIG_CONFIRM_E;
  15347. }
  15348. break;
  15349. }
  15350. #endif /* HAVE_SPHINCS */
  15351. #endif /* HAVE_PQC */
  15352. default:
  15353. break;
  15354. } /* switch (keyOID) */
  15355. break;
  15356. } /* SIG_STATE_CHECK */
  15357. default:
  15358. break;
  15359. } /* switch (sigCtx->state) */
  15360. exit_cs:
  15361. #endif /* !NO_ASN_CRYPT */
  15362. (void)keyOID;
  15363. (void)sigOID;
  15364. WOLFSSL_LEAVE("ConfirmSignature", ret);
  15365. #ifdef WOLFSSL_ASYNC_CRYPT
  15366. if (ret == WC_PENDING_E)
  15367. return ret;
  15368. #endif
  15369. FreeSignatureCtx(sigCtx);
  15370. return ret;
  15371. }
  15372. #ifndef IGNORE_NAME_CONSTRAINTS
  15373. static int MatchBaseName(int type, const char* name, int nameSz,
  15374. const char* base, int baseSz)
  15375. {
  15376. if (base == NULL || baseSz <= 0 || name == NULL || nameSz <= 0 ||
  15377. name[0] == '.' || nameSz < baseSz ||
  15378. (type != ASN_RFC822_TYPE && type != ASN_DNS_TYPE &&
  15379. type != ASN_DIR_TYPE)) {
  15380. return 0;
  15381. }
  15382. if (type == ASN_DIR_TYPE)
  15383. return XMEMCMP(name, base, (size_t)baseSz) == 0;
  15384. /* If an email type, handle special cases where the base is only
  15385. * a domain, or is an email address itself. */
  15386. if (type == ASN_RFC822_TYPE) {
  15387. const char* p = NULL;
  15388. int count = 0;
  15389. if (base[0] != '.') {
  15390. p = base;
  15391. count = 0;
  15392. /* find the '@' in the base */
  15393. while (*p != '@' && count < baseSz) {
  15394. count++;
  15395. p++;
  15396. }
  15397. /* No '@' in base, reset p to NULL */
  15398. if (count >= baseSz)
  15399. p = NULL;
  15400. }
  15401. if (p == NULL) {
  15402. /* Base isn't an email address, it is a domain name,
  15403. * wind the name forward one character past its '@'. */
  15404. p = name;
  15405. count = 0;
  15406. while (*p != '@' && count < baseSz) {
  15407. count++;
  15408. p++;
  15409. }
  15410. if (count < baseSz && *p == '@') {
  15411. name = p + 1;
  15412. nameSz -= count + 1;
  15413. }
  15414. }
  15415. }
  15416. /* RFC 5280 section 4.2.1.10
  15417. * "...Any DNS name that can be constructed by simply adding zero or more
  15418. * labels to the left-hand side of the name satisfies the name constraint."
  15419. * i.e www.host.example.com works for host.example.com name constraint and
  15420. * host1.example.com does not. */
  15421. if (type == ASN_DNS_TYPE || (type == ASN_RFC822_TYPE && base[0] == '.')) {
  15422. int szAdjust = nameSz - baseSz;
  15423. name += szAdjust;
  15424. nameSz -= szAdjust;
  15425. }
  15426. while (nameSz > 0) {
  15427. if (XTOLOWER((unsigned char)*name++) !=
  15428. XTOLOWER((unsigned char)*base++))
  15429. return 0;
  15430. nameSz--;
  15431. }
  15432. return 1;
  15433. }
  15434. /* Search through the list to find if the name is permitted.
  15435. * name The DNS name to search for
  15436. * dnsList The list to search through
  15437. * nameType Type of DNS name to currently searching
  15438. * return 1 if found in list or if not needed
  15439. * return 0 if not found in the list but is needed
  15440. */
  15441. static int PermittedListOk(DNS_entry* name, Base_entry* dnsList, byte nameType)
  15442. {
  15443. Base_entry* current = dnsList;
  15444. int match = 0;
  15445. int need = 0;
  15446. int ret = 1; /* is ok unless needed and no match found */
  15447. while (current != NULL) {
  15448. if (current->type == nameType) {
  15449. need = 1; /* restriction on permitted names is set for this type */
  15450. if (name->len >= current->nameSz &&
  15451. MatchBaseName(nameType, name->name, name->len,
  15452. current->name, current->nameSz)) {
  15453. match = 1; /* found the current name in the permitted list*/
  15454. break;
  15455. }
  15456. }
  15457. current = current->next;
  15458. }
  15459. /* check if permitted name restriction was set and no matching name found */
  15460. if (need && !match)
  15461. ret = 0;
  15462. return ret;
  15463. }
  15464. /* Search through the list to find if the name is excluded.
  15465. * name The DNS name to search for
  15466. * dnsList The list to search through
  15467. * nameType Type of DNS name to currently searching
  15468. * return 1 if found in list and 0 if not found in the list
  15469. */
  15470. static int IsInExcludedList(DNS_entry* name, Base_entry* dnsList, byte nameType)
  15471. {
  15472. int ret = 0; /* default of not found in the list */
  15473. Base_entry* current = dnsList;
  15474. while (current != NULL) {
  15475. if (current->type == nameType) {
  15476. if (name->len >= current->nameSz &&
  15477. MatchBaseName(nameType, name->name, name->len,
  15478. current->name, current->nameSz)) {
  15479. ret = 1;
  15480. break;
  15481. }
  15482. }
  15483. current = current->next;
  15484. }
  15485. return ret;
  15486. }
  15487. static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert)
  15488. {
  15489. const byte nameTypes[] = {ASN_RFC822_TYPE, ASN_DNS_TYPE, ASN_DIR_TYPE};
  15490. int i;
  15491. if (signer == NULL || cert == NULL)
  15492. return 0;
  15493. if (signer->excludedNames == NULL && signer->permittedNames == NULL)
  15494. return 1;
  15495. for (i=0; i < (int)sizeof(nameTypes); i++) {
  15496. byte nameType = nameTypes[i];
  15497. DNS_entry* name = NULL;
  15498. DNS_entry subjectDnsName; /* temporary node used for subject name */
  15499. XMEMSET(&subjectDnsName, 0, sizeof(DNS_entry));
  15500. switch (nameType) {
  15501. case ASN_DNS_TYPE:
  15502. /* Should it also consider CN in subject? It could use
  15503. * subjectDnsName too */
  15504. name = cert->altNames;
  15505. break;
  15506. case ASN_RFC822_TYPE:
  15507. /* Shouldn't it validate E= in subject as well? */
  15508. name = cert->altEmailNames;
  15509. /* Add subject email for checking. */
  15510. if (cert->subjectEmail != NULL) {
  15511. /* RFC 5280 section 4.2.1.10
  15512. * "When constraints are imposed on the rfc822Name name
  15513. * form, but the certificate does not include a subject
  15514. * alternative name, the rfc822Name constraint MUST be
  15515. * applied to the attribute of type emailAddress in the
  15516. * subject distinguished name" */
  15517. subjectDnsName.next = NULL;
  15518. subjectDnsName.type = ASN_RFC822_TYPE;
  15519. subjectDnsName.len = cert->subjectEmailLen;
  15520. subjectDnsName.name = (char *)cert->subjectEmail;
  15521. }
  15522. break;
  15523. case ASN_DIR_TYPE:
  15524. #ifndef WOLFSSL_NO_ASN_STRICT
  15525. name = cert->altDirNames;
  15526. #endif
  15527. /* RFC 5280 section 4.2.1.10
  15528. "Restrictions of the form directoryName MUST be
  15529. applied to the subject field .... and to any names
  15530. of type directoryName in the subjectAltName
  15531. extension"
  15532. */
  15533. if (cert->subjectRaw != NULL) {
  15534. subjectDnsName.next = NULL;
  15535. subjectDnsName.type = ASN_DIR_TYPE;
  15536. subjectDnsName.len = cert->subjectRawLen;
  15537. subjectDnsName.name = (char *)cert->subjectRaw;
  15538. }
  15539. break;
  15540. default:
  15541. /* Other types of names are ignored for now.
  15542. * Shouldn't it be rejected if it there is a altNamesByType[nameType]
  15543. * and signer->extNameConstraintCrit is set? */
  15544. return 0;
  15545. }
  15546. while (name != NULL) {
  15547. if (IsInExcludedList(name, signer->excludedNames, nameType) == 1) {
  15548. WOLFSSL_MSG("Excluded name was found!");
  15549. return 0;
  15550. }
  15551. /* Check against the permitted list */
  15552. if (PermittedListOk(name, signer->permittedNames, nameType) != 1) {
  15553. WOLFSSL_MSG("Permitted name was not found!");
  15554. return 0;
  15555. }
  15556. name = name->next;
  15557. }
  15558. /* handle comparing against subject name too */
  15559. if (subjectDnsName.len > 0 && subjectDnsName.name != NULL) {
  15560. if (IsInExcludedList(&subjectDnsName, signer->excludedNames,
  15561. nameType) == 1) {
  15562. WOLFSSL_MSG("Excluded name was found!");
  15563. return 0;
  15564. }
  15565. /* Check against the permitted list */
  15566. if (PermittedListOk(&subjectDnsName, signer->permittedNames,
  15567. nameType) != 1) {
  15568. WOLFSSL_MSG("Permitted name was not found!");
  15569. return 0;
  15570. }
  15571. }
  15572. }
  15573. return 1;
  15574. }
  15575. #endif /* IGNORE_NAME_CONSTRAINTS */
  15576. #ifndef WOLFSSL_ASN_TEMPLATE
  15577. static void AddAltName(DecodedCert* cert, DNS_entry* dnsEntry)
  15578. {
  15579. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  15580. dnsEntry->next = NULL;
  15581. if (cert->altNames == NULL) {
  15582. /* First on list */
  15583. cert->altNames = dnsEntry;
  15584. }
  15585. else {
  15586. DNS_entry* temp = cert->altNames;
  15587. /* Find end */
  15588. for (; (temp->next != NULL); temp = temp->next);
  15589. /* Add to end */
  15590. temp->next = dnsEntry;
  15591. }
  15592. #else
  15593. dnsEntry->next = cert->altNames;
  15594. cert->altNames = dnsEntry;
  15595. #endif
  15596. }
  15597. #endif
  15598. #ifdef WOLFSSL_ASN_TEMPLATE
  15599. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
  15600. /* ASN.1 template for OtherName of an X.509 certificate.
  15601. * X.509: RFC 5280, 4.2.1.6 - OtherName (without implicit outer SEQUENCE).
  15602. * HW Name: RFC 4108, 5 - Hardware Module Name
  15603. * Only support HW Name where the type is a HW serial number.
  15604. *
  15605. * Other Names handled for FPKI (Federal PKI) use:
  15606. * UPN (Universal Principal Name), a non-standard Other Name
  15607. * (RFC3280 sec 4.2.1.7). Often used with FIPS 201 smartcard login.
  15608. * FASC-N (Federal Agency Smart Credential Number), defined in the document
  15609. * fpki-x509-cert-policy-common.pdf. Used for a smart card ID.
  15610. */
  15611. static const ASNItem otherNameASN[] = {
  15612. /* TYPEID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  15613. /* VALUE */ { 0, ASN_CONTEXT_SPECIFIC | ASN_OTHERNAME_VALUE, 1, 1, 0 },
  15614. /* UPN */ { 1, ASN_UTF8STRING, 0, 0, 2 },
  15615. /* FASC-N */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
  15616. /* HWN_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 2 },
  15617. /* HWN_TYPE */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  15618. /* HWN_NUM */ { 2, ASN_OCTET_STRING, 0, 0, 0 }
  15619. };
  15620. enum {
  15621. OTHERNAMEASN_IDX_TYPEID = 0,
  15622. OTHERNAMEASN_IDX_VALUE,
  15623. OTHERNAMEASN_IDX_UPN,
  15624. OTHERNAMEASN_IDX_FASCN,
  15625. OTHERNAMEASN_IDX_HWN_SEQ,
  15626. OTHERNAMEASN_IDX_HWN_TYPE,
  15627. OTHERNAMEASN_IDX_HWN_NUM
  15628. };
  15629. /* Number of items in ASN.1 template for OtherName of an X.509 certificate. */
  15630. #define otherNameASN_Length (sizeof(otherNameASN) / sizeof(ASNItem))
  15631. #ifdef WOLFSSL_SEP
  15632. static int DecodeSEP(ASNGetData* dataASN, DecodedCert* cert)
  15633. {
  15634. int ret = 0;
  15635. word32 oidLen, serialLen;
  15636. oidLen = dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.length;
  15637. serialLen = dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.length;
  15638. /* Allocate space for HW type OID. */
  15639. cert->hwType = (byte*)XMALLOC(oidLen, cert->heap,
  15640. DYNAMIC_TYPE_X509_EXT);
  15641. if (cert->hwType == NULL)
  15642. ret = MEMORY_E;
  15643. if (ret == 0) {
  15644. /* Copy, into cert HW type OID */
  15645. XMEMCPY(cert->hwType,
  15646. dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.data, oidLen);
  15647. cert->hwTypeSz = (int)oidLen;
  15648. /* TODO: check this is the HW serial number OID - no test data. */
  15649. /* Allocate space for HW serial number, +1 for null terminator. */
  15650. cert->hwSerialNum = (byte*)XMALLOC(serialLen + 1, cert->heap,
  15651. DYNAMIC_TYPE_X509_EXT);
  15652. if (cert->hwSerialNum == NULL) {
  15653. WOLFSSL_MSG("\tOut of Memory");
  15654. ret = MEMORY_E;
  15655. }
  15656. }
  15657. if (ret == 0) {
  15658. /* Copy into cert HW serial number. */
  15659. XMEMCPY(cert->hwSerialNum,
  15660. dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.data, serialLen);
  15661. cert->hwSerialNum[serialLen] = '\0';
  15662. cert->hwSerialNumSz = (int)serialLen;
  15663. }
  15664. return ret;
  15665. }
  15666. #endif /* WOLFSSL_SEP */
  15667. static int DecodeOtherHelper(ASNGetData* dataASN, DecodedCert* cert, int oid)
  15668. {
  15669. DNS_entry* entry = NULL;
  15670. int ret = 0;
  15671. word32 bufLen = 0;
  15672. const char* buf = NULL;
  15673. switch (oid) {
  15674. #ifdef WOLFSSL_FPKI
  15675. case FASCN_OID:
  15676. bufLen = dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.length;
  15677. buf = (const char*)dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.data;
  15678. break;
  15679. #endif /* WOLFSSL_FPKI */
  15680. case UPN_OID:
  15681. bufLen = dataASN[OTHERNAMEASN_IDX_UPN].data.ref.length;
  15682. buf = (const char*)dataASN[OTHERNAMEASN_IDX_UPN].data.ref.data;
  15683. break;
  15684. default:
  15685. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  15686. ret = ASN_UNKNOWN_OID_E;
  15687. break;
  15688. }
  15689. if (ret == 0) {
  15690. ret = SetDNSEntry(cert, buf, (int)bufLen, ASN_OTHER_TYPE, &entry);
  15691. if (ret == 0) {
  15692. #ifdef WOLFSSL_FPKI
  15693. entry->oidSum = oid;
  15694. #endif
  15695. AddDNSEntryToList(&cert->altNames, entry);
  15696. }
  15697. }
  15698. return ret;
  15699. }
  15700. /* Decode data with OtherName format from after implicit SEQUENCE.
  15701. *
  15702. * @param [in, out] cert Certificate object.
  15703. * @param [in] input Buffer containing encoded OtherName.
  15704. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  15705. * On out, index after OtherName.
  15706. * @param [in] maxIdx Maximum index of data in buffer.
  15707. * @return 0 on success.
  15708. * @return MEMORY_E on dynamic memory allocation failure.
  15709. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15710. * is invalid.
  15711. * @return ASN_PARSE_E when OID does is not HW Name.
  15712. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15713. * @return BUFFER_E when data in buffer is too small.
  15714. */
  15715. static int DecodeOtherName(DecodedCert* cert, const byte* input,
  15716. word32* inOutIdx, word32 maxIdx)
  15717. {
  15718. DECL_ASNGETDATA(dataASN, otherNameASN_Length);
  15719. int ret = 0;
  15720. CALLOC_ASNGETDATA(dataASN, otherNameASN_Length, ret, cert->heap);
  15721. if (ret == 0) {
  15722. /* Check the first OID is a recognized Alt Cert Name type. */
  15723. GetASN_OID(&dataASN[OTHERNAMEASN_IDX_TYPEID], oidCertAltNameType);
  15724. /* Parse OtherName. */
  15725. ret = GetASN_Items(otherNameASN, dataASN, otherNameASN_Length, 1, input,
  15726. inOutIdx, maxIdx);
  15727. }
  15728. if (ret == 0) {
  15729. /* Ensure expected OID. */
  15730. switch (dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum) {
  15731. #ifdef WOLFSSL_SEP
  15732. case HW_NAME_OID:
  15733. /* Only support HW serial number. */
  15734. GetASN_OID(&dataASN[OTHERNAMEASN_IDX_HWN_TYPE], oidIgnoreType);
  15735. ret = DecodeSEP(dataASN, cert);
  15736. break;
  15737. #endif /* WOLFSSL_SEP */
  15738. #ifdef WOLFSSL_FPKI
  15739. case FASCN_OID:
  15740. #endif /* WOLFSSL_FPKI */
  15741. case UPN_OID:
  15742. ret = DecodeOtherHelper(dataASN, cert,
  15743. (int)dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum);
  15744. break;
  15745. default:
  15746. WOLFSSL_MSG("\tunsupported OID skipping");
  15747. break;
  15748. }
  15749. }
  15750. FREE_ASNGETDATA(dataASN, cert->heap);
  15751. return ret;
  15752. }
  15753. #endif /* WOLFSSL_SEP || WOLFSSL_FPKI */
  15754. /* Decode a GeneralName.
  15755. *
  15756. * @param [in] input Buffer containing encoded OtherName.
  15757. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  15758. * On out, index after OtherName.
  15759. * @param [in] len Length of data in buffer.
  15760. * @param [in] cert Decoded certificate object.
  15761. * @return 0 on success.
  15762. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15763. * is invalid.
  15764. * @return BUFFER_E when data in buffer is too small.
  15765. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15766. * @return MEMORY_E when dynamic memory allocation fails.
  15767. */
  15768. static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag,
  15769. int len, DecodedCert* cert)
  15770. {
  15771. int ret = 0;
  15772. word32 idx = *inOutIdx;
  15773. /* GeneralName choice: dnsName */
  15774. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  15775. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_DNS_TYPE,
  15776. &cert->altNames);
  15777. if (ret == 0) {
  15778. idx += (word32)len;
  15779. }
  15780. }
  15781. #ifndef IGNORE_NAME_CONSTRAINTS
  15782. /* GeneralName choice: directoryName */
  15783. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  15784. int strLen;
  15785. word32 idxDir = idx;
  15786. /* Expecting a SEQUENCE using up all data. */
  15787. if (GetASN_Sequence(input, &idxDir, &strLen, idx + (word32)len, 1) < 0)
  15788. {
  15789. WOLFSSL_MSG("\tfail: seq length");
  15790. return ASN_PARSE_E;
  15791. }
  15792. ret = SetDNSEntry(cert, (const char*)(input + idxDir), strLen,
  15793. ASN_DIR_TYPE, &cert->altDirNames);
  15794. if (ret == 0) {
  15795. idx += (word32)len;
  15796. }
  15797. }
  15798. /* GeneralName choice: rfc822Name */
  15799. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  15800. ret = SetDNSEntry(cert, (const char*)(input + idx), len,
  15801. ASN_RFC822_TYPE, &cert->altEmailNames);
  15802. if (ret == 0) {
  15803. idx += (word32)len;
  15804. }
  15805. }
  15806. /* GeneralName choice: uniformResourceIdentifier */
  15807. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  15808. WOLFSSL_MSG("\tPutting URI into list but not using");
  15809. #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
  15810. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  15811. "The name MUST NOT be a relative URI"
  15812. As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
  15813. a scheme and hier-part. So the only strict requirement is a ':'
  15814. being present after the scheme. If a '/' is present as part of the
  15815. hier-part, it must come after the ':' (see RFC 3986 Sec 3). */
  15816. {
  15817. int i;
  15818. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  15819. for (i = 0; i < len; i++) {
  15820. if (input[idx + (word32)i] == ':') {
  15821. break;
  15822. }
  15823. if (input[idx + (word32)i] == '/') {
  15824. i = len; /* error, found relative path since '/' was
  15825. * encountered before ':'. Returning error
  15826. * value in next if statement. */
  15827. }
  15828. }
  15829. /* test hier-part is empty */
  15830. if (i == 0 || i == len) {
  15831. WOLFSSL_MSG("\tEmpty or malformed URI");
  15832. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15833. return ASN_ALT_NAME_E;
  15834. }
  15835. /* test if scheme is missing */
  15836. if (input[idx + (word32)i] != ':') {
  15837. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  15838. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15839. return ASN_ALT_NAME_E;
  15840. }
  15841. }
  15842. #endif
  15843. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_URI_TYPE,
  15844. &cert->altNames);
  15845. if (ret == 0) {
  15846. idx += (word32)len;
  15847. }
  15848. }
  15849. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || \
  15850. defined(WOLFSSL_IP_ALT_NAME)
  15851. /* GeneralName choice: iPAddress */
  15852. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  15853. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_IP_TYPE,
  15854. &cert->altNames);
  15855. if (ret == 0) {
  15856. idx += len;
  15857. }
  15858. }
  15859. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  15860. #endif /* IGNORE_NAME_CONSTRAINTS */
  15861. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
  15862. /* GeneralName choice: otherName */
  15863. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
  15864. /* TODO: test data for code path */
  15865. ret = DecodeOtherName(cert, input, &idx, idx + (word32)len);
  15866. }
  15867. #endif
  15868. /* GeneralName choice: dNSName, x400Address, ediPartyName,
  15869. * registeredID */
  15870. else {
  15871. WOLFSSL_MSG("\tUnsupported name type, skipping");
  15872. idx += (word32)len;
  15873. }
  15874. if (ret == 0) {
  15875. /* Return index of next encoded byte. */
  15876. *inOutIdx = idx;
  15877. }
  15878. return ret;
  15879. }
  15880. /* ASN.1 choices for GeneralName.
  15881. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  15882. */
  15883. static const byte generalNameChoice[] = {
  15884. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0,
  15885. ASN_CONTEXT_SPECIFIC | 1,
  15886. ASN_CONTEXT_SPECIFIC | 2,
  15887. ASN_CONTEXT_SPECIFIC | 3,
  15888. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 4,
  15889. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 5,
  15890. ASN_CONTEXT_SPECIFIC | 6,
  15891. ASN_CONTEXT_SPECIFIC | 7,
  15892. ASN_CONTEXT_SPECIFIC | 8,
  15893. 0
  15894. };
  15895. /* ASN.1 template for GeneralName.
  15896. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  15897. */
  15898. static const ASNItem altNameASN[] = {
  15899. { 0, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 0 }
  15900. };
  15901. enum {
  15902. ALTNAMEASN_IDX_GN = 0
  15903. };
  15904. /* Number of items in ASN.1 template for GeneralName. */
  15905. #define altNameASN_Length (sizeof(altNameASN) / sizeof(ASNItem))
  15906. #endif /* WOLFSSL_ASN_TEMPLATE */
  15907. #if defined(WOLFSSL_SEP) && !defined(WOLFSSL_ASN_TEMPLATE)
  15908. /* return 0 on success */
  15909. static int DecodeSepHwAltName(DecodedCert* cert, const byte* input,
  15910. word32* idxIn, word32 sz)
  15911. {
  15912. word32 idx = *idxIn;
  15913. int strLen;
  15914. int ret;
  15915. byte tag;
  15916. /* Certificates issued with this OID in the subject alt name are for
  15917. * verifying signatures created on a module.
  15918. * RFC 4108 Section 5. */
  15919. if (cert->hwType != NULL) {
  15920. WOLFSSL_MSG("\tAlready seen Hardware Module Name");
  15921. return ASN_PARSE_E;
  15922. }
  15923. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  15924. return ASN_PARSE_E;
  15925. }
  15926. if (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  15927. WOLFSSL_MSG("\twrong type");
  15928. return ASN_PARSE_E;
  15929. }
  15930. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15931. WOLFSSL_MSG("\tfail: str len");
  15932. return ASN_PARSE_E;
  15933. }
  15934. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  15935. WOLFSSL_MSG("\tBad Sequence");
  15936. return ASN_PARSE_E;
  15937. }
  15938. ret = GetASNObjectId(input, &idx, &strLen, sz);
  15939. if (ret != 0) {
  15940. WOLFSSL_MSG("\tbad OID");
  15941. return ret;
  15942. }
  15943. cert->hwType = (byte*)XMALLOC((size_t)strLen, cert->heap,
  15944. DYNAMIC_TYPE_X509_EXT);
  15945. if (cert->hwType == NULL) {
  15946. WOLFSSL_MSG("\tOut of Memory");
  15947. return MEMORY_E;
  15948. }
  15949. XMEMCPY(cert->hwType, &input[idx], (size_t)strLen);
  15950. cert->hwTypeSz = strLen;
  15951. idx += (word32)strLen;
  15952. ret = GetOctetString(input, &idx, &strLen, sz);
  15953. if (ret < 0) {
  15954. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  15955. cert->hwType = NULL;
  15956. return ret;
  15957. }
  15958. cert->hwSerialNum = (byte*)XMALLOC((size_t)strLen + 1, cert->heap,
  15959. DYNAMIC_TYPE_X509_EXT);
  15960. if (cert->hwSerialNum == NULL) {
  15961. WOLFSSL_MSG("\tOut of Memory");
  15962. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  15963. cert->hwType = NULL;
  15964. return MEMORY_E;
  15965. }
  15966. XMEMCPY(cert->hwSerialNum, &input[idx], (size_t)strLen);
  15967. cert->hwSerialNum[strLen] = '\0';
  15968. cert->hwSerialNumSz = strLen;
  15969. idx += (word32)strLen;
  15970. *idxIn = idx;
  15971. return 0;
  15972. }
  15973. #endif /* WOLFSSL_SEP */
  15974. #if !defined(WOLFSSL_ASN_TEMPLATE)
  15975. /* return 0 on success */
  15976. static int DecodeConstructedOtherName(DecodedCert* cert, const byte* input,
  15977. word32* idx, word32 sz, int oid)
  15978. {
  15979. int ret = 0;
  15980. int strLen = 0;
  15981. byte tag;
  15982. DNS_entry* dnsEntry = NULL;
  15983. if (GetASNTag(input, idx, &tag, sz) < 0) {
  15984. ret = ASN_PARSE_E;
  15985. }
  15986. if (ret == 0 && (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))) {
  15987. ret = ASN_PARSE_E;
  15988. }
  15989. if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
  15990. ret = ASN_PARSE_E;
  15991. }
  15992. if (ret == 0) {
  15993. dnsEntry = AltNameNew(cert->heap);
  15994. if (dnsEntry == NULL) {
  15995. WOLFSSL_MSG("\tOut of Memory");
  15996. return MEMORY_E;
  15997. }
  15998. switch (oid) {
  15999. #ifdef WOLFSSL_FPKI
  16000. case FASCN_OID:
  16001. ret = GetOctetString(input, idx, &strLen, sz);
  16002. if (ret > 0) {
  16003. ret = 0;
  16004. }
  16005. break;
  16006. #endif /* WOLFSSL_FPKI */
  16007. case UPN_OID:
  16008. if (GetASNTag(input, idx, &tag, sz) < 0) {
  16009. ret = ASN_PARSE_E;
  16010. }
  16011. if (ret == 0 &&
  16012. tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  16013. tag != ASN_IA5_STRING) {
  16014. WOLFSSL_MSG("Was expecting a string for UPN");
  16015. ret = ASN_PARSE_E;
  16016. }
  16017. if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
  16018. WOLFSSL_MSG("Was expecting a string for UPN");
  16019. ret = ASN_PARSE_E;
  16020. }
  16021. break;
  16022. default:
  16023. WOLFSSL_MSG("Unknown constructed other name, skipping");
  16024. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16025. dnsEntry = NULL;
  16026. }
  16027. }
  16028. if (ret == 0 && dnsEntry != NULL) {
  16029. dnsEntry->type = ASN_OTHER_TYPE;
  16030. dnsEntry->len = strLen;
  16031. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16032. DYNAMIC_TYPE_ALTNAME);
  16033. #ifdef WOLFSSL_FPKI
  16034. dnsEntry->oidSum = oid;
  16035. #endif /* WOLFSSL_FPKI */
  16036. if (dnsEntry->name == NULL) {
  16037. WOLFSSL_MSG("\tOut of Memory");
  16038. ret = MEMORY_E;
  16039. }
  16040. else {
  16041. XMEMCPY(dnsEntry->name, &input[*idx], (size_t)strLen);
  16042. dnsEntry->name[strLen] = '\0';
  16043. AddAltName(cert, dnsEntry);
  16044. }
  16045. }
  16046. if (ret == 0) {
  16047. *idx += (word32)strLen;
  16048. }
  16049. else {
  16050. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16051. }
  16052. return ret;
  16053. }
  16054. #endif
  16055. /* Decode subject alternative names extension.
  16056. *
  16057. * RFC 5280 4.2.1.6. Subject Alternative Name
  16058. *
  16059. * @param [in] input Buffer holding encoded data.
  16060. * @param [in] sz Size of encoded data in bytes.
  16061. * @param [in, out] cert Decoded certificate object.
  16062. * @return 0 on success.
  16063. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16064. * is invalid.
  16065. * @return BUFFER_E when data in buffer is too small.
  16066. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  16067. * @return MEMORY_E when dynamic memory allocation fails.
  16068. */
  16069. static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert)
  16070. {
  16071. #ifndef WOLFSSL_ASN_TEMPLATE
  16072. word32 idx = 0;
  16073. int length = 0;
  16074. WOLFSSL_ENTER("DecodeAltNames");
  16075. if (GetSequence(input, &idx, &length, sz) < 0) {
  16076. WOLFSSL_MSG("\tBad Sequence");
  16077. return ASN_PARSE_E;
  16078. }
  16079. if (length == 0) {
  16080. /* RFC 5280 4.2.1.6. Subject Alternative Name
  16081. If the subjectAltName extension is present, the sequence MUST
  16082. contain at least one entry. */
  16083. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16084. return ASN_PARSE_E;
  16085. }
  16086. #ifdef OPENSSL_ALL
  16087. cert->extSubjAltNameSrc = input;
  16088. cert->extSubjAltNameSz = sz;
  16089. #endif
  16090. cert->weOwnAltNames = 1;
  16091. while (length > 0) {
  16092. byte current_byte;
  16093. /* Verify idx can't overflow input buffer */
  16094. if (idx >= (word32)sz) {
  16095. WOLFSSL_MSG("\tBad Index");
  16096. return BUFFER_E;
  16097. }
  16098. current_byte = input[idx++];
  16099. length--;
  16100. /* Save DNS Type names in the altNames list. */
  16101. /* Save Other Type names in the cert's OidMap */
  16102. if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  16103. DNS_entry* dnsEntry;
  16104. int strLen;
  16105. word32 lenStartIdx = idx;
  16106. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16107. WOLFSSL_MSG("\tfail: str length");
  16108. return ASN_PARSE_E;
  16109. }
  16110. length -= (int)(idx - lenStartIdx);
  16111. dnsEntry = AltNameNew(cert->heap);
  16112. if (dnsEntry == NULL) {
  16113. WOLFSSL_MSG("\tOut of Memory");
  16114. return MEMORY_E;
  16115. }
  16116. dnsEntry->type = ASN_DNS_TYPE;
  16117. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16118. DYNAMIC_TYPE_ALTNAME);
  16119. if (dnsEntry->name == NULL) {
  16120. WOLFSSL_MSG("\tOut of Memory");
  16121. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16122. return MEMORY_E;
  16123. }
  16124. dnsEntry->len = strLen;
  16125. XMEMCPY(dnsEntry->name, &input[idx], (size_t)strLen);
  16126. dnsEntry->name[strLen] = '\0';
  16127. AddAltName(cert, dnsEntry);
  16128. length -= strLen;
  16129. idx += (word32)strLen;
  16130. }
  16131. #ifndef IGNORE_NAME_CONSTRAINTS
  16132. else if (current_byte ==
  16133. (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  16134. DNS_entry* dirEntry;
  16135. int strLen;
  16136. word32 lenStartIdx = idx;
  16137. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16138. WOLFSSL_MSG("\tfail: str length");
  16139. return ASN_PARSE_E;
  16140. }
  16141. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  16142. WOLFSSL_MSG("\tfail: seq length");
  16143. return ASN_PARSE_E;
  16144. }
  16145. length -= (int)(idx - lenStartIdx);
  16146. dirEntry = AltNameNew(cert->heap);
  16147. if (dirEntry == NULL) {
  16148. WOLFSSL_MSG("\tOut of Memory");
  16149. return MEMORY_E;
  16150. }
  16151. dirEntry->type = ASN_DIR_TYPE;
  16152. dirEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16153. DYNAMIC_TYPE_ALTNAME);
  16154. if (dirEntry->name == NULL) {
  16155. WOLFSSL_MSG("\tOut of Memory");
  16156. XFREE(dirEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16157. return MEMORY_E;
  16158. }
  16159. dirEntry->len = strLen;
  16160. XMEMCPY(dirEntry->name, &input[idx], (size_t)strLen);
  16161. dirEntry->name[strLen] = '\0';
  16162. dirEntry->next = cert->altDirNames;
  16163. cert->altDirNames = dirEntry;
  16164. length -= strLen;
  16165. idx += (word32)strLen;
  16166. }
  16167. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  16168. DNS_entry* emailEntry;
  16169. int strLen;
  16170. word32 lenStartIdx = idx;
  16171. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16172. WOLFSSL_MSG("\tfail: str length");
  16173. return ASN_PARSE_E;
  16174. }
  16175. length -= (int)(idx - lenStartIdx);
  16176. emailEntry = AltNameNew(cert->heap);
  16177. if (emailEntry == NULL) {
  16178. WOLFSSL_MSG("\tOut of Memory");
  16179. return MEMORY_E;
  16180. }
  16181. emailEntry->type = ASN_RFC822_TYPE;
  16182. emailEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16183. DYNAMIC_TYPE_ALTNAME);
  16184. if (emailEntry->name == NULL) {
  16185. WOLFSSL_MSG("\tOut of Memory");
  16186. XFREE(emailEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16187. return MEMORY_E;
  16188. }
  16189. emailEntry->len = strLen;
  16190. XMEMCPY(emailEntry->name, &input[idx], (size_t)strLen);
  16191. emailEntry->name[strLen] = '\0';
  16192. emailEntry->next = cert->altEmailNames;
  16193. cert->altEmailNames = emailEntry;
  16194. length -= strLen;
  16195. idx += (word32)strLen;
  16196. }
  16197. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  16198. DNS_entry* uriEntry;
  16199. int strLen;
  16200. word32 lenStartIdx = idx;
  16201. WOLFSSL_MSG("\tPutting URI into list but not using");
  16202. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16203. WOLFSSL_MSG("\tfail: str length");
  16204. return ASN_PARSE_E;
  16205. }
  16206. length -= (int)(idx - lenStartIdx);
  16207. /* check that strLen at index is not past input buffer */
  16208. if ((word32)strLen + idx > sz) {
  16209. return BUFFER_E;
  16210. }
  16211. #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
  16212. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  16213. "The name MUST NOT be a relative URI"
  16214. As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
  16215. a scheme and hier-part. So the only strict requirement is a ':'
  16216. being present after the scheme. If a '/' is present as part of the
  16217. hier-part, it must come after the ':' (see RFC 3986 Sec 3). */
  16218. {
  16219. word32 i;
  16220. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  16221. for (i = 0; i < (word32)strLen; i++) {
  16222. if (input[idx + i] == ':') {
  16223. break;
  16224. }
  16225. if (input[idx + i] == '/') {
  16226. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  16227. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16228. return ASN_ALT_NAME_E;
  16229. }
  16230. }
  16231. /* test hier-part is empty */
  16232. if (i == 0 || i == (word32)strLen) {
  16233. WOLFSSL_MSG("\tEmpty or malformed URI");
  16234. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16235. return ASN_ALT_NAME_E;
  16236. }
  16237. /* test if scheme is missing */
  16238. if (input[idx + i] != ':') {
  16239. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  16240. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16241. return ASN_ALT_NAME_E;
  16242. }
  16243. }
  16244. #endif
  16245. uriEntry = AltNameNew(cert->heap);
  16246. if (uriEntry == NULL) {
  16247. WOLFSSL_MSG("\tOut of Memory");
  16248. return MEMORY_E;
  16249. }
  16250. uriEntry->type = ASN_URI_TYPE;
  16251. uriEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16252. DYNAMIC_TYPE_ALTNAME);
  16253. if (uriEntry->name == NULL) {
  16254. WOLFSSL_MSG("\tOut of Memory");
  16255. XFREE(uriEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16256. return MEMORY_E;
  16257. }
  16258. uriEntry->len = strLen;
  16259. XMEMCPY(uriEntry->name, &input[idx], (size_t)strLen);
  16260. uriEntry->name[strLen] = '\0';
  16261. AddAltName(cert, uriEntry);
  16262. length -= strLen;
  16263. idx += (word32)strLen;
  16264. }
  16265. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  16266. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  16267. DNS_entry* ipAddr;
  16268. int strLen;
  16269. word32 lenStartIdx = idx;
  16270. WOLFSSL_MSG("Decoding Subject Alt. Name: IP Address");
  16271. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16272. WOLFSSL_MSG("\tfail: str length");
  16273. return ASN_PARSE_E;
  16274. }
  16275. length -= (idx - lenStartIdx);
  16276. /* check that strLen at index is not past input buffer */
  16277. if (strLen + idx > sz) {
  16278. return BUFFER_E;
  16279. }
  16280. ipAddr = AltNameNew(cert->heap);
  16281. if (ipAddr == NULL) {
  16282. WOLFSSL_MSG("\tOut of Memory");
  16283. return MEMORY_E;
  16284. }
  16285. ipAddr->type = ASN_IP_TYPE;
  16286. ipAddr->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16287. DYNAMIC_TYPE_ALTNAME);
  16288. if (ipAddr->name == NULL) {
  16289. WOLFSSL_MSG("\tOut of Memory");
  16290. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16291. return MEMORY_E;
  16292. }
  16293. ipAddr->len = strLen;
  16294. XMEMCPY(ipAddr->name, &input[idx], strLen);
  16295. ipAddr->name[strLen] = '\0';
  16296. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  16297. if (GenerateDNSEntryIPString(ipAddr, cert->heap) != 0) {
  16298. WOLFSSL_MSG("\tOut of Memory for IP string");
  16299. XFREE(ipAddr->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16300. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16301. return MEMORY_E;
  16302. }
  16303. #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  16304. AddAltName(cert, ipAddr);
  16305. length -= strLen;
  16306. idx += (word32)strLen;
  16307. }
  16308. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  16309. #endif /* IGNORE_NAME_CONSTRAINTS */
  16310. else if (current_byte ==
  16311. (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
  16312. int strLen;
  16313. word32 lenStartIdx = idx;
  16314. word32 oid = 0;
  16315. int ret = 0;
  16316. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16317. WOLFSSL_MSG("\tfail: other name length");
  16318. return ASN_PARSE_E;
  16319. }
  16320. /* Consume the rest of this sequence. */
  16321. length -= (int)(((word32)strLen + idx - lenStartIdx));
  16322. if (GetObjectId(input, &idx, &oid, oidCertAltNameType, sz) < 0) {
  16323. WOLFSSL_MSG("\tbad OID");
  16324. return ASN_PARSE_E;
  16325. }
  16326. /* handle parsing other type alt names */
  16327. switch (oid) {
  16328. #ifdef WOLFSSL_SEP
  16329. case HW_NAME_OID:
  16330. ret = DecodeSepHwAltName(cert, input, &idx, sz);
  16331. if (ret != 0)
  16332. return ret;
  16333. break;
  16334. #endif /* WOLFSSL_SEP */
  16335. #ifdef WOLFSSL_FPKI
  16336. case FASCN_OID:
  16337. case UPN_OID:
  16338. ret = DecodeConstructedOtherName(cert, input, &idx, sz,
  16339. oid);
  16340. if (ret != 0)
  16341. return ret;
  16342. break;
  16343. #endif /* WOLFSSL_FPKI */
  16344. default:
  16345. WOLFSSL_MSG("\tUnsupported other name type, skipping");
  16346. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16347. /* check to skip constructed other names too */
  16348. if (DecodeConstructedOtherName(cert, input, &idx, sz,
  16349. (int)oid) != 0) {
  16350. WOLFSSL_MSG("\tfail: unsupported other name length");
  16351. return ASN_PARSE_E;
  16352. }
  16353. }
  16354. else {
  16355. idx += (word32)strLen;
  16356. }
  16357. }
  16358. (void)ret;
  16359. }
  16360. else {
  16361. int strLen;
  16362. word32 lenStartIdx = idx;
  16363. WOLFSSL_MSG("\tUnsupported name type, skipping");
  16364. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16365. WOLFSSL_MSG("\tfail: unsupported name length");
  16366. return ASN_PARSE_E;
  16367. }
  16368. length -= (int)((word32)strLen + idx - lenStartIdx);
  16369. idx += (word32)strLen;
  16370. }
  16371. }
  16372. return 0;
  16373. #else
  16374. word32 idx = 0;
  16375. int length = 0;
  16376. int ret = 0;
  16377. WOLFSSL_ENTER("DecodeAltNames");
  16378. /* Get SEQUENCE and expect all data to be accounted for. */
  16379. if (GetASN_Sequence(input, &idx, &length, sz, 1) != 0) {
  16380. WOLFSSL_MSG("\tBad Sequence");
  16381. ret = ASN_PARSE_E;
  16382. }
  16383. if ((ret == 0) && (length == 0)) {
  16384. /* RFC 5280 4.2.1.6. Subject Alternative Name
  16385. If the subjectAltName extension is present, the sequence MUST
  16386. contain at least one entry. */
  16387. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16388. ret = ASN_PARSE_E;
  16389. }
  16390. if (ret == 0) {
  16391. #ifdef OPENSSL_ALL
  16392. cert->extSubjAltNameSrc = input;
  16393. cert->extSubjAltNameSz = sz;
  16394. #endif
  16395. cert->weOwnAltNames = 1;
  16396. if ((word32)length + idx != sz) {
  16397. ret = ASN_PARSE_E;
  16398. }
  16399. }
  16400. while ((ret == 0) && (idx < sz)) {
  16401. ASNGetData dataASN[altNameASN_Length];
  16402. /* Clear dynamic data items. */
  16403. XMEMSET(dataASN, 0, sizeof(dataASN));
  16404. /* Parse GeneralName with the choices supported. */
  16405. GetASN_Choice(&dataASN[ALTNAMEASN_IDX_GN], generalNameChoice);
  16406. /* Decode a GeneralName choice. */
  16407. ret = GetASN_Items(altNameASN, dataASN, altNameASN_Length, 0, input,
  16408. &idx, sz);
  16409. if (ret == 0) {
  16410. ret = DecodeGeneralName(input, &idx, dataASN[ALTNAMEASN_IDX_GN].tag,
  16411. (int)dataASN[ALTNAMEASN_IDX_GN].length, cert);
  16412. }
  16413. }
  16414. return ret;
  16415. #endif
  16416. }
  16417. #ifdef WOLFSSL_ASN_TEMPLATE
  16418. /* ASN.1 template for BasicConstraints.
  16419. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  16420. */
  16421. static const ASNItem basicConsASN[] = {
  16422. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16423. /* CA */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  16424. /* PLEN */ { 1, ASN_INTEGER, 0, 0, 1 }
  16425. };
  16426. enum {
  16427. BASICCONSASN_IDX_SEQ = 0,
  16428. BASICCONSASN_IDX_CA,
  16429. BASICCONSASN_IDX_PLEN
  16430. };
  16431. /* Number of items in ASN.1 template for BasicContraints. */
  16432. #define basicConsASN_Length (sizeof(basicConsASN) / sizeof(ASNItem))
  16433. #endif
  16434. /* Decode basic constraints extension in a certificate.
  16435. *
  16436. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  16437. *
  16438. * @param [in] input Buffer holding data.
  16439. * @param [in] sz Size of data in buffer.
  16440. * @param [in, out] cert Certificate object.
  16441. * @return 0 on success.
  16442. * @return MEMORY_E on dynamic memory allocation failure.
  16443. * @return ASN_PARSE_E when CA boolean is present and false (default is false).
  16444. * @return ASN_PARSE_E when CA boolean is not present unless
  16445. * WOLFSSL_X509_BASICCONS_INT is defined. Only a CA extension.
  16446. * @return ASN_PARSE_E when path length more than 7 bits.
  16447. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16448. * is invalid.
  16449. * @return BUFFER_E when data in buffer is too small.
  16450. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  16451. * non-zero length.
  16452. */
  16453. static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert)
  16454. {
  16455. #ifndef WOLFSSL_ASN_TEMPLATE
  16456. word32 idx = 0;
  16457. int length = 0;
  16458. int ret;
  16459. WOLFSSL_ENTER("DecodeBasicCaConstraint");
  16460. if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
  16461. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  16462. return ASN_PARSE_E;
  16463. }
  16464. if (length == 0)
  16465. return 0;
  16466. /* If the basic ca constraint is false, this extension may be named, but
  16467. * left empty. So, if the length is 0, just return. */
  16468. ret = GetBoolean(input, &idx, (word32)sz);
  16469. /* Removed logic for WOLFSSL_X509_BASICCONS_INT which was mistreating the
  16470. * pathlen value as if it were the CA Boolean value 7/2/2021 - KH.
  16471. * When CA Boolean not asserted use the default value "False" */
  16472. if (ret < 0) {
  16473. WOLFSSL_MSG("\tfail: constraint not valid BOOLEAN, set default FALSE");
  16474. ret = 0;
  16475. }
  16476. cert->isCA = ret ? 1 : 0;
  16477. /* If there isn't any more data, return. */
  16478. if (idx >= (word32)sz) {
  16479. return 0;
  16480. }
  16481. ret = GetInteger7Bit(input, &idx, (word32)sz);
  16482. if (ret < 0)
  16483. return ret;
  16484. cert->pathLength = (byte)ret;
  16485. cert->pathLengthSet = 1;
  16486. return 0;
  16487. #else
  16488. DECL_ASNGETDATA(dataASN, basicConsASN_Length);
  16489. int ret = 0;
  16490. word32 idx = 0;
  16491. byte isCA = 0;
  16492. WOLFSSL_ENTER("DecodeBasicCaConstraints");
  16493. CALLOC_ASNGETDATA(dataASN, basicConsASN_Length, ret, cert->heap);
  16494. if (ret == 0) {
  16495. /* Get the CA boolean and path length when present. */
  16496. GetASN_Boolean(&dataASN[BASICCONSASN_IDX_CA], &isCA);
  16497. GetASN_Int8Bit(&dataASN[BASICCONSASN_IDX_PLEN], &cert->pathLength);
  16498. ret = GetASN_Items(basicConsASN, dataASN, basicConsASN_Length, 1, input,
  16499. &idx, (word32)sz);
  16500. }
  16501. /* Empty SEQUENCE is OK - nothing to store. */
  16502. if ((ret == 0) && (dataASN[BASICCONSASN_IDX_SEQ].length != 0)) {
  16503. /* Bad encoding when CA Boolean is false
  16504. * (default when not present). */
  16505. if ((dataASN[BASICCONSASN_IDX_CA].length != 0) && (!isCA)) {
  16506. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16507. ret = ASN_PARSE_E;
  16508. }
  16509. /* Path length must be a 7-bit value. */
  16510. if ((ret == 0) && (cert->pathLength >= (1 << 7))) {
  16511. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16512. ret = ASN_PARSE_E;
  16513. }
  16514. /* Store CA boolean and whether a path length was seen. */
  16515. if (ret == 0) {
  16516. /* isCA in certificate is a 1 bit of a byte. */
  16517. cert->isCA = isCA ? 1 : 0;
  16518. cert->pathLengthSet = (dataASN[BASICCONSASN_IDX_PLEN].length > 0);
  16519. }
  16520. }
  16521. FREE_ASNGETDATA(dataASN, cert->heap);
  16522. return ret;
  16523. #endif
  16524. }
  16525. static int DecodePolicyConstraints(const byte* input, int sz, DecodedCert* cert)
  16526. {
  16527. word32 idx = 0;
  16528. int length = 0;
  16529. int skipLength = 0;
  16530. int ret;
  16531. byte tag;
  16532. WOLFSSL_ENTER("DecodePolicyConstraints");
  16533. if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
  16534. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  16535. return ASN_PARSE_E;
  16536. }
  16537. if (length == 0)
  16538. return ASN_PARSE_E;
  16539. if (GetASNTag(input, &idx, &tag, (word32)sz) < 0) {
  16540. WOLFSSL_MSG("\tfail: bad TAG");
  16541. return ASN_PARSE_E;
  16542. }
  16543. if (tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  16544. /* requireExplicitPolicy */
  16545. cert->extPolicyConstRxpSet = 1;
  16546. }
  16547. else if (tag == (ASN_CONTEXT_SPECIFIC | 1)) {
  16548. /* inhibitPolicyMapping */
  16549. cert->extPolicyConstIpmSet = 1;
  16550. }
  16551. else {
  16552. WOLFSSL_MSG("\tfail: invalid TAG");
  16553. return ASN_PARSE_E;
  16554. }
  16555. ret = GetLength(input, &idx, &skipLength, (word32)sz);
  16556. if (ret < 0) {
  16557. WOLFSSL_MSG("\tfail: invalid length");
  16558. return ret;
  16559. }
  16560. if (skipLength > 1) {
  16561. WOLFSSL_MSG("\tfail: skip value too big");
  16562. return BUFFER_E;
  16563. }
  16564. if (idx >= (word32)sz) {
  16565. WOLFSSL_MSG("\tfail: no policy const skip to read");
  16566. return BUFFER_E;
  16567. }
  16568. cert->policyConstSkip = input[idx];
  16569. return 0;
  16570. }
  16571. /* Context-Specific value for: DistributionPoint.distributionPoint
  16572. * From RFC5280 SS4.2.1.13, Distribution Point */
  16573. #define DISTRIBUTION_POINT (ASN_CONTEXT_SPECIFIC | 0)
  16574. /* Context-Specific value for: DistributionPoint.DistributionPointName.fullName
  16575. * From RFC3280 SS4.2.1.13, Distribution Point Name */
  16576. #define CRLDP_FULL_NAME (ASN_CONTEXT_SPECIFIC | 0)
  16577. /* Context-Specific value for choice: GeneralName.uniformResourceIdentifier
  16578. * From RFC3280 SS4.2.1.7, GeneralName */
  16579. #define GENERALNAME_URI (ASN_CONTEXT_SPECIFIC | 6)
  16580. #ifdef WOLFSSL_ASN_TEMPLATE
  16581. /* ASN.1 template for CRL distribution points.
  16582. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  16583. */
  16584. static const ASNItem crlDistASN[] = {
  16585. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16586. /* DP_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  16587. /* Distribution point name */
  16588. /* DP_DISTPOINT */ { 2, DISTRIBUTION_POINT, 1, 1, 1 },
  16589. /* fullName */
  16590. /* DP_DISTPOINT_FN */ { 3, CRLDP_FULL_NAME, 1, 1, 2 },
  16591. /* DP_DISTPOINT_FN_GN */ { 4, GENERALNAME_URI, 0, 0, 0 },
  16592. /* nameRelativeToCRLIssuer */
  16593. /* DP_DISTPOINT_RN */ { 3, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  16594. /* reasons: IMPLICIT BIT STRING */
  16595. /* DP_REASONS */ { 2, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  16596. /* cRLIssuer */
  16597. /* DP_CRLISSUER */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 1 },
  16598. };
  16599. enum {
  16600. CRLDISTASN_IDX_SEQ = 0,
  16601. CRLDISTASN_IDX_DP_SEQ,
  16602. CRLDISTASN_IDX_DP_DISTPOINT,
  16603. CRLDISTASN_IDX_DP_DISTPOINT_FN,
  16604. CRLDISTASN_IDX_DP_DISTPOINT_FN_GN,
  16605. CRLDISTASN_IDX_DP_DISTPOINT_RN, /* Relative name */
  16606. CRLDISTASN_IDX_DP_REASONS,
  16607. CRLDISTASN_IDX_DP_CRLISSUER
  16608. };
  16609. /* Number of items in ASN.1 template for CRL distribution points. */
  16610. #define crlDistASN_Length (sizeof(crlDistASN) / sizeof(ASNItem))
  16611. #endif
  16612. /* Decode CRL distribution point extension in a certificate.
  16613. *
  16614. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  16615. *
  16616. * @param [in] input Buffer holding data.
  16617. * @param [in] sz Size of data in buffer.
  16618. * @param [in, out] cert Certificate object.
  16619. * @return 0 on success.
  16620. * @return MEMORY_E on dynamic memory allocation failure.
  16621. * @return ASN_PARSE_E when invalid bits of reason are set.
  16622. * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
  16623. * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
  16624. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16625. * is invalid.
  16626. * @return BUFFER_E when data in buffer is too small.
  16627. */
  16628. static int DecodeCrlDist(const byte* input, word32 sz, DecodedCert* cert)
  16629. {
  16630. #ifndef WOLFSSL_ASN_TEMPLATE
  16631. word32 idx = 0, localIdx;
  16632. int length = 0;
  16633. byte tag = 0;
  16634. WOLFSSL_ENTER("DecodeCrlDist");
  16635. cert->extCrlInfoRaw = input;
  16636. cert->extCrlInfoRawSz = (int)sz;
  16637. /* Unwrap the list of Distribution Points*/
  16638. if (GetSequence(input, &idx, &length, sz) < 0)
  16639. return ASN_PARSE_E;
  16640. /* Unwrap a single Distribution Point */
  16641. if (GetSequence(input, &idx, &length, sz) < 0)
  16642. return ASN_PARSE_E;
  16643. /* The Distribution Point has three explicit optional members
  16644. * First check for a DistributionPointName
  16645. */
  16646. localIdx = idx;
  16647. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16648. tag == (ASN_CONSTRUCTED | DISTRIBUTION_POINT))
  16649. {
  16650. idx++;
  16651. if (GetLength(input, &idx, &length, sz) < 0)
  16652. return ASN_PARSE_E;
  16653. localIdx = idx;
  16654. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16655. tag == (ASN_CONSTRUCTED | CRLDP_FULL_NAME))
  16656. {
  16657. idx++;
  16658. if (GetLength(input, &idx, &length, sz) < 0)
  16659. return ASN_PARSE_E;
  16660. localIdx = idx;
  16661. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16662. tag == GENERALNAME_URI)
  16663. {
  16664. idx++;
  16665. if (GetLength(input, &idx, &length, sz) < 0)
  16666. return ASN_PARSE_E;
  16667. cert->extCrlInfoSz = length;
  16668. cert->extCrlInfo = input + idx;
  16669. idx += (word32)length;
  16670. }
  16671. else
  16672. /* This isn't a URI, skip it. */
  16673. idx += (word32)length;
  16674. }
  16675. else {
  16676. /* This isn't a FULLNAME, skip it. */
  16677. idx += (word32)length;
  16678. }
  16679. }
  16680. /* Check for reasonFlags */
  16681. localIdx = idx;
  16682. if (idx < (word32)sz &&
  16683. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16684. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  16685. {
  16686. idx++;
  16687. if (GetLength(input, &idx, &length, sz) < 0)
  16688. return ASN_PARSE_E;
  16689. idx += (word32)length;
  16690. }
  16691. /* Check for cRLIssuer */
  16692. localIdx = idx;
  16693. if (idx < (word32)sz &&
  16694. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16695. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
  16696. {
  16697. idx++;
  16698. if (GetLength(input, &idx, &length, sz) < 0)
  16699. return ASN_PARSE_E;
  16700. idx += (word32)length;
  16701. }
  16702. if (idx < (word32)sz)
  16703. {
  16704. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  16705. "but we only use the first one.");
  16706. }
  16707. return 0;
  16708. #else
  16709. DECL_ASNGETDATA(dataASN, crlDistASN_Length);
  16710. word32 idx = 0;
  16711. int ret = 0;
  16712. #ifdef CRLDP_VALIDATE_DATA
  16713. word16 reason;
  16714. #endif
  16715. WOLFSSL_ENTER("DecodeCrlDist");
  16716. CALLOC_ASNGETDATA(dataASN, crlDistASN_Length, ret, cert->heap);
  16717. cert->extCrlInfoRaw = input;
  16718. cert->extCrlInfoRawSz = (int)sz;
  16719. if (ret == 0) {
  16720. /* Get the GeneralName choice */
  16721. GetASN_Choice(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN], generalNameChoice);
  16722. /* Parse CRL distribution point. */
  16723. ret = GetASN_Items(crlDistASN, dataASN, crlDistASN_Length, 0, input,
  16724. &idx, sz);
  16725. }
  16726. if (ret == 0) {
  16727. /* If the choice was a URI, store it in certificate. */
  16728. if (dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN].tag == GENERALNAME_URI) {
  16729. word32 sz32;
  16730. GetASN_GetConstRef(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN],
  16731. &cert->extCrlInfo, &sz32);
  16732. cert->extCrlInfoSz = (int)sz32;
  16733. }
  16734. #ifdef CRLDP_VALIDATE_DATA
  16735. if (dataASN[CRLDISTASN_IDX_DP_REASONS].data.ref.data != NULL) {
  16736. /* TODO: test case */
  16737. /* Validate ReasonFlags. */
  16738. ret = GetASN_BitString_Int16Bit(&dataASN[CRLDISTASN_IDX_DP_REASONS],
  16739. &reason);
  16740. /* First bit (LSB) unused and eight other bits defined. */
  16741. if ((ret == 0) && ((reason >> 9) || (reason & 0x01))) {
  16742. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16743. ret = ASN_PARSE_E;
  16744. }
  16745. }
  16746. #endif
  16747. }
  16748. /* Only parsing the first one. */
  16749. if (ret == 0 && idx < (word32)sz) {
  16750. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  16751. "but we only use the first one.");
  16752. }
  16753. /* TODO: validate other points. */
  16754. FREE_ASNGETDATA(dataASN, cert->heap);
  16755. return ret;
  16756. #endif /* WOLFSSL_ASN_TEMPLATE */
  16757. }
  16758. #ifdef WOLFSSL_ASN_TEMPLATE
  16759. /* ASN.1 template for the access description.
  16760. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16761. */
  16762. static const ASNItem accessDescASN[] = {
  16763. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16764. /* accessMethod */
  16765. /* METH */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  16766. /* accessLocation: GeneralName */
  16767. /* LOC */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  16768. };
  16769. enum {
  16770. ACCESSDESCASN_IDX_SEQ = 0,
  16771. ACCESSDESCASN_IDX_METH,
  16772. ACCESSDESCASN_IDX_LOC
  16773. };
  16774. /* Number of items in ASN.1 template for the access description. */
  16775. #define accessDescASN_Length (sizeof(accessDescASN) / sizeof(ASNItem))
  16776. #endif
  16777. /* Decode authority information access extension in a certificate.
  16778. *
  16779. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16780. *
  16781. * @param [in] input Buffer holding data.
  16782. * @param [in] sz Size of data in buffer.
  16783. * @param [in, out] cert Certificate object.
  16784. * @return 0 on success.
  16785. * @return MEMORY_E on dynamic memory allocation failure.
  16786. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16787. * is invalid.
  16788. * @return BUFFER_E when data in buffer is too small.
  16789. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  16790. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  16791. */
  16792. static int DecodeAuthInfo(const byte* input, word32 sz, DecodedCert* cert)
  16793. {
  16794. #ifndef WOLFSSL_ASN_TEMPLATE
  16795. word32 idx = 0;
  16796. int length = 0;
  16797. int count = 0;
  16798. byte b = 0;
  16799. word32 oid;
  16800. WOLFSSL_ENTER("DecodeAuthInfo");
  16801. /* Unwrap the list of AIAs */
  16802. if (GetSequence(input, &idx, &length, sz) < 0)
  16803. return ASN_PARSE_E;
  16804. while ((idx < (word32)sz) && (count < MAX_AIA_SZ)) {
  16805. /* Unwrap a single AIA */
  16806. if (GetSequence(input, &idx, &length, sz) < 0)
  16807. return ASN_PARSE_E;
  16808. oid = 0;
  16809. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0) {
  16810. return ASN_PARSE_E;
  16811. }
  16812. /* Only supporting URIs right now. */
  16813. if (GetASNTag(input, &idx, &b, sz) < 0)
  16814. return ASN_PARSE_E;
  16815. if (GetLength(input, &idx, &length, sz) < 0)
  16816. return ASN_PARSE_E;
  16817. /* Set ocsp entry */
  16818. if (b == GENERALNAME_URI && oid == AIA_OCSP_OID)
  16819. {
  16820. cert->extAuthInfoSz = length;
  16821. cert->extAuthInfo = input + idx;
  16822. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16823. count++;
  16824. #else
  16825. break;
  16826. #endif
  16827. }
  16828. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16829. /* Set CaIssuers entry */
  16830. else if ((b == GENERALNAME_URI) && oid == AIA_CA_ISSUER_OID)
  16831. {
  16832. cert->extAuthInfoCaIssuerSz = length;
  16833. cert->extAuthInfoCaIssuer = input + idx;
  16834. count++;
  16835. }
  16836. #endif
  16837. idx += (word32)length;
  16838. }
  16839. return 0;
  16840. #else
  16841. word32 idx = 0;
  16842. int length = 0;
  16843. int count = 0;
  16844. int ret = 0;
  16845. WOLFSSL_ENTER("DecodeAuthInfo");
  16846. /* Unwrap the list of AIAs */
  16847. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  16848. ret = ASN_PARSE_E;
  16849. }
  16850. while ((ret == 0) && (idx < (word32)sz) && (count < MAX_AIA_SZ)) {
  16851. ASNGetData dataASN[accessDescASN_Length];
  16852. /* Clear dynamic data and retrieve OID and name. */
  16853. XMEMSET(dataASN, 0, sizeof(dataASN));
  16854. GetASN_OID(&dataASN[ACCESSDESCASN_IDX_METH], oidCertAuthInfoType);
  16855. GetASN_Choice(&dataASN[ACCESSDESCASN_IDX_LOC], generalNameChoice);
  16856. /* Parse AccessDescription. */
  16857. ret = GetASN_Items(accessDescASN, dataASN, accessDescASN_Length, 0,
  16858. input, &idx, sz);
  16859. if (ret == 0) {
  16860. word32 sz32;
  16861. /* Check we have OCSP and URI. */
  16862. if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum == AIA_OCSP_OID) &&
  16863. (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
  16864. /* Store URI for OCSP lookup. */
  16865. GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
  16866. &cert->extAuthInfo, &sz32);
  16867. cert->extAuthInfoSz = (int)sz32;
  16868. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16869. count++;
  16870. #else
  16871. break;
  16872. #endif
  16873. }
  16874. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16875. /* Check we have CA Issuer and URI. */
  16876. else if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum ==
  16877. AIA_CA_ISSUER_OID) &&
  16878. (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
  16879. /* Set CaIssuers entry */
  16880. GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
  16881. &cert->extAuthInfoCaIssuer, &sz32);
  16882. cert->extAuthInfoCaIssuerSz = sz32;
  16883. count++;
  16884. }
  16885. #endif
  16886. /* Otherwise skip. */
  16887. }
  16888. }
  16889. return ret;
  16890. #endif
  16891. }
  16892. #ifdef WOLFSSL_ASN_TEMPLATE
  16893. /* ASN.1 template for AuthorityKeyIdentifier.
  16894. * X.509: RFC 5280, 4.2.1.1 - Authority Key Identifier.
  16895. */
  16896. static const ASNItem authKeyIdASN[] = {
  16897. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16898. /* keyIdentifier */
  16899. /* KEYID */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_KEYID, 0, 0, 1 },
  16900. /* authorityCertIssuer */
  16901. /* ISSUER */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_ISSUER, 1, 0, 1 },
  16902. /* authorityCertSerialNumber */
  16903. /* SERIAL */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_SERIAL, 0, 0, 1 },
  16904. };
  16905. enum {
  16906. AUTHKEYIDASN_IDX_SEQ = 0,
  16907. AUTHKEYIDASN_IDX_KEYID,
  16908. AUTHKEYIDASN_IDX_ISSUER,
  16909. AUTHKEYIDASN_IDX_SERIAL
  16910. };
  16911. /* Number of items in ASN.1 template for AuthorityKeyIdentifier. */
  16912. #define authKeyIdASN_Length (sizeof(authKeyIdASN) / sizeof(ASNItem))
  16913. #endif
  16914. /* Decode authority information access extension in a certificate.
  16915. *
  16916. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16917. *
  16918. * @param [in] input Buffer holding data.
  16919. * @param [in] sz Size of data in buffer.
  16920. * @param [in, out] cert Certificate object.
  16921. * @return 0 on success.
  16922. * @return MEMORY_E on dynamic memory allocation failure.
  16923. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16924. * is invalid.
  16925. * @return BUFFER_E when data in buffer is too small.
  16926. */
  16927. static int DecodeAuthKeyId(const byte* input, word32 sz, DecodedCert* cert)
  16928. {
  16929. #ifndef WOLFSSL_ASN_TEMPLATE
  16930. word32 idx = 0;
  16931. int length = 0;
  16932. byte tag;
  16933. WOLFSSL_ENTER("DecodeAuthKeyId");
  16934. if (GetSequence(input, &idx, &length, sz) < 0) {
  16935. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  16936. return ASN_PARSE_E;
  16937. }
  16938. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  16939. return ASN_PARSE_E;
  16940. }
  16941. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  16942. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  16943. cert->extAuthKeyIdSet = 0;
  16944. return 0;
  16945. }
  16946. if (GetLength(input, &idx, &length, sz) <= 0) {
  16947. WOLFSSL_MSG("\tfail: extension data length");
  16948. return ASN_PARSE_E;
  16949. }
  16950. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16951. #ifdef WOLFSSL_AKID_NAME
  16952. cert->extRawAuthKeyIdSrc = input;
  16953. cert->extRawAuthKeyIdSz = sz;
  16954. #endif
  16955. cert->extAuthKeyIdSrc = &input[idx];
  16956. cert->extAuthKeyIdSz = length;
  16957. #endif /* OPENSSL_EXTRA */
  16958. return GetHashId(input + idx, length, cert->extAuthKeyId);
  16959. #else
  16960. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  16961. int ret = 0;
  16962. word32 idx = 0;
  16963. WOLFSSL_ENTER("DecodeAuthKeyId");
  16964. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, cert->heap);
  16965. if (ret == 0) {
  16966. /* Parse an authority key identifier. */
  16967. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  16968. &idx, sz);
  16969. }
  16970. if (ret == 0) {
  16971. /* Key id is optional. */
  16972. if (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data == NULL) {
  16973. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  16974. }
  16975. else {
  16976. #ifdef OPENSSL_EXTRA
  16977. /* Store the authority key id. */
  16978. #ifdef WOLFSSL_AKID_NAME
  16979. cert->extRawAuthKeyIdSrc = input;
  16980. cert->extRawAuthKeyIdSz = sz;
  16981. #endif
  16982. GetASN_GetConstRef(&dataASN[AUTHKEYIDASN_IDX_KEYID], &cert->extAuthKeyIdSrc,
  16983. &cert->extAuthKeyIdSz);
  16984. #endif /* OPENSSL_EXTRA */
  16985. /* Get the hash or hash of the hash if wrong size. */
  16986. ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  16987. (int)dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  16988. cert->extAuthKeyId);
  16989. }
  16990. }
  16991. FREE_ASNGETDATA(dataASN, cert->heap);
  16992. return ret;
  16993. #endif /* WOLFSSL_ASN_TEMPLATE */
  16994. }
  16995. /* Decode subject key id extension in a certificate.
  16996. *
  16997. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16998. *
  16999. * @param [in] input Buffer holding data.
  17000. * @param [in] sz Size of data in buffer.
  17001. * @param [in, out] cert Certificate object.
  17002. * @return 0 on success.
  17003. * @return ASN_PARSE_E when the OCTET_STRING tag is not found or length is
  17004. * invalid.
  17005. * @return MEMORY_E on dynamic memory allocation failure.
  17006. */
  17007. static int DecodeSubjKeyId(const byte* input, word32 sz, DecodedCert* cert)
  17008. {
  17009. word32 idx = 0;
  17010. int length = 0;
  17011. int ret = 0;
  17012. WOLFSSL_ENTER("DecodeSubjKeyId");
  17013. ret = GetOctetString(input, &idx, &length, sz);
  17014. if (ret > 0) {
  17015. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17016. cert->extSubjKeyIdSrc = &input[idx];
  17017. cert->extSubjKeyIdSz = length;
  17018. #endif /* OPENSSL_EXTRA */
  17019. /* Get the hash or hash of the hash if wrong size. */
  17020. ret = GetHashId(input + idx, length, cert->extSubjKeyId);
  17021. }
  17022. return ret;
  17023. }
  17024. #ifdef WOLFSSL_ASN_TEMPLATE
  17025. /* ASN.1 template for KeyUsage.
  17026. * X.509: RFC 5280, 4.2.1.3 - Key Usage.
  17027. */
  17028. static const ASNItem keyUsageASN[] = {
  17029. /* STR */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  17030. };
  17031. enum {
  17032. KEYUSAGEASN_IDX_STR = 0
  17033. };
  17034. /* Number of items in ASN.1 template for KeyUsage. */
  17035. #define keyUsageASN_Length (sizeof(keyUsageASN) / sizeof(ASNItem))
  17036. #endif
  17037. /* Decode key usage extension in a certificate.
  17038. *
  17039. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  17040. *
  17041. * @param [in] input Buffer holding data.
  17042. * @param [in] sz Size of data in buffer.
  17043. * @param [in, out] cert Certificate object.
  17044. * @return 0 on success.
  17045. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  17046. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17047. * is invalid.
  17048. * @return MEMORY_E on dynamic memory allocation failure.
  17049. */
  17050. static int DecodeKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
  17051. {
  17052. #ifndef WOLFSSL_ASN_TEMPLATE
  17053. word32 idx = 0;
  17054. int length;
  17055. int ret;
  17056. WOLFSSL_ENTER("DecodeKeyUsage");
  17057. ret = CheckBitString(input, &idx, &length, sz, 0, NULL);
  17058. if (ret != 0)
  17059. return ret;
  17060. if (length == 0 || length > 2)
  17061. return ASN_PARSE_E;
  17062. cert->extKeyUsage = (word16)(input[idx]);
  17063. if (length == 2)
  17064. cert->extKeyUsage |= (word16)(input[idx+1] << 8);
  17065. return 0;
  17066. #else
  17067. ASNGetData dataASN[keyUsageASN_Length];
  17068. word32 idx = 0;
  17069. WOLFSSL_ENTER("DecodeKeyUsage");
  17070. /* Clear dynamic data and set where to store extended key usage. */
  17071. XMEMSET(dataASN, 0, sizeof(dataASN));
  17072. GetASN_Int16Bit(&dataASN[KEYUSAGEASN_IDX_STR], &cert->extKeyUsage);
  17073. /* Parse key usage. */
  17074. return GetASN_Items(keyUsageASN, dataASN, keyUsageASN_Length, 0, input,
  17075. &idx, sz);
  17076. #endif /* WOLFSSL_ASN_TEMPLATE */
  17077. }
  17078. #ifdef WOLFSSL_ASN_TEMPLATE
  17079. /* ASN.1 template for KeyPurposeId.
  17080. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  17081. */
  17082. static const ASNItem keyPurposeIdASN[] = {
  17083. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  17084. };
  17085. enum {
  17086. KEYPURPOSEIDASN_IDX_OID = 0
  17087. };
  17088. /* Number of items in ASN.1 template for KeyPurposeId. */
  17089. #define keyPurposeIdASN_Length (sizeof(keyPurposeIdASN) / sizeof(ASNItem))
  17090. #endif
  17091. /* Decode extended key usage extension in a certificate.
  17092. *
  17093. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  17094. *
  17095. * @param [in] input Buffer holding data.
  17096. * @param [in] sz Size of data in buffer.
  17097. * @param [in, out] cert Certificate object.
  17098. * @return 0 on success.
  17099. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  17100. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17101. * is invalid.
  17102. * @return MEMORY_E on dynamic memory allocation failure.
  17103. */
  17104. static int DecodeExtKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
  17105. {
  17106. #ifndef WOLFSSL_ASN_TEMPLATE
  17107. word32 idx = 0, oid;
  17108. int length, ret;
  17109. WOLFSSL_ENTER("DecodeExtKeyUsage");
  17110. if (GetSequence(input, &idx, &length, sz) < 0) {
  17111. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17112. return ASN_PARSE_E;
  17113. }
  17114. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17115. cert->extExtKeyUsageSrc = input + idx;
  17116. cert->extExtKeyUsageSz = length;
  17117. #endif
  17118. while (idx < (word32)sz) {
  17119. ret = GetObjectId(input, &idx, &oid, oidCertKeyUseType, sz);
  17120. if (ret == ASN_UNKNOWN_OID_E)
  17121. continue;
  17122. else if (ret < 0)
  17123. return ret;
  17124. switch (oid) {
  17125. case EKU_ANY_OID:
  17126. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  17127. break;
  17128. case EKU_SERVER_AUTH_OID:
  17129. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  17130. break;
  17131. case EKU_CLIENT_AUTH_OID:
  17132. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  17133. break;
  17134. case EKU_CODESIGNING_OID:
  17135. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  17136. break;
  17137. case EKU_EMAILPROTECT_OID:
  17138. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  17139. break;
  17140. case EKU_TIMESTAMP_OID:
  17141. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  17142. break;
  17143. case EKU_OCSP_SIGN_OID:
  17144. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  17145. break;
  17146. #ifdef WOLFSSL_WOLFSSH
  17147. case EKU_SSH_CLIENT_AUTH_OID:
  17148. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_CLIENT_AUTH;
  17149. break;
  17150. case EKU_SSH_MSCL_OID:
  17151. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_MSCL;
  17152. break;
  17153. case EKU_SSH_KP_CLIENT_AUTH_OID:
  17154. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_KP_CLIENT_AUTH;
  17155. break;
  17156. #endif /* WOLFSSL_WOLFSSH */
  17157. default:
  17158. break;
  17159. }
  17160. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17161. cert->extExtKeyUsageCount++;
  17162. #endif
  17163. }
  17164. return 0;
  17165. #else
  17166. word32 idx = 0;
  17167. int length;
  17168. int ret = 0;
  17169. WOLFSSL_ENTER("DecodeExtKeyUsage");
  17170. /* Strip SEQUENCE OF and expect to account for all the data. */
  17171. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  17172. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17173. ret = ASN_PARSE_E;
  17174. }
  17175. if (ret == 0) {
  17176. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17177. /* Keep reference for WOLFSSL_X509. */
  17178. cert->extExtKeyUsageSrc = input + idx;
  17179. cert->extExtKeyUsageSz = length;
  17180. #endif
  17181. }
  17182. /* Check all OIDs. */
  17183. while ((ret == 0) && (idx < (word32)sz)) {
  17184. ASNGetData dataASN[keyPurposeIdASN_Length];
  17185. /* Clear dynamic data items and set OID type expected. */
  17186. XMEMSET(dataASN, 0, sizeof(dataASN));
  17187. GetASN_OID(&dataASN[KEYPURPOSEIDASN_IDX_OID], oidIgnoreType);
  17188. /* Decode KeyPurposeId. */
  17189. ret = GetASN_Items(keyPurposeIdASN, dataASN, keyPurposeIdASN_Length, 0,
  17190. input, &idx, sz);
  17191. /* Skip unknown OIDs. */
  17192. if (ret == ASN_UNKNOWN_OID_E) {
  17193. ret = 0;
  17194. }
  17195. else if (ret == 0) {
  17196. /* Store the bit for the OID. */
  17197. switch (dataASN[KEYPURPOSEIDASN_IDX_OID].data.oid.sum) {
  17198. case EKU_ANY_OID:
  17199. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  17200. break;
  17201. case EKU_SERVER_AUTH_OID:
  17202. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  17203. break;
  17204. case EKU_CLIENT_AUTH_OID:
  17205. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  17206. break;
  17207. case EKU_CODESIGNING_OID:
  17208. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  17209. break;
  17210. case EKU_EMAILPROTECT_OID:
  17211. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  17212. break;
  17213. case EKU_TIMESTAMP_OID:
  17214. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  17215. break;
  17216. case EKU_OCSP_SIGN_OID:
  17217. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  17218. break;
  17219. }
  17220. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17221. /* Keep count for WOLFSSL_X509. */
  17222. cert->extExtKeyUsageCount++;
  17223. #endif
  17224. }
  17225. }
  17226. return ret;
  17227. #endif /* WOLFSSL_ASN_TEMPLATE */
  17228. }
  17229. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  17230. static int DecodeNsCertType(const byte* input, int sz, DecodedCert* cert)
  17231. {
  17232. word32 idx = 0;
  17233. int len = 0;
  17234. WOLFSSL_ENTER("DecodeNsCertType");
  17235. if (CheckBitString(input, &idx, &len, (word32)sz, 0, NULL) < 0)
  17236. return ASN_PARSE_E;
  17237. /* Don't need to worry about unused bits as CheckBitString makes sure
  17238. * they're zero. */
  17239. if (idx < (word32)sz)
  17240. cert->nsCertType = input[idx];
  17241. else
  17242. return ASN_PARSE_E;
  17243. return 0;
  17244. }
  17245. #endif
  17246. #ifndef IGNORE_NAME_CONSTRAINTS
  17247. #ifdef WOLFSSL_ASN_TEMPLATE
  17248. /* ASN.1 template for GeneralSubtree.
  17249. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  17250. */
  17251. static const ASNItem subTreeASN[] = {
  17252. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17253. /* base GeneralName */
  17254. /* BASE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  17255. /* minimum BaseDistance DEFAULT 0*/
  17256. /* MIN */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MIN, 0, 0, 1 },
  17257. /* maximum BaseDistance OPTIONAL */
  17258. /* MAX */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MAX, 0, 0, 1 },
  17259. };
  17260. enum {
  17261. SUBTREEASN_IDX_SEQ = 0,
  17262. SUBTREEASN_IDX_BASE,
  17263. SUBTREEASN_IDX_MIN,
  17264. SUBTREEASN_IDX_MAX
  17265. };
  17266. /* Number of items in ASN.1 template for GeneralSubtree. */
  17267. #define subTreeASN_Length (sizeof(subTreeASN) / sizeof(ASNItem))
  17268. #endif
  17269. #ifdef WOLFSSL_ASN_TEMPLATE
  17270. /* Decode the Subtree's GeneralName.
  17271. *
  17272. * @param [in] input Buffer holding data.
  17273. * @param [in] sz Size of data in buffer.
  17274. * @param [in] tag BER tag on GeneralName.
  17275. * @param [in, out] head Linked list of subtree names.
  17276. * @param [in] heap Dynamic memory hint.
  17277. * @return 0 on success.
  17278. * @return MEMORY_E when dynamic memory allocation fails.
  17279. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  17280. */
  17281. static int DecodeSubtreeGeneralName(const byte* input, word32 sz, byte tag,
  17282. Base_entry** head, void* heap)
  17283. {
  17284. Base_entry* entry;
  17285. word32 nameIdx = 0;
  17286. word32 len = sz;
  17287. int strLen;
  17288. int ret = 0;
  17289. (void)heap;
  17290. /* if constructed has leading sequence */
  17291. if ((tag & ASN_CONSTRUCTED) == ASN_CONSTRUCTED) {
  17292. ret = GetASN_Sequence(input, &nameIdx, &strLen, sz, 0);
  17293. if (ret < 0) {
  17294. ret = ASN_PARSE_E;
  17295. }
  17296. else {
  17297. len = (word32)strLen;
  17298. ret = 0;
  17299. }
  17300. }
  17301. if (ret == 0) {
  17302. /* TODO: consider one malloc. */
  17303. /* Allocate Base Entry object. */
  17304. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  17305. DYNAMIC_TYPE_ALTNAME);
  17306. if (entry == NULL) {
  17307. ret = MEMORY_E;
  17308. }
  17309. }
  17310. if (ret == 0) {
  17311. /* Allocate name. */
  17312. entry->name = (char*)XMALLOC(len + 1, heap, DYNAMIC_TYPE_ALTNAME);
  17313. if (entry->name == NULL) {
  17314. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  17315. ret = MEMORY_E;
  17316. }
  17317. }
  17318. if (ret == 0) {
  17319. /* Store name, size and tag in object. */
  17320. XMEMCPY(entry->name, &input[nameIdx], len);
  17321. entry->name[len] = '\0';
  17322. entry->nameSz = (int)len;
  17323. entry->type = tag & ASN_TYPE_MASK;
  17324. /* Put entry at front of linked list. */
  17325. entry->next = *head;
  17326. *head = entry;
  17327. }
  17328. return ret;
  17329. }
  17330. #endif
  17331. /* Decode a subtree of a name constraints in a certificate.
  17332. *
  17333. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  17334. *
  17335. * @param [in] input Buffer holding data.
  17336. * @param [in] sz Size of data in buffer.
  17337. * @param [in, out] head Linked list of subtree names.
  17338. * @param [in] heap Dynamic memory hint.
  17339. * @return 0 on success.
  17340. * @return MEMORY_E when dynamic memory allocation fails.
  17341. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  17342. */
  17343. static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head,
  17344. void* heap)
  17345. {
  17346. #ifndef WOLFSSL_ASN_TEMPLATE
  17347. word32 idx = 0;
  17348. int ret = 0;
  17349. (void)heap;
  17350. while (idx < (word32)sz) {
  17351. int seqLength, strLength;
  17352. word32 nameIdx;
  17353. byte b, bType;
  17354. if (GetSequence(input, &idx, &seqLength, sz) < 0) {
  17355. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17356. return ASN_PARSE_E;
  17357. }
  17358. if (idx >= (word32)sz) {
  17359. WOLFSSL_MSG("\tfail: expecting tag");
  17360. return ASN_PARSE_E;
  17361. }
  17362. nameIdx = idx;
  17363. b = input[nameIdx++];
  17364. if (GetLength(input, &nameIdx, &strLength, sz) <= 0) {
  17365. WOLFSSL_MSG("\tinvalid length");
  17366. return ASN_PARSE_E;
  17367. }
  17368. /* Get type, LSB 4-bits */
  17369. bType = (byte)(b & ASN_TYPE_MASK);
  17370. if (bType == ASN_DNS_TYPE || bType == ASN_RFC822_TYPE ||
  17371. bType == ASN_DIR_TYPE) {
  17372. Base_entry* entry;
  17373. /* if constructed has leading sequence */
  17374. if (b & ASN_CONSTRUCTED) {
  17375. if (GetSequence(input, &nameIdx, &strLength, sz) < 0) {
  17376. WOLFSSL_MSG("\tfail: constructed be a SEQUENCE");
  17377. return ASN_PARSE_E;
  17378. }
  17379. }
  17380. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  17381. DYNAMIC_TYPE_ALTNAME);
  17382. if (entry == NULL) {
  17383. WOLFSSL_MSG("allocate error");
  17384. return MEMORY_E;
  17385. }
  17386. entry->name = (char*)XMALLOC((size_t)strLength+1, heap,
  17387. DYNAMIC_TYPE_ALTNAME);
  17388. if (entry->name == NULL) {
  17389. WOLFSSL_MSG("allocate error");
  17390. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  17391. return MEMORY_E;
  17392. }
  17393. XMEMCPY(entry->name, &input[nameIdx], (size_t)strLength);
  17394. entry->name[strLength] = '\0';
  17395. entry->nameSz = strLength;
  17396. entry->type = bType;
  17397. entry->next = *head;
  17398. *head = entry;
  17399. }
  17400. idx += (word32)seqLength;
  17401. }
  17402. return ret;
  17403. #else
  17404. DECL_ASNGETDATA(dataASN, subTreeASN_Length);
  17405. word32 idx = 0;
  17406. int ret = 0;
  17407. (void)heap;
  17408. ALLOC_ASNGETDATA(dataASN, subTreeASN_Length, ret, heap);
  17409. /* Process all subtrees. */
  17410. while ((ret == 0) && (idx < (word32)sz)) {
  17411. byte minVal = 0;
  17412. byte maxVal = 0;
  17413. /* Clear dynamic data and set choice for GeneralName and location to
  17414. * store minimum and maximum.
  17415. */
  17416. XMEMSET(dataASN, 0, sizeof(*dataASN) * subTreeASN_Length);
  17417. GetASN_Choice(&dataASN[SUBTREEASN_IDX_BASE], generalNameChoice);
  17418. GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MIN], &minVal);
  17419. GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MAX], &maxVal);
  17420. /* Parse GeneralSubtree. */
  17421. ret = GetASN_Items(subTreeASN, dataASN, subTreeASN_Length, 0, input,
  17422. &idx, sz);
  17423. if (ret == 0) {
  17424. byte t = dataASN[SUBTREEASN_IDX_BASE].tag;
  17425. /* Check GeneralName tag is one of the types we can handle. */
  17426. if (t == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE) ||
  17427. t == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE) ||
  17428. t == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  17429. /* Parse the general name and store a new entry. */
  17430. ret = DecodeSubtreeGeneralName(input +
  17431. GetASNItem_DataIdx(dataASN[SUBTREEASN_IDX_BASE], input),
  17432. dataASN[SUBTREEASN_IDX_BASE].length, t, head, heap);
  17433. }
  17434. /* Skip entry. */
  17435. }
  17436. }
  17437. FREE_ASNGETDATA(dataASN, heap);
  17438. return ret;
  17439. #endif
  17440. }
  17441. #ifdef WOLFSSL_ASN_TEMPLATE
  17442. /* ASN.1 template for NameConstraints.
  17443. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  17444. */
  17445. static const ASNItem nameConstraintsASN[] = {
  17446. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17447. /* permittedSubtrees */
  17448. /* PERMIT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  17449. /* excludededSubtrees */
  17450. /* EXCLUDE */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  17451. };
  17452. enum {
  17453. NAMECONSTRAINTSASN_IDX_SEQ = 0,
  17454. NAMECONSTRAINTSASN_IDX_PERMIT,
  17455. NAMECONSTRAINTSASN_IDX_EXCLUDE
  17456. };
  17457. /* Number of items in ASN.1 template for NameConstraints. */
  17458. #define nameConstraintsASN_Length (sizeof(nameConstraintsASN) / sizeof(ASNItem))
  17459. #endif
  17460. /* Decode name constraints extension in a certificate.
  17461. *
  17462. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  17463. *
  17464. * @param [in] input Buffer holding data.
  17465. * @param [in] sz Size of data in buffer.
  17466. * @param [in, out] cert Certificate object.
  17467. * @return 0 on success.
  17468. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17469. * is invalid.
  17470. * @return MEMORY_E on dynamic memory allocation failure.
  17471. */
  17472. static int DecodeNameConstraints(const byte* input, word32 sz,
  17473. DecodedCert* cert)
  17474. {
  17475. #ifndef WOLFSSL_ASN_TEMPLATE
  17476. word32 idx = 0;
  17477. int length = 0;
  17478. WOLFSSL_ENTER("DecodeNameConstraints");
  17479. if (GetSequence(input, &idx, &length, sz) < 0) {
  17480. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17481. return ASN_PARSE_E;
  17482. }
  17483. while (idx < (word32)sz) {
  17484. byte b = input[idx++];
  17485. Base_entry** subtree = NULL;
  17486. if (GetLength(input, &idx, &length, sz) <= 0) {
  17487. WOLFSSL_MSG("\tinvalid length");
  17488. return ASN_PARSE_E;
  17489. }
  17490. if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
  17491. subtree = &cert->permittedNames;
  17492. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
  17493. subtree = &cert->excludedNames;
  17494. else {
  17495. WOLFSSL_MSG("\tinvalid subtree");
  17496. return ASN_PARSE_E;
  17497. }
  17498. if (DecodeSubtree(input + idx, (word32)length, subtree,
  17499. cert->heap) < 0) {
  17500. WOLFSSL_MSG("\terror parsing subtree");
  17501. return ASN_PARSE_E;
  17502. }
  17503. idx += (word32)length;
  17504. }
  17505. return 0;
  17506. #else
  17507. DECL_ASNGETDATA(dataASN, nameConstraintsASN_Length);
  17508. word32 idx = 0;
  17509. int ret = 0;
  17510. CALLOC_ASNGETDATA(dataASN, nameConstraintsASN_Length, ret, cert->heap);
  17511. if (ret == 0) {
  17512. /* Parse NameConstraints. */
  17513. ret = GetASN_Items(nameConstraintsASN, dataASN,
  17514. nameConstraintsASN_Length, 1, input, &idx, sz);
  17515. }
  17516. if (ret == 0) {
  17517. /* If there was a permittedSubtrees then parse it. */
  17518. if (dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data != NULL) {
  17519. ret = DecodeSubtree(
  17520. dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data,
  17521. dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.length,
  17522. &cert->permittedNames, cert->heap);
  17523. }
  17524. }
  17525. if (ret == 0) {
  17526. /* If there was a excludedSubtrees then parse it. */
  17527. if (dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data != NULL) {
  17528. ret = DecodeSubtree(
  17529. dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data,
  17530. dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.length,
  17531. &cert->excludedNames, cert->heap);
  17532. }
  17533. }
  17534. FREE_ASNGETDATA(dataASN, cert->heap);
  17535. return ret;
  17536. #endif /* WOLFSSL_ASN_TEMPLATE */
  17537. }
  17538. #endif /* IGNORE_NAME_CONSTRAINTS */
  17539. #if (defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_SEP)) || \
  17540. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17541. /* Decode ITU-T X.690 OID format to a string representation
  17542. * return string length */
  17543. int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz)
  17544. {
  17545. word32 val, inIdx = 0, outIdx = 0;
  17546. int w = 0;
  17547. if (out == NULL || in == NULL || outSz < 4 || inSz < 2)
  17548. return BAD_FUNC_ARG;
  17549. /* The first byte expands into b/40 dot b%40. */
  17550. val = in[inIdx++];
  17551. w = XSNPRINTF(out, outSz, "%u.%u", val / 40, val % 40);
  17552. if (w < 0) {
  17553. w = BUFFER_E;
  17554. goto exit;
  17555. }
  17556. outIdx += w;
  17557. val = 0;
  17558. while (inIdx < inSz && outIdx < outSz) {
  17559. /* extract the next OID digit from in to val */
  17560. /* first bit is used to set if value is coded on 1 or multiple bytes */
  17561. if (in[inIdx] & 0x80) {
  17562. val += in[inIdx] & 0x7F;
  17563. val *= 128;
  17564. }
  17565. else {
  17566. /* write val as text into out */
  17567. val += in[inIdx];
  17568. w = XSNPRINTF(out + outIdx, outSz - outIdx, ".%u", val);
  17569. if (w < 0 || (word32)w > outSz - outIdx) {
  17570. w = BUFFER_E;
  17571. goto exit;
  17572. }
  17573. outIdx += w;
  17574. val = 0;
  17575. }
  17576. inIdx++;
  17577. }
  17578. if (outIdx == outSz)
  17579. outIdx--;
  17580. out[outIdx] = 0;
  17581. w = (int)outIdx;
  17582. exit:
  17583. return w;
  17584. }
  17585. #endif /* WOLFSSL_CERT_EXT && !WOLFSSL_SEP */
  17586. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_QT)
  17587. #ifdef WOLFSSL_ASN_TEMPLATE
  17588. /* ASN.1 template for PolicyInformation.
  17589. * X.509: RFC 5280, 4.2.1.4 - Certificate Policies.
  17590. */
  17591. static const ASNItem policyInfoASN[] = {
  17592. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17593. /* policyIdentifier */
  17594. /* ID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  17595. /* policyQualifiers */
  17596. /* QUALI */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  17597. };
  17598. enum {
  17599. POLICYINFOASN_IDX_SEQ = 0,
  17600. POLICYINFOASN_IDX_ID,
  17601. POLICYINFOASN_IDX_QUALI
  17602. };
  17603. /* Number of items in ASN.1 template for PolicyInformation. */
  17604. #define policyInfoASN_Length (sizeof(policyInfoASN) / sizeof(ASNItem))
  17605. #endif
  17606. /* Reference: https://tools.ietf.org/html/rfc5280#section-4.2.1.4 */
  17607. static int DecodeCertPolicy(const byte* input, word32 sz, DecodedCert* cert)
  17608. {
  17609. #ifndef WOLFSSL_ASN_TEMPLATE
  17610. word32 idx = 0;
  17611. word32 oldIdx;
  17612. int policy_length = 0;
  17613. int ret;
  17614. int total_length = 0;
  17615. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  17616. !defined(WOLFSSL_DUP_CERTPOL)
  17617. int i;
  17618. #endif
  17619. WOLFSSL_ENTER("DecodeCertPolicy");
  17620. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  17621. /* Check if cert is null before dereferencing below */
  17622. if (cert == NULL)
  17623. return BAD_FUNC_ARG;
  17624. #else
  17625. (void)cert;
  17626. #endif
  17627. #if defined(WOLFSSL_CERT_EXT)
  17628. cert->extCertPoliciesNb = 0;
  17629. #endif
  17630. if (GetSequence(input, &idx, &total_length, sz) < 0) {
  17631. WOLFSSL_MSG("\tGet CertPolicy total seq failed");
  17632. return ASN_PARSE_E;
  17633. }
  17634. /* Validate total length */
  17635. if (total_length > (int)(sz - idx)) {
  17636. WOLFSSL_MSG("\tCertPolicy length mismatch");
  17637. return ASN_PARSE_E;
  17638. }
  17639. /* Unwrap certificatePolicies */
  17640. do {
  17641. int length = 0;
  17642. if (GetSequence(input, &idx, &policy_length, sz) < 0) {
  17643. WOLFSSL_MSG("\tGet CertPolicy seq failed");
  17644. return ASN_PARSE_E;
  17645. }
  17646. oldIdx = idx;
  17647. ret = GetASNObjectId(input, &idx, &length, sz);
  17648. if (ret != 0)
  17649. return ret;
  17650. policy_length -= (int)(idx - oldIdx);
  17651. if (length > 0) {
  17652. /* Verify length won't overrun buffer */
  17653. if (length > (int)(sz - idx)) {
  17654. WOLFSSL_MSG("\tCertPolicy length exceeds input buffer");
  17655. return ASN_PARSE_E;
  17656. }
  17657. #if defined(WOLFSSL_SEP)
  17658. cert->deviceType = (byte*)XMALLOC((size_t)length, cert->heap,
  17659. DYNAMIC_TYPE_X509_EXT);
  17660. if (cert->deviceType == NULL) {
  17661. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  17662. return MEMORY_E;
  17663. }
  17664. cert->deviceTypeSz = length;
  17665. XMEMCPY(cert->deviceType, input + idx, (size_t)length);
  17666. break;
  17667. #elif defined(WOLFSSL_CERT_EXT)
  17668. /* decode cert policy */
  17669. if (DecodePolicyOID(cert->extCertPolicies[
  17670. cert->extCertPoliciesNb], MAX_CERTPOL_SZ,
  17671. input + idx, length) <= 0) {
  17672. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  17673. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17674. return ASN_PARSE_E;
  17675. }
  17676. #ifndef WOLFSSL_DUP_CERTPOL
  17677. /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
  17678. * NOT appear more than once in a certificate policies
  17679. * extension". This is a sanity check for duplicates.
  17680. * extCertPolicies should only have OID values, additional
  17681. * qualifiers need to be stored in a separate array. */
  17682. for (i = 0; i < cert->extCertPoliciesNb; i++) {
  17683. if (XMEMCMP(cert->extCertPolicies[i],
  17684. cert->extCertPolicies[cert->extCertPoliciesNb],
  17685. MAX_CERTPOL_SZ) == 0) {
  17686. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  17687. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  17688. WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
  17689. return CERTPOLICIES_E;
  17690. }
  17691. }
  17692. #endif /* !WOLFSSL_DUP_CERTPOL */
  17693. cert->extCertPoliciesNb++;
  17694. #else
  17695. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  17696. return 0;
  17697. #endif
  17698. }
  17699. idx += (word32)policy_length;
  17700. } while((int)idx < total_length
  17701. #if defined(WOLFSSL_CERT_EXT)
  17702. && cert->extCertPoliciesNb < MAX_CERTPOL_NB
  17703. #endif
  17704. );
  17705. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  17706. return 0;
  17707. #else /* WOLFSSL_ASN_TEMPLATE */
  17708. word32 idx = 0;
  17709. int ret = 0;
  17710. int total_length = 0;
  17711. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  17712. !defined(WOLFSSL_DUP_CERTPOL)
  17713. int i;
  17714. #endif
  17715. WOLFSSL_ENTER("DecodeCertPolicy");
  17716. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  17717. /* Check if cert is null before dereferencing below */
  17718. if (cert == NULL)
  17719. ret = BAD_FUNC_ARG;
  17720. #endif
  17721. if (ret == 0) {
  17722. #if defined(WOLFSSL_CERT_EXT)
  17723. cert->extCertPoliciesNb = 0;
  17724. #endif
  17725. /* Strip SEQUENCE OF and check using all data. */
  17726. if (GetASN_Sequence(input, &idx, &total_length, (word32)sz, 1) < 0)
  17727. {
  17728. ret = ASN_PARSE_E;
  17729. }
  17730. }
  17731. /* Unwrap certificatePolicies */
  17732. while ((ret == 0) && ((int)idx < total_length)
  17733. #if defined(WOLFSSL_CERT_EXT)
  17734. && (cert->extCertPoliciesNb < MAX_CERTPOL_NB)
  17735. #endif
  17736. ) {
  17737. ASNGetData dataASN[policyInfoASN_Length];
  17738. byte* data = NULL;
  17739. word32 length = 0;
  17740. /* Clear dynamic data and check OID is a cert policy type. */
  17741. XMEMSET(dataASN, 0, sizeof(dataASN));
  17742. GetASN_OID(&dataASN[POLICYINFOASN_IDX_ID], oidCertPolicyType);
  17743. ret = GetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length, 1,
  17744. input, &idx, (word32)sz);
  17745. if (ret == 0) {
  17746. /* Get the OID. */
  17747. GetASN_OIDData(&dataASN[POLICYINFOASN_IDX_ID], &data, &length);
  17748. if (length == 0) {
  17749. ret = ASN_PARSE_E;
  17750. }
  17751. }
  17752. #if defined(WOLFSSL_SEP)
  17753. /* Store OID in device type. */
  17754. if (ret == 0) {
  17755. cert->deviceType = (byte*)XMALLOC(length, cert->heap,
  17756. DYNAMIC_TYPE_X509_EXT);
  17757. if (cert->deviceType == NULL) {
  17758. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  17759. ret = MEMORY_E;
  17760. }
  17761. }
  17762. if (ret == 0) {
  17763. /* Store device type data and length. */
  17764. cert->deviceTypeSz = (int)length;
  17765. XMEMCPY(cert->deviceType, data, length);
  17766. break;
  17767. }
  17768. #elif defined(WOLFSSL_CERT_EXT)
  17769. if (ret == 0) {
  17770. /* Decode cert policy. */
  17771. if (DecodePolicyOID(
  17772. cert->extCertPolicies[cert->extCertPoliciesNb],
  17773. MAX_CERTPOL_SZ, data, length) <= 0) {
  17774. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  17775. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17776. ret = ASN_PARSE_E;
  17777. }
  17778. }
  17779. #ifndef WOLFSSL_DUP_CERTPOL
  17780. /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
  17781. * NOT appear more than once in a certificate policies
  17782. * extension". This is a sanity check for duplicates.
  17783. * extCertPolicies should only have OID values, additional
  17784. * qualifiers need to be stored in a separate array. */
  17785. for (i = 0; (ret == 0) && (i < cert->extCertPoliciesNb); i++) {
  17786. if (XMEMCMP(cert->extCertPolicies[i],
  17787. cert->extCertPolicies[cert->extCertPoliciesNb],
  17788. MAX_CERTPOL_SZ) == 0) {
  17789. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  17790. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  17791. WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
  17792. ret = CERTPOLICIES_E;
  17793. }
  17794. }
  17795. #endif /* !defined(WOLFSSL_DUP_CERTPOL) */
  17796. if (ret == 0) {
  17797. /* Keep count of policies seen. */
  17798. cert->extCertPoliciesNb++;
  17799. }
  17800. #else
  17801. (void)data;
  17802. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  17803. break;
  17804. #endif
  17805. }
  17806. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  17807. return ret;
  17808. #endif /* WOLFSSL_ASN_TEMPLATE */
  17809. }
  17810. #endif /* WOLFSSL_SEP */
  17811. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  17812. #ifdef WOLFSSL_ASN_TEMPLATE
  17813. /* ASN.1 template for subject dir attribute.
  17814. * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
  17815. */
  17816. static const ASNItem subjDirAttrASN[] = {
  17817. /* SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  17818. /* OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  17819. /* PLEN */ { 2, ASN_SET, 1, 0, 0 },
  17820. };
  17821. enum {
  17822. SUBJDIRATTRASN_IDX_SEQ = 0,
  17823. SUBJDIRATTRASN_IDX_OID,
  17824. SUBJDIRATTRASN_IDX_SET,
  17825. };
  17826. /* Number of items in ASN.1 template for BasicConstraints. */
  17827. #define subjDirAttrASN_Length (sizeof(subjDirAttrASN) / sizeof(ASNItem))
  17828. #endif
  17829. /* Decode subject directory attributes extension in a certificate.
  17830. *
  17831. * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
  17832. *
  17833. * @param [in] input Buffer holding data.
  17834. * @param [in] sz Size of data in buffer.
  17835. * @param [in, out] cert Certificate object.
  17836. * @return 0 on success.
  17837. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17838. * is invalid.
  17839. */
  17840. static int DecodeSubjDirAttr(const byte* input, int sz, DecodedCert* cert)
  17841. {
  17842. #ifndef WOLFSSL_ASN_TEMPLATE
  17843. word32 idx = 0;
  17844. int length = 0;
  17845. int ret = 0;
  17846. WOLFSSL_ENTER("DecodeSubjDirAttr");
  17847. #ifdef OPENSSL_ALL
  17848. cert->extSubjDirAttrSrc = input;
  17849. cert->extSubjDirAttrSz = sz;
  17850. #endif /* OPENSSL_ALL */
  17851. /* Unwrap the list of Attributes */
  17852. if (GetSequence(input, &idx, &length, sz) < 0)
  17853. return ASN_PARSE_E;
  17854. if (length == 0) {
  17855. /* RFC 5280 4.2.1.8. Subject Directory Attributes
  17856. If the subjectDirectoryAttributes extension is present, the
  17857. sequence MUST contain at least one entry. */
  17858. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17859. return ASN_PARSE_E;
  17860. }
  17861. /* length is the length of the list contents */
  17862. while (idx < (word32)sz) {
  17863. word32 oid;
  17864. if (GetSequence(input, &idx, &length, sz) < 0)
  17865. return ASN_PARSE_E;
  17866. if (GetObjectId(input, &idx, &oid, oidSubjDirAttrType, sz) < 0)
  17867. return ASN_PARSE_E;
  17868. if (GetSet(input, &idx, &length, sz) < 0)
  17869. return ASN_PARSE_E;
  17870. /* There may be more than one countryOfCitizenship, but save the
  17871. * first one for now. */
  17872. if (oid == SDA_COC_OID) {
  17873. byte tag;
  17874. if (GetHeader(input, &tag, &idx, &length, sz, 1) < 0)
  17875. return ASN_PARSE_E;
  17876. if (length != COUNTRY_CODE_LEN)
  17877. return ASN_PARSE_E;
  17878. if (tag == ASN_PRINTABLE_STRING) {
  17879. XMEMCPY(cert->countryOfCitizenship,
  17880. input + idx, COUNTRY_CODE_LEN);
  17881. cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
  17882. }
  17883. }
  17884. idx += length;
  17885. }
  17886. return ret;
  17887. #else
  17888. DECL_ASNGETDATA(dataASN, subjDirAttrASN_Length);
  17889. int ret = 0;
  17890. word32 idx = 0;
  17891. int length;
  17892. WOLFSSL_ENTER("DecodeSubjDirAttr");
  17893. CALLOC_ASNGETDATA(dataASN, subjDirAttrASN_Length, ret, cert->heap);
  17894. /* Strip outer SEQUENCE. */
  17895. if ((ret == 0) && (GetSequence(input, &idx, &length, sz) < 0)) {
  17896. ret = ASN_PARSE_E;
  17897. }
  17898. /* Handle each inner SEQUENCE. */
  17899. while ((ret == 0) && (idx < (word32)sz)) {
  17900. ret = GetASN_Items(subjDirAttrASN, dataASN, subjDirAttrASN_Length, 1,
  17901. input, &idx, sz);
  17902. /* There may be more than one countryOfCitizenship, but save the
  17903. * first one for now. */
  17904. if ((ret == 0) &&
  17905. (dataASN[SUBJDIRATTRASN_IDX_OID].data.oid.sum == SDA_COC_OID)) {
  17906. int cuLen;
  17907. word32 setIdx = 0;
  17908. byte* setData;
  17909. word32 setLen;
  17910. GetASN_GetRef(&dataASN[SUBJDIRATTRASN_IDX_SET], &setData, &setLen);
  17911. if (GetASNHeader(setData, ASN_PRINTABLE_STRING, &setIdx, &cuLen,
  17912. setLen) < 0) {
  17913. ret = ASN_PARSE_E;
  17914. }
  17915. if ((ret == 0) && (cuLen != COUNTRY_CODE_LEN)) {
  17916. ret = ASN_PARSE_E;
  17917. }
  17918. if (ret == 0) {
  17919. XMEMCPY(cert->countryOfCitizenship, setData + setIdx, cuLen);
  17920. cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
  17921. }
  17922. }
  17923. }
  17924. FREE_ASNGETDATA(dataASN, cert->heap);
  17925. return ret;
  17926. #endif /* WOLFSSL_ASN_TEMPLATE */
  17927. }
  17928. #endif /* WOLFSSL_SUBJ_DIR_ATTR */
  17929. #ifdef WOLFSSL_SUBJ_INFO_ACC
  17930. /* Decode subject information access extension in a certificate.
  17931. *
  17932. * X.509: RFC 5280, 4.2.2.2 - Subject Information Access.
  17933. *
  17934. * @param [in] input Buffer holding data.
  17935. * @param [in] sz Size of data in buffer.
  17936. * @param [in, out] cert Certificate object.
  17937. * @return 0 on success.
  17938. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  17939. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17940. * is invalid.
  17941. * @return MEMORY_E on dynamic memory allocation failure.
  17942. */
  17943. static int DecodeSubjInfoAcc(const byte* input, int sz, DecodedCert* cert)
  17944. {
  17945. word32 idx = 0;
  17946. int length = 0;
  17947. int ret = 0;
  17948. WOLFSSL_ENTER("DecodeSubjInfoAcc");
  17949. #ifdef OPENSSL_ALL
  17950. cert->extSubjAltNameSrc = input;
  17951. cert->extSubjAltNameSz = sz;
  17952. #endif /* OPENSSL_ALL */
  17953. /* Unwrap SubjectInfoAccessSyntax, the list of AccessDescriptions */
  17954. if (GetSequence(input, &idx, &length, sz) < 0)
  17955. return ASN_PARSE_E;
  17956. if (length == 0) {
  17957. /* RFC 5280 4.2.2.2. Subject Information Access
  17958. If the subjectInformationAccess extension is present, the
  17959. sequence MUST contain at least one entry. */
  17960. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17961. return ASN_PARSE_E;
  17962. }
  17963. /* Per fpkx-x509-cert-profile-common... section 5.3.
  17964. * [The] subjectInfoAccess extension must contain at least one
  17965. * instance of the id-ad-caRepository access method containing a
  17966. * publicly accessible HTTP URI which returns as certs-only
  17967. * CMS.
  17968. */
  17969. while (idx < (word32)sz) {
  17970. word32 oid = 0;
  17971. byte b;
  17972. /* Unwrap an AccessDescription */
  17973. if (GetSequence(input, &idx, &length, sz) < 0)
  17974. return ASN_PARSE_E;
  17975. /* Get the accessMethod */
  17976. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0)
  17977. return ASN_PARSE_E;
  17978. /* Only supporting URIs right now. */
  17979. if (GetASNTag(input, &idx, &b, sz) < 0)
  17980. return ASN_PARSE_E;
  17981. if (GetLength(input, &idx, &length, sz) < 0)
  17982. return ASN_PARSE_E;
  17983. /* Set caRepo entry */
  17984. if (b == GENERALNAME_URI && oid == AIA_CA_REPO_OID) {
  17985. cert->extSubjInfoAccCaRepoSz = length;
  17986. cert->extSubjInfoAccCaRepo = input + idx;
  17987. break;
  17988. }
  17989. idx += length;
  17990. }
  17991. if (cert->extSubjInfoAccCaRepo == NULL ||
  17992. cert->extSubjInfoAccCaRepoSz == 0) {
  17993. WOLFSSL_MSG("SubjectInfoAccess missing an URL.");
  17994. ret = ASN_PARSE_E;
  17995. }
  17996. WOLFSSL_LEAVE("DecodeSubjInfoAcc", ret);
  17997. return ret;
  17998. }
  17999. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  18000. /* Macro to check if bit is set, if not sets and return success.
  18001. Otherwise returns failure */
  18002. /* Macro required here because bit-field operation */
  18003. #ifndef WOLFSSL_NO_ASN_STRICT
  18004. #define VERIFY_AND_SET_OID(bit) \
  18005. if ((bit) == 0) \
  18006. (bit) = 1; \
  18007. else \
  18008. return ASN_OBJECT_ID_E;
  18009. #else
  18010. /* With no strict defined, the verify is skipped */
  18011. #define VERIFY_AND_SET_OID(bit) bit = 1;
  18012. #endif
  18013. /* Parse extension type specific data based on OID sum.
  18014. *
  18015. * Supported extensions:
  18016. * Basic Constraints - BASIC_CA_OID
  18017. * CRL Distribution Points - CRL_DIST_OID
  18018. * Authority Information Access - AUTH_INFO_OID
  18019. * Subject Alternative Name - ALT_NAMES_OID
  18020. * Authority Key Identifier - AUTH_KEY_OID
  18021. * Subject Key Identifier - SUBJ_KEY_OID
  18022. * Certificate Policies - CERT_POLICY_OID (conditional parsing)
  18023. * Key Usage - KEY_USAGE_OID
  18024. * Extended Key Usage - EXT_KEY_USAGE_OID
  18025. * Name Constraints - NAME_CONS_OID
  18026. * Inhibit anyPolicy - INHIBIT_ANY_OID
  18027. * Netscape Certificate Type - NETSCAPE_CT_OID (able to be excluded)
  18028. * OCSP no check - OCSP_NOCHECK_OID (when compiling OCSP)
  18029. * Subject Directory Attributes - SUBJ_DIR_ATTR_OID
  18030. * Subject Information Access - SUBJ_INFO_ACC_OID
  18031. * Unsupported extensions from RFC 5280:
  18032. * 4.2.1.5 - Policy mappings
  18033. * 4.2.1.7 - Issuer Alternative Name
  18034. * 4.2.1.11 - Policy Constraints
  18035. * 4.2.1.15 - Freshest CRL
  18036. *
  18037. * @param [in] input Buffer containing extension type specific data.
  18038. * @param [in] length Length of data.
  18039. * @param [in] oid OID sum for extension.
  18040. * @param [in] critical Whether extension is critical.
  18041. * @param [in, out] cert Certificate object.
  18042. * @return 0 on success.
  18043. * @return ASN_PARSE_E when BER encoding is invalid.
  18044. * @return MEMORY_E on dynamic memory allocation failure.
  18045. * @return Other negative values on error.
  18046. */
  18047. static int DecodeExtensionType(const byte* input, word32 length, word32 oid,
  18048. byte critical, DecodedCert* cert,
  18049. int *isUnknownExt)
  18050. {
  18051. int ret = 0;
  18052. word32 idx = 0;
  18053. if (isUnknownExt != NULL)
  18054. *isUnknownExt = 0;
  18055. switch (oid) {
  18056. /* Basic Constraints. */
  18057. case BASIC_CA_OID:
  18058. VERIFY_AND_SET_OID(cert->extBasicConstSet);
  18059. cert->extBasicConstCrit = critical ? 1 : 0;
  18060. if (DecodeBasicCaConstraint(input, (int)length, cert) < 0) {
  18061. ret = ASN_PARSE_E;
  18062. }
  18063. break;
  18064. /* CRL Distribution point. */
  18065. case CRL_DIST_OID:
  18066. VERIFY_AND_SET_OID(cert->extCRLdistSet);
  18067. cert->extCRLdistCrit = critical ? 1 : 0;
  18068. if (DecodeCrlDist(input, length, cert) < 0) {
  18069. ret = ASN_PARSE_E;
  18070. }
  18071. break;
  18072. /* Authority information access. */
  18073. case AUTH_INFO_OID:
  18074. VERIFY_AND_SET_OID(cert->extAuthInfoSet);
  18075. cert->extAuthInfoCrit = critical ? 1 : 0;
  18076. if (DecodeAuthInfo(input, length, cert) < 0) {
  18077. ret = ASN_PARSE_E;
  18078. }
  18079. break;
  18080. /* Subject alternative name. */
  18081. case ALT_NAMES_OID:
  18082. VERIFY_AND_SET_OID(cert->extSubjAltNameSet);
  18083. cert->extSubjAltNameCrit = critical ? 1 : 0;
  18084. ret = DecodeAltNames(input, length, cert);
  18085. break;
  18086. /* Authority Key Identifier. */
  18087. case AUTH_KEY_OID:
  18088. VERIFY_AND_SET_OID(cert->extAuthKeyIdSet);
  18089. cert->extAuthKeyIdCrit = critical ? 1 : 0;
  18090. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  18091. /* This check is added due to RFC 5280 section 4.2.1.1
  18092. * stating that conforming CA's must mark this extension
  18093. * as non-critical. When parsing extensions check that
  18094. * certificate was made in compliance with this. */
  18095. if (critical) {
  18096. WOLFSSL_MSG("Critical Auth Key ID is not allowed");
  18097. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  18098. ret = ASN_CRIT_EXT_E;
  18099. }
  18100. #endif
  18101. if ((ret == 0) && (DecodeAuthKeyId(input, length, cert) < 0)) {
  18102. ret = ASN_PARSE_E;
  18103. }
  18104. break;
  18105. /* Subject Key Identifier. */
  18106. case SUBJ_KEY_OID:
  18107. VERIFY_AND_SET_OID(cert->extSubjKeyIdSet);
  18108. cert->extSubjKeyIdCrit = critical ? 1 : 0;
  18109. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  18110. /* This check is added due to RFC 5280 section 4.2.1.2
  18111. * stating that conforming CA's must mark this extension
  18112. * as non-critical. When parsing extensions check that
  18113. * certificate was made in compliance with this. */
  18114. if (critical) {
  18115. WOLFSSL_MSG("Critical Subject Key ID is not allowed");
  18116. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  18117. ret = ASN_CRIT_EXT_E;
  18118. }
  18119. #endif
  18120. if ((ret == 0) && (DecodeSubjKeyId(input, length, cert) < 0)) {
  18121. ret = ASN_PARSE_E;
  18122. }
  18123. break;
  18124. /* Certificate policies. */
  18125. case CERT_POLICY_OID:
  18126. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT)
  18127. VERIFY_AND_SET_OID(cert->extCertPolicySet);
  18128. #if defined(OPENSSL_EXTRA) || \
  18129. defined(OPENSSL_EXTRA_X509_SMALL)
  18130. cert->extCertPolicyCrit = critical ? 1 : 0;
  18131. #endif
  18132. #endif
  18133. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || \
  18134. defined(WOLFSSL_QT)
  18135. if (DecodeCertPolicy(input, length, cert) < 0) {
  18136. ret = ASN_PARSE_E;
  18137. }
  18138. #else
  18139. WOLFSSL_MSG("Certificate Policy extension not supported yet.");
  18140. #endif
  18141. break;
  18142. /* Key usage. */
  18143. case KEY_USAGE_OID:
  18144. VERIFY_AND_SET_OID(cert->extKeyUsageSet);
  18145. cert->extKeyUsageCrit = critical ? 1 : 0;
  18146. if (DecodeKeyUsage(input, length, cert) < 0) {
  18147. ret = ASN_PARSE_E;
  18148. }
  18149. break;
  18150. /* Extended key usage. */
  18151. case EXT_KEY_USAGE_OID:
  18152. VERIFY_AND_SET_OID(cert->extExtKeyUsageSet);
  18153. cert->extExtKeyUsageCrit = critical ? 1 : 0;
  18154. if (DecodeExtKeyUsage(input, length, cert) < 0) {
  18155. ret = ASN_PARSE_E;
  18156. }
  18157. break;
  18158. #ifndef IGNORE_NAME_CONSTRAINTS
  18159. /* Name constraints. */
  18160. case NAME_CONS_OID:
  18161. #ifndef WOLFSSL_NO_ASN_STRICT
  18162. /* Verify RFC 5280 Sec 4.2.1.10 rule:
  18163. "The name constraints extension,
  18164. which MUST be used only in a CA certificate" */
  18165. if (!cert->isCA) {
  18166. WOLFSSL_MSG("Name constraints allowed only for CA certs");
  18167. WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
  18168. ret = ASN_NAME_INVALID_E;
  18169. }
  18170. #endif
  18171. VERIFY_AND_SET_OID(cert->extNameConstraintSet);
  18172. cert->extNameConstraintCrit = critical ? 1 : 0;
  18173. if (DecodeNameConstraints(input, length, cert) < 0) {
  18174. ret = ASN_PARSE_E;
  18175. }
  18176. break;
  18177. #endif /* IGNORE_NAME_CONSTRAINTS */
  18178. /* Inhibit anyPolicy. */
  18179. case INHIBIT_ANY_OID:
  18180. VERIFY_AND_SET_OID(cert->inhibitAnyOidSet);
  18181. WOLFSSL_MSG("Inhibit anyPolicy extension not supported yet.");
  18182. break;
  18183. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  18184. /* Netscape's certificate type. */
  18185. case NETSCAPE_CT_OID:
  18186. if (DecodeNsCertType(input, (int)length, cert) < 0)
  18187. ret = ASN_PARSE_E;
  18188. break;
  18189. #endif
  18190. #ifdef HAVE_OCSP
  18191. /* OCSP no check. */
  18192. case OCSP_NOCHECK_OID:
  18193. VERIFY_AND_SET_OID(cert->ocspNoCheckSet);
  18194. ret = GetASNNull(input, &idx, length);
  18195. if (ret != 0) {
  18196. ret = ASN_PARSE_E;
  18197. }
  18198. break;
  18199. #endif
  18200. case POLICY_CONST_OID:
  18201. VERIFY_AND_SET_OID(cert->extPolicyConstSet);
  18202. cert->extPolicyConstCrit = critical ? 1 : 0;
  18203. if (DecodePolicyConstraints(&input[idx], (int)length, cert) < 0)
  18204. return ASN_PARSE_E;
  18205. break;
  18206. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  18207. case SUBJ_DIR_ATTR_OID:
  18208. VERIFY_AND_SET_OID(cert->extSubjDirAttrSet);
  18209. if (DecodeSubjDirAttr(&input[idx], length, cert) < 0)
  18210. return ASN_PARSE_E;
  18211. break;
  18212. #endif
  18213. #ifdef WOLFSSL_SUBJ_INFO_ACC
  18214. case SUBJ_INFO_ACC_OID:
  18215. VERIFY_AND_SET_OID(cert->extSubjInfoAccSet);
  18216. if (DecodeSubjInfoAcc(&input[idx], length, cert) < 0)
  18217. return ASN_PARSE_E;
  18218. break;
  18219. #endif
  18220. default:
  18221. if (isUnknownExt != NULL)
  18222. *isUnknownExt = 1;
  18223. #ifndef WOLFSSL_NO_ASN_STRICT
  18224. /* While it is a failure to not support critical extensions,
  18225. * still parse the certificate ignoring the unsupported
  18226. * extension to allow caller to accept it with the verify
  18227. * callback. */
  18228. if (critical) {
  18229. WOLFSSL_ERROR_VERBOSE(ASN_CRIT_EXT_E);
  18230. ret = ASN_CRIT_EXT_E;
  18231. }
  18232. #endif
  18233. break;
  18234. }
  18235. return ret;
  18236. }
  18237. #ifdef WOLFSSL_ASN_TEMPLATE
  18238. /* ASN.1 template for extensions.
  18239. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  18240. */
  18241. static const ASNItem certExtHdrASN[] = {
  18242. /* EXTTAG */ { 0, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 0 },
  18243. /* EXTSEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18244. };
  18245. enum {
  18246. CERTEXTHDRASN_IDX_EXTTAG = 0,
  18247. CERTEXTHDRASN_IDX_EXTSEQ
  18248. };
  18249. /* Number of items in ASN.1 template for extensions. */
  18250. #define certExtHdrASN_Length (sizeof(certExtHdrASN) / sizeof(ASNItem))
  18251. /* ASN.1 template for Extension.
  18252. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  18253. */
  18254. static const ASNItem certExtASN[] = {
  18255. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18256. /* Extension object id */
  18257. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  18258. /* critical - when true, must be parseable. */
  18259. /* CRIT */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  18260. /* Data for extension - leave index at start of data. */
  18261. /* VAL */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  18262. };
  18263. enum {
  18264. CERTEXTASN_IDX_SEQ = 0,
  18265. CERTEXTASN_IDX_OID,
  18266. CERTEXTASN_IDX_CRIT,
  18267. CERTEXTASN_IDX_VAL
  18268. };
  18269. /* Number of items in ASN.1 template for Extension. */
  18270. #define certExtASN_Length (sizeof(certExtASN) / sizeof(ASNItem))
  18271. #endif
  18272. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \
  18273. && defined(HAVE_OID_DECODING)
  18274. int wc_SetUnknownExtCallback(DecodedCert* cert,
  18275. wc_UnknownExtCallback cb) {
  18276. if (cert == NULL) {
  18277. return BAD_FUNC_ARG;
  18278. }
  18279. cert->unknownExtCallback = cb;
  18280. return 0;
  18281. }
  18282. #endif
  18283. /*
  18284. * Processing the Certificate Extensions. This does not modify the current
  18285. * index. It is works starting with the recorded extensions pointer.
  18286. */
  18287. static int DecodeCertExtensions(DecodedCert* cert)
  18288. {
  18289. #ifndef WOLFSSL_ASN_TEMPLATE
  18290. int ret = 0;
  18291. word32 idx = 0;
  18292. word32 sz = (word32)cert->extensionsSz;
  18293. const byte* input = cert->extensions;
  18294. int length;
  18295. word32 oid;
  18296. byte critical = 0;
  18297. byte criticalFail = 0;
  18298. byte tag = 0;
  18299. WOLFSSL_ENTER("DecodeCertExtensions");
  18300. if (input == NULL || sz == 0)
  18301. return BAD_FUNC_ARG;
  18302. #ifdef WOLFSSL_CERT_REQ
  18303. if (!cert->isCSR)
  18304. #endif
  18305. { /* Not included in CSR */
  18306. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  18307. return ASN_PARSE_E;
  18308. }
  18309. if (tag != ASN_EXTENSIONS) {
  18310. WOLFSSL_MSG("\tfail: should be an EXTENSIONS");
  18311. return ASN_PARSE_E;
  18312. }
  18313. if (GetLength(input, &idx, &length, sz) < 0) {
  18314. WOLFSSL_MSG("\tfail: invalid length");
  18315. return ASN_PARSE_E;
  18316. }
  18317. }
  18318. if (GetSequence(input, &idx, &length, sz) < 0) {
  18319. WOLFSSL_MSG("\tfail: should be a SEQUENCE (1)");
  18320. return ASN_PARSE_E;
  18321. }
  18322. while (idx < (word32)sz) {
  18323. word32 localIdx;
  18324. if (GetSequence(input, &idx, &length, sz) < 0) {
  18325. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  18326. return ASN_PARSE_E;
  18327. }
  18328. oid = 0;
  18329. if ((ret = GetObjectId(input, &idx, &oid, oidCertExtType, sz)) < 0) {
  18330. WOLFSSL_MSG("\tfail: OBJECT ID");
  18331. return ret;
  18332. }
  18333. /* check for critical flag */
  18334. critical = 0;
  18335. if ((idx + 1) > (word32)sz) {
  18336. WOLFSSL_MSG("\tfail: malformed buffer");
  18337. return BUFFER_E;
  18338. }
  18339. localIdx = idx;
  18340. if (GetASNTag(input, &localIdx, &tag, sz) == 0) {
  18341. if (tag == ASN_BOOLEAN) {
  18342. ret = GetBoolean(input, &idx, sz);
  18343. if (ret < 0) {
  18344. WOLFSSL_MSG("\tfail: critical boolean");
  18345. return ret;
  18346. }
  18347. critical = (byte)ret;
  18348. }
  18349. }
  18350. /* process the extension based on the OID */
  18351. ret = GetOctetString(input, &idx, &length, sz);
  18352. if (ret < 0) {
  18353. WOLFSSL_MSG("\tfail: bad OCTET STRING");
  18354. return ret;
  18355. }
  18356. ret = DecodeExtensionType(input + idx, (word32)length, oid, critical,
  18357. cert, NULL);
  18358. if (ret == ASN_CRIT_EXT_E) {
  18359. ret = 0;
  18360. criticalFail = 1;
  18361. }
  18362. if (ret < 0)
  18363. goto end;
  18364. idx += (word32)length;
  18365. }
  18366. ret = criticalFail ? ASN_CRIT_EXT_E : 0;
  18367. end:
  18368. return ret;
  18369. #else
  18370. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  18371. ASNGetData dataExtsASN[certExtHdrASN_Length];
  18372. int ret = 0;
  18373. const byte* input = cert->extensions;
  18374. int sz = cert->extensionsSz;
  18375. word32 idx = 0;
  18376. int criticalRet = 0;
  18377. int offset = 0;
  18378. WOLFSSL_ENTER("DecodeCertExtensions");
  18379. if (input == NULL || sz == 0)
  18380. ret = BAD_FUNC_ARG;
  18381. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, cert->heap);
  18382. #ifdef WOLFSSL_CERT_REQ
  18383. if (cert->isCSR) {
  18384. offset = CERTEXTHDRASN_IDX_EXTSEQ;
  18385. }
  18386. #endif
  18387. if (ret == 0) {
  18388. /* Clear dynamic data. */
  18389. XMEMSET(dataExtsASN, 0, sizeof(dataExtsASN));
  18390. /* Parse extensions header. */
  18391. ret = GetASN_Items(certExtHdrASN + offset, dataExtsASN + offset,
  18392. (int)(certExtHdrASN_Length - (size_t)offset), 0,
  18393. input, &idx, (word32)sz);
  18394. }
  18395. /* Parse each extension. */
  18396. while ((ret == 0) && (idx < (word32)sz)) {
  18397. byte critical = 0;
  18398. int isUnknownExt = 0;
  18399. /* Clear dynamic data. */
  18400. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  18401. /* Ensure OID is an extension type. */
  18402. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  18403. /* Set criticality variable. */
  18404. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  18405. /* Parse extension wrapper. */
  18406. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  18407. &idx, (word32)sz);
  18408. if (ret == 0) {
  18409. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  18410. word32 length = dataASN[CERTEXTASN_IDX_VAL].length;
  18411. /* Decode the extension by type. */
  18412. ret = DecodeExtensionType(input + idx, length, oid, critical, cert,
  18413. &isUnknownExt);
  18414. #if defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_DECODING)
  18415. if (isUnknownExt && (cert->unknownExtCallback != NULL)) {
  18416. word16 decOid[MAX_OID_SZ];
  18417. word32 decOidSz = sizeof(decOid);
  18418. ret = DecodeObjectId(
  18419. dataASN[CERTEXTASN_IDX_OID].data.oid.data,
  18420. dataASN[CERTEXTASN_IDX_OID].data.oid.length,
  18421. decOid, &decOidSz);
  18422. if (ret != 0) {
  18423. /* Should never get here as the extension was successfully
  18424. * decoded earlier. Something might be corrupted. */
  18425. WOLFSSL_MSG("DecodeObjectId() failed. Corruption?");
  18426. WOLFSSL_ERROR(ret);
  18427. }
  18428. ret = cert->unknownExtCallback(decOid, decOidSz, critical,
  18429. dataASN[CERTEXTASN_IDX_VAL].data.buffer.data,
  18430. dataASN[CERTEXTASN_IDX_VAL].length);
  18431. }
  18432. #endif
  18433. (void)isUnknownExt;
  18434. /* Move index on to next extension. */
  18435. idx += length;
  18436. }
  18437. /* Don't fail criticality until all other extensions have been checked.
  18438. */
  18439. if (ret == ASN_CRIT_EXT_E) {
  18440. criticalRet = ASN_CRIT_EXT_E;
  18441. ret = 0;
  18442. }
  18443. }
  18444. if (ret == 0) {
  18445. /* Use criticality return. */
  18446. ret = criticalRet;
  18447. }
  18448. FREE_ASNGETDATA(dataASN, cert->heap);
  18449. return ret;
  18450. #endif
  18451. }
  18452. #ifdef WOLFSSL_ASN_TEMPLATE
  18453. /* ASN template for an X509 certificate.
  18454. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  18455. */
  18456. static const ASNItem x509CertASN[] = {
  18457. /* Certificate ::= SEQUENCE */
  18458. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18459. /* tbsCertificate TBSCertificate */
  18460. /* TBSCertificate ::= SEQUENCE */
  18461. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18462. /* version [0] EXPLICIT Version DEFAULT v1 */
  18463. /* TBS_VER */ { 2, ASN_CONTEXT_SPECIFIC | ASN_X509_CERT_VERSION, 1, 1, 1 },
  18464. /* Version ::= INTEGER { v1(0), v2(1), v3(2) */
  18465. /* TBS_VER_INT */ { 3, ASN_INTEGER, 0, 0, 0 },
  18466. /* serialNumber CertificateSerialNumber */
  18467. /* CetificateSerialNumber ::= INTEGER */
  18468. /* TBS_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
  18469. /* signature AlgorithmIdentifier */
  18470. /* AlgorithmIdentifier ::= SEQUENCE */
  18471. /* TBS_ALGOID_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18472. /* Algorithm OBJECT IDENTIFIER */
  18473. /* TBS_ALGOID_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  18474. /* parameters ANY defined by algorithm OPTIONAL */
  18475. /* TBS_ALGOID_PARAMS_NULL */ { 3, ASN_TAG_NULL, 0, 0, 2 },
  18476. #ifdef WC_RSA_PSS
  18477. /* TBS_ALGOID_PARAMS */ { 3, ASN_SEQUENCE, 1, 0, 2 },
  18478. #endif
  18479. /* issuer Name */
  18480. /* TBS_ISSUER_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  18481. /* validity Validity */
  18482. /* Validity ::= SEQUENCE */
  18483. /* TBS_VALIDITY_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18484. /* notBefore Time */
  18485. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  18486. /* TBS_VALIDITY_NOTB_UTC */ { 3, ASN_UTC_TIME, 0, 0, 2 },
  18487. /* TBS_VALIDITY_NOTB_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 2 },
  18488. /* notAfter Time */
  18489. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  18490. /* TBS_VALIDITY_NOTA_UTC */ { 3, ASN_UTC_TIME, 0, 0, 3 },
  18491. /* TBS_VALIDITY_NOTA_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 3 },
  18492. /* subject Name */
  18493. /* TBS_SUBJECT_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  18494. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  18495. /* TBS_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18496. /* algorithm AlgorithmIdentifier */
  18497. /* AlgorithmIdentifier ::= SEQUENCE */
  18498. /* TBS_SPUBKEYINFO_ALGO_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  18499. /* Algorithm OBJECT IDENTIFIER */
  18500. /* TBS_SPUBKEYINFO_ALGO_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  18501. /* parameters ANY defined by algorithm OPTIONAL */
  18502. /* TBS_SPUBKEYINFO_ALGO_NULL */ { 4, ASN_TAG_NULL, 0, 0, 2 },
  18503. /* TBS_SPUBKEYINFO_ALGO_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 2 },
  18504. #ifdef WC_RSA_PSS
  18505. /* TBS_SPUBKEYINFO_ALGO_P_SEQ */ { 4, ASN_SEQUENCE, 1, 0, 2 },
  18506. #endif
  18507. /* subjectPublicKey BIT STRING */
  18508. /* TBS_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  18509. /* issuerUniqueID UniqueIdentfier OPTIONAL */
  18510. /* TBS_ISSUERUID */ { 2, ASN_CONTEXT_SPECIFIC | 1, 0, 0, 1 },
  18511. /* subjectUniqueID UniqueIdentfier OPTIONAL */
  18512. /* TBS_SUBJECTUID */ { 2, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 1 },
  18513. /* extensions Extensions OPTIONAL */
  18514. /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 1 },
  18515. /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
  18516. /* signatureAlgorithm AlgorithmIdentifier */
  18517. /* AlgorithmIdentifier ::= SEQUENCE */
  18518. /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18519. /* Algorithm OBJECT IDENTIFIER */
  18520. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  18521. /* parameters ANY defined by algorithm OPTIONAL */
  18522. /* SIGALGO_PARAMS_NULL */ { 2, ASN_TAG_NULL, 0, 0, 2 },
  18523. #ifdef WC_RSA_PSS
  18524. /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  18525. #endif
  18526. /* signature BIT STRING */
  18527. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  18528. };
  18529. enum {
  18530. X509CERTASN_IDX_SEQ = 0,
  18531. X509CERTASN_IDX_TBS_SEQ,
  18532. X509CERTASN_IDX_TBS_VER,
  18533. X509CERTASN_IDX_TBS_VER_INT,
  18534. X509CERTASN_IDX_TBS_SERIAL,
  18535. X509CERTASN_IDX_TBS_ALGOID_SEQ,
  18536. X509CERTASN_IDX_TBS_ALGOID_OID,
  18537. X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL,
  18538. #ifdef WC_RSA_PSS
  18539. X509CERTASN_IDX_TBS_ALGOID_PARAMS,
  18540. #endif
  18541. X509CERTASN_IDX_TBS_ISSUER_SEQ,
  18542. X509CERTASN_IDX_TBS_VALIDITY_SEQ,
  18543. X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC,
  18544. X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT,
  18545. X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC,
  18546. X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT,
  18547. X509CERTASN_IDX_TBS_SUBJECT_SEQ,
  18548. X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ,
  18549. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
  18550. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID,
  18551. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_NULL,
  18552. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID,
  18553. #ifdef WC_RSA_PSS
  18554. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_P_SEQ,
  18555. #endif
  18556. X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY,
  18557. X509CERTASN_IDX_TBS_ISSUERUID,
  18558. X509CERTASN_IDX_TBS_SUBJECTUID,
  18559. X509CERTASN_IDX_TBS_EXT,
  18560. X509CERTASN_IDX_TBS_EXT_SEQ,
  18561. X509CERTASN_IDX_SIGALGO_SEQ,
  18562. X509CERTASN_IDX_SIGALGO_OID,
  18563. X509CERTASN_IDX_SIGALGO_PARAMS_NULL,
  18564. #ifdef WC_RSA_PSS
  18565. X509CERTASN_IDX_SIGALGO_PARAMS,
  18566. #endif
  18567. X509CERTASN_IDX_SIGNATURE,
  18568. WOLF_ENUM_DUMMY_LAST_ELEMENT(X509CERTASN_IDX)
  18569. };
  18570. /* Number of items in ASN template for an X509 certificate. */
  18571. #define x509CertASN_Length (sizeof(x509CertASN) / sizeof(ASNItem))
  18572. /* Check the data data.
  18573. *
  18574. * @param [in] dataASN ASN template dynamic data item.
  18575. * @param [in] dataType BEFORE or AFTER date.
  18576. * @return 0 on success.
  18577. * @return ASN_TIME_E when BER tag is nor UTC or GENERALIZED time.
  18578. * @return ASN_DATE_SZ_E when time data is not supported.
  18579. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  18580. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  18581. */
  18582. static int CheckDate(ASNGetData *dataASN, int dateType)
  18583. {
  18584. int ret = 0;
  18585. /* Check BER tag is valid. */
  18586. if ((dataASN->tag != ASN_UTC_TIME) &&
  18587. (dataASN->tag != ASN_GENERALIZED_TIME)) {
  18588. ret = ASN_TIME_E;
  18589. }
  18590. /* Check date length is valid. */
  18591. if ((ret == 0) && ((dataASN->length > MAX_DATE_SIZE) ||
  18592. (dataASN->length < MIN_DATE_SIZE))) {
  18593. ret = ASN_DATE_SZ_E;
  18594. }
  18595. #ifndef NO_ASN_TIME_CHECK
  18596. /* Check date is a valid string and BEFORE or AFTER now. */
  18597. if ((ret == 0) &&
  18598. (!XVALIDATE_DATE(dataASN->data.ref.data, dataASN->tag, dateType))) {
  18599. if (dateType == BEFORE) {
  18600. ret = ASN_BEFORE_DATE_E;
  18601. }
  18602. else {
  18603. ret = ASN_AFTER_DATE_E;
  18604. }
  18605. }
  18606. #endif
  18607. (void)dateType;
  18608. return ret;
  18609. }
  18610. /* Decode a certificate. Internal/non-public API.
  18611. *
  18612. * @param [in] cert Certificate object.
  18613. * @param [in] verify Whether to verify dates before and after now.
  18614. * @param [out] criticalExt Critical extension return code.
  18615. * @param [out] badDateRet Bad date return code.
  18616. * @param [in] stopAtPubKey Stop parsing before subkectPublicKeyInfo.
  18617. * @param [in] stopAfterPubKey Stop parsing after subkectPublicKeyInfo.
  18618. * @return 0 on success.
  18619. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  18620. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  18621. * @return ASN_DATE_SZ_E when time data is not supported.
  18622. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  18623. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  18624. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18625. * is invalid.
  18626. * @return BUFFER_E when data in buffer is too small.
  18627. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  18628. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  18629. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  18630. * non-zero length.
  18631. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  18632. */
  18633. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  18634. int* badDateRet, int stopAtPubKey,
  18635. int stopAfterPubKey)
  18636. {
  18637. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  18638. int ret = 0;
  18639. int badDate = 0;
  18640. byte version;
  18641. word32 idx;
  18642. word32 serialSz;
  18643. const unsigned char* issuer = NULL;
  18644. word32 issuerSz = 0;
  18645. const unsigned char* subject = NULL;
  18646. word32 subjectSz = 0;
  18647. word32 pubKeyOffset = 0;
  18648. word32 pubKeyEnd = 0;
  18649. int done = 0;
  18650. CALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  18651. if (ret == 0) {
  18652. version = 0;
  18653. serialSz = EXTERNAL_SERIAL_SIZE;
  18654. /* Get the version and put the serial number into the buffer. */
  18655. GetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT], &version);
  18656. GetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
  18657. &serialSz);
  18658. /* Check OID types for signature, algorithm, ECC curve and sigAlg. */
  18659. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
  18660. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
  18661. oidKeyType);
  18662. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
  18663. oidCurveType);
  18664. GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
  18665. /* Parse the X509 certificate. */
  18666. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1,
  18667. cert->source, &cert->srcIdx, cert->maxIdx);
  18668. #ifdef WOLFSSL_CLANG_TIDY
  18669. /* work around clang-tidy false positive re cert->source. */
  18670. if ((ret == 0) && (cert->source == NULL)) {
  18671. ret = ASN_PARSE_E;
  18672. }
  18673. #endif
  18674. }
  18675. /* Check version is valid/supported - can't be negative. */
  18676. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  18677. WOLFSSL_MSG("Unexpected certificate version");
  18678. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18679. ret = ASN_PARSE_E;
  18680. }
  18681. if (ret == 0) {
  18682. int i;
  18683. pubKeyOffset = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset;
  18684. /* Set fields extracted from data. */
  18685. cert->version = version;
  18686. cert->serialSz = (int)serialSz;
  18687. cert->signatureOID = dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum;
  18688. cert->keyOID = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID].data.oid.sum;
  18689. cert->certBegin = dataASN[X509CERTASN_IDX_TBS_SEQ].offset;
  18690. /* No bad date error - don't always care. */
  18691. badDate = 0;
  18692. /* Find the item with the BEFORE date and check it. */
  18693. i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].tag != 0)
  18694. ? X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC
  18695. : X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT;
  18696. if ((CheckDate(&dataASN[i], BEFORE) < 0) && verify) {
  18697. badDate = ASN_BEFORE_DATE_E;
  18698. }
  18699. /* Store reference to BEFOREdate. */
  18700. cert->beforeDate = GetASNItem_Addr(dataASN[i], cert->source);
  18701. cert->beforeDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);
  18702. /* Find the item with the AFTER date and check it. */
  18703. i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].tag != 0)
  18704. ? X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC
  18705. : X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT;
  18706. if ((CheckDate(&dataASN[i], AFTER) < 0) && verify) {
  18707. badDate = ASN_AFTER_DATE_E;
  18708. }
  18709. /* Store reference to AFTER date. */
  18710. cert->afterDate = GetASNItem_Addr(dataASN[i], cert->source);
  18711. cert->afterDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);
  18712. /* Get the issuer name. */
  18713. issuer = cert->source + dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
  18714. issuerSz = dataASN[X509CERTASN_IDX_TBS_VALIDITY_SEQ].offset -
  18715. dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
  18716. /* Get the subject name. */
  18717. subject = cert->source +
  18718. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
  18719. subjectSz = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset -
  18720. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
  18721. }
  18722. if ((ret == 0) && stopAtPubKey) {
  18723. /* Return any bad date error through badDateRet and return offset of
  18724. * subjectPublicKeyInfo.
  18725. */
  18726. if (badDateRet != NULL) {
  18727. *badDateRet = badDate;
  18728. }
  18729. done = 1;
  18730. }
  18731. if ((ret == 0) && (!done)) {
  18732. /* Store the signature information. */
  18733. cert->sigIndex = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
  18734. GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE],
  18735. &cert->signature, &cert->sigLength);
  18736. /* Make sure 'signature' and 'signatureAlgorithm' are the same. */
  18737. if (dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum
  18738. != cert->signatureOID) {
  18739. WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
  18740. ret = ASN_SIG_OID_E;
  18741. }
  18742. /* Parameters not allowed after ECDSA or EdDSA algorithm OID. */
  18743. else if (IsSigAlgoECC(cert->signatureOID)) {
  18744. if ((dataASN[X509CERTASN_IDX_SIGALGO_PARAMS_NULL].tag != 0)
  18745. #ifdef WC_RSA_PSS
  18746. || (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0)
  18747. #endif
  18748. ) {
  18749. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18750. ret = ASN_PARSE_E;
  18751. }
  18752. }
  18753. #ifdef WC_RSA_PSS
  18754. /* Check parameters starting with a SEQUENCE. */
  18755. else if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
  18756. word32 oid = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
  18757. word32 sigAlgParamsSz = 0;
  18758. /* Parameters only with RSA PSS. */
  18759. if (oid != CTC_RSASSAPSS) {
  18760. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18761. ret = ASN_PARSE_E;
  18762. }
  18763. if (ret == 0) {
  18764. const byte* tbsParams;
  18765. word32 tbsParamsSz;
  18766. const byte* sigAlgParams;
  18767. /* Check RSA PSS parameters are the same. */
  18768. tbsParams =
  18769. GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  18770. cert->source);
  18771. tbsParamsSz =
  18772. GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  18773. cert->source);
  18774. sigAlgParams =
  18775. GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  18776. cert->source);
  18777. sigAlgParamsSz =
  18778. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  18779. cert->source);
  18780. if ((tbsParamsSz != sigAlgParamsSz) ||
  18781. (XMEMCMP(tbsParams, sigAlgParams, tbsParamsSz) != 0)) {
  18782. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18783. ret = ASN_PARSE_E;
  18784. }
  18785. }
  18786. if (ret == 0) {
  18787. /* Store parameters for use in signature verification. */
  18788. cert->sigParamsIndex =
  18789. dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].offset;
  18790. cert->sigParamsLength = sigAlgParamsSz;
  18791. }
  18792. }
  18793. #endif
  18794. }
  18795. if ((ret == 0) && (!done)) {
  18796. pubKeyEnd = dataASN[X509CERTASN_IDX_TBS_ISSUERUID].offset;
  18797. if (stopAfterPubKey) {
  18798. /* Return any bad date error through badDateRed and return offset
  18799. * after subjectPublicKeyInfo.
  18800. */
  18801. if (badDateRet != NULL) {
  18802. *badDateRet = badDate;
  18803. }
  18804. done = 1;
  18805. }
  18806. }
  18807. if ((ret == 0) && (!done) &&
  18808. (dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data != NULL)) {
  18809. #ifndef ALLOW_V1_EXTENSIONS
  18810. /* Certificate extensions were only defined in version 2. */
  18811. if (cert->version < 2) {
  18812. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  18813. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  18814. ret = ASN_VERSION_E;
  18815. }
  18816. #endif
  18817. if (ret == 0) {
  18818. /* Save references to extension data. */
  18819. cert->extensions = GetASNItem_Addr(
  18820. dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
  18821. cert->extensionsSz = (int)GetASNItem_Length(
  18822. dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
  18823. cert->extensionsIdx = dataASN[X509CERTASN_IDX_TBS_EXT].offset;
  18824. /* Advance past extensions. */
  18825. cert->srcIdx = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
  18826. }
  18827. }
  18828. /* Dispose of memory before allocating for extension decoding. */
  18829. FREE_ASNGETDATA(dataASN, cert->heap);
  18830. if ((ret == 0) && (issuer != NULL)) {
  18831. idx = 0;
  18832. /* Put issuer into cert and calculate hash. */
  18833. ret = GetCertName(cert, cert->issuer, cert->issuerHash, ISSUER, issuer,
  18834. &idx, issuerSz);
  18835. }
  18836. if ((ret == 0) && (subject != NULL)) {
  18837. idx = 0;
  18838. /* Put subject into cert and calculate hash. */
  18839. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  18840. subject, &idx, subjectSz);
  18841. }
  18842. if (ret == 0) {
  18843. /* Determine if self signed by comparing issuer and subject hashes. */
  18844. #ifdef WOLFSSL_CERT_REQ
  18845. if (cert->isCSR) {
  18846. cert->selfSigned = 1;
  18847. }
  18848. else
  18849. #endif
  18850. {
  18851. cert->selfSigned = (XMEMCMP(cert->issuerHash, cert->subjectHash,
  18852. KEYID_SIZE) == 0);
  18853. }
  18854. if (stopAtPubKey) {
  18855. ret = (int)pubKeyOffset;
  18856. }
  18857. }
  18858. if ((ret == 0) && (!stopAtPubKey)) {
  18859. /* Parse the public key. */
  18860. idx = pubKeyOffset;
  18861. ret = GetCertKey(cert, cert->source, &idx, pubKeyEnd);
  18862. }
  18863. if ((ret == 0) && (!stopAtPubKey) && (!stopAfterPubKey) &&
  18864. (cert->extensions != NULL)) {
  18865. /* Decode the extension data starting at [3]. */
  18866. ret = DecodeCertExtensions(cert);
  18867. if (criticalExt != NULL) {
  18868. if (ret == ASN_CRIT_EXT_E) {
  18869. /* Return critical extension not recognized. */
  18870. *criticalExt = ret;
  18871. ret = 0;
  18872. }
  18873. else {
  18874. /* No critical extension error. */
  18875. *criticalExt = 0;
  18876. }
  18877. }
  18878. }
  18879. if ((ret == 0) && (!done) && (badDate != 0)) {
  18880. /* Parsed whole certificate fine but return any date errors. */
  18881. ret = badDate;
  18882. }
  18883. return ret;
  18884. }
  18885. /* Decode BER/DER data into certificate object.
  18886. *
  18887. * BER/DER data information held in source, srcIdx and maxIdx fields of
  18888. * certificate object.
  18889. *
  18890. * @param [in] cert Decoded certificate object.
  18891. * @param [in] verify Whether to find CA and verify certificate.
  18892. * @param [in] criticalExt Any error for critical extensions not recognized.
  18893. * @return 0 on success.
  18894. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  18895. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  18896. * @return ASN_DATE_SZ_E when time data is not supported.
  18897. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  18898. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  18899. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18900. * is invalid.
  18901. * @return BUFFER_E when data in buffer is too small.
  18902. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  18903. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  18904. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  18905. * non-zero length.
  18906. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  18907. */
  18908. int DecodeCert(DecodedCert* cert, int verify, int* criticalExt)
  18909. {
  18910. return DecodeCertInternal(cert, verify, criticalExt, NULL, 0, 0);
  18911. }
  18912. #ifdef WOLFSSL_CERT_REQ
  18913. /* ASN.1 template for certificate request Attribute.
  18914. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  18915. */
  18916. static const ASNItem reqAttrASN[] = {
  18917. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18918. /* type */
  18919. /* TYPE */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  18920. /* values */
  18921. /* VALS */ { 1, ASN_SET, 1, 0, 0 },
  18922. };
  18923. enum {
  18924. REQATTRASN_IDX_SEQ = 0,
  18925. REQATTRASN_IDX_TYPE,
  18926. REQATTRASN_IDX_VALS
  18927. };
  18928. /* Number of items in ASN.1 template for certificate request Attribute. */
  18929. #define reqAttrASN_Length (sizeof(reqAttrASN) / sizeof(ASNItem))
  18930. /* ASN.1 template for a string choice. */
  18931. static const ASNItem strAttrASN[] = {
  18932. { 0, 0, 0, 0, 0 },
  18933. };
  18934. enum {
  18935. STRATTRASN_IDX_STR = 0
  18936. };
  18937. /* Number of items in ASN.1 template for a string choice. */
  18938. #define strAttrASN_Length (sizeof(strAttrASN) / sizeof(ASNItem))
  18939. /* ASN.1 choices for types for a string in an attribute. */
  18940. static const byte strAttrChoice[] = {
  18941. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, 0
  18942. };
  18943. /* Decode a certificate request attribute's value.
  18944. *
  18945. * @param [in] cert Certificate request object.
  18946. * @param [out] criticalExt Critical extension return code.
  18947. * @param [in] oid OID describing which attribute was found.
  18948. * @param [in] aIdx Index into certificate source to start parsing.
  18949. * @param [in] input Attribute value data.
  18950. * @param [in] maxIdx Maximum index to parse to.
  18951. * @return 0 on success.
  18952. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18953. * is invalid.
  18954. */
  18955. static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt,
  18956. word32 oid, word32 aIdx, const byte* input, word32 maxIdx)
  18957. {
  18958. int ret = 0;
  18959. word32 idx = 0;
  18960. ASNGetData strDataASN[strAttrASN_Length];
  18961. switch (oid) {
  18962. case PKCS9_CONTENT_TYPE_OID:
  18963. /* Clear dynamic data and specify choices acceptable. */
  18964. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  18965. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  18966. /* Parse a string. */
  18967. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  18968. 1, input, &idx, maxIdx);
  18969. if (ret == 0) {
  18970. /* Store references to password data. */
  18971. cert->contentType =
  18972. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  18973. cert->contentTypeLen =
  18974. (int)strDataASN[STRATTRASN_IDX_STR].data.ref.length;
  18975. }
  18976. break;
  18977. /* A password by which the entity may request certificate revocation.
  18978. * PKCS#9: RFC 2985, 5.4.1 - Challenge password
  18979. */
  18980. case CHALLENGE_PASSWORD_OID:
  18981. /* Clear dynamic data and specify choices acceptable. */
  18982. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  18983. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  18984. /* Parse a string. */
  18985. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  18986. 1, input, &idx, maxIdx);
  18987. if (ret == 0) {
  18988. /* Store references to password data. */
  18989. cert->cPwd =
  18990. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  18991. cert->cPwdLen = (int)strDataASN[STRATTRASN_IDX_STR].
  18992. data.ref.length;
  18993. }
  18994. break;
  18995. /* Requested serial number to issue with.
  18996. * PKCS#9: RFC 2985, 5.2.10 - Serial Number
  18997. * (References: ISO/IEC 9594-6:1997)
  18998. */
  18999. case SERIAL_NUMBER_OID:
  19000. /* Clear dynamic data and specify choices acceptable. */
  19001. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  19002. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  19003. /* Parse a string. */
  19004. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  19005. 1, input, &idx, maxIdx);
  19006. if (ret == 0) {
  19007. /* Store references to serial number. */
  19008. cert->sNum =
  19009. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  19010. cert->sNumLen = (int)strDataASN[STRATTRASN_IDX_STR].
  19011. data.ref.length;
  19012. /* Store serial number if small enough. */
  19013. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  19014. XMEMCPY(cert->serial, cert->sNum, (size_t)cert->sNumLen);
  19015. cert->serialSz = cert->sNumLen;
  19016. }
  19017. }
  19018. break;
  19019. /* Certificate extensions to be included in generated certificate.
  19020. * PKCS#9: RFC 2985, 5.4.2 - Extension request
  19021. */
  19022. case EXTENSION_REQUEST_OID:
  19023. /* Store references to all extensions. */
  19024. cert->extensions = input;
  19025. cert->extensionsSz = (int)maxIdx;
  19026. cert->extensionsIdx = aIdx;
  19027. /* Decode and validate extensions. */
  19028. ret = DecodeCertExtensions(cert);
  19029. if (ret == ASN_CRIT_EXT_E) {
  19030. /* Return critical extension not recognized. */
  19031. *criticalExt = ret;
  19032. ret = 0;
  19033. }
  19034. else {
  19035. /* No critical extension error. */
  19036. *criticalExt = 0;
  19037. }
  19038. break;
  19039. default:
  19040. ret = ASN_PARSE_E;
  19041. break;
  19042. }
  19043. return ret;
  19044. }
  19045. /* Decode attributes of a BER encoded certificate request.
  19046. *
  19047. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  19048. *
  19049. * Outer sequence has been removed.
  19050. *
  19051. * @param [in] cert Certificate request object.
  19052. * @param [out] criticalExt Critical extension return code.
  19053. * @param [in] idx Index into certificate source to start parsing.
  19054. * @param [in] maxIdx Maximum index to parse to.
  19055. * @return 0 on success.
  19056. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  19057. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19058. * is invalid.
  19059. * @return BUFFER_E when data in buffer is too small.
  19060. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  19061. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  19062. * non-zero length.
  19063. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  19064. */
  19065. static int DecodeCertReqAttributes(DecodedCert* cert, int* criticalExt,
  19066. word32 idx, word32 maxIdx)
  19067. {
  19068. DECL_ASNGETDATA(dataASN, reqAttrASN_Length);
  19069. int ret = 0;
  19070. WOLFSSL_ENTER("DecodeCertReqAttributes");
  19071. ALLOC_ASNGETDATA(dataASN, reqAttrASN_Length, ret, cert->heap);
  19072. /* Parse each attribute until all data used up. */
  19073. while ((ret == 0) && (idx < maxIdx)) {
  19074. /* Clear dynamic data. */
  19075. XMEMSET(dataASN, 0, sizeof(ASNGetData) * reqAttrASN_Length);
  19076. GetASN_OID(&dataASN[REQATTRASN_IDX_TYPE], oidIgnoreType);
  19077. /* Parse an attribute. */
  19078. ret = GetASN_Items(reqAttrASN, dataASN, reqAttrASN_Length, 0,
  19079. cert->source, &idx, maxIdx);
  19080. /* idx is now at end of attribute data. */
  19081. if (ret == 0) {
  19082. ret = DecodeCertReqAttrValue(cert, criticalExt,
  19083. dataASN[REQATTRASN_IDX_TYPE].data.oid.sum,
  19084. GetASNItem_DataIdx(dataASN[REQATTRASN_IDX_VALS], cert->source),
  19085. dataASN[REQATTRASN_IDX_VALS].data.ref.data,
  19086. dataASN[REQATTRASN_IDX_VALS].data.ref.length);
  19087. }
  19088. }
  19089. FREE_ASNGETDATA(dataASN, cert->heap);
  19090. return ret;
  19091. }
  19092. /* ASN.1 template for a certificate request.
  19093. * PKCS#10: RFC 2986, 4.1 - CertificationRequestInfo
  19094. * PKCS#10: RFC 2986, 4.2 - CertificationRequest
  19095. */
  19096. static const ASNItem certReqASN[] = {
  19097. /* CertificationRequest */
  19098. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  19099. /* CertificationRequestInfo */
  19100. /* INFO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  19101. /* version INTEGER { v1(0), v2(1), v3(2) */
  19102. /* INFO_VER */ { 2, ASN_INTEGER, 0, 0, 0 },
  19103. /* subject Name */
  19104. /* INFO_SUBJ_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  19105. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  19106. /* INFO_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  19107. /* algorithm AlgorithmIdentifier */
  19108. /* INFO_SPUBKEYINFO_ALGOID_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  19109. /* Algorithm OBJECT IDENTIFIER */
  19110. /* INFO_SPUBKEYINFO_ALGOID_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  19111. /* parameters ANY defined by algorithm OPTIONAL */
  19112. /* INFO_SPUBKEYINFO_ALGOID_NULL */ { 4, ASN_TAG_NULL, 0, 0, 1 },
  19113. /* INFO_SPUBKEYINFO_ALGOID_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 1 },
  19114. /* INFO_SPUBKEYINFO_ALGOID_PARAMS */ { 4, ASN_SEQUENCE, 1, 0, 1 },
  19115. /* subjectPublicKey BIT STRING */
  19116. /* INFO_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  19117. /* attributes [0] Attributes */
  19118. /* INFO_ATTRS */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  19119. /* signatureAlgorithm AlgorithmIdentifier */
  19120. /* INFO_SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  19121. /* Algorithm OBJECT IDENTIFIER */
  19122. /* INFO_SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  19123. /* parameters ANY defined by algorithm OPTIONAL */
  19124. /* INFO_SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  19125. /* signature BIT STRING */
  19126. /* INFO_SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  19127. };
  19128. enum {
  19129. CERTREQASN_IDX_SEQ = 0,
  19130. CERTREQASN_IDX_INFO_SEQ,
  19131. CERTREQASN_IDX_INFO_VER,
  19132. CERTREQASN_IDX_INFO_SUBJ_SEQ,
  19133. CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ,
  19134. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_SEQ,
  19135. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID,
  19136. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_NULL,
  19137. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID,
  19138. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_PARAMS,
  19139. CERTREQASN_IDX_INFO_SPUBKEYINFO_PUBKEY,
  19140. CERTREQASN_IDX_INFO_ATTRS,
  19141. CERTREQASN_IDX_INFO_SIGALGO_SEQ,
  19142. CERTREQASN_IDX_INFO_SIGALGO_OID,
  19143. CERTREQASN_IDX_INFO_SIGALGO_NULL,
  19144. CERTREQASN_IDX_INFO_SIGNATURE
  19145. };
  19146. /* Number of items in ASN.1 template for a certificate request. */
  19147. #define certReqASN_Length (sizeof(certReqASN) / sizeof(ASNItem))
  19148. /* Parse BER encoded certificate request.
  19149. *
  19150. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  19151. *
  19152. * @param [in] cert Certificate request object.
  19153. * @param [out] criticalExt Critical extension return code.
  19154. * @return 0 on success.
  19155. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  19156. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19157. * is invalid.
  19158. * @return BUFFER_E when data in buffer is too small.
  19159. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  19160. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  19161. * non-zero length.
  19162. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  19163. * @return MEMORY_E on dynamic memory allocation failure.
  19164. */
  19165. static int DecodeCertReq(DecodedCert* cert, int* criticalExt)
  19166. {
  19167. DECL_ASNGETDATA(dataASN, certReqASN_Length);
  19168. int ret = 0;
  19169. byte version;
  19170. word32 idx;
  19171. CALLOC_ASNGETDATA(dataASN, certReqASN_Length, ret, cert->heap);
  19172. if (ret == 0) {
  19173. /* Default version is 0. */
  19174. version = 0;
  19175. /* Set version var and OID types to expect. */
  19176. GetASN_Int8Bit(&dataASN[CERTREQASN_IDX_INFO_VER], &version);
  19177. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
  19178. oidKeyType);
  19179. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
  19180. oidCurveType);
  19181. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
  19182. /* Parse a certificate request. */
  19183. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1,
  19184. cert->source, &cert->srcIdx, cert->maxIdx);
  19185. }
  19186. /* Check version is valid/supported - can't be negative. */
  19187. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  19188. WOLFSSL_MSG("Unexpected certificate request version");
  19189. ret = ASN_PARSE_E;
  19190. }
  19191. if (ret == 0) {
  19192. /* Set fields of certificate request. */
  19193. cert->version = version;
  19194. cert->signatureOID =
  19195. dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
  19196. cert->keyOID =
  19197. dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID].data.oid.sum;
  19198. cert->certBegin = dataASN[CERTREQASN_IDX_INFO_SEQ].offset;
  19199. /* Parse the subject name. */
  19200. idx = dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ].offset;
  19201. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  19202. cert->source, &idx,
  19203. dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset);
  19204. }
  19205. if (ret == 0) {
  19206. /* Parse the certificate request Attributes. */
  19207. ret = DecodeCertReqAttributes(cert, criticalExt,
  19208. GetASNItem_DataIdx(dataASN[CERTREQASN_IDX_INFO_ATTRS],
  19209. cert->source),
  19210. dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset);
  19211. }
  19212. if (ret == 0) {
  19213. /* Parse the certificate request's key. */
  19214. idx = dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset;
  19215. ret = GetCertKey(cert, cert->source, &idx,
  19216. dataASN[CERTREQASN_IDX_INFO_ATTRS].offset);
  19217. }
  19218. if (ret == 0) {
  19219. /* Store references to signature. */
  19220. cert->sigIndex = dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset;
  19221. GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE],
  19222. &cert->signature, &cert->sigLength);
  19223. }
  19224. FREE_ASNGETDATA(dataASN, cert->heap);
  19225. return ret;
  19226. }
  19227. #endif /* WOLFSSL_CERT_REQ */
  19228. #endif
  19229. int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  19230. {
  19231. int ret;
  19232. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  19233. defined(WOLFSSL_DYN_CERT)
  19234. char* ptr;
  19235. #endif
  19236. ret = ParseCertRelative(cert, type, verify, cm);
  19237. if (ret < 0)
  19238. return ret;
  19239. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  19240. defined(WOLFSSL_DYN_CERT)
  19241. /* cert->subjectCN not stored as copy of WOLFSSL_NO_MALLOC defined */
  19242. if (cert->subjectCNLen > 0) {
  19243. ptr = (char*)XMALLOC((size_t)cert->subjectCNLen + 1, cert->heap,
  19244. DYNAMIC_TYPE_SUBJECT_CN);
  19245. if (ptr == NULL)
  19246. return MEMORY_E;
  19247. XMEMCPY(ptr, cert->subjectCN, (size_t)cert->subjectCNLen);
  19248. ptr[cert->subjectCNLen] = '\0';
  19249. cert->subjectCN = ptr;
  19250. cert->subjectCNStored = 1;
  19251. }
  19252. #endif
  19253. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  19254. defined(WOLFSSL_DYN_CERT)
  19255. /* cert->publicKey not stored as copy if WOLFSSL_NO_MALLOC defined */
  19256. if ((cert->keyOID == RSAk
  19257. #ifdef WC_RSA_PSS
  19258. || cert->keyOID == RSAPSSk
  19259. #endif
  19260. ) && cert->publicKey != NULL && cert->pubKeySize > 0) {
  19261. ptr = (char*)XMALLOC(cert->pubKeySize, cert->heap,
  19262. DYNAMIC_TYPE_PUBLIC_KEY);
  19263. if (ptr == NULL)
  19264. return MEMORY_E;
  19265. XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
  19266. cert->publicKey = (byte *)ptr;
  19267. cert->pubKeyStored = 1;
  19268. }
  19269. #endif
  19270. return ret;
  19271. }
  19272. int wc_ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  19273. {
  19274. return ParseCert(cert, type, verify, cm);
  19275. }
  19276. #if !defined(OPENSSL_EXTRA) && !defined(OPENSSL_EXTRA_X509_SMALL) && \
  19277. !defined(GetCA)
  19278. /* from SSL proper, for locking can't do find here anymore.
  19279. * brought in from internal.h if built with compat layer.
  19280. * if defined(GetCA), it's a predefined macro and these prototypes
  19281. * would conflict.
  19282. */
  19283. #ifdef __cplusplus
  19284. extern "C" {
  19285. #endif
  19286. Signer* GetCA(void* signers, byte* hash);
  19287. #ifndef NO_SKID
  19288. Signer* GetCAByName(void* signers, byte* hash);
  19289. #endif
  19290. #ifdef __cplusplus
  19291. }
  19292. #endif
  19293. #endif /* !OPENSSL_EXTRA && !OPENSSL_EXTRA_X509_SMALL && !GetCA */
  19294. #if defined(WOLFCRYPT_ONLY)
  19295. /* dummy functions, not using wolfSSL so don't need actual ones */
  19296. Signer* GetCA(void* signers, byte* hash)
  19297. {
  19298. (void)hash;
  19299. return (Signer*)signers;
  19300. }
  19301. #ifndef NO_SKID
  19302. Signer* GetCAByName(void* signers, byte* hash)
  19303. {
  19304. (void)hash;
  19305. return (Signer*)signers;
  19306. }
  19307. #endif /* NO_SKID */
  19308. #endif /* WOLFCRYPT_ONLY */
  19309. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  19310. static Signer* GetCABySubjectAndPubKey(DecodedCert* cert, void* cm)
  19311. {
  19312. Signer* ca = NULL;
  19313. if (cert->extSubjKeyIdSet)
  19314. ca = GetCA(cm, cert->extSubjKeyId);
  19315. if (ca == NULL)
  19316. ca = GetCAByName(cm, cert->subjectHash);
  19317. if (ca) {
  19318. if ((ca->pubKeySize == cert->pubKeySize) &&
  19319. (XMEMCMP(ca->publicKey, cert->publicKey, ca->pubKeySize) == 0)) {
  19320. return ca;
  19321. }
  19322. }
  19323. return NULL;
  19324. }
  19325. #endif
  19326. #if defined(WOLFSSL_SMALL_CERT_VERIFY) || defined(OPENSSL_EXTRA)
  19327. #ifdef WOLFSSL_ASN_TEMPLATE
  19328. /* Get the Hash of the Authority Key Identifier from the list of extensions.
  19329. *
  19330. * @param [in] input Input data.
  19331. * @param [in] maxIdx Maximum index for data.
  19332. * @param [out] hash Hash of AKI.
  19333. * @param [out] set Whether the hash buffer was set.
  19334. * @param [in] heap Dynamic memory allocation hint.
  19335. * @return 0 on success.
  19336. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19337. * is invalid.
  19338. * @return MEMORY_E on dynamic memory allocation failure.
  19339. */
  19340. static int GetAKIHash(const byte* input, word32 maxIdx, byte* hash, int* set,
  19341. void* heap)
  19342. {
  19343. /* AKI and Certificate Extension ASN.1 templates are the same length. */
  19344. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  19345. int ret = 0;
  19346. word32 idx = 0;
  19347. word32 extEndIdx;
  19348. byte* extData;
  19349. word32 extDataSz;
  19350. byte critical;
  19351. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, heap);
  19352. (void)heap;
  19353. extEndIdx = idx + maxIdx;
  19354. /* Step through each extension looking for AKI. */
  19355. while ((ret == 0) && (idx < extEndIdx)) {
  19356. /* Clear dynamic data and check for certificate extension type OIDs. */
  19357. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  19358. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  19359. /* Set criticality variable. */
  19360. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  19361. /* Parse an extension. */
  19362. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  19363. &idx, extEndIdx);
  19364. if (ret == 0) {
  19365. /* Get reference to extension data and move index on past this
  19366. * extension. */
  19367. GetASN_GetRef(&dataASN[CERTEXTASN_IDX_VAL], &extData, &extDataSz);
  19368. idx += extDataSz;
  19369. /* Check whether we have the AKI extension. */
  19370. if (dataASN[CERTEXTASN_IDX_OID].data.oid.sum == AUTH_KEY_OID) {
  19371. /* Clear dynamic data. */
  19372. XMEMSET(dataASN, 0, sizeof(*dataASN) * authKeyIdASN_Length);
  19373. /* Start parsing extension data from the start. */
  19374. idx = 0;
  19375. /* Parse AKI extension data. */
  19376. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length,
  19377. 1, extData, &idx, extDataSz);
  19378. if ((ret == 0) &&
  19379. (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data
  19380. != NULL)) {
  19381. /* We parsed successfully and have data. */
  19382. *set = 1;
  19383. /* Get the hash or hash of the hash if wrong size. */
  19384. ret = GetHashId(
  19385. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  19386. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  19387. hash);
  19388. }
  19389. break;
  19390. }
  19391. }
  19392. }
  19393. FREE_ASNGETDATA(dataASN, heap);
  19394. return ret;
  19395. }
  19396. #endif
  19397. /* Only quick step through the certificate to find fields that are then used
  19398. * in certificate signature verification.
  19399. * Must use the signature OID from the signed part of the certificate.
  19400. * Works also on certificate signing requests.
  19401. *
  19402. * This is only for minimizing dynamic memory usage during TLS certificate
  19403. * chain processing.
  19404. * Doesn't support:
  19405. * OCSP Only: alt lookup using subject and pub key w/o sig check
  19406. */
  19407. static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap,
  19408. void* cm, const byte* pubKey, word32 pubKeySz, int pubKeyOID, int req)
  19409. {
  19410. #ifndef WOLFSSL_ASN_TEMPLATE
  19411. #ifndef WOLFSSL_SMALL_STACK
  19412. SignatureCtx sigCtx[1];
  19413. #else
  19414. SignatureCtx* sigCtx;
  19415. #endif
  19416. byte hash[KEYID_SIZE];
  19417. Signer* ca = NULL;
  19418. word32 idx = 0;
  19419. int len;
  19420. word32 tbsCertIdx = 0;
  19421. word32 sigIndex = 0;
  19422. word32 signatureOID = 0;
  19423. word32 oid = 0;
  19424. word32 issuerIdx = 0;
  19425. word32 issuerSz = 0;
  19426. #ifndef NO_SKID
  19427. int extLen = 0;
  19428. word32 extIdx = 0;
  19429. word32 extEndIdx = 0;
  19430. int extAuthKeyIdSet = 0;
  19431. #endif
  19432. int ret = 0;
  19433. word32 localIdx;
  19434. byte tag;
  19435. const byte* sigParams = NULL;
  19436. word32 sigParamsSz = 0;
  19437. if (cert == NULL) {
  19438. return BAD_FUNC_ARG;
  19439. }
  19440. #ifdef WOLFSSL_SMALL_STACK
  19441. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, DYNAMIC_TYPE_SIGNATURE);
  19442. if (sigCtx == NULL)
  19443. return MEMORY_E;
  19444. #endif
  19445. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  19446. /* Certificate SEQUENCE */
  19447. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19448. ret = ASN_PARSE_E;
  19449. if (ret == 0) {
  19450. tbsCertIdx = idx;
  19451. /* TBSCertificate SEQUENCE */
  19452. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19453. ret = ASN_PARSE_E;
  19454. }
  19455. if (ret == 0) {
  19456. sigIndex = len + idx;
  19457. if ((idx + 1) > certSz)
  19458. ret = BUFFER_E;
  19459. }
  19460. if (ret == 0) {
  19461. /* version - optional */
  19462. localIdx = idx;
  19463. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19464. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  19465. idx++;
  19466. if (GetLength(cert, &idx, &len, certSz) < 0)
  19467. ret = ASN_PARSE_E;
  19468. idx += len;
  19469. }
  19470. }
  19471. }
  19472. if (ret == 0) {
  19473. /* serialNumber */
  19474. if (GetASNHeader(cert, ASN_INTEGER, &idx, &len, certSz) < 0)
  19475. ret = ASN_PARSE_E;
  19476. }
  19477. if (ret == 0) {
  19478. idx += len;
  19479. /* signature */
  19480. if (!req) {
  19481. if (GetAlgoId(cert, &idx, &signatureOID, oidSigType, certSz) < 0)
  19482. ret = ASN_PARSE_E;
  19483. #ifdef WC_RSA_PSS
  19484. else if (signatureOID == CTC_RSASSAPSS) {
  19485. int start = idx;
  19486. sigParams = cert + idx;
  19487. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19488. ret = ASN_PARSE_E;
  19489. if (ret == 0) {
  19490. idx += len;
  19491. sigParamsSz = idx - start;
  19492. }
  19493. }
  19494. #endif
  19495. }
  19496. }
  19497. if (ret == 0) {
  19498. issuerIdx = idx;
  19499. /* issuer for cert or subject for csr */
  19500. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19501. ret = ASN_PARSE_E;
  19502. }
  19503. if (ret == 0) {
  19504. issuerSz = len + idx - issuerIdx;
  19505. }
  19506. #ifndef NO_SKID
  19507. if (!req && ret == 0) {
  19508. idx += len;
  19509. /* validity */
  19510. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19511. ret = ASN_PARSE_E;
  19512. }
  19513. if (!req && ret == 0) {
  19514. idx += len;
  19515. /* subject */
  19516. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19517. ret = ASN_PARSE_E;
  19518. }
  19519. if (ret == 0) {
  19520. idx += len;
  19521. /* subjectPublicKeyInfo */
  19522. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19523. ret = ASN_PARSE_E;
  19524. }
  19525. if (req && ret == 0) {
  19526. idx += len;
  19527. /* attributes */
  19528. if (GetASNHeader_ex(cert,
  19529. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &idx,
  19530. &len, certSz, 1) < 0)
  19531. ret = ASN_PARSE_E;
  19532. }
  19533. if (!req) {
  19534. if (ret == 0) {
  19535. idx += len;
  19536. if ((idx + 1) > certSz)
  19537. ret = BUFFER_E;
  19538. }
  19539. if (ret == 0) {
  19540. /* issuerUniqueID - optional */
  19541. localIdx = idx;
  19542. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19543. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) {
  19544. idx++;
  19545. if (GetLength(cert, &idx, &len, certSz) < 0)
  19546. ret = ASN_PARSE_E;
  19547. idx += len;
  19548. }
  19549. }
  19550. }
  19551. if (ret == 0) {
  19552. if ((idx + 1) > certSz)
  19553. ret = BUFFER_E;
  19554. }
  19555. if (ret == 0) {
  19556. /* subjectUniqueID - optional */
  19557. localIdx = idx;
  19558. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19559. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)) {
  19560. idx++;
  19561. if (GetLength(cert, &idx, &len, certSz) < 0)
  19562. ret = ASN_PARSE_E;
  19563. idx += len;
  19564. }
  19565. }
  19566. }
  19567. if (ret == 0) {
  19568. if ((idx + 1) > certSz)
  19569. ret = BUFFER_E;
  19570. }
  19571. /* extensions - optional */
  19572. localIdx = idx;
  19573. if (ret == 0 && GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  19574. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)) {
  19575. idx++;
  19576. if (GetLength(cert, &idx, &extLen, certSz) < 0)
  19577. ret = ASN_PARSE_E;
  19578. if (ret == 0) {
  19579. if (GetSequence(cert, &idx, &extLen, certSz) < 0)
  19580. ret = ASN_PARSE_E;
  19581. }
  19582. if (ret == 0) {
  19583. extEndIdx = idx + extLen;
  19584. /* Check each extension for the ones we want. */
  19585. while (ret == 0 && idx < extEndIdx) {
  19586. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19587. ret = ASN_PARSE_E;
  19588. if (ret == 0) {
  19589. extIdx = idx;
  19590. if (GetObjectId(cert, &extIdx, &oid, oidCertExtType,
  19591. certSz) < 0) {
  19592. ret = ASN_PARSE_E;
  19593. }
  19594. if (ret == 0) {
  19595. if ((extIdx + 1) > certSz)
  19596. ret = BUFFER_E;
  19597. }
  19598. }
  19599. if (ret == 0) {
  19600. localIdx = extIdx;
  19601. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  19602. tag == ASN_BOOLEAN) {
  19603. if (GetBoolean(cert, &extIdx, certSz) < 0)
  19604. ret = ASN_PARSE_E;
  19605. }
  19606. }
  19607. if (ret == 0) {
  19608. if (GetOctetString(cert, &extIdx, &extLen, certSz) < 0)
  19609. ret = ASN_PARSE_E;
  19610. }
  19611. if (ret == 0) {
  19612. switch (oid) {
  19613. case AUTH_KEY_OID:
  19614. if (GetSequence(cert, &extIdx, &extLen, certSz) < 0)
  19615. ret = ASN_PARSE_E;
  19616. if (ret == 0 && (extIdx + 1) >= certSz)
  19617. ret = BUFFER_E;
  19618. if (ret == 0 &&
  19619. GetASNTag(cert, &extIdx, &tag, certSz) == 0 &&
  19620. tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  19621. if (GetLength(cert, &extIdx, &extLen, certSz) <= 0)
  19622. ret = ASN_PARSE_E;
  19623. if (ret == 0) {
  19624. extAuthKeyIdSet = 1;
  19625. /* Get the hash or hash of the hash if wrong
  19626. * size. */
  19627. ret = GetHashId(cert + extIdx, extLen,
  19628. hash);
  19629. }
  19630. }
  19631. break;
  19632. default:
  19633. break;
  19634. }
  19635. }
  19636. idx += len;
  19637. }
  19638. }
  19639. }
  19640. }
  19641. else if (ret == 0) {
  19642. idx += len;
  19643. }
  19644. if (ret == 0 && pubKey == NULL) {
  19645. if (extAuthKeyIdSet)
  19646. ca = GetCA(cm, hash);
  19647. if (ca == NULL) {
  19648. ret = CalcHashId(cert + issuerIdx, issuerSz, hash);
  19649. if (ret == 0)
  19650. ca = GetCAByName(cm, hash);
  19651. }
  19652. }
  19653. #else
  19654. if (ret == 0 && pubKey == NULL) {
  19655. ret = CalcHashId(cert + issuerIdx, issuerSz, hash);
  19656. if (ret == 0)
  19657. ca = GetCA(cm, hash);
  19658. }
  19659. #endif /* !NO_SKID */
  19660. if (ca == NULL && pubKey == NULL)
  19661. ret = ASN_NO_SIGNER_E;
  19662. if (ret == 0) {
  19663. idx = sigIndex;
  19664. /* signatureAlgorithm */
  19665. if (GetAlgoId(cert, &idx, &oid, oidSigType, certSz) < 0)
  19666. ret = ASN_PARSE_E;
  19667. #ifdef WC_RSA_PSS
  19668. else if (signatureOID == CTC_RSASSAPSS) {
  19669. word32 sz = idx;
  19670. const byte* params = cert + idx;
  19671. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19672. ret = ASN_PARSE_E;
  19673. if (ret == 0) {
  19674. idx += len;
  19675. sz = idx - sz;
  19676. if (req) {
  19677. if ((sz != sigParamsSz) ||
  19678. (XMEMCMP(sigParams, params, sz) != 0)) {
  19679. ret = ASN_PARSE_E;
  19680. }
  19681. }
  19682. else {
  19683. sigParams = params;
  19684. sigParamsSz = sz;
  19685. }
  19686. }
  19687. }
  19688. #endif
  19689. /* In CSR signature data is not present in body */
  19690. if (req)
  19691. signatureOID = oid;
  19692. }
  19693. if (ret == 0) {
  19694. if (oid != signatureOID)
  19695. ret = ASN_SIG_OID_E;
  19696. }
  19697. if (ret == 0) {
  19698. /* signatureValue */
  19699. if (CheckBitString(cert, &idx, &len, certSz, 1, NULL) < 0)
  19700. ret = ASN_PARSE_E;
  19701. }
  19702. if (ret == 0) {
  19703. if (pubKey != NULL) {
  19704. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  19705. sigIndex - tbsCertIdx, pubKey, pubKeySz, pubKeyOID,
  19706. cert + idx, len, signatureOID, sigParams, sigParamsSz, NULL);
  19707. }
  19708. else {
  19709. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  19710. sigIndex - tbsCertIdx, ca->publicKey, ca->pubKeySize,
  19711. ca->keyOID, cert + idx, len, signatureOID, sigParams,
  19712. sigParamsSz, NULL);
  19713. }
  19714. if (ret != 0) {
  19715. WOLFSSL_ERROR_VERBOSE(ret);
  19716. WOLFSSL_MSG("Confirm signature failed");
  19717. }
  19718. }
  19719. FreeSignatureCtx(sigCtx);
  19720. #ifdef WOLFSSL_SMALL_STACK
  19721. if (sigCtx != NULL)
  19722. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  19723. #endif
  19724. return ret;
  19725. #else /* WOLFSSL_ASN_TEMPLATE */
  19726. /* X509 ASN.1 template longer than Certificate Request template. */
  19727. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  19728. #ifndef WOLFSSL_SMALL_STACK
  19729. SignatureCtx sigCtx[1];
  19730. #else
  19731. SignatureCtx* sigCtx = NULL;
  19732. #endif
  19733. byte hash[KEYID_SIZE];
  19734. Signer* ca = NULL;
  19735. int ret = 0;
  19736. word32 idx = 0;
  19737. #ifndef NO_SKID
  19738. int extAuthKeyIdSet = 0;
  19739. #endif
  19740. const byte* tbs = NULL;
  19741. word32 tbsSz = 0;
  19742. #ifdef WC_RSA_PSS
  19743. const byte* tbsParams = NULL;
  19744. word32 tbsParamsSz = 0;
  19745. #endif
  19746. const byte* sig = NULL;
  19747. word32 sigSz = 0;
  19748. word32 sigOID = 0;
  19749. const byte* sigParams = NULL;
  19750. word32 sigParamsSz = 0;
  19751. const byte* caName = NULL;
  19752. word32 caNameLen = 0;
  19753. #ifndef NO_SKID
  19754. const byte* akiData = NULL;
  19755. word32 akiLen = 0;
  19756. #endif
  19757. (void)req;
  19758. (void)heap;
  19759. if (cert == NULL) {
  19760. ret = BAD_FUNC_ARG;
  19761. }
  19762. ALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, heap);
  19763. if ((ret == 0) && (!req)) {
  19764. /* Clear dynamic data for certificate items. */
  19765. XMEMSET(dataASN, 0, sizeof(ASNGetData) * x509CertASN_Length);
  19766. /* Set OID types expected for signature and public key. */
  19767. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
  19768. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
  19769. oidKeyType);
  19770. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
  19771. oidCurveType);
  19772. GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
  19773. /* Parse certificate. */
  19774. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1, cert,
  19775. &idx, certSz);
  19776. /* Check signature OIDs match. */
  19777. if ((ret == 0) && dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum
  19778. != dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum) {
  19779. ret = ASN_SIG_OID_E;
  19780. }
  19781. /* Store the data for verification in the certificate. */
  19782. if (ret == 0) {
  19783. tbs = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
  19784. tbsSz = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
  19785. caName = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  19786. cert);
  19787. caNameLen = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  19788. cert);
  19789. sigOID = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
  19790. #ifdef WC_RSA_PSS
  19791. if (dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].tag != 0) {
  19792. tbsParams =
  19793. GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  19794. cert);
  19795. tbsParamsSz =
  19796. GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  19797. cert);
  19798. }
  19799. if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
  19800. sigParams =
  19801. GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19802. cert);
  19803. sigParamsSz =
  19804. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19805. cert);
  19806. }
  19807. #endif
  19808. GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE], &sig, &sigSz);
  19809. #ifdef WC_RSA_PSS
  19810. if (tbsParamsSz != sigParamsSz) {
  19811. ret = ASN_PARSE_E;
  19812. }
  19813. else if ((tbsParamsSz > 0) && (sigOID != CTC_RSASSAPSS)) {
  19814. ret = ASN_PARSE_E;
  19815. }
  19816. else if ((tbsParamsSz > 0) &&
  19817. (XMEMCMP(tbsParams, sigParams, tbsParamsSz) != 0)) {
  19818. ret = ASN_PARSE_E;
  19819. }
  19820. #endif
  19821. }
  19822. }
  19823. else if (ret == 0) {
  19824. #ifndef WOLFSSL_CERT_REQ
  19825. ret = NOT_COMPILED_IN;
  19826. #else
  19827. /* Clear dynamic data for certificate request items. */
  19828. XMEMSET(dataASN, 0, sizeof(ASNGetData) * certReqASN_Length);
  19829. /* Set OID types expected for signature and public key. */
  19830. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
  19831. oidKeyType);
  19832. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
  19833. oidCurveType);
  19834. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
  19835. /* Parse certificate request. */
  19836. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1, cert,
  19837. &idx, certSz);
  19838. if (ret == 0) {
  19839. /* Store the data for verification in the certificate. */
  19840. tbs = GetASNItem_Addr(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
  19841. tbsSz = GetASNItem_Length(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
  19842. caName = GetASNItem_Addr(
  19843. dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
  19844. caNameLen = GetASNItem_Length(
  19845. dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
  19846. sigOID = dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
  19847. #ifdef WC_RSA_PSS
  19848. sigParams = GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19849. cert);
  19850. sigParamsSz =
  19851. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19852. cert);
  19853. #endif
  19854. GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE], &sig,
  19855. &sigSz);
  19856. }
  19857. #endif
  19858. }
  19859. #ifndef NO_SKID
  19860. if ((ret == 0) && (pubKey == NULL) && !req) {
  19861. akiData = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data;
  19862. akiLen = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.length;
  19863. }
  19864. #endif
  19865. FREE_ASNGETDATA(dataASN, heap);
  19866. /* If no public passed, then find the CA. */
  19867. if ((ret == 0) && (pubKey == NULL)) {
  19868. #ifndef NO_SKID
  19869. /* Find the AKI extension in list of extensions and get hash. */
  19870. if ((!req) && (akiData != NULL)) {
  19871. /* TODO: test case */
  19872. ret = GetAKIHash(akiData, akiLen, hash, &extAuthKeyIdSet, heap);
  19873. }
  19874. /* Get the CA by hash one was found. */
  19875. if (extAuthKeyIdSet) {
  19876. ca = GetCA(cm, hash);
  19877. }
  19878. if (ca == NULL)
  19879. #endif
  19880. {
  19881. /* Try hash of issuer name. */
  19882. ret = CalcHashId(caName, caNameLen, hash);
  19883. if (ret == 0) {
  19884. ca = GetCAByName(cm, hash);
  19885. }
  19886. }
  19887. if (ca != NULL) {
  19888. /* Extract public key information. */
  19889. pubKey = ca->publicKey;
  19890. pubKeySz = ca->pubKeySize;
  19891. pubKeyOID = ca->keyOID;
  19892. }
  19893. else {
  19894. /* No public key to verify with. */
  19895. ret = ASN_NO_SIGNER_E;
  19896. }
  19897. }
  19898. if (ret == 0) {
  19899. #ifdef WOLFSSL_SMALL_STACK
  19900. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap,
  19901. DYNAMIC_TYPE_SIGNATURE);
  19902. if (sigCtx == NULL) {
  19903. ret = MEMORY_E;
  19904. }
  19905. if (ret == 0)
  19906. #endif
  19907. {
  19908. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  19909. /* Check signature. */
  19910. ret = ConfirmSignature(sigCtx, tbs, tbsSz, pubKey, pubKeySz,
  19911. pubKeyOID, sig, sigSz, sigOID, sigParams, sigParamsSz, NULL);
  19912. if (ret != 0) {
  19913. WOLFSSL_MSG("Confirm signature failed");
  19914. }
  19915. FreeSignatureCtx(sigCtx);
  19916. #ifdef WOLFSSL_SMALL_STACK
  19917. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  19918. #endif
  19919. }
  19920. }
  19921. return ret;
  19922. #endif /* WOLFSSL_ASN_TEMPLATE */
  19923. }
  19924. #ifdef OPENSSL_EXTRA
  19925. /* Call CheckCertSignature_ex using a public key buffer for verification
  19926. */
  19927. int CheckCertSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  19928. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  19929. {
  19930. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  19931. pubKey, pubKeySz, pubKeyOID, 0);
  19932. }
  19933. int wc_CheckCertSigPubKey(const byte* cert, word32 certSz, void* heap,
  19934. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  19935. {
  19936. return CheckCertSignaturePubKey(cert, certSz, heap, pubKey, pubKeySz,
  19937. pubKeyOID);
  19938. }
  19939. #ifdef WOLFSSL_CERT_REQ
  19940. int CheckCSRSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  19941. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  19942. {
  19943. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  19944. pubKey, pubKeySz, pubKeyOID, 1);
  19945. }
  19946. #endif /* WOLFSSL_CERT_REQ */
  19947. #endif /* OPENSSL_EXTRA */
  19948. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  19949. /* Call CheckCertSignature_ex using a certificate manager (cm)
  19950. */
  19951. int CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm)
  19952. {
  19953. return CheckCertSignature_ex(cert, certSz, heap, cm, NULL, 0, 0, 0);
  19954. }
  19955. #endif /* WOLFSSL_SMALL_CERT_VERIFY */
  19956. #endif /* WOLFSSL_SMALL_CERT_VERIFY || OPENSSL_EXTRA */
  19957. #if (defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) || \
  19958. (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)))
  19959. /* ASN.1 DER decode instruction. */
  19960. typedef struct DecodeInstr {
  19961. /* Tag expected. */
  19962. byte tag;
  19963. /* Operation to perform: step in or go over */
  19964. byte op:1;
  19965. /* ASN.1 item is optional. */
  19966. byte optional:1;
  19967. } DecodeInstr;
  19968. /* Step into ASN.1 item. */
  19969. #define DECODE_INSTR_IN 0
  19970. /* Step over ASN.1 item. */
  19971. #define DECODE_INSTR_OVER 1
  19972. /* Get the public key data from the DER encoded X.509 certificate.
  19973. *
  19974. * Assumes data has previously been parsed for complete validity.
  19975. *
  19976. * @param [in] cert DER encoded X.509 certificate data.
  19977. * @param [in] certSz Length of DER encoding.
  19978. * @param [out] pubKey Public key data. (From the BIT_STRING.)
  19979. * @param [out] pubKeySz Length of public key data in bytes.
  19980. * @return 0 on success.
  19981. * @return BAD_FUNC_ARG when cert, pubKey or pubKeySz is NULL.
  19982. * @return ASN_PARSE_E when certificate encoding is invalid.
  19983. */
  19984. int wc_CertGetPubKey(const byte* cert, word32 certSz,
  19985. const unsigned char** pubKey, word32* pubKeySz)
  19986. {
  19987. int ret = 0;
  19988. int l;
  19989. word32 o = 0;
  19990. int i;
  19991. static DecodeInstr ops[] = {
  19992. /* Outer SEQ */
  19993. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  19994. /* TBSCertificate: SEQ */
  19995. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  19996. /* Version: [0] */
  19997. { ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_X509_CERT_VERSION,
  19998. DECODE_INSTR_OVER, 1 },
  19999. /* CertificateSerialNumber: INT */
  20000. { ASN_INTEGER, DECODE_INSTR_OVER, 0 },
  20001. /* AlgorithmIdentifier: SEQ */
  20002. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20003. /* issuer: SEQ */
  20004. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20005. /* Validity: SEQ */
  20006. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20007. /* subject: SEQ */
  20008. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20009. /* subjectPublicKeyInfo SEQ */
  20010. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  20011. /* AlgorithmIdentifier: SEQ */
  20012. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20013. /* PublicKey: BIT_STRING */
  20014. { ASN_BIT_STRING, DECODE_INSTR_IN , 0 },
  20015. };
  20016. /* Validate parameters. */
  20017. if ((cert == NULL) || (pubKey == NULL) || (pubKeySz == NULL)) {
  20018. ret = BAD_FUNC_ARG;
  20019. }
  20020. /* Process each instruction to take us to public key data. */
  20021. for (i = 0; (ret == 0) && (i < (int)(sizeof(ops) / sizeof(*ops))); i++) {
  20022. DecodeInstr op = ops[i];
  20023. /* Check the current ASN.1 item has the expected tag. */
  20024. if (cert[o] != op.tag) {
  20025. /* If not optional then error, otherwise skip op. */
  20026. if (!op.optional) {
  20027. ret = ASN_PARSE_E;
  20028. }
  20029. }
  20030. else {
  20031. /* Move past tag. */
  20032. o++;
  20033. /* Get the length of ASN.1 item and move past length encoding. */
  20034. if (GetLength(cert, &o, &l, certSz) < 0) {
  20035. ret = ASN_PARSE_E;
  20036. }
  20037. /* Skip data if required. */
  20038. else if (op.op == DECODE_INSTR_OVER) {
  20039. o += l;
  20040. }
  20041. }
  20042. }
  20043. if (ret == 0) {
  20044. /* Return the public key data and length.
  20045. * Skip first byte of BIT_STRING data: unused bits. */
  20046. *pubKey = cert + o + 1;
  20047. *pubKeySz = l - 1;
  20048. }
  20049. return ret;
  20050. }
  20051. #endif
  20052. int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
  20053. {
  20054. int ret = 0;
  20055. #ifndef WOLFSSL_ASN_TEMPLATE
  20056. word32 confirmOID = 0;
  20057. #ifdef WOLFSSL_CERT_REQ
  20058. int len = 0;
  20059. #endif
  20060. #endif
  20061. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  20062. int idx = 0;
  20063. #endif
  20064. byte* sce_tsip_encRsaKeyIdx;
  20065. if (cert == NULL) {
  20066. return BAD_FUNC_ARG;
  20067. }
  20068. #ifdef WOLFSSL_CERT_REQ
  20069. if (type == CERTREQ_TYPE)
  20070. cert->isCSR = 1;
  20071. #endif
  20072. if (cert->sigCtx.state == SIG_STATE_BEGIN) {
  20073. #ifndef WOLFSSL_ASN_TEMPLATE
  20074. cert->badDate = 0;
  20075. cert->criticalExt = 0;
  20076. if ((ret = DecodeToKey(cert, verify)) < 0) {
  20077. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
  20078. cert->badDate = ret;
  20079. if (verify == VERIFY_SKIP_DATE)
  20080. ret = 0;
  20081. }
  20082. else
  20083. return ret;
  20084. }
  20085. WOLFSSL_MSG("Parsed Past Key");
  20086. #ifdef WOLFSSL_CERT_REQ
  20087. /* Read attributes */
  20088. if (cert->isCSR) {
  20089. if (GetASNHeader_ex(cert->source,
  20090. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &cert->srcIdx,
  20091. &len, cert->maxIdx, 1) < 0) {
  20092. WOLFSSL_MSG("GetASNHeader_ex error");
  20093. return ASN_PARSE_E;
  20094. }
  20095. if (len) {
  20096. word32 attrMaxIdx = cert->srcIdx + (word32)len;
  20097. word32 oid;
  20098. byte tag;
  20099. if (attrMaxIdx > cert->maxIdx) {
  20100. WOLFSSL_MSG("Attribute length greater than CSR length");
  20101. return ASN_PARSE_E;
  20102. }
  20103. while (cert->srcIdx < attrMaxIdx) {
  20104. /* Attributes have the structure:
  20105. * SEQ -> OID -> SET -> ATTRIBUTE */
  20106. if (GetSequence(cert->source, &cert->srcIdx, &len,
  20107. attrMaxIdx) < 0) {
  20108. WOLFSSL_MSG("attr GetSequence error");
  20109. return ASN_PARSE_E;
  20110. }
  20111. if (GetObjectId(cert->source, &cert->srcIdx, &oid,
  20112. oidCsrAttrType, attrMaxIdx) < 0) {
  20113. WOLFSSL_MSG("attr GetObjectId error");
  20114. return ASN_PARSE_E;
  20115. }
  20116. if (GetSet(cert->source, &cert->srcIdx, &len,
  20117. attrMaxIdx) < 0) {
  20118. WOLFSSL_MSG("attr GetSet error");
  20119. return ASN_PARSE_E;
  20120. }
  20121. switch (oid) {
  20122. case PKCS9_CONTENT_TYPE_OID:
  20123. if (GetHeader(cert->source, &tag,
  20124. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20125. WOLFSSL_MSG("attr GetHeader error");
  20126. return ASN_PARSE_E;
  20127. }
  20128. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  20129. tag != ASN_IA5_STRING) {
  20130. WOLFSSL_MSG("Unsupported attribute value format");
  20131. return ASN_PARSE_E;
  20132. }
  20133. cert->contentType = (char*)cert->source + cert->srcIdx;
  20134. cert->contentTypeLen = len;
  20135. cert->srcIdx += (word32)len;
  20136. break;
  20137. case CHALLENGE_PASSWORD_OID:
  20138. if (GetHeader(cert->source, &tag,
  20139. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20140. WOLFSSL_MSG("attr GetHeader error");
  20141. return ASN_PARSE_E;
  20142. }
  20143. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  20144. tag != ASN_IA5_STRING) {
  20145. WOLFSSL_MSG("Unsupported attribute value format");
  20146. return ASN_PARSE_E;
  20147. }
  20148. cert->cPwd = (char*)cert->source + cert->srcIdx;
  20149. cert->cPwdLen = len;
  20150. cert->srcIdx += (word32)len;
  20151. break;
  20152. case SERIAL_NUMBER_OID:
  20153. if (GetHeader(cert->source, &tag,
  20154. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20155. WOLFSSL_MSG("attr GetHeader error");
  20156. return ASN_PARSE_E;
  20157. }
  20158. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  20159. tag != ASN_IA5_STRING) {
  20160. WOLFSSL_MSG("Unsupported attribute value format");
  20161. return ASN_PARSE_E;
  20162. }
  20163. cert->sNum = (char*)cert->source + cert->srcIdx;
  20164. cert->sNumLen = len;
  20165. cert->srcIdx += (word32)len;
  20166. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  20167. XMEMCPY(cert->serial, cert->sNum,
  20168. (size_t)cert->sNumLen);
  20169. cert->serialSz = cert->sNumLen;
  20170. }
  20171. break;
  20172. case DNQUALIFIER_OID:
  20173. if (GetHeader(cert->source, &tag,
  20174. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20175. WOLFSSL_MSG("attr GetHeader error");
  20176. return ASN_PARSE_E;
  20177. }
  20178. cert->dnQualifier = (char*)cert->source + cert->srcIdx;
  20179. cert->dnQualifierLen = len;
  20180. cert->srcIdx += (word32)len;
  20181. break;
  20182. case INITIALS_OID:
  20183. if (GetHeader(cert->source, &tag,
  20184. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20185. WOLFSSL_MSG("attr GetHeader error");
  20186. return ASN_PARSE_E;
  20187. }
  20188. cert->initials = (char*)cert->source + cert->srcIdx;
  20189. cert->initialsLen = len;
  20190. cert->srcIdx += (word32)len;
  20191. break;
  20192. case SURNAME_OID:
  20193. if (GetHeader(cert->source, &tag,
  20194. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20195. WOLFSSL_MSG("attr GetHeader error");
  20196. return ASN_PARSE_E;
  20197. }
  20198. cert->surname = (char*)cert->source + cert->srcIdx;
  20199. cert->surnameLen = len;
  20200. cert->srcIdx += (word32)len;
  20201. break;
  20202. case GIVEN_NAME_OID:
  20203. if (GetHeader(cert->source, &tag,
  20204. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20205. WOLFSSL_MSG("attr GetHeader error");
  20206. return ASN_PARSE_E;
  20207. }
  20208. cert->givenName = (char*)cert->source + cert->srcIdx;
  20209. cert->givenNameLen = len;
  20210. cert->srcIdx += (word32)len;
  20211. break;
  20212. case UNSTRUCTURED_NAME_OID:
  20213. if (GetHeader(cert->source, &tag,
  20214. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20215. WOLFSSL_MSG("attr GetHeader error");
  20216. return ASN_PARSE_E;
  20217. }
  20218. cert->unstructuredName =
  20219. (char*)cert->source + cert->srcIdx;
  20220. cert->unstructuredNameLen = len;
  20221. cert->srcIdx += (word32)len;
  20222. break;
  20223. case EXTENSION_REQUEST_OID:
  20224. /* save extensions */
  20225. cert->extensions = &cert->source[cert->srcIdx];
  20226. cert->extensionsSz = len;
  20227. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  20228. if ((ret = DecodeCertExtensions(cert)) < 0) {
  20229. if (ret == ASN_CRIT_EXT_E) {
  20230. cert->criticalExt = ret;
  20231. }
  20232. else {
  20233. return ret;
  20234. }
  20235. }
  20236. cert->srcIdx += (word32)len;
  20237. break;
  20238. default:
  20239. WOLFSSL_MSG("Unsupported attribute type");
  20240. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  20241. return ASN_PARSE_E;
  20242. }
  20243. }
  20244. }
  20245. }
  20246. #endif
  20247. if (cert->srcIdx < cert->sigIndex) {
  20248. #ifndef ALLOW_V1_EXTENSIONS
  20249. if (cert->version < 2) {
  20250. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  20251. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  20252. return ASN_VERSION_E;
  20253. }
  20254. #endif
  20255. /* save extensions */
  20256. cert->extensions = &cert->source[cert->srcIdx];
  20257. cert->extensionsSz = (int)(cert->sigIndex - cert->srcIdx);
  20258. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  20259. if ((ret = DecodeCertExtensions(cert)) < 0) {
  20260. if (ret == ASN_CRIT_EXT_E)
  20261. cert->criticalExt = ret;
  20262. else
  20263. return ret;
  20264. }
  20265. #ifdef HAVE_OCSP
  20266. if (verify == VERIFY_OCSP_CERT) {
  20267. /* trust for the lifetime of the responder's cert*/
  20268. if (cert->ocspNoCheckSet)
  20269. verify = VERIFY;
  20270. else
  20271. verify = VERIFY_OCSP;
  20272. }
  20273. #endif
  20274. /* advance past extensions */
  20275. cert->srcIdx = cert->sigIndex;
  20276. }
  20277. if ((ret = GetSigAlg(cert,
  20278. #ifdef WOLFSSL_CERT_REQ
  20279. !cert->isCSR ? &confirmOID : &cert->signatureOID,
  20280. #else
  20281. &confirmOID,
  20282. #endif
  20283. cert->maxIdx)) < 0) {
  20284. return ret;
  20285. }
  20286. if ((ret = GetSignature(cert)) < 0) {
  20287. return ret;
  20288. }
  20289. if (confirmOID != cert->signatureOID
  20290. #ifdef WOLFSSL_CERT_REQ
  20291. && !cert->isCSR
  20292. #endif
  20293. ) {
  20294. WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
  20295. return ASN_SIG_OID_E;
  20296. }
  20297. #else
  20298. #ifdef WOLFSSL_CERT_REQ
  20299. if (cert->isCSR) {
  20300. ret = DecodeCertReq(cert, &cert->criticalExt);
  20301. if (ret < 0) {
  20302. return ret;
  20303. }
  20304. }
  20305. else
  20306. #endif
  20307. {
  20308. ret = DecodeCert(cert, verify, &cert->criticalExt);
  20309. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
  20310. cert->badDate = ret;
  20311. if (verify == VERIFY_SKIP_DATE)
  20312. ret = 0;
  20313. }
  20314. else if (ret < 0) {
  20315. WOLFSSL_ERROR_VERBOSE(ret);
  20316. return ret;
  20317. }
  20318. }
  20319. #endif
  20320. #ifndef NO_SKID
  20321. if (cert->extSubjKeyIdSet == 0 && cert->publicKey != NULL &&
  20322. cert->pubKeySize > 0) {
  20323. ret = CalcHashId(cert->publicKey, cert->pubKeySize,
  20324. cert->extSubjKeyId);
  20325. if (ret != 0) {
  20326. WOLFSSL_ERROR_VERBOSE(ret);
  20327. return ret;
  20328. }
  20329. }
  20330. #endif /* !NO_SKID */
  20331. if (!cert->selfSigned || (verify != NO_VERIFY && type != CA_TYPE &&
  20332. type != TRUSTED_PEER_TYPE)) {
  20333. cert->ca = NULL;
  20334. #ifndef NO_SKID
  20335. if (cert->extAuthKeyIdSet) {
  20336. cert->ca = GetCA(cm, cert->extAuthKeyId);
  20337. }
  20338. if (cert->ca == NULL && cert->extSubjKeyIdSet
  20339. && verify != VERIFY_OCSP) {
  20340. cert->ca = GetCA(cm, cert->extSubjKeyId);
  20341. }
  20342. if (cert->ca != NULL && XMEMCMP(cert->issuerHash,
  20343. cert->ca->subjectNameHash, KEYID_SIZE) != 0) {
  20344. cert->ca = NULL;
  20345. }
  20346. if (cert->ca == NULL) {
  20347. cert->ca = GetCAByName(cm, cert->issuerHash);
  20348. /* If AKID is available then this CA doesn't have the public
  20349. * key required */
  20350. if (cert->ca && cert->extAuthKeyIdSet) {
  20351. WOLFSSL_MSG("CA SKID doesn't match AKID");
  20352. cert->ca = NULL;
  20353. }
  20354. }
  20355. /* OCSP Only: alt lookup using subject and pub key w/o sig check */
  20356. #ifdef WOLFSSL_NO_TRUSTED_CERTS_VERIFY
  20357. if (cert->ca == NULL && verify == VERIFY_OCSP) {
  20358. cert->ca = GetCABySubjectAndPubKey(cert, cm);
  20359. if (cert->ca) {
  20360. ret = 0; /* success */
  20361. goto exit_pcr;
  20362. }
  20363. }
  20364. #endif /* WOLFSSL_NO_TRUSTED_CERTS_VERIFY */
  20365. #else
  20366. cert->ca = GetCA(cm, cert->issuerHash);
  20367. #endif /* !NO_SKID */
  20368. if (cert->ca) {
  20369. WOLFSSL_MSG("CA found");
  20370. }
  20371. }
  20372. if (cert->selfSigned) {
  20373. cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
  20374. } else {
  20375. /* RFC 5280 Section 4.2.1.9:
  20376. *
  20377. * load/receive check
  20378. *
  20379. * 1) Is CA boolean set?
  20380. * No - SKIP CHECK
  20381. * Yes - Check key usage
  20382. * 2) Is Key usage extension present?
  20383. * No - goto 3
  20384. * Yes - check keyCertSign assertion
  20385. * 2.a) Is keyCertSign asserted?
  20386. * No - goto 4
  20387. * Yes - goto 3
  20388. * 3) Is pathLen set?
  20389. * No - goto 4
  20390. * Yes - check pathLen against maxPathLen.
  20391. * 3.a) Is pathLen less than maxPathLen?
  20392. * No - goto 4
  20393. * Yes - set maxPathLen to pathLen and EXIT
  20394. * 4) Is maxPathLen > 0?
  20395. * Yes - Reduce by 1
  20396. * No - ERROR
  20397. */
  20398. if (cert->ca && cert->pathLengthSet) {
  20399. int checkPathLen = 0;
  20400. int decrementMaxPathLen = 0;
  20401. cert->maxPathLen = cert->pathLength;
  20402. if (cert->isCA) {
  20403. WOLFSSL_MSG("\tCA boolean set");
  20404. if (cert->extKeyUsageSet) {
  20405. WOLFSSL_MSG("\tExtension Key Usage Set");
  20406. if ((cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) != 0) {
  20407. checkPathLen = 1;
  20408. }
  20409. else {
  20410. decrementMaxPathLen = 1;
  20411. }
  20412. }
  20413. else {
  20414. checkPathLen = 1;
  20415. } /* !cert->ca check */
  20416. } /* cert is not a CA (assuming entity cert) */
  20417. if (checkPathLen && cert->pathLengthSet) {
  20418. if (cert->pathLength < cert->ca->maxPathLen) {
  20419. WOLFSSL_MSG("\tmaxPathLen status: set to pathLength");
  20420. cert->maxPathLen = cert->pathLength;
  20421. }
  20422. else {
  20423. decrementMaxPathLen = 1;
  20424. }
  20425. }
  20426. if (decrementMaxPathLen && cert->ca->maxPathLen > 0) {
  20427. WOLFSSL_MSG("\tmaxPathLen status: reduce by 1");
  20428. cert->maxPathLen = (byte)(cert->ca->maxPathLen - 1);
  20429. if (verify != NO_VERIFY && type != CA_TYPE &&
  20430. type != TRUSTED_PEER_TYPE) {
  20431. WOLFSSL_MSG("\tmaxPathLen status: OK");
  20432. }
  20433. } else if (decrementMaxPathLen && cert->ca->maxPathLen == 0) {
  20434. cert->maxPathLen = 0;
  20435. if (verify != NO_VERIFY && type != CA_TYPE &&
  20436. type != TRUSTED_PEER_TYPE) {
  20437. WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
  20438. WOLFSSL_MSG("\tmaxPathLen status: ERROR");
  20439. WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_INV_E);
  20440. return ASN_PATHLEN_INV_E;
  20441. }
  20442. }
  20443. } else if (cert->ca && cert->isCA) {
  20444. /* case where cert->pathLength extension is not set */
  20445. if (cert->ca->maxPathLen > 0) {
  20446. cert->maxPathLen = (byte)(cert->ca->maxPathLen - 1);
  20447. } else {
  20448. cert->maxPathLen = 0;
  20449. if (verify != NO_VERIFY && type != CA_TYPE &&
  20450. type != TRUSTED_PEER_TYPE) {
  20451. WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
  20452. WOLFSSL_MSG("\tmaxPathLen status: ERROR");
  20453. WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_INV_E);
  20454. return ASN_PATHLEN_INV_E;
  20455. }
  20456. }
  20457. }
  20458. }
  20459. #ifdef HAVE_OCSP
  20460. if (verify != NO_VERIFY && type != CA_TYPE &&
  20461. type != TRUSTED_PEER_TYPE) {
  20462. if (cert->ca) {
  20463. /* Need the CA's public key hash for OCSP */
  20464. XMEMCPY(cert->issuerKeyHash, cert->ca->subjectKeyHash,
  20465. KEYID_SIZE);
  20466. }
  20467. }
  20468. #endif /* HAVE_OCSP */
  20469. }
  20470. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  20471. /* prepare for TSIP TLS cert verification API use */
  20472. if (cert->keyOID == RSAk) {
  20473. /* to call TSIP API, it needs keys position info in bytes */
  20474. if ((ret = RsaPublicKeyDecodeRawIndex(cert->publicKey, (word32*)&idx,
  20475. cert->pubKeySize,
  20476. &cert->sigCtx.CertAtt.pubkey_n_start,
  20477. &cert->sigCtx.CertAtt.pubkey_n_len,
  20478. &cert->sigCtx.CertAtt.pubkey_e_start,
  20479. &cert->sigCtx.CertAtt.pubkey_e_len)) != 0) {
  20480. WOLFSSL_MSG("Decoding index from cert failed.");
  20481. return ret;
  20482. }
  20483. cert->sigCtx.CertAtt.certBegin = cert->certBegin;
  20484. } else if (cert->keyOID == ECDSAk) {
  20485. cert->sigCtx.CertAtt.certBegin = cert->certBegin;
  20486. }
  20487. /* check if we can use TSIP for cert verification */
  20488. /* if the ca is verified as tsip root ca. */
  20489. /* TSIP can only handle 2048 bits(256 byte) key. */
  20490. if (cert->ca && Renesas_cmn_checkCA(cert->ca->cm_idx) != 0 &&
  20491. (cert->sigCtx.CertAtt.pubkey_n_len == 256 ||
  20492. cert->sigCtx.CertAtt.curve_id == ECC_SECP256R1)) {
  20493. /* assign memory to encrypted tsip Rsa key index */
  20494. if (!cert->sce_tsip_encRsaKeyIdx)
  20495. cert->sce_tsip_encRsaKeyIdx =
  20496. (byte*)XMALLOC(TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY,
  20497. cert->heap, DYNAMIC_TYPE_RSA);
  20498. if (cert->sce_tsip_encRsaKeyIdx == NULL)
  20499. return MEMORY_E;
  20500. }
  20501. else {
  20502. if (cert->ca) {
  20503. /* TSIP isn't usable */
  20504. if (Renesas_cmn_checkCA(cert->ca->cm_idx) == 0)
  20505. WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't verified "
  20506. "by TSIP.");
  20507. else if (cert->sigCtx.CertAtt.pubkey_n_len != 256)
  20508. WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't signed by "
  20509. "RSA 2048.");
  20510. else
  20511. WOLFSSL_MSG("SCE-TSIP isn't usable");
  20512. }
  20513. cert->sce_tsip_encRsaKeyIdx = NULL;
  20514. }
  20515. sce_tsip_encRsaKeyIdx = cert->sce_tsip_encRsaKeyIdx;
  20516. #else
  20517. sce_tsip_encRsaKeyIdx = NULL;
  20518. #endif
  20519. if (verify != NO_VERIFY && type != CA_TYPE && type != TRUSTED_PEER_TYPE) {
  20520. if (cert->ca) {
  20521. if (verify == VERIFY || verify == VERIFY_OCSP ||
  20522. verify == VERIFY_SKIP_DATE) {
  20523. /* try to confirm/verify signature */
  20524. if ((ret = ConfirmSignature(&cert->sigCtx,
  20525. cert->source + cert->certBegin,
  20526. cert->sigIndex - cert->certBegin,
  20527. cert->ca->publicKey, cert->ca->pubKeySize,
  20528. cert->ca->keyOID, cert->signature,
  20529. cert->sigLength, cert->signatureOID,
  20530. #ifdef WC_RSA_PSS
  20531. cert->source + cert->sigParamsIndex,
  20532. cert->sigParamsLength,
  20533. #else
  20534. NULL, 0,
  20535. #endif
  20536. sce_tsip_encRsaKeyIdx)) != 0) {
  20537. if (ret != WC_PENDING_E) {
  20538. WOLFSSL_MSG("Confirm signature failed");
  20539. }
  20540. WOLFSSL_ERROR_VERBOSE(ret);
  20541. return ret;
  20542. }
  20543. }
  20544. #ifndef IGNORE_NAME_CONSTRAINTS
  20545. if (verify == VERIFY || verify == VERIFY_OCSP ||
  20546. verify == VERIFY_NAME || verify == VERIFY_SKIP_DATE) {
  20547. /* check that this cert's name is permitted by the signer's
  20548. * name constraints */
  20549. if (!ConfirmNameConstraints(cert->ca, cert)) {
  20550. WOLFSSL_MSG("Confirm name constraint failed");
  20551. WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
  20552. return ASN_NAME_INVALID_E;
  20553. }
  20554. }
  20555. #endif /* IGNORE_NAME_CONSTRAINTS */
  20556. }
  20557. #ifdef WOLFSSL_CERT_REQ
  20558. else if (type == CERTREQ_TYPE) {
  20559. if ((ret = ConfirmSignature(&cert->sigCtx,
  20560. cert->source + cert->certBegin,
  20561. cert->sigIndex - cert->certBegin,
  20562. cert->publicKey, cert->pubKeySize,
  20563. cert->keyOID, cert->signature,
  20564. cert->sigLength, cert->signatureOID,
  20565. #ifdef WC_RSA_PSS
  20566. cert->source + cert->sigParamsIndex, cert->sigParamsLength,
  20567. #else
  20568. NULL, 0,
  20569. #endif
  20570. sce_tsip_encRsaKeyIdx)) != 0) {
  20571. if (ret != WC_PENDING_E) {
  20572. WOLFSSL_MSG("Confirm signature failed");
  20573. }
  20574. WOLFSSL_ERROR_VERBOSE(ret);
  20575. return ret;
  20576. }
  20577. }
  20578. #endif
  20579. else {
  20580. /* no signer */
  20581. WOLFSSL_MSG("No CA signer to verify with");
  20582. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  20583. /* ret needs to be self-signer error for Qt compat */
  20584. if (cert->selfSigned) {
  20585. WOLFSSL_ERROR_VERBOSE(ASN_SELF_SIGNED_E);
  20586. return ASN_SELF_SIGNED_E;
  20587. }
  20588. else
  20589. #endif
  20590. {
  20591. WOLFSSL_ERROR_VERBOSE(ASN_NO_SIGNER_E);
  20592. return ASN_NO_SIGNER_E;
  20593. }
  20594. }
  20595. }
  20596. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  20597. exit_pcr:
  20598. #endif
  20599. if (cert->badDate != 0) {
  20600. if (verify != VERIFY_SKIP_DATE) {
  20601. return cert->badDate;
  20602. }
  20603. WOLFSSL_MSG("Date error: Verify option is skipping");
  20604. }
  20605. if (cert->criticalExt != 0)
  20606. return cert->criticalExt;
  20607. return ret;
  20608. }
  20609. /* Create and init an new signer */
  20610. Signer* MakeSigner(void* heap)
  20611. {
  20612. Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
  20613. DYNAMIC_TYPE_SIGNER);
  20614. if (signer) {
  20615. XMEMSET(signer, 0, sizeof(Signer));
  20616. }
  20617. (void)heap;
  20618. return signer;
  20619. }
  20620. /* Free an individual signer.
  20621. *
  20622. * Used by Certificate Manager.
  20623. *
  20624. * @param [in, out] signer On in, signer object.
  20625. * On out, pointer is no longer valid.
  20626. * @param [in] heap Dynamic memory hint.
  20627. */
  20628. void FreeSigner(Signer* signer, void* heap)
  20629. {
  20630. (void)signer;
  20631. (void)heap;
  20632. XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  20633. XFREE((void*)signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  20634. #ifndef IGNORE_NAME_CONSTRAINTS
  20635. if (signer->permittedNames)
  20636. FreeNameSubtrees(signer->permittedNames, heap);
  20637. if (signer->excludedNames)
  20638. FreeNameSubtrees(signer->excludedNames, heap);
  20639. #endif
  20640. #ifdef WOLFSSL_SIGNER_DER_CERT
  20641. FreeDer(&signer->derCert);
  20642. #endif
  20643. XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
  20644. }
  20645. /* Free the whole singer table with number of rows.
  20646. *
  20647. * Each table entry is a linked list of signers.
  20648. * Used by Certificate Manager.
  20649. *
  20650. * @param [in, out] table Array of signer objects.
  20651. * @param [in] rows Number of entries in table.
  20652. * @param [in] heap Dynamic memory hint.
  20653. */
  20654. void FreeSignerTable(Signer** table, int rows, void* heap)
  20655. {
  20656. int i;
  20657. for (i = 0; i < rows; i++) {
  20658. Signer* signer = table[i];
  20659. while (signer) {
  20660. Signer* next = signer->next;
  20661. FreeSigner(signer, heap);
  20662. signer = next;
  20663. }
  20664. table[i] = NULL;
  20665. }
  20666. }
  20667. #ifdef WOLFSSL_TRUST_PEER_CERT
  20668. /* Free an individual trusted peer cert.
  20669. *
  20670. * @param [in, out] tp Trusted peer certificate object.
  20671. * @param [in] heap Dynamic memory hint.
  20672. */
  20673. void FreeTrustedPeer(TrustedPeerCert* tp, void* heap)
  20674. {
  20675. if (tp == NULL) {
  20676. return;
  20677. }
  20678. if (tp->name) {
  20679. XFREE(tp->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  20680. }
  20681. if (tp->sig) {
  20682. XFREE(tp->sig, heap, DYNAMIC_TYPE_SIGNATURE);
  20683. }
  20684. #ifndef IGNORE_NAME_CONSTRAINTS
  20685. if (tp->permittedNames)
  20686. FreeNameSubtrees(tp->permittedNames, heap);
  20687. if (tp->excludedNames)
  20688. FreeNameSubtrees(tp->excludedNames, heap);
  20689. #endif
  20690. XFREE(tp, heap, DYNAMIC_TYPE_CERT);
  20691. (void)heap;
  20692. }
  20693. /* Free the whole Trusted Peer linked list.
  20694. *
  20695. * Each table entry is a linked list of trusted peer certificates.
  20696. * Used by Certificate Manager.
  20697. *
  20698. * @param [in, out] table Array of trusted peer certificate objects.
  20699. * @param [in] rows Number of entries in table.
  20700. * @param [in] heap Dynamic memory hint.
  20701. */
  20702. void FreeTrustedPeerTable(TrustedPeerCert** table, int rows, void* heap)
  20703. {
  20704. int i;
  20705. for (i = 0; i < rows; i++) {
  20706. TrustedPeerCert* tp = table[i];
  20707. while (tp) {
  20708. TrustedPeerCert* next = tp->next;
  20709. FreeTrustedPeer(tp, heap);
  20710. tp = next;
  20711. }
  20712. table[i] = NULL;
  20713. }
  20714. }
  20715. #endif /* WOLFSSL_TRUST_PEER_CERT */
  20716. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7)
  20717. int SetSerialNumber(const byte* sn, word32 snSz, byte* output,
  20718. word32 outputSz, int maxSnSz)
  20719. {
  20720. int i;
  20721. int snSzInt = (int)snSz;
  20722. if (sn == NULL || output == NULL || snSzInt < 0)
  20723. return BAD_FUNC_ARG;
  20724. /* remove leading zeros */
  20725. while (snSzInt > 0 && sn[0] == 0) {
  20726. snSzInt--;
  20727. sn++;
  20728. }
  20729. /* RFC 5280 - 4.1.2.2:
  20730. * Serial numbers must be a positive value (and not zero) */
  20731. if (snSzInt == 0) {
  20732. WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
  20733. return BAD_FUNC_ARG;
  20734. }
  20735. if (sn[0] & 0x80)
  20736. maxSnSz--;
  20737. /* truncate if input is too long */
  20738. if (snSzInt > maxSnSz)
  20739. snSzInt = maxSnSz;
  20740. i = SetASNInt(snSzInt, sn[0], NULL);
  20741. /* truncate if input is too long */
  20742. if (snSzInt > (int)outputSz - i)
  20743. snSzInt = (int)outputSz - i;
  20744. /* sanity check number of bytes to copy */
  20745. if (snSzInt <= 0) {
  20746. return BUFFER_E;
  20747. }
  20748. /* write out ASN.1 Integer */
  20749. (void)SetASNInt(snSzInt, sn[0], output);
  20750. XMEMCPY(output + i, sn, (size_t)snSzInt);
  20751. /* compute final length */
  20752. i += snSzInt;
  20753. return i;
  20754. }
  20755. #endif /* !WOLFSSL_ASN_TEMPLATE */
  20756. #endif /* !NO_CERTS */
  20757. #if defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS12) || \
  20758. (defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT))
  20759. int SetMyVersion(word32 version, byte* output, int header)
  20760. {
  20761. int i = 0;
  20762. if (output == NULL)
  20763. return BAD_FUNC_ARG;
  20764. if (header) {
  20765. output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  20766. output[i++] = 3;
  20767. }
  20768. output[i++] = ASN_INTEGER;
  20769. output[i++] = 0x01;
  20770. output[i++] = (byte)version;
  20771. return i;
  20772. }
  20773. #endif
  20774. #ifndef WOLFSSL_ASN_TEMPLATE
  20775. int wc_GetSerialNumber(const byte* input, word32* inOutIdx,
  20776. byte* serial, int* serialSz, word32 maxIdx)
  20777. {
  20778. int result = 0;
  20779. int ret;
  20780. WOLFSSL_ENTER("wc_GetSerialNumber");
  20781. if (serial == NULL || input == NULL || serialSz == NULL) {
  20782. return BAD_FUNC_ARG;
  20783. }
  20784. /* First byte is ASN type */
  20785. if ((*inOutIdx+1) > maxIdx) {
  20786. WOLFSSL_MSG("Bad idx first");
  20787. return BUFFER_E;
  20788. }
  20789. ret = GetASNInt(input, inOutIdx, serialSz, maxIdx);
  20790. if (ret != 0)
  20791. return ret;
  20792. if (*serialSz > EXTERNAL_SERIAL_SIZE || *serialSz <= 0) {
  20793. WOLFSSL_MSG("Serial size bad");
  20794. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  20795. return ASN_PARSE_E;
  20796. }
  20797. /* return serial */
  20798. XMEMCPY(serial, &input[*inOutIdx], (size_t)*serialSz);
  20799. *inOutIdx += (word32)*serialSz;
  20800. return result;
  20801. }
  20802. #endif
  20803. #ifndef NO_CERTS
  20804. /* TODO: consider moving PEM code out to a different file. */
  20805. int AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  20806. {
  20807. int ret = BAD_FUNC_ARG;
  20808. if (pDer) {
  20809. int dynType = 0;
  20810. DerBuffer* der;
  20811. /* Determine dynamic type */
  20812. switch (type) {
  20813. case CA_TYPE: dynType = DYNAMIC_TYPE_CA; break;
  20814. case CERT_TYPE: dynType = DYNAMIC_TYPE_CERT; break;
  20815. case CRL_TYPE: dynType = DYNAMIC_TYPE_CRL; break;
  20816. case DSA_TYPE: dynType = DYNAMIC_TYPE_DSA; break;
  20817. case ECC_TYPE: dynType = DYNAMIC_TYPE_ECC; break;
  20818. case RSA_TYPE: dynType = DYNAMIC_TYPE_RSA; break;
  20819. default: dynType = DYNAMIC_TYPE_KEY; break;
  20820. }
  20821. /* Setup new buffer */
  20822. *pDer = (DerBuffer*)XMALLOC(sizeof(DerBuffer) + length, heap, dynType);
  20823. if (*pDer == NULL) {
  20824. return MEMORY_E;
  20825. }
  20826. XMEMSET(*pDer, 0, sizeof(DerBuffer) + length);
  20827. der = *pDer;
  20828. der->type = type;
  20829. der->dynType = dynType; /* Cache this for FreeDer */
  20830. der->heap = heap;
  20831. der->buffer = (byte*)der + sizeof(DerBuffer);
  20832. der->length = length;
  20833. ret = 0; /* Success */
  20834. }
  20835. return ret;
  20836. }
  20837. void FreeDer(DerBuffer** pDer)
  20838. {
  20839. if (pDer && *pDer)
  20840. {
  20841. DerBuffer* der = (DerBuffer*)*pDer;
  20842. /* ForceZero private keys */
  20843. if (der->type == PRIVATEKEY_TYPE && der->buffer != NULL) {
  20844. ForceZero(der->buffer, der->length);
  20845. }
  20846. der->buffer = NULL;
  20847. der->length = 0;
  20848. XFREE(der, der->heap, der->dynType);
  20849. *pDer = NULL;
  20850. }
  20851. }
  20852. int wc_AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  20853. {
  20854. return AllocDer(pDer, length, type, heap);
  20855. }
  20856. void wc_FreeDer(DerBuffer** pDer)
  20857. {
  20858. FreeDer(pDer);
  20859. }
  20860. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  20861. /* Note: If items added make sure MAX_X509_HEADER_SZ is
  20862. updated to reflect maximum length and pem_struct_min_sz
  20863. to reflect minimum size */
  20864. wcchar BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
  20865. wcchar END_CERT = "-----END CERTIFICATE-----";
  20866. #ifdef WOLFSSL_CERT_REQ
  20867. wcchar BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----";
  20868. wcchar END_CERT_REQ = "-----END CERTIFICATE REQUEST-----";
  20869. #endif
  20870. #ifndef NO_DH
  20871. wcchar BEGIN_DH_PARAM = "-----BEGIN DH PARAMETERS-----";
  20872. wcchar END_DH_PARAM = "-----END DH PARAMETERS-----";
  20873. wcchar BEGIN_X942_PARAM = "-----BEGIN X9.42 DH PARAMETERS-----";
  20874. wcchar END_X942_PARAM = "-----END X9.42 DH PARAMETERS-----";
  20875. #endif
  20876. #ifndef NO_DSA
  20877. wcchar BEGIN_DSA_PARAM = "-----BEGIN DSA PARAMETERS-----";
  20878. wcchar END_DSA_PARAM = "-----END DSA PARAMETERS-----";
  20879. #endif
  20880. wcchar BEGIN_X509_CRL = "-----BEGIN X509 CRL-----";
  20881. wcchar END_X509_CRL = "-----END X509 CRL-----";
  20882. wcchar BEGIN_RSA_PRIV = "-----BEGIN RSA PRIVATE KEY-----";
  20883. wcchar END_RSA_PRIV = "-----END RSA PRIVATE KEY-----";
  20884. wcchar BEGIN_RSA_PUB = "-----BEGIN RSA PUBLIC KEY-----";
  20885. wcchar END_RSA_PUB = "-----END RSA PUBLIC KEY-----";
  20886. wcchar BEGIN_PRIV_KEY = "-----BEGIN PRIVATE KEY-----";
  20887. wcchar END_PRIV_KEY = "-----END PRIVATE KEY-----";
  20888. wcchar BEGIN_ENC_PRIV_KEY = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
  20889. wcchar END_ENC_PRIV_KEY = "-----END ENCRYPTED PRIVATE KEY-----";
  20890. #ifdef HAVE_ECC
  20891. wcchar BEGIN_EC_PRIV = "-----BEGIN EC PRIVATE KEY-----";
  20892. wcchar END_EC_PRIV = "-----END EC PRIVATE KEY-----";
  20893. #ifdef OPENSSL_EXTRA
  20894. wcchar BEGIN_EC_PARAM = "-----BEGIN EC PARAMETERS-----";
  20895. wcchar END_EC_PARAM = "-----END EC PARAMETERS-----";
  20896. #endif
  20897. #endif
  20898. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  20899. !defined(NO_DSA)
  20900. wcchar BEGIN_DSA_PRIV = "-----BEGIN DSA PRIVATE KEY-----";
  20901. wcchar END_DSA_PRIV = "-----END DSA PRIVATE KEY-----";
  20902. #endif
  20903. #ifdef OPENSSL_EXTRA
  20904. const char BEGIN_PRIV_KEY_PREFIX[] = "-----BEGIN";
  20905. const char PRIV_KEY_SUFFIX[] = "PRIVATE KEY-----";
  20906. const char END_PRIV_KEY_PREFIX[] = "-----END";
  20907. #endif
  20908. wcchar BEGIN_PUB_KEY = "-----BEGIN PUBLIC KEY-----";
  20909. wcchar END_PUB_KEY = "-----END PUBLIC KEY-----";
  20910. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  20911. wcchar BEGIN_EDDSA_PRIV = "-----BEGIN EDDSA PRIVATE KEY-----";
  20912. wcchar END_EDDSA_PRIV = "-----END EDDSA PRIVATE KEY-----";
  20913. #endif
  20914. #if defined(HAVE_PQC)
  20915. #if defined(HAVE_FALCON)
  20916. wcchar BEGIN_FALCON_LEVEL1_PRIV = "-----BEGIN FALCON_LEVEL1 PRIVATE KEY-----";
  20917. wcchar END_FALCON_LEVEL1_PRIV = "-----END FALCON_LEVEL1 PRIVATE KEY-----";
  20918. wcchar BEGIN_FALCON_LEVEL5_PRIV = "-----BEGIN FALCON_LEVEL5 PRIVATE KEY-----";
  20919. wcchar END_FALCON_LEVEL5_PRIV = "-----END FALCON_LEVEL5 PRIVATE KEY-----";
  20920. #endif /* HAVE_FALCON */
  20921. #if defined(HAVE_DILITHIUM)
  20922. wcchar BEGIN_DILITHIUM_LEVEL2_PRIV = "-----BEGIN DILITHIUM_LEVEL2 PRIVATE KEY-----";
  20923. wcchar END_DILITHIUM_LEVEL2_PRIV = "-----END DILITHIUM_LEVEL2 PRIVATE KEY-----";
  20924. wcchar BEGIN_DILITHIUM_LEVEL3_PRIV = "-----BEGIN DILITHIUM_LEVEL3 PRIVATE KEY-----";
  20925. wcchar END_DILITHIUM_LEVEL3_PRIV = "-----END DILITHIUM_LEVEL3 PRIVATE KEY-----";
  20926. wcchar BEGIN_DILITHIUM_LEVEL5_PRIV = "-----BEGIN DILITHIUM_LEVEL5 PRIVATE KEY-----";
  20927. wcchar END_DILITHIUM_LEVEL5_PRIV = "-----END DILITHIUM_LEVEL5 PRIVATE KEY-----";
  20928. #endif /* HAVE_DILITHIUM */
  20929. #if defined(HAVE_SPHINCS)
  20930. wcchar BEGIN_SPHINCS_FAST_LEVEL1_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
  20931. wcchar END_SPHINCS_FAST_LEVEL1_PRIV = "-----END SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
  20932. wcchar BEGIN_SPHINCS_FAST_LEVEL3_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
  20933. wcchar END_SPHINCS_FAST_LEVEL3_PRIV = "-----END SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
  20934. wcchar BEGIN_SPHINCS_FAST_LEVEL5_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
  20935. wcchar END_SPHINCS_FAST_LEVEL5_PRIV = "-----END SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
  20936. wcchar BEGIN_SPHINCS_SMALL_LEVEL1_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
  20937. wcchar END_SPHINCS_SMALL_LEVEL1_PRIV = "-----END SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
  20938. wcchar BEGIN_SPHINCS_SMALL_LEVEL3_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
  20939. wcchar END_SPHINCS_SMALL_LEVEL3_PRIV = "-----END SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
  20940. wcchar BEGIN_SPHINCS_SMALL_LEVEL5_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
  20941. wcchar END_SPHINCS_SMALL_LEVEL5_PRIV = "-----END SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
  20942. #endif /* HAVE_SPHINCS */
  20943. #endif /* HAVE_PQC */
  20944. const int pem_struct_min_sz = XSTR_SIZEOF("-----BEGIN X509 CRL-----"
  20945. "-----END X509 CRL-----");
  20946. #ifdef WOLFSSL_PEM_TO_DER
  20947. static WC_INLINE const char* SkipEndOfLineChars(const char* line,
  20948. const char* endOfLine)
  20949. {
  20950. /* eat end of line characters */
  20951. while (line < endOfLine &&
  20952. (line[0] == '\r' || line[0] == '\n')) {
  20953. line++;
  20954. }
  20955. return line;
  20956. }
  20957. #endif
  20958. int wc_PemGetHeaderFooter(int type, const char** header, const char** footer)
  20959. {
  20960. int ret = BAD_FUNC_ARG;
  20961. switch (type) {
  20962. case CA_TYPE: /* same as below */
  20963. case TRUSTED_PEER_TYPE:
  20964. case CERT_TYPE:
  20965. if (header) *header = BEGIN_CERT;
  20966. if (footer) *footer = END_CERT;
  20967. ret = 0;
  20968. break;
  20969. case CRL_TYPE:
  20970. if (header) *header = BEGIN_X509_CRL;
  20971. if (footer) *footer = END_X509_CRL;
  20972. ret = 0;
  20973. break;
  20974. #ifndef NO_DH
  20975. case DH_PARAM_TYPE:
  20976. if (header) *header = BEGIN_DH_PARAM;
  20977. if (footer) *footer = END_DH_PARAM;
  20978. ret = 0;
  20979. break;
  20980. case X942_PARAM_TYPE:
  20981. if (header) *header = BEGIN_X942_PARAM;
  20982. if (footer) *footer = END_X942_PARAM;
  20983. ret = 0;
  20984. break;
  20985. #endif
  20986. #ifndef NO_DSA
  20987. case DSA_PARAM_TYPE:
  20988. if (header) *header = BEGIN_DSA_PARAM;
  20989. if (footer) *footer = END_DSA_PARAM;
  20990. ret = 0;
  20991. break;
  20992. #endif
  20993. #ifdef WOLFSSL_CERT_REQ
  20994. case CERTREQ_TYPE:
  20995. if (header) *header = BEGIN_CERT_REQ;
  20996. if (footer) *footer = END_CERT_REQ;
  20997. ret = 0;
  20998. break;
  20999. #endif
  21000. #ifndef NO_DSA
  21001. case DSA_TYPE:
  21002. case DSA_PRIVATEKEY_TYPE:
  21003. if (header) *header = BEGIN_DSA_PRIV;
  21004. if (footer) *footer = END_DSA_PRIV;
  21005. ret = 0;
  21006. break;
  21007. #endif
  21008. #ifdef HAVE_ECC
  21009. case ECC_TYPE:
  21010. case ECC_PRIVATEKEY_TYPE:
  21011. if (header) *header = BEGIN_EC_PRIV;
  21012. if (footer) *footer = END_EC_PRIV;
  21013. ret = 0;
  21014. break;
  21015. #ifdef OPENSSL_EXTRA
  21016. case ECC_PARAM_TYPE:
  21017. if (header) *header = BEGIN_EC_PARAM;
  21018. if (footer) *footer = END_EC_PARAM;
  21019. ret = 0;
  21020. break;
  21021. #endif
  21022. #endif
  21023. case RSA_TYPE:
  21024. case PRIVATEKEY_TYPE:
  21025. if (header) *header = BEGIN_RSA_PRIV;
  21026. if (footer) *footer = END_RSA_PRIV;
  21027. ret = 0;
  21028. break;
  21029. #ifdef HAVE_ED25519
  21030. case ED25519_TYPE:
  21031. #endif
  21032. #ifdef HAVE_ED448
  21033. case ED448_TYPE:
  21034. #endif
  21035. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  21036. case EDDSA_PRIVATEKEY_TYPE:
  21037. if (header) *header = BEGIN_EDDSA_PRIV;
  21038. if (footer) *footer = END_EDDSA_PRIV;
  21039. ret = 0;
  21040. break;
  21041. #endif
  21042. #ifdef HAVE_PQC
  21043. #ifdef HAVE_FALCON
  21044. case FALCON_LEVEL1_TYPE:
  21045. if (header) *header = BEGIN_FALCON_LEVEL1_PRIV;
  21046. if (footer) *footer = END_FALCON_LEVEL1_PRIV;
  21047. ret = 0;
  21048. break;
  21049. case FALCON_LEVEL5_TYPE:
  21050. if (header) *header = BEGIN_FALCON_LEVEL5_PRIV;
  21051. if (footer) *footer = END_FALCON_LEVEL5_PRIV;
  21052. ret = 0;
  21053. break;
  21054. #endif /* HAVE_FALCON */
  21055. #ifdef HAVE_DILITHIUM
  21056. case DILITHIUM_LEVEL2_TYPE:
  21057. if (header) *header = BEGIN_DILITHIUM_LEVEL2_PRIV;
  21058. if (footer) *footer = END_DILITHIUM_LEVEL2_PRIV;
  21059. ret = 0;
  21060. break;
  21061. case DILITHIUM_LEVEL3_TYPE:
  21062. if (header) *header = BEGIN_DILITHIUM_LEVEL3_PRIV;
  21063. if (footer) *footer = END_DILITHIUM_LEVEL3_PRIV;
  21064. ret = 0;
  21065. break;
  21066. case DILITHIUM_LEVEL5_TYPE:
  21067. if (header) *header = BEGIN_DILITHIUM_LEVEL5_PRIV;
  21068. if (footer) *footer = END_DILITHIUM_LEVEL5_PRIV;
  21069. ret = 0;
  21070. break;
  21071. #endif /* HAVE_DILITHIUM */
  21072. #ifdef HAVE_SPHINCS
  21073. case SPHINCS_FAST_LEVEL1_TYPE:
  21074. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL1_PRIV;
  21075. if (footer) *footer = END_SPHINCS_FAST_LEVEL1_PRIV;
  21076. ret = 0;
  21077. break;
  21078. case SPHINCS_FAST_LEVEL3_TYPE:
  21079. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL3_PRIV;
  21080. if (footer) *footer = END_SPHINCS_FAST_LEVEL3_PRIV;
  21081. ret = 0;
  21082. break;
  21083. case SPHINCS_FAST_LEVEL5_TYPE:
  21084. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL5_PRIV;
  21085. if (footer) *footer = END_SPHINCS_FAST_LEVEL5_PRIV;
  21086. ret = 0;
  21087. break;
  21088. case SPHINCS_SMALL_LEVEL1_TYPE:
  21089. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL1_PRIV;
  21090. if (footer) *footer = END_SPHINCS_SMALL_LEVEL1_PRIV;
  21091. ret = 0;
  21092. break;
  21093. case SPHINCS_SMALL_LEVEL3_TYPE:
  21094. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL3_PRIV;
  21095. if (footer) *footer = END_SPHINCS_SMALL_LEVEL3_PRIV;
  21096. ret = 0;
  21097. break;
  21098. case SPHINCS_SMALL_LEVEL5_TYPE:
  21099. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL5_PRIV;
  21100. if (footer) *footer = END_SPHINCS_SMALL_LEVEL5_PRIV;
  21101. ret = 0;
  21102. break;
  21103. #endif /* HAVE_SPHINCS */
  21104. #endif /* HAVE_PQC */
  21105. case PUBLICKEY_TYPE:
  21106. case ECC_PUBLICKEY_TYPE:
  21107. if (header) *header = BEGIN_PUB_KEY;
  21108. if (footer) *footer = END_PUB_KEY;
  21109. ret = 0;
  21110. break;
  21111. case RSA_PUBLICKEY_TYPE:
  21112. if (header) *header = BEGIN_RSA_PUB;
  21113. if (footer) *footer = END_RSA_PUB;
  21114. ret = 0;
  21115. break;
  21116. #ifndef NO_DH
  21117. case DH_PRIVATEKEY_TYPE:
  21118. #endif
  21119. case PKCS8_PRIVATEKEY_TYPE:
  21120. if (header) *header = BEGIN_PRIV_KEY;
  21121. if (footer) *footer = END_PRIV_KEY;
  21122. ret = 0;
  21123. break;
  21124. case PKCS8_ENC_PRIVATEKEY_TYPE:
  21125. if (header) *header = BEGIN_ENC_PRIV_KEY;
  21126. if (footer) *footer = END_ENC_PRIV_KEY;
  21127. ret = 0;
  21128. break;
  21129. default:
  21130. break;
  21131. }
  21132. return ret;
  21133. }
  21134. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21135. static wcchar kProcTypeHeader = "Proc-Type";
  21136. static wcchar kDecInfoHeader = "DEK-Info";
  21137. #ifdef WOLFSSL_PEM_TO_DER
  21138. #ifndef NO_DES3
  21139. static wcchar kEncTypeDes = "DES-CBC";
  21140. static wcchar kEncTypeDes3 = "DES-EDE3-CBC";
  21141. #endif
  21142. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  21143. static wcchar kEncTypeAesCbc128 = "AES-128-CBC";
  21144. #endif
  21145. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  21146. static wcchar kEncTypeAesCbc192 = "AES-192-CBC";
  21147. #endif
  21148. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  21149. static wcchar kEncTypeAesCbc256 = "AES-256-CBC";
  21150. #endif
  21151. int wc_EncryptedInfoGet(EncryptedInfo* info, const char* cipherInfo)
  21152. {
  21153. int ret = 0;
  21154. if (info == NULL || cipherInfo == NULL)
  21155. return BAD_FUNC_ARG;
  21156. /* determine cipher information */
  21157. #ifndef NO_DES3
  21158. if (XSTRCMP(cipherInfo, kEncTypeDes) == 0) {
  21159. info->cipherType = WC_CIPHER_DES;
  21160. info->keySz = DES_KEY_SIZE;
  21161. /* DES_IV_SIZE is incorrectly 16 in FIPS v2. It should be 8, same as the
  21162. * block size. */
  21163. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  21164. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  21165. #else
  21166. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  21167. #endif
  21168. }
  21169. else if (XSTRCMP(cipherInfo, kEncTypeDes3) == 0) {
  21170. info->cipherType = WC_CIPHER_DES3;
  21171. info->keySz = DES3_KEY_SIZE;
  21172. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  21173. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  21174. #else
  21175. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  21176. #endif
  21177. }
  21178. else
  21179. #endif /* !NO_DES3 */
  21180. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  21181. if (XSTRCMP(cipherInfo, kEncTypeAesCbc128) == 0) {
  21182. info->cipherType = WC_CIPHER_AES_CBC;
  21183. info->keySz = AES_128_KEY_SIZE;
  21184. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  21185. }
  21186. else
  21187. #endif
  21188. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  21189. if (XSTRCMP(cipherInfo, kEncTypeAesCbc192) == 0) {
  21190. info->cipherType = WC_CIPHER_AES_CBC;
  21191. info->keySz = AES_192_KEY_SIZE;
  21192. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  21193. }
  21194. else
  21195. #endif
  21196. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  21197. if (XSTRCMP(cipherInfo, kEncTypeAesCbc256) == 0) {
  21198. info->cipherType = WC_CIPHER_AES_CBC;
  21199. info->keySz = AES_256_KEY_SIZE;
  21200. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  21201. }
  21202. else
  21203. #endif
  21204. {
  21205. ret = NOT_COMPILED_IN;
  21206. }
  21207. return ret;
  21208. }
  21209. int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer,
  21210. size_t bufSz)
  21211. {
  21212. int err = 0;
  21213. const char* bufferStart;
  21214. const char* bufferEnd;
  21215. char* line;
  21216. if (info == NULL || pBuffer == NULL || bufSz == 0)
  21217. return BAD_FUNC_ARG;
  21218. bufferStart = *pBuffer;
  21219. bufferEnd = bufferStart + bufSz;
  21220. /* find encrypted info marker */
  21221. line = XSTRNSTR(bufferStart, kProcTypeHeader,
  21222. min((word32)bufSz, PEM_LINE_LEN));
  21223. if (line != NULL) {
  21224. word32 lineSz;
  21225. char* finish;
  21226. char* start;
  21227. word32 startSz;
  21228. const char* newline = NULL;
  21229. if (line >= bufferEnd) {
  21230. return BUFFER_E;
  21231. }
  21232. lineSz = (word32)(bufferEnd - line);
  21233. /* find DEC-Info marker */
  21234. start = XSTRNSTR(line, kDecInfoHeader, min(lineSz, PEM_LINE_LEN));
  21235. if (start == NULL)
  21236. return BUFFER_E;
  21237. /* skip dec-info and ": " */
  21238. start += XSTRLEN(kDecInfoHeader);
  21239. if (start >= bufferEnd)
  21240. return BUFFER_E;
  21241. if (start[0] == ':') {
  21242. start++;
  21243. if (start >= bufferEnd)
  21244. return BUFFER_E;
  21245. }
  21246. if (start[0] == ' ')
  21247. start++;
  21248. startSz = (word32)(bufferEnd - start);
  21249. finish = XSTRNSTR(start, ",", min(startSz, PEM_LINE_LEN));
  21250. if ((start != NULL) && (finish != NULL) && (start < finish)) {
  21251. word32 finishSz;
  21252. if (finish >= bufferEnd) {
  21253. return BUFFER_E;
  21254. }
  21255. finishSz = (word32)(bufferEnd - finish);
  21256. newline = XSTRNSTR(finish, "\r", min(finishSz, PEM_LINE_LEN));
  21257. /* get cipher name */
  21258. if (NAME_SZ < (finish - start)) /* buffer size of info->name */
  21259. return BUFFER_E;
  21260. if (XMEMCPY(info->name, start, (size_t)(finish - start)) == NULL)
  21261. return BUFFER_E;
  21262. info->name[finish - start] = '\0'; /* null term */
  21263. /* populate info */
  21264. err = wc_EncryptedInfoGet(info, info->name);
  21265. if (err != 0)
  21266. return err;
  21267. /* get IV */
  21268. if (finishSz < info->ivSz + 1)
  21269. return BUFFER_E;
  21270. if (newline == NULL) {
  21271. newline = XSTRNSTR(finish, "\n", min(finishSz,
  21272. PEM_LINE_LEN));
  21273. }
  21274. if ((newline != NULL) && (newline > finish)) {
  21275. finish++;
  21276. info->ivSz = (word32)(newline - finish);
  21277. if (info->ivSz > IV_SZ)
  21278. return BUFFER_E;
  21279. if (XMEMCPY(info->iv, finish, info->ivSz) == NULL)
  21280. return BUFFER_E;
  21281. info->set = 1;
  21282. }
  21283. else
  21284. return BUFFER_E;
  21285. }
  21286. else
  21287. return BUFFER_E;
  21288. /* eat end of line characters */
  21289. newline = SkipEndOfLineChars(newline, bufferEnd);
  21290. /* return new headerEnd */
  21291. *pBuffer = newline;
  21292. }
  21293. return err;
  21294. }
  21295. #endif /* WOLFSSL_PEM_TO_DER */
  21296. #ifdef WOLFSSL_DER_TO_PEM
  21297. static int wc_EncryptedInfoAppend(char* dest, int destSz, char* cipherInfo)
  21298. {
  21299. if (cipherInfo != NULL) {
  21300. int cipherInfoStrLen = (int)XSTRLEN((char*)cipherInfo);
  21301. if (cipherInfoStrLen > HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3))
  21302. cipherInfoStrLen = HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3);
  21303. if (destSz - (int)XSTRLEN(dest) >= cipherInfoStrLen + (9+14+8+2+2+1)) {
  21304. /* strncat's src length needs to include the NULL */
  21305. XSTRNCAT(dest, kProcTypeHeader, 10);
  21306. XSTRNCAT(dest, ": 4,ENCRYPTED\n", 15);
  21307. XSTRNCAT(dest, kDecInfoHeader, 9);
  21308. XSTRNCAT(dest, ": ", 3);
  21309. XSTRNCAT(dest, cipherInfo, (size_t)destSz - XSTRLEN(dest) - 1);
  21310. XSTRNCAT(dest, "\n\n", 4);
  21311. }
  21312. }
  21313. return 0;
  21314. }
  21315. #endif /* WOLFSSL_DER_TO_PEM */
  21316. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  21317. #ifdef WOLFSSL_DER_TO_PEM
  21318. /* Used for compatibility API */
  21319. WOLFSSL_ABI
  21320. int wc_DerToPem(const byte* der, word32 derSz,
  21321. byte* output, word32 outSz, int type)
  21322. {
  21323. return wc_DerToPemEx(der, derSz, output, outSz, NULL, type);
  21324. }
  21325. /* convert der buffer to pem into output, can't do inplace, der and output
  21326. need to be different */
  21327. int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz,
  21328. byte *cipher_info, int type)
  21329. {
  21330. const char* headerStr = NULL;
  21331. const char* footerStr = NULL;
  21332. #ifdef WOLFSSL_SMALL_STACK
  21333. char* header = NULL;
  21334. char* footer = NULL;
  21335. #else
  21336. char header[MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE];
  21337. char footer[MAX_X509_HEADER_SZ];
  21338. #endif
  21339. int headerLen = MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE;
  21340. int footerLen = MAX_X509_HEADER_SZ;
  21341. int i;
  21342. int err;
  21343. int outLen; /* return length or error */
  21344. (void)cipher_info;
  21345. if (der == output) /* no in place conversion */
  21346. return BAD_FUNC_ARG;
  21347. err = wc_PemGetHeaderFooter(type, &headerStr, &footerStr);
  21348. if (err != 0)
  21349. return err;
  21350. #ifdef WOLFSSL_SMALL_STACK
  21351. header = (char*)XMALLOC(headerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21352. if (header == NULL)
  21353. return MEMORY_E;
  21354. footer = (char*)XMALLOC(footerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21355. if (footer == NULL) {
  21356. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21357. return MEMORY_E;
  21358. }
  21359. #endif
  21360. /* build header and footer based on type */
  21361. XSTRNCPY(header, headerStr, (size_t)headerLen - 1);
  21362. header[headerLen - 2] = 0;
  21363. XSTRNCPY(footer, footerStr, (size_t)footerLen - 1);
  21364. footer[footerLen - 2] = 0;
  21365. /* add new line to end */
  21366. XSTRNCAT(header, "\n", 2);
  21367. XSTRNCAT(footer, "\n", 2);
  21368. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21369. err = wc_EncryptedInfoAppend(header, headerLen, (char*)cipher_info);
  21370. if (err != 0) {
  21371. #ifdef WOLFSSL_SMALL_STACK
  21372. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21373. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21374. #endif
  21375. return err;
  21376. }
  21377. #endif
  21378. headerLen = (int)XSTRLEN(header);
  21379. footerLen = (int)XSTRLEN(footer);
  21380. /* if null output and 0 size passed in then return size needed */
  21381. if (!output && outSz == 0) {
  21382. #ifdef WOLFSSL_SMALL_STACK
  21383. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21384. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21385. #endif
  21386. outLen = 0;
  21387. if ((err = Base64_Encode(der, derSz, NULL, (word32*)&outLen))
  21388. != LENGTH_ONLY_E) {
  21389. WOLFSSL_ERROR_VERBOSE(err);
  21390. return err;
  21391. }
  21392. return headerLen + footerLen + outLen;
  21393. }
  21394. if (!der || !output) {
  21395. #ifdef WOLFSSL_SMALL_STACK
  21396. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21397. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21398. #endif
  21399. return BAD_FUNC_ARG;
  21400. }
  21401. /* don't even try if outSz too short */
  21402. if (outSz < (word32)headerLen + (word32)footerLen + derSz) {
  21403. #ifdef WOLFSSL_SMALL_STACK
  21404. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21405. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21406. #endif
  21407. return BAD_FUNC_ARG;
  21408. }
  21409. /* header */
  21410. XMEMCPY(output, header, (size_t)headerLen);
  21411. i = headerLen;
  21412. #ifdef WOLFSSL_SMALL_STACK
  21413. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21414. #endif
  21415. /* body */
  21416. outLen = (int)outSz - (headerLen + footerLen); /* input to Base64_Encode */
  21417. if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0) {
  21418. #ifdef WOLFSSL_SMALL_STACK
  21419. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21420. #endif
  21421. WOLFSSL_ERROR_VERBOSE(err);
  21422. return err;
  21423. }
  21424. i += outLen;
  21425. /* footer */
  21426. if ( (i + footerLen) > (int)outSz) {
  21427. #ifdef WOLFSSL_SMALL_STACK
  21428. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21429. #endif
  21430. return BAD_FUNC_ARG;
  21431. }
  21432. XMEMCPY(output + i, footer, (size_t)footerLen);
  21433. #ifdef WOLFSSL_SMALL_STACK
  21434. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21435. #endif
  21436. return outLen + headerLen + footerLen;
  21437. }
  21438. #endif /* WOLFSSL_DER_TO_PEM */
  21439. #ifdef WOLFSSL_PEM_TO_DER
  21440. /* Remove PEM header/footer, convert to ASN1, store any encrypted data
  21441. info->consumed tracks of PEM bytes consumed in case multiple parts */
  21442. int PemToDer(const unsigned char* buff, long longSz, int type,
  21443. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  21444. {
  21445. const char* header = NULL;
  21446. const char* footer = NULL;
  21447. const char* headerEnd;
  21448. const char* footerEnd;
  21449. const char* consumedEnd;
  21450. const char* bufferEnd = (const char*)(buff + longSz);
  21451. long neededSz;
  21452. int ret = 0;
  21453. int sz = (int)longSz;
  21454. int encrypted_key = 0;
  21455. DerBuffer* der;
  21456. word32 algId = 0;
  21457. word32 idx;
  21458. #ifdef OPENSSL_EXTRA
  21459. char beginBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  21460. char endBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  21461. #endif
  21462. WOLFSSL_ENTER("PemToDer");
  21463. /* get PEM header and footer based on type */
  21464. ret = wc_PemGetHeaderFooter(type, &header, &footer);
  21465. if (ret != 0)
  21466. return ret;
  21467. /* map header if not found for type */
  21468. for (;;) {
  21469. headerEnd = XSTRNSTR((char*)buff, header, (word32)sz);
  21470. if (headerEnd) {
  21471. break;
  21472. }
  21473. if (type == PRIVATEKEY_TYPE) {
  21474. if (header == BEGIN_RSA_PRIV) {
  21475. header = BEGIN_PRIV_KEY;
  21476. footer = END_PRIV_KEY;
  21477. }
  21478. else if (header == BEGIN_PRIV_KEY) {
  21479. header = BEGIN_ENC_PRIV_KEY;
  21480. footer = END_ENC_PRIV_KEY;
  21481. }
  21482. #ifdef HAVE_ECC
  21483. else if (header == BEGIN_ENC_PRIV_KEY) {
  21484. header = BEGIN_EC_PRIV;
  21485. footer = END_EC_PRIV;
  21486. }
  21487. else if (header == BEGIN_EC_PRIV) {
  21488. header = BEGIN_DSA_PRIV;
  21489. footer = END_DSA_PRIV;
  21490. }
  21491. #endif
  21492. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  21493. #ifdef HAVE_ECC
  21494. else if (header == BEGIN_DSA_PRIV) {
  21495. #else
  21496. else if (header == BEGIN_ENC_PRIV_KEY) {
  21497. #endif
  21498. header = BEGIN_EDDSA_PRIV;
  21499. footer = END_EDDSA_PRIV;
  21500. }
  21501. #endif
  21502. else {
  21503. #ifdef WOLF_PRIVATE_KEY_ID
  21504. /* allow loading a public key for use with crypto or PK callbacks */
  21505. type = PUBLICKEY_TYPE;
  21506. header = BEGIN_PUB_KEY;
  21507. footer = END_PUB_KEY;
  21508. #else
  21509. break;
  21510. #endif
  21511. }
  21512. }
  21513. else if (type == PUBLICKEY_TYPE) {
  21514. if (header == BEGIN_PUB_KEY) {
  21515. header = BEGIN_RSA_PUB;
  21516. footer = END_RSA_PUB;
  21517. }
  21518. else {
  21519. break;
  21520. }
  21521. }
  21522. #if defined(HAVE_ECC) && defined(OPENSSL_EXTRA)
  21523. else if (type == ECC_PARAM_TYPE) {
  21524. if (header == BEGIN_EC_PARAM) {
  21525. header = BEGIN_EC_PARAM;
  21526. footer = END_EC_PARAM;
  21527. }
  21528. else {
  21529. break;
  21530. }
  21531. }
  21532. #endif
  21533. #ifdef HAVE_CRL
  21534. else if ((type == CRL_TYPE) && (header != BEGIN_X509_CRL)) {
  21535. header = BEGIN_X509_CRL;
  21536. footer = END_X509_CRL;
  21537. }
  21538. #endif
  21539. else {
  21540. break;
  21541. }
  21542. }
  21543. if (!headerEnd) {
  21544. #ifdef OPENSSL_EXTRA
  21545. if (type == PRIVATEKEY_TYPE) {
  21546. /* see if there is a -----BEGIN * PRIVATE KEY----- header */
  21547. headerEnd = XSTRNSTR((char*)buff, PRIV_KEY_SUFFIX, sz);
  21548. if (headerEnd) {
  21549. const char* beginEnd;
  21550. int endLen;
  21551. beginEnd = headerEnd + XSTR_SIZEOF(PRIV_KEY_SUFFIX);
  21552. if (beginEnd >= (char*)buff + sz) {
  21553. return BUFFER_E;
  21554. }
  21555. /* back up to BEGIN_PRIV_KEY_PREFIX */
  21556. while (headerEnd > (char*)buff &&
  21557. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  21558. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 &&
  21559. *headerEnd != '\n') {
  21560. headerEnd--;
  21561. }
  21562. if (headerEnd <= (char*)buff ||
  21563. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  21564. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 ||
  21565. beginEnd - headerEnd > PEM_LINE_LEN) {
  21566. WOLFSSL_MSG("Couldn't find PEM header");
  21567. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21568. return ASN_NO_PEM_HEADER;
  21569. }
  21570. /* headerEnd now points to beginning of header */
  21571. XMEMCPY(beginBuf, headerEnd, beginEnd - headerEnd);
  21572. beginBuf[beginEnd - headerEnd] = '\0';
  21573. /* look for matching footer */
  21574. footer = XSTRNSTR(beginEnd,
  21575. beginBuf + XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX),
  21576. (unsigned int)((char*)buff + sz - beginEnd));
  21577. if (!footer) {
  21578. WOLFSSL_MSG("Couldn't find PEM footer");
  21579. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21580. return ASN_NO_PEM_HEADER;
  21581. }
  21582. footer -= XSTR_SIZEOF(END_PRIV_KEY_PREFIX);
  21583. if (footer > (char*)buff + sz - XSTR_SIZEOF(END_PRIV_KEY_PREFIX)
  21584. || XSTRNCMP(footer, END_PRIV_KEY_PREFIX,
  21585. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)) != 0) {
  21586. WOLFSSL_MSG("Unexpected footer for PEM");
  21587. return BUFFER_E;
  21588. }
  21589. endLen = (unsigned int)(beginEnd - headerEnd -
  21590. (XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX) -
  21591. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)));
  21592. XMEMCPY(endBuf, footer, endLen);
  21593. endBuf[endLen] = '\0';
  21594. header = beginBuf;
  21595. footer = endBuf;
  21596. headerEnd = beginEnd;
  21597. }
  21598. }
  21599. if (!headerEnd) {
  21600. WOLFSSL_MSG("Couldn't find PEM header");
  21601. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21602. return ASN_NO_PEM_HEADER;
  21603. }
  21604. #else
  21605. WOLFSSL_MSG("Couldn't find PEM header");
  21606. return ASN_NO_PEM_HEADER;
  21607. #endif
  21608. } else {
  21609. headerEnd += XSTRLEN(header);
  21610. }
  21611. /* eat end of line characters */
  21612. headerEnd = SkipEndOfLineChars(headerEnd, bufferEnd);
  21613. if (keyFormat) {
  21614. /* keyFormat is Key_Sum enum */
  21615. if (type == PRIVATEKEY_TYPE) {
  21616. #ifndef NO_RSA
  21617. if (header == BEGIN_RSA_PRIV)
  21618. *keyFormat = RSAk;
  21619. #endif
  21620. #ifdef HAVE_ECC
  21621. if (header == BEGIN_EC_PRIV)
  21622. *keyFormat = ECDSAk;
  21623. #endif
  21624. #ifndef NO_DSA
  21625. if (header == BEGIN_DSA_PRIV)
  21626. *keyFormat = DSAk;
  21627. #endif
  21628. }
  21629. #ifdef WOLF_PRIVATE_KEY_ID
  21630. else if (type == PUBLICKEY_TYPE) {
  21631. #ifndef NO_RSA
  21632. if (header == BEGIN_RSA_PUB)
  21633. *keyFormat = RSAk;
  21634. #endif
  21635. }
  21636. #endif
  21637. }
  21638. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21639. if (info) {
  21640. ret = wc_EncryptedInfoParse(info, &headerEnd,
  21641. (size_t)(bufferEnd - headerEnd));
  21642. if (ret < 0)
  21643. return ret;
  21644. if (info->set)
  21645. encrypted_key = 1;
  21646. }
  21647. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  21648. /* find footer */
  21649. footerEnd = XSTRNSTR(headerEnd, footer, (unsigned int)((char*)buff +
  21650. sz - headerEnd));
  21651. if (!footerEnd) {
  21652. if (info)
  21653. info->consumed = longSz; /* No more certs if no footer */
  21654. return BUFFER_E;
  21655. }
  21656. consumedEnd = footerEnd + XSTRLEN(footer);
  21657. if (consumedEnd < bufferEnd) { /* handle no end of line on last line */
  21658. /* eat end of line characters */
  21659. consumedEnd = SkipEndOfLineChars(consumedEnd, bufferEnd);
  21660. /* skip possible null term */
  21661. if (consumedEnd < bufferEnd && consumedEnd[0] == '\0')
  21662. consumedEnd++;
  21663. }
  21664. if (info)
  21665. info->consumed = (long)(consumedEnd - (const char*)buff);
  21666. /* set up der buffer */
  21667. neededSz = (long)(footerEnd - headerEnd);
  21668. if (neededSz > sz || neededSz <= 0)
  21669. return BUFFER_E;
  21670. ret = AllocDer(pDer, (word32)neededSz, type, heap);
  21671. if (ret < 0) {
  21672. return ret;
  21673. }
  21674. der = *pDer;
  21675. if (Base64_Decode((byte*)headerEnd, (word32)neededSz,
  21676. der->buffer, &der->length) < 0) {
  21677. WOLFSSL_ERROR(BUFFER_E);
  21678. return BUFFER_E;
  21679. }
  21680. if ((header == BEGIN_PRIV_KEY
  21681. #ifdef OPENSSL_EXTRA
  21682. || header == beginBuf
  21683. #endif
  21684. #ifdef HAVE_ECC
  21685. || header == BEGIN_EC_PRIV
  21686. #endif
  21687. ) && !encrypted_key)
  21688. {
  21689. /* detect pkcs8 key and get alg type */
  21690. /* keep PKCS8 header */
  21691. idx = 0;
  21692. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length, &algId);
  21693. if (ret > 0) {
  21694. if (keyFormat)
  21695. *keyFormat = (int)algId;
  21696. }
  21697. else {
  21698. /* ignore failure here and assume key is not pkcs8 wrapped */
  21699. }
  21700. return 0;
  21701. }
  21702. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21703. if (encrypted_key || header == BEGIN_ENC_PRIV_KEY) {
  21704. int passwordSz = NAME_SZ;
  21705. #ifdef WOLFSSL_SMALL_STACK
  21706. char* password = NULL;
  21707. #else
  21708. char password[NAME_SZ];
  21709. #endif
  21710. if (!info || !info->passwd_cb) {
  21711. WOLFSSL_MSG("No password callback set");
  21712. WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
  21713. return NO_PASSWORD;
  21714. }
  21715. #ifdef WOLFSSL_SMALL_STACK
  21716. password = (char*)XMALLOC(passwordSz, heap, DYNAMIC_TYPE_STRING);
  21717. if (password == NULL) {
  21718. return MEMORY_E;
  21719. }
  21720. #endif
  21721. /* get password */
  21722. ret = info->passwd_cb(password, passwordSz, PEM_PASS_READ,
  21723. info->passwd_userdata);
  21724. if (ret >= 0) {
  21725. passwordSz = ret;
  21726. #ifdef WOLFSSL_CHECK_MEM_ZERO
  21727. wc_MemZero_Add("PEM password", password, passwordSz);
  21728. #endif
  21729. /* convert and adjust length */
  21730. if (header == BEGIN_ENC_PRIV_KEY) {
  21731. #ifndef NO_PWDBASED
  21732. ret = wc_DecryptPKCS8Key(der->buffer, der->length,
  21733. password, passwordSz);
  21734. if (ret > 0) {
  21735. /* update length by decrypted content */
  21736. der->length = (word32)ret;
  21737. idx = 0;
  21738. /* detect pkcs8 key and get alg type */
  21739. /* keep PKCS8 header */
  21740. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length,
  21741. &algId);
  21742. if (ret >= 0) {
  21743. if (keyFormat)
  21744. *keyFormat = (int)algId;
  21745. ret = 0;
  21746. }
  21747. }
  21748. #else
  21749. WOLFSSL_ERROR_VERBOSE(NOT_COMPILED_IN);
  21750. ret = NOT_COMPILED_IN;
  21751. #endif
  21752. }
  21753. /* decrypt the key */
  21754. else {
  21755. if (passwordSz == 0) {
  21756. /* The key is encrypted but does not have a password */
  21757. WOLFSSL_MSG("No password for encrypted key");
  21758. WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
  21759. ret = NO_PASSWORD;
  21760. }
  21761. else {
  21762. #if ((defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_DES3)) || \
  21763. (!defined(NO_AES) && defined(HAVE_AES_CBC) && \
  21764. defined(HAVE_AES_DECRYPT))) && \
  21765. !defined(NO_WOLFSSL_SKIP_TRAILING_PAD)
  21766. int padVal = 0;
  21767. #endif
  21768. ret = wc_BufferKeyDecrypt(info, der->buffer, der->length,
  21769. (byte*)password, passwordSz, WC_MD5);
  21770. #ifndef NO_WOLFSSL_SKIP_TRAILING_PAD
  21771. #ifndef NO_DES3
  21772. if (info->cipherType == WC_CIPHER_DES3) {
  21773. /* Assuming there is padding:
  21774. * (der->length > 0 && der->length > DES_BLOCK_SIZE &&
  21775. * (der->length % DES_BLOCK_SIZE) != 0)
  21776. * and assuming the last value signifies the number of
  21777. * padded bytes IE if last value is 0x08 then there are
  21778. * 8 bytes of padding:
  21779. * padVal = der->buffer[der->length-1];
  21780. * then strip this padding before proceeding:
  21781. * der->length -= padVal;
  21782. */
  21783. if (der->length > DES_BLOCK_SIZE &&
  21784. (der->length % DES_BLOCK_SIZE) != 0) {
  21785. padVal = der->buffer[der->length-1];
  21786. if (padVal < DES_BLOCK_SIZE) {
  21787. der->length -= (word32)padVal;
  21788. }
  21789. }
  21790. }
  21791. #endif /* !NO_DES3 */
  21792. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && \
  21793. defined(HAVE_AES_DECRYPT)
  21794. if (info->cipherType == WC_CIPHER_AES_CBC) {
  21795. if (der->length > AES_BLOCK_SIZE) {
  21796. padVal = der->buffer[der->length-1];
  21797. if (padVal <= AES_BLOCK_SIZE) {
  21798. der->length -= (word32)padVal;
  21799. }
  21800. }
  21801. }
  21802. #endif
  21803. #endif /* !NO_WOLFSSL_SKIP_TRAILING_PAD */
  21804. }
  21805. }
  21806. #ifdef OPENSSL_EXTRA
  21807. if (ret) {
  21808. PEMerr(0, PEM_R_BAD_DECRYPT);
  21809. }
  21810. #endif
  21811. ForceZero(password, (word32)passwordSz);
  21812. }
  21813. #ifdef OPENSSL_EXTRA
  21814. else {
  21815. PEMerr(0, PEM_R_BAD_PASSWORD_READ);
  21816. }
  21817. #endif
  21818. #ifdef WOLFSSL_SMALL_STACK
  21819. XFREE(password, heap, DYNAMIC_TYPE_STRING);
  21820. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  21821. wc_MemZero_Check(password, NAME_SZ);
  21822. #endif
  21823. }
  21824. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  21825. return ret;
  21826. }
  21827. int wc_PemToDer(const unsigned char* buff, long longSz, int type,
  21828. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  21829. {
  21830. int ret = PemToDer(buff, longSz, type, pDer, heap, info, keyFormat);
  21831. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  21832. if (ret == 0 && type == PRIVATEKEY_TYPE) {
  21833. DerBuffer* der = *pDer;
  21834. /* if a PKCS8 key header exists remove it */
  21835. ret = ToTraditional(der->buffer, der->length);
  21836. if (ret > 0) {
  21837. der->length = (word32)ret;
  21838. }
  21839. ret = 0; /* ignore error removing PKCS8 header */
  21840. }
  21841. #endif
  21842. return ret;
  21843. }
  21844. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21845. /* our KeyPemToDer password callback, password in userData */
  21846. static int KeyPemToDerPassCb(char* passwd, int sz, int rw, void* userdata)
  21847. {
  21848. (void)rw;
  21849. if (userdata == NULL)
  21850. return 0;
  21851. XSTRNCPY(passwd, (char*)userdata, (size_t)sz);
  21852. return (int)min((word32)sz, (word32)XSTRLEN((char*)userdata));
  21853. }
  21854. #endif
  21855. /* Return bytes written to buff or < 0 for error */
  21856. int wc_KeyPemToDer(const unsigned char* pem, int pemSz,
  21857. unsigned char* buff, int buffSz, const char* pass)
  21858. {
  21859. int ret;
  21860. DerBuffer* der = NULL;
  21861. #ifdef WOLFSSL_SMALL_STACK
  21862. EncryptedInfo* info = NULL;
  21863. #else
  21864. EncryptedInfo info[1];
  21865. #endif
  21866. WOLFSSL_ENTER("wc_KeyPemToDer");
  21867. if (pem == NULL || (buff != NULL && buffSz <= 0)) {
  21868. WOLFSSL_MSG("Bad pem der args");
  21869. return BAD_FUNC_ARG;
  21870. }
  21871. #ifdef WOLFSSL_SMALL_STACK
  21872. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  21873. DYNAMIC_TYPE_ENCRYPTEDINFO);
  21874. if (info == NULL)
  21875. return MEMORY_E;
  21876. #endif
  21877. XMEMSET(info, 0, sizeof(EncryptedInfo));
  21878. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21879. info->passwd_cb = KeyPemToDerPassCb;
  21880. info->passwd_userdata = (void*)pass;
  21881. #else
  21882. (void)pass;
  21883. #endif
  21884. ret = PemToDer(pem, pemSz, PRIVATEKEY_TYPE, &der, NULL, info, NULL);
  21885. #ifdef WOLFSSL_SMALL_STACK
  21886. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  21887. #endif
  21888. if (ret < 0 || der == NULL) {
  21889. WOLFSSL_MSG("Bad Pem To Der");
  21890. }
  21891. else if (buff == NULL) {
  21892. WOLFSSL_MSG("Return needed der buff length");
  21893. ret = (int)der->length;
  21894. }
  21895. else if (der->length <= (word32)buffSz) {
  21896. XMEMCPY(buff, der->buffer, der->length);
  21897. ret = (int)der->length;
  21898. }
  21899. else {
  21900. WOLFSSL_MSG("Bad der length");
  21901. ret = BAD_FUNC_ARG;
  21902. }
  21903. FreeDer(&der);
  21904. return ret;
  21905. }
  21906. /* Return bytes written to buff or < 0 for error */
  21907. int wc_CertPemToDer(const unsigned char* pem, int pemSz,
  21908. unsigned char* buff, int buffSz, int type)
  21909. {
  21910. int ret;
  21911. DerBuffer* der = NULL;
  21912. WOLFSSL_ENTER("wc_CertPemToDer");
  21913. if (pem == NULL || buff == NULL || buffSz <= 0) {
  21914. WOLFSSL_MSG("Bad pem der args");
  21915. return BAD_FUNC_ARG;
  21916. }
  21917. if (type != CERT_TYPE && type != CA_TYPE && type != CERTREQ_TYPE) {
  21918. WOLFSSL_MSG("Bad cert type");
  21919. return BAD_FUNC_ARG;
  21920. }
  21921. ret = PemToDer(pem, pemSz, type, &der, NULL, NULL, NULL);
  21922. if (ret < 0 || der == NULL) {
  21923. WOLFSSL_MSG("Bad Pem To Der");
  21924. }
  21925. else {
  21926. if (der->length <= (word32)buffSz) {
  21927. XMEMCPY(buff, der->buffer, der->length);
  21928. ret = (int)der->length;
  21929. }
  21930. else {
  21931. WOLFSSL_MSG("Bad der length");
  21932. ret = BAD_FUNC_ARG;
  21933. }
  21934. }
  21935. FreeDer(&der);
  21936. return ret;
  21937. }
  21938. #endif /* WOLFSSL_PEM_TO_DER */
  21939. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  21940. #ifdef WOLFSSL_PEM_TO_DER
  21941. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  21942. /* Return bytes written to buff, needed buff size if buff is NULL, or less than
  21943. zero for error */
  21944. int wc_PubKeyPemToDer(const unsigned char* pem, int pemSz,
  21945. unsigned char* buff, int buffSz)
  21946. {
  21947. int ret;
  21948. DerBuffer* der = NULL;
  21949. WOLFSSL_ENTER("wc_PubKeyPemToDer");
  21950. if (pem == NULL || (buff != NULL && buffSz <= 0)) {
  21951. WOLFSSL_MSG("Bad pem der args");
  21952. return BAD_FUNC_ARG;
  21953. }
  21954. ret = PemToDer(pem, pemSz, PUBLICKEY_TYPE, &der, NULL, NULL, NULL);
  21955. if (ret < 0 || der == NULL) {
  21956. WOLFSSL_MSG("Bad Pem To Der");
  21957. }
  21958. else if (buff == NULL) {
  21959. WOLFSSL_MSG("Return needed der buff length");
  21960. ret = (int)der->length;
  21961. }
  21962. else if (der->length <= (word32)buffSz) {
  21963. XMEMCPY(buff, der->buffer, der->length);
  21964. ret = (int)der->length;
  21965. }
  21966. else {
  21967. WOLFSSL_MSG("Bad der length");
  21968. ret = BAD_FUNC_ARG;
  21969. }
  21970. FreeDer(&der);
  21971. return ret;
  21972. }
  21973. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  21974. #endif /* WOLFSSL_PEM_TO_DER */
  21975. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_PEM_TO_DER)
  21976. #ifdef WOLFSSL_CERT_GEN
  21977. int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der)
  21978. {
  21979. #ifndef WOLFSSL_SMALL_STACK
  21980. byte staticBuffer[FILE_BUFFER_SIZE];
  21981. #endif
  21982. byte* fileBuf = NULL;
  21983. int ret = 0;
  21984. XFILE file = XBADFILE;
  21985. int dynamic = 0;
  21986. long sz = 0;
  21987. WOLFSSL_ENTER("wc_PemCertToDer");
  21988. if (fileName == NULL) {
  21989. ret = BAD_FUNC_ARG;
  21990. }
  21991. else {
  21992. file = XFOPEN(fileName, "rb");
  21993. if (file == XBADFILE) {
  21994. ret = IO_FAILED_E;
  21995. }
  21996. }
  21997. if (ret == 0) {
  21998. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  21999. ret = IO_FAILED_E;
  22000. }
  22001. }
  22002. if (ret == 0) {
  22003. sz = XFTELL(file);
  22004. if (sz <= 0) {
  22005. ret = IO_FAILED_E;
  22006. }
  22007. }
  22008. if (ret == 0) {
  22009. if (XFSEEK(file, 0, XSEEK_SET) != 0) {
  22010. ret = IO_FAILED_E;
  22011. }
  22012. }
  22013. if (ret == 0) {
  22014. #ifndef WOLFSSL_SMALL_STACK
  22015. if (sz <= (long)sizeof(staticBuffer))
  22016. fileBuf = staticBuffer;
  22017. else
  22018. #endif
  22019. {
  22020. fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
  22021. if (fileBuf == NULL)
  22022. ret = MEMORY_E;
  22023. else
  22024. dynamic = 1;
  22025. }
  22026. }
  22027. if (ret == 0) {
  22028. if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
  22029. ret = IO_FAILED_E;
  22030. }
  22031. else {
  22032. ret = PemToDer(fileBuf, sz, CA_TYPE, der, 0, NULL,NULL);
  22033. }
  22034. }
  22035. if (file != XBADFILE)
  22036. XFCLOSE(file);
  22037. if (dynamic)
  22038. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  22039. return ret;
  22040. }
  22041. /* load pem cert from file into der buffer, return der size or error */
  22042. int wc_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz)
  22043. {
  22044. int ret;
  22045. DerBuffer* converted = NULL;
  22046. ret = wc_PemCertToDer_ex(fileName, &converted);
  22047. if (ret == 0) {
  22048. if (converted->length < (word32)derSz) {
  22049. XMEMCPY(derBuf, converted->buffer, converted->length);
  22050. ret = (int)converted->length;
  22051. }
  22052. else
  22053. ret = BUFFER_E;
  22054. FreeDer(&converted);
  22055. }
  22056. return ret;
  22057. }
  22058. #endif /* WOLFSSL_CERT_GEN */
  22059. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  22060. /* load pem public key from file into der buffer, return der size or error */
  22061. int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der)
  22062. {
  22063. #ifndef WOLFSSL_SMALL_STACK
  22064. byte staticBuffer[FILE_BUFFER_SIZE];
  22065. #endif
  22066. byte* fileBuf = NULL;
  22067. int dynamic = 0;
  22068. int ret = 0;
  22069. long sz = 0;
  22070. XFILE file = XBADFILE;
  22071. WOLFSSL_ENTER("wc_PemPubKeyToDer");
  22072. if (fileName == NULL) {
  22073. ret = BAD_FUNC_ARG;
  22074. }
  22075. else {
  22076. file = XFOPEN(fileName, "rb");
  22077. if (file == XBADFILE) {
  22078. ret = IO_FAILED_E;
  22079. }
  22080. }
  22081. if (ret == 0) {
  22082. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  22083. ret = IO_FAILED_E;
  22084. }
  22085. }
  22086. if (ret == 0) {
  22087. sz = XFTELL(file);
  22088. if (sz <= 0) {
  22089. ret = IO_FAILED_E;
  22090. }
  22091. }
  22092. if (ret == 0) {
  22093. if (XFSEEK(file, 0, XSEEK_SET) != 0) {
  22094. ret = IO_FAILED_E;
  22095. }
  22096. }
  22097. if (ret == 0) {
  22098. #ifndef WOLFSSL_SMALL_STACK
  22099. if (sz <= (long)sizeof(staticBuffer))
  22100. fileBuf = staticBuffer;
  22101. else
  22102. #endif
  22103. {
  22104. fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
  22105. if (fileBuf == NULL)
  22106. ret = MEMORY_E;
  22107. else
  22108. dynamic = 1;
  22109. }
  22110. }
  22111. if (ret == 0) {
  22112. if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
  22113. ret = BUFFER_E;
  22114. }
  22115. else {
  22116. ret = PemToDer(fileBuf, sz, PUBLICKEY_TYPE, der,
  22117. 0, NULL, NULL);
  22118. }
  22119. }
  22120. if (file != XBADFILE)
  22121. XFCLOSE(file);
  22122. if (dynamic)
  22123. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  22124. return ret;
  22125. }
  22126. /* load pem public key from file into der buffer, return der size or error */
  22127. int wc_PemPubKeyToDer(const char* fileName,
  22128. unsigned char* derBuf, int derSz)
  22129. {
  22130. int ret;
  22131. DerBuffer* converted = NULL;
  22132. ret = wc_PemPubKeyToDer_ex(fileName, &converted);
  22133. if (ret == 0) {
  22134. if (converted->length < (word32)derSz) {
  22135. XMEMCPY(derBuf, converted->buffer, converted->length);
  22136. ret = (int)converted->length;
  22137. }
  22138. else
  22139. ret = BUFFER_E;
  22140. FreeDer(&converted);
  22141. }
  22142. return ret;
  22143. }
  22144. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  22145. #endif /* !NO_FILESYSTEM && WOLFSSL_PEM_TO_DER */
  22146. /* Get public key in DER format from a populated DecodedCert struct.
  22147. *
  22148. * Users must call wc_InitDecodedCert() and wc_ParseCert() before calling
  22149. * this API. wc_InitDecodedCert() accepts a DER/ASN.1 encoded certificate.
  22150. * To convert a PEM cert to DER first use wc_CertPemToDer() before calling
  22151. * wc_InitDecodedCert().
  22152. *
  22153. * cert - populated DecodedCert struct holding X.509 certificate
  22154. * derKey - output buffer to place DER/ASN.1 encoded public key
  22155. * derKeySz [IN/OUT] - size of derKey buffer on input, size of public key
  22156. * on return. If derKey is passed in as NULL, derKeySz
  22157. * will be set to required buffer size for public key
  22158. * and LENGTH_ONLY_E will be returned from function.
  22159. * Returns 0 on success, or negative error code on failure. LENGTH_ONLY_E
  22160. * if derKey is NULL and returning length only.
  22161. */
  22162. int wc_GetPubKeyDerFromCert(struct DecodedCert* cert,
  22163. byte* derKey, word32* derKeySz)
  22164. {
  22165. int ret = 0;
  22166. /* derKey may be NULL to return length only */
  22167. if (cert == NULL || derKeySz == NULL ||
  22168. (derKey != NULL && *derKeySz == 0)) {
  22169. return BAD_FUNC_ARG;
  22170. }
  22171. if (cert->publicKey == NULL) {
  22172. WOLFSSL_MSG("DecodedCert does not contain public key\n");
  22173. return BAD_FUNC_ARG;
  22174. }
  22175. /* if derKey is NULL, return required output buffer size in derKeySz */
  22176. if (derKey == NULL) {
  22177. *derKeySz = cert->pubKeySize;
  22178. ret = LENGTH_ONLY_E;
  22179. }
  22180. if (ret == 0) {
  22181. if (cert->pubKeySize > *derKeySz) {
  22182. WOLFSSL_MSG("Output buffer not large enough for public key DER");
  22183. ret = BAD_FUNC_ARG;
  22184. }
  22185. else {
  22186. XMEMCPY(derKey, cert->publicKey, cert->pubKeySize);
  22187. *derKeySz = cert->pubKeySize;
  22188. }
  22189. }
  22190. return ret;
  22191. }
  22192. #ifdef WOLFSSL_FPKI
  22193. /* Search through list for first matching alt name of the same type
  22194. * If 'current' is null then the search starts at the head of the list
  22195. * otherwise the search starts from the node after 'current' alt name.
  22196. * Returns 0 on success
  22197. */
  22198. static DNS_entry* FindAltName(struct DecodedCert* cert, int nameType,
  22199. DNS_entry* current)
  22200. {
  22201. DNS_entry* entry;
  22202. if (current == NULL) {
  22203. entry = cert->altNames;
  22204. }
  22205. else {
  22206. entry = current->next;
  22207. }
  22208. /* cycle through alt names to check for needed types */
  22209. while (entry != NULL) {
  22210. if (entry->type == nameType) {
  22211. break;
  22212. }
  22213. entry = entry->next;
  22214. }
  22215. return entry;
  22216. }
  22217. /* returns 0 on success */
  22218. int wc_GetUUIDFromCert(struct DecodedCert* cert, byte* uuid, word32* uuidSz)
  22219. {
  22220. int ret = ALT_NAME_E;
  22221. DNS_entry* id = NULL;
  22222. do {
  22223. id = FindAltName(cert, ASN_URI_TYPE, id);
  22224. if (id != NULL) {
  22225. /* check if URI string matches expected format for UUID */
  22226. if (id->len != DEFAULT_UUID_SZ) {
  22227. continue; /* size not right not a UUID URI */
  22228. }
  22229. if (XMEMCMP(id->name, "urn:uuid:", 9) != 0) {
  22230. continue; /* beginning text not right for a UUID URI */
  22231. }
  22232. if (uuid == NULL) {
  22233. *uuidSz = id->len;
  22234. return LENGTH_ONLY_E;
  22235. }
  22236. if ((int)*uuidSz < id->len) {
  22237. return BUFFER_E;
  22238. }
  22239. XMEMCPY(uuid, id->name, id->len);
  22240. ret = 0; /* success */
  22241. break;
  22242. }
  22243. } while (id != NULL);
  22244. return ret;
  22245. }
  22246. /* returns 0 on success */
  22247. int wc_GetFASCNFromCert(struct DecodedCert* cert, byte* fascn, word32* fascnSz)
  22248. {
  22249. int ret = ALT_NAME_E;
  22250. DNS_entry* id = NULL;
  22251. do {
  22252. id = FindAltName(cert, ASN_OTHER_TYPE, id);
  22253. if (id != NULL && id->oidSum == FASCN_OID) {
  22254. if (fascn == NULL) {
  22255. *fascnSz = id->len;
  22256. return LENGTH_ONLY_E;
  22257. }
  22258. if ((int)*fascnSz < id->len) {
  22259. return BUFFER_E;
  22260. }
  22261. XMEMCPY(fascn, id->name, id->len);
  22262. ret = 0; /* success */
  22263. }
  22264. } while (id != NULL);
  22265. return ret;
  22266. }
  22267. #endif /* WOLFSSL_FPKI */
  22268. #if !defined(NO_RSA) && (defined(WOLFSSL_CERT_GEN) || \
  22269. defined(WOLFSSL_KCAPI_RSA) || \
  22270. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA)))
  22271. /* USER RSA ifdef portions used instead of refactor in consideration for
  22272. possible fips build */
  22273. /* Encode a public RSA key to output.
  22274. *
  22275. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  22276. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  22277. *
  22278. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  22279. * (RSAPublicKey).
  22280. *
  22281. * @param [out] output Buffer to put encoded data in.
  22282. * @param [in] key RSA key object.
  22283. * @param [in] outLen Size of the output buffer in bytes.
  22284. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  22285. * @return Size of encoded data in bytes on success.
  22286. * @return BAD_FUNC_ARG when output or key is NULL, or outLen is less than
  22287. * minimum length (5 bytes).
  22288. * @return MEMORY_E when dynamic memory allocation failed.
  22289. */
  22290. static int SetRsaPublicKey(byte* output, RsaKey* key, int outLen,
  22291. int with_header)
  22292. {
  22293. #ifndef WOLFSSL_ASN_TEMPLATE
  22294. int nSz, eSz;
  22295. word32 seqSz, algoSz = 0, headSz = 0, bitStringSz = 0, idx;
  22296. byte seq[MAX_SEQ_SZ];
  22297. byte headSeq[MAX_SEQ_SZ];
  22298. byte bitString[1 + MAX_LENGTH_SZ + 1];
  22299. byte algo[MAX_ALGO_SZ]; /* 20 bytes */
  22300. if (key == NULL) {
  22301. return BAD_FUNC_ARG;
  22302. }
  22303. #ifdef HAVE_USER_RSA
  22304. nSz = SetASNIntRSA(key->n, NULL);
  22305. #else
  22306. nSz = SetASNIntMP(&key->n, MAX_RSA_INT_SZ, NULL);
  22307. #endif
  22308. if (nSz < 0)
  22309. return nSz;
  22310. #ifdef HAVE_USER_RSA
  22311. eSz = SetASNIntRSA(key->e, NULL);
  22312. #else
  22313. eSz = SetASNIntMP(&key->e, MAX_RSA_INT_SZ, NULL);
  22314. #endif
  22315. if (eSz < 0)
  22316. return eSz;
  22317. seqSz = SetSequence((word32)(nSz + eSz), seq);
  22318. /* headers */
  22319. if (with_header) {
  22320. algoSz = SetAlgoID(RSAk, algo, oidKeyType, 0);
  22321. bitStringSz = SetBitString(seqSz + (word32)(nSz + eSz), 0, bitString);
  22322. headSz = SetSequence((word32)(nSz + eSz) + seqSz + bitStringSz + algoSz,
  22323. headSeq);
  22324. }
  22325. /* if getting length only */
  22326. if (output == NULL) {
  22327. return (int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz;
  22328. }
  22329. /* check output size */
  22330. if (((int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz) > outLen) {
  22331. return BUFFER_E;
  22332. }
  22333. /* write output */
  22334. idx = 0;
  22335. if (with_header) {
  22336. /* header size */
  22337. XMEMCPY(output + idx, headSeq, headSz);
  22338. idx += headSz;
  22339. /* algo */
  22340. XMEMCPY(output + idx, algo, algoSz);
  22341. idx += algoSz;
  22342. /* bit string */
  22343. XMEMCPY(output + idx, bitString, bitStringSz);
  22344. idx += bitStringSz;
  22345. }
  22346. /* seq */
  22347. XMEMCPY(output + idx, seq, seqSz);
  22348. idx += seqSz;
  22349. /* n */
  22350. #ifdef HAVE_USER_RSA
  22351. nSz = SetASNIntRSA(key->n, output + idx);
  22352. #else
  22353. nSz = SetASNIntMP(&key->n, nSz, output + idx);
  22354. #endif
  22355. idx += (word32)nSz;
  22356. /* e */
  22357. #ifdef HAVE_USER_RSA
  22358. eSz = SetASNIntRSA(key->e, output + idx);
  22359. #else
  22360. eSz = SetASNIntMP(&key->e, eSz, output + idx);
  22361. #endif
  22362. idx += (word32)eSz;
  22363. return (int)idx;
  22364. #else
  22365. DECL_ASNSETDATA(dataASN, rsaPublicKeyASN_Length);
  22366. int sz = 0;
  22367. int ret = 0;
  22368. int o = 0;
  22369. /* Check parameter validity. */
  22370. if ((key == NULL) || ((output != NULL) && (outLen < MAX_SEQ_SZ))) {
  22371. ret = BAD_FUNC_ARG;
  22372. }
  22373. CALLOC_ASNSETDATA(dataASN, rsaPublicKeyASN_Length, ret, key->heap);
  22374. if (ret == 0) {
  22375. if (!with_header) {
  22376. /* Start encoding with items after header. */
  22377. o = RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ;
  22378. }
  22379. /* Set OID for RSA key. */
  22380. SetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], RSAk, oidKeyType);
  22381. #ifdef WC_RSA_PSS
  22382. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].noOut = 1;
  22383. #endif
  22384. /* Set public key mp_ints. */
  22385. #ifdef HAVE_USER_RSA
  22386. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], key->n);
  22387. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], key->e);
  22388. #else
  22389. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], &key->n);
  22390. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], &key->e);
  22391. #endif
  22392. /* Calculate size of RSA public key. */
  22393. ret = SizeASN_Items(rsaPublicKeyASN + o, dataASN + o,
  22394. (int)rsaPublicKeyASN_Length - o, &sz);
  22395. }
  22396. /* Check output buffer is big enough for encoding. */
  22397. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  22398. ret = BUFFER_E;
  22399. }
  22400. if ((ret == 0) && (output != NULL)) {
  22401. /* Encode RSA public key. */
  22402. SetASN_Items(rsaPublicKeyASN + o, dataASN + o,
  22403. (int)rsaPublicKeyASN_Length - o, output);
  22404. }
  22405. if (ret == 0) {
  22406. /* Return size of encoding. */
  22407. ret = sz;
  22408. }
  22409. FREE_ASNSETDATA(dataASN, key->heap);
  22410. return ret;
  22411. #endif /* WOLFSSL_ASN_TEMPLATE */
  22412. }
  22413. /* Calculate size of encoded public RSA key in bytes.
  22414. *
  22415. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  22416. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  22417. *
  22418. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  22419. * (RSAPublicKey).
  22420. *
  22421. * @param [in] key RSA key object.
  22422. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  22423. * @return Size of encoded data in bytes on success.
  22424. * @return BAD_FUNC_ARG when key is NULL.
  22425. * @return MEMORY_E when dynamic memory allocation failed.
  22426. */
  22427. int wc_RsaPublicKeyDerSize(RsaKey* key, int with_header)
  22428. {
  22429. return SetRsaPublicKey(NULL, key, 0, with_header);
  22430. }
  22431. /* Encode public RSA key in DER format.
  22432. *
  22433. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  22434. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  22435. *
  22436. * @param [in] key RSA key object.
  22437. * @param [out] output Buffer to put encoded data in.
  22438. * @param [in] inLen Size of buffer in bytes.
  22439. * @return Size of encoded data in bytes on success.
  22440. * @return BAD_FUNC_ARG when key or output is NULL.
  22441. * @return MEMORY_E when dynamic memory allocation failed.
  22442. */
  22443. int wc_RsaKeyToPublicDer(RsaKey* key, byte* output, word32 inLen)
  22444. {
  22445. return SetRsaPublicKey(output, key, (int)inLen, 1);
  22446. }
  22447. /* Returns public DER version of the RSA key. If with_header is 0 then only a
  22448. * seq + n + e is returned in ASN.1 DER format */
  22449. int wc_RsaKeyToPublicDer_ex(RsaKey* key, byte* output, word32 inLen,
  22450. int with_header)
  22451. {
  22452. return SetRsaPublicKey(output, key, (int)inLen, with_header);
  22453. }
  22454. #endif /* !NO_RSA && (WOLFSSL_CERT_GEN || WOLFSSL_KCAPI_RSA ||
  22455. ((OPENSSL_EXTRA || WOLFSSL_KEY_GEN) && !HAVE_USER_RSA))) */
  22456. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  22457. defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)) && \
  22458. !defined(NO_RSA) && !defined(HAVE_USER_RSA)
  22459. /* Encode private RSA key in DER format.
  22460. *
  22461. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  22462. *
  22463. * @param [in] key RSA key object.
  22464. * @param [out] output Buffer to put encoded data in.
  22465. * @param [in] inLen Size of buffer in bytes.
  22466. * @return Size of encoded data in bytes on success.
  22467. * @return BAD_FUNC_ARG when key is NULL or not a private key.
  22468. * @return MEMORY_E when dynamic memory allocation failed.
  22469. */
  22470. int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
  22471. {
  22472. #ifndef WOLFSSL_ASN_TEMPLATE
  22473. int ret = 0, i;
  22474. word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen = 0;
  22475. word32 sizes[RSA_INTS];
  22476. byte seq[MAX_SEQ_SZ];
  22477. byte ver[MAX_VERSION_SZ];
  22478. byte* tmps[RSA_INTS];
  22479. if (key == NULL)
  22480. return BAD_FUNC_ARG;
  22481. if (key->type != RSA_PRIVATE)
  22482. return BAD_FUNC_ARG;
  22483. for (i = 0; i < RSA_INTS; i++)
  22484. tmps[i] = NULL;
  22485. /* write all big ints from key to DER tmps */
  22486. for (i = 0; i < RSA_INTS; i++) {
  22487. mp_int* keyInt = GetRsaInt(key, i);
  22488. int mpSz;
  22489. word32 rawLen;
  22490. ret = mp_unsigned_bin_size(keyInt);
  22491. if (ret < 0)
  22492. return ret;
  22493. rawLen = (word32)ret + 1;
  22494. ret = 0;
  22495. if (output != NULL) {
  22496. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  22497. DYNAMIC_TYPE_RSA);
  22498. if (tmps[i] == NULL) {
  22499. ret = MEMORY_E;
  22500. break;
  22501. }
  22502. }
  22503. mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, tmps[i]);
  22504. if (mpSz < 0) {
  22505. ret = mpSz;
  22506. break;
  22507. }
  22508. sizes[i] = (word32)mpSz;
  22509. intTotalLen += (word32)mpSz;
  22510. }
  22511. if (ret == 0) {
  22512. /* make headers */
  22513. ret = SetMyVersion(0, ver, FALSE);
  22514. }
  22515. if (ret >= 0) {
  22516. verSz = (word32)ret;
  22517. ret = 0;
  22518. seqSz = SetSequence(verSz + intTotalLen, seq);
  22519. outLen = seqSz + verSz + intTotalLen;
  22520. if (output != NULL && outLen > inLen)
  22521. ret = BUFFER_E;
  22522. }
  22523. if (ret == 0 && output != NULL) {
  22524. word32 j;
  22525. /* write to output */
  22526. XMEMCPY(output, seq, seqSz);
  22527. j = seqSz;
  22528. XMEMCPY(output + j, ver, verSz);
  22529. j += verSz;
  22530. for (i = 0; i < RSA_INTS; i++) {
  22531. XMEMCPY(output + j, tmps[i], sizes[i]);
  22532. j += sizes[i];
  22533. }
  22534. }
  22535. for (i = 0; i < RSA_INTS; i++) {
  22536. if (tmps[i])
  22537. XFREE(tmps[i], key->heap, DYNAMIC_TYPE_RSA);
  22538. }
  22539. if (ret == 0)
  22540. ret = (int)outLen;
  22541. return ret;
  22542. #else
  22543. DECL_ASNSETDATA(dataASN, rsaKeyASN_Length);
  22544. int i;
  22545. int sz = 0;
  22546. int ret = 0;
  22547. if ((key == NULL) || (key->type != RSA_PRIVATE)) {
  22548. ret = BAD_FUNC_ARG;
  22549. }
  22550. CALLOC_ASNSETDATA(dataASN, rsaKeyASN_Length, ret, key->heap);
  22551. if (ret == 0) {
  22552. /* Set the version. */
  22553. SetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], 0);
  22554. /* Set all the mp_ints in private key. */
  22555. for (i = 0; i < RSA_INTS; i++) {
  22556. SetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i], GetRsaInt(key, i));
  22557. }
  22558. /* Calculate size of RSA private key encoding. */
  22559. ret = SizeASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, &sz);
  22560. }
  22561. /* Check output buffer has enough space for encoding. */
  22562. if ((ret == 0) && (output != NULL) && (sz > (int)inLen)) {
  22563. ret = BAD_FUNC_ARG;
  22564. }
  22565. if ((ret == 0) && (output != NULL)) {
  22566. /* Encode RSA private key. */
  22567. SetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, output);
  22568. }
  22569. if (ret == 0) {
  22570. /* Return size of encoding. */
  22571. ret = sz;
  22572. }
  22573. FREE_ASNSETDATA(dataASN, key->heap);
  22574. return ret;
  22575. #endif
  22576. }
  22577. #endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA && !HAVE_USER_RSA */
  22578. #ifdef WOLFSSL_CERT_GEN
  22579. /* Initialize and Set Certificate defaults:
  22580. version = 3 (0x2)
  22581. serial = 0
  22582. sigType = SHA_WITH_RSA
  22583. issuer = blank
  22584. daysValid = 500
  22585. selfSigned = 1 (true) use subject as issuer
  22586. subject = blank
  22587. */
  22588. int wc_InitCert_ex(Cert* cert, void* heap, int devId)
  22589. {
  22590. #ifdef WOLFSSL_MULTI_ATTRIB
  22591. int i = 0;
  22592. #endif
  22593. if (cert == NULL) {
  22594. return BAD_FUNC_ARG;
  22595. }
  22596. XMEMSET(cert, 0, sizeof(Cert));
  22597. cert->version = 2; /* version 3 is hex 2 */
  22598. #ifndef NO_SHA
  22599. cert->sigType = CTC_SHAwRSA;
  22600. #elif !defined(NO_SHA256)
  22601. cert->sigType = CTC_SHA256wRSA;
  22602. #else
  22603. cert->sigType = 0;
  22604. #endif
  22605. cert->daysValid = 500;
  22606. cert->selfSigned = 1;
  22607. cert->keyType = RSA_KEY;
  22608. cert->issuer.countryEnc = CTC_PRINTABLE;
  22609. cert->issuer.stateEnc = CTC_UTF8;
  22610. cert->issuer.streetEnc = CTC_UTF8;
  22611. cert->issuer.localityEnc = CTC_UTF8;
  22612. cert->issuer.surEnc = CTC_UTF8;
  22613. #ifdef WOLFSSL_CERT_NAME_ALL
  22614. cert->issuer.givenNameEnc = CTC_UTF8;
  22615. cert->issuer.initialsEnc = CTC_UTF8;
  22616. cert->issuer.dnQualifierEnc = CTC_UTF8;
  22617. cert->issuer.dnNameEnc = CTC_UTF8;
  22618. #endif
  22619. cert->issuer.orgEnc = CTC_UTF8;
  22620. cert->issuer.unitEnc = CTC_UTF8;
  22621. cert->issuer.commonNameEnc = CTC_UTF8;
  22622. cert->issuer.serialDevEnc = CTC_PRINTABLE;
  22623. cert->issuer.userIdEnc = CTC_UTF8;
  22624. cert->issuer.postalCodeEnc = CTC_UTF8;
  22625. #ifdef WOLFSSL_CERT_EXT
  22626. cert->issuer.busCatEnc = CTC_UTF8;
  22627. cert->issuer.joiCEnc = CTC_UTF8;
  22628. cert->issuer.joiStEnc = CTC_UTF8;
  22629. #endif
  22630. cert->subject.countryEnc = CTC_PRINTABLE;
  22631. cert->subject.stateEnc = CTC_UTF8;
  22632. cert->subject.streetEnc = CTC_UTF8;
  22633. cert->subject.localityEnc = CTC_UTF8;
  22634. cert->subject.surEnc = CTC_UTF8;
  22635. #ifdef WOLFSSL_CERT_NAME_ALL
  22636. cert->subject.givenNameEnc = CTC_UTF8;
  22637. cert->subject.initialsEnc = CTC_UTF8;
  22638. cert->subject.dnQualifierEnc = CTC_UTF8;
  22639. cert->subject.dnNameEnc = CTC_UTF8;
  22640. #endif
  22641. cert->subject.orgEnc = CTC_UTF8;
  22642. cert->subject.unitEnc = CTC_UTF8;
  22643. cert->subject.commonNameEnc = CTC_UTF8;
  22644. cert->subject.serialDevEnc = CTC_PRINTABLE;
  22645. cert->subject.userIdEnc = CTC_UTF8;
  22646. cert->subject.postalCodeEnc = CTC_UTF8;
  22647. #ifdef WOLFSSL_CERT_EXT
  22648. cert->subject.busCatEnc = CTC_UTF8;
  22649. cert->subject.joiCEnc = CTC_UTF8;
  22650. cert->subject.joiStEnc = CTC_UTF8;
  22651. #endif
  22652. #ifdef WOLFSSL_MULTI_ATTRIB
  22653. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  22654. cert->issuer.name[i].type = CTC_UTF8;
  22655. cert->subject.name[i].type = CTC_UTF8;
  22656. }
  22657. #endif /* WOLFSSL_MULTI_ATTRIB */
  22658. cert->heap = heap;
  22659. (void)devId; /* future */
  22660. return 0;
  22661. }
  22662. WOLFSSL_ABI
  22663. int wc_InitCert(Cert* cert)
  22664. {
  22665. return wc_InitCert_ex(cert, NULL, INVALID_DEVID);
  22666. }
  22667. WOLFSSL_ABI
  22668. Cert* wc_CertNew(void* heap)
  22669. {
  22670. Cert* certNew;
  22671. certNew = (Cert*)XMALLOC(sizeof(Cert), heap, DYNAMIC_TYPE_CERT);
  22672. if (certNew) {
  22673. if (wc_InitCert_ex(certNew, heap, INVALID_DEVID) != 0) {
  22674. XFREE(certNew, heap, DYNAMIC_TYPE_CERT);
  22675. certNew = NULL;
  22676. }
  22677. }
  22678. return certNew;
  22679. }
  22680. WOLFSSL_ABI
  22681. void wc_CertFree(Cert* cert)
  22682. {
  22683. if (cert) {
  22684. void* heap = cert->heap;
  22685. ForceZero(cert, sizeof(Cert));
  22686. XFREE(cert, heap, DYNAMIC_TYPE_CERT);
  22687. (void)heap;
  22688. }
  22689. }
  22690. /* DER encoded x509 Certificate */
  22691. typedef struct DerCert {
  22692. byte size[MAX_LENGTH_SZ]; /* length encoded */
  22693. byte version[MAX_VERSION_SZ]; /* version encoded */
  22694. byte serial[(int)CTC_SERIAL_SIZE + (int)MAX_LENGTH_SZ]; /* serial number encoded */
  22695. byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
  22696. byte issuer[WC_ASN_NAME_MAX]; /* issuer encoded */
  22697. byte subject[WC_ASN_NAME_MAX]; /* subject encoded */
  22698. byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
  22699. byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa public key encoded */
  22700. byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
  22701. byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
  22702. #ifdef WOLFSSL_CERT_EXT
  22703. byte skid[MAX_KID_SZ]; /* Subject Key Identifier extension */
  22704. byte akid[MAX_KID_SZ
  22705. #ifdef WOLFSSL_AKID_NAME
  22706. + sizeof(CertName) + CTC_SERIAL_SIZE
  22707. #endif
  22708. ]; /* Authority Key Identifier extension */
  22709. byte keyUsage[MAX_KEYUSAGE_SZ]; /* Key Usage extension */
  22710. byte extKeyUsage[MAX_EXTKEYUSAGE_SZ]; /* Extended Key Usage extension */
  22711. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  22712. byte nsCertType[MAX_NSCERTTYPE_SZ]; /* Extended Key Usage extension */
  22713. #endif
  22714. byte certPolicies[MAX_CERTPOL_NB*MAX_CERTPOL_SZ]; /* Certificate Policies */
  22715. byte crlInfo[CTC_MAX_CRLINFO_SZ]; /* CRL Distribution Points */
  22716. #endif
  22717. #ifdef WOLFSSL_CERT_REQ
  22718. byte attrib[MAX_ATTRIB_SZ]; /* Cert req attributes encoded */
  22719. #ifdef WOLFSSL_CUSTOM_OID
  22720. byte extCustom[MAX_ATTRIB_SZ]; /* Encoded user oid and value */
  22721. #endif
  22722. #endif
  22723. #ifdef WOLFSSL_ALT_NAMES
  22724. byte altNames[CTC_MAX_ALT_SIZE]; /* Alternative Names encoded */
  22725. #endif
  22726. int sizeSz; /* encoded size length */
  22727. int versionSz; /* encoded version length */
  22728. int serialSz; /* encoded serial length */
  22729. int sigAlgoSz; /* encoded sig algo length */
  22730. int issuerSz; /* encoded issuer length */
  22731. int subjectSz; /* encoded subject length */
  22732. int validitySz; /* encoded validity length */
  22733. int publicKeySz; /* encoded public key length */
  22734. int caSz; /* encoded CA extension length */
  22735. #ifdef WOLFSSL_CERT_EXT
  22736. int skidSz; /* encoded SKID extension length */
  22737. int akidSz; /* encoded SKID extension length */
  22738. int keyUsageSz; /* encoded KeyUsage extension length */
  22739. int extKeyUsageSz; /* encoded ExtendedKeyUsage extension length */
  22740. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  22741. int nsCertTypeSz; /* encoded Netscape Certificate Type
  22742. * extension length */
  22743. #endif
  22744. int certPoliciesSz; /* encoded CertPolicies extension length*/
  22745. int crlInfoSz; /* encoded CRL Dist Points length */
  22746. #endif
  22747. #ifdef WOLFSSL_ALT_NAMES
  22748. int altNamesSz; /* encoded AltNames extension length */
  22749. #endif
  22750. int extensionsSz; /* encoded extensions total length */
  22751. int total; /* total encoded lengths */
  22752. #ifdef WOLFSSL_CERT_REQ
  22753. int attribSz;
  22754. #ifdef WOLFSSL_CUSTOM_OID
  22755. int extCustomSz;
  22756. #endif
  22757. #endif
  22758. } DerCert;
  22759. #ifdef WOLFSSL_CERT_REQ
  22760. #ifndef WOLFSSL_ASN_TEMPLATE
  22761. /* Write a set header to output */
  22762. static word32 SetPrintableString(word32 len, byte* output)
  22763. {
  22764. output[0] = ASN_PRINTABLE_STRING;
  22765. return SetLength(len, output + 1) + 1;
  22766. }
  22767. static word32 SetUTF8String(word32 len, byte* output)
  22768. {
  22769. output[0] = ASN_UTF8STRING;
  22770. return SetLength(len, output + 1) + 1;
  22771. }
  22772. #endif
  22773. #endif /* WOLFSSL_CERT_REQ */
  22774. #ifndef WOLFSSL_CERT_GEN_CACHE
  22775. /* wc_SetCert_Free is only public when WOLFSSL_CERT_GEN_CACHE is not defined */
  22776. static
  22777. #endif
  22778. WOLFSSL_ABI
  22779. void wc_SetCert_Free(Cert* cert)
  22780. {
  22781. if (cert != NULL) {
  22782. cert->der = NULL;
  22783. if (cert->decodedCert) {
  22784. FreeDecodedCert((DecodedCert*)cert->decodedCert);
  22785. XFREE(cert->decodedCert, cert->heap, DYNAMIC_TYPE_DCERT);
  22786. cert->decodedCert = NULL;
  22787. }
  22788. }
  22789. }
  22790. static int wc_SetCert_LoadDer(Cert* cert, const byte* der, word32 derSz,
  22791. int devId)
  22792. {
  22793. int ret;
  22794. if (cert == NULL) {
  22795. ret = BAD_FUNC_ARG;
  22796. }
  22797. else {
  22798. /* Allocate DecodedCert struct and Zero */
  22799. cert->decodedCert = (void*)XMALLOC(sizeof(DecodedCert), cert->heap,
  22800. DYNAMIC_TYPE_DCERT);
  22801. if (cert->decodedCert == NULL) {
  22802. ret = MEMORY_E;
  22803. }
  22804. else {
  22805. XMEMSET(cert->decodedCert, 0, sizeof(DecodedCert));
  22806. InitDecodedCert_ex((DecodedCert*)cert->decodedCert, der, derSz,
  22807. cert->heap, devId);
  22808. ret = ParseCertRelative((DecodedCert*)cert->decodedCert,
  22809. CERT_TYPE, 0, NULL);
  22810. if (ret >= 0) {
  22811. cert->der = (byte*)der;
  22812. }
  22813. else {
  22814. wc_SetCert_Free(cert);
  22815. }
  22816. }
  22817. }
  22818. return ret;
  22819. }
  22820. #endif /* WOLFSSL_CERT_GEN */
  22821. #ifdef WOLFSSL_CERT_GEN
  22822. #ifndef NO_ASN_TIME
  22823. static WC_INLINE byte itob(int number)
  22824. {
  22825. return (byte)number + 0x30;
  22826. }
  22827. /* write time to output, format */
  22828. static void SetTime(struct tm* date, byte* output)
  22829. {
  22830. int i = 0;
  22831. output[i++] = itob((date->tm_year % 10000) / 1000);
  22832. output[i++] = itob((date->tm_year % 1000) / 100);
  22833. output[i++] = itob((date->tm_year % 100) / 10);
  22834. output[i++] = itob( date->tm_year % 10);
  22835. output[i++] = itob(date->tm_mon / 10);
  22836. output[i++] = itob(date->tm_mon % 10);
  22837. output[i++] = itob(date->tm_mday / 10);
  22838. output[i++] = itob(date->tm_mday % 10);
  22839. output[i++] = itob(date->tm_hour / 10);
  22840. output[i++] = itob(date->tm_hour % 10);
  22841. output[i++] = itob(date->tm_min / 10);
  22842. output[i++] = itob(date->tm_min % 10);
  22843. output[i++] = itob(date->tm_sec / 10);
  22844. output[i++] = itob(date->tm_sec % 10);
  22845. output[i] = 'Z'; /* Zulu profile */
  22846. }
  22847. #endif
  22848. #ifndef WOLFSSL_ASN_TEMPLATE
  22849. /* Copy Dates from cert, return bytes written */
  22850. static int CopyValidity(byte* output, Cert* cert)
  22851. {
  22852. word32 seqSz;
  22853. WOLFSSL_ENTER("CopyValidity");
  22854. /* headers and output */
  22855. seqSz = SetSequence((word32)(cert->beforeDateSz + cert->afterDateSz),
  22856. output);
  22857. if (output) {
  22858. XMEMCPY(output + seqSz, cert->beforeDate, (size_t)cert->beforeDateSz);
  22859. XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
  22860. (size_t)cert->afterDateSz);
  22861. }
  22862. return (int)seqSz + cert->beforeDateSz + cert->afterDateSz;
  22863. }
  22864. #endif /* !WOLFSSL_ASN_TEMPLATE */
  22865. /* Simple name OID size. */
  22866. #define NAME_OID_SZ 3
  22867. /* Domain name OIDs. */
  22868. static const byte nameOid[][NAME_OID_SZ] = {
  22869. { 0x55, 0x04, ASN_COUNTRY_NAME },
  22870. { 0x55, 0x04, ASN_STATE_NAME },
  22871. { 0x55, 0x04, ASN_STREET_ADDR },
  22872. { 0x55, 0x04, ASN_LOCALITY_NAME },
  22873. #ifdef WOLFSSL_CERT_NAME_ALL
  22874. { 0x55, 0x04, ASN_NAME },
  22875. { 0x55, 0x04, ASN_GIVEN_NAME },
  22876. { 0x55, 0x04, ASN_INITIALS },
  22877. { 0x55, 0x04, ASN_DNQUALIFIER },
  22878. #endif
  22879. { 0x55, 0x04, ASN_SUR_NAME },
  22880. { 0x55, 0x04, ASN_ORG_NAME },
  22881. { 0x00, 0x00, ASN_DOMAIN_COMPONENT}, /* not actual OID - see dcOid */
  22882. /* list all DC values before OUs */
  22883. { 0x55, 0x04, ASN_ORGUNIT_NAME },
  22884. { 0x55, 0x04, ASN_COMMON_NAME },
  22885. { 0x55, 0x04, ASN_SERIAL_NUMBER },
  22886. #ifdef WOLFSSL_CERT_EXT
  22887. { 0x55, 0x04, ASN_BUS_CAT },
  22888. #endif
  22889. { 0x55, 0x04, ASN_POSTAL_CODE },
  22890. { 0x00, 0x00, ASN_EMAIL_NAME}, /* not actual OID - see attrEmailOid */
  22891. { 0x00, 0x00, ASN_USER_ID}, /* not actual OID - see uidOid */
  22892. #ifdef WOLFSSL_CUSTOM_OID
  22893. { 0x00, 0x00, ASN_CUSTOM_NAME} /* OID comes from CertOidField */
  22894. #endif
  22895. };
  22896. #define NAME_ENTRIES (int)(sizeof(nameOid)/NAME_OID_SZ)
  22897. /* Get ASN Name from index */
  22898. byte GetCertNameId(int idx)
  22899. {
  22900. if (idx < NAME_ENTRIES)
  22901. return nameOid[idx][2];
  22902. return 0;
  22903. }
  22904. /* Get Which Name from index */
  22905. const char* GetOneCertName(CertName* name, int idx)
  22906. {
  22907. byte type = GetCertNameId(idx);
  22908. switch (type) {
  22909. case ASN_COUNTRY_NAME:
  22910. return name->country;
  22911. case ASN_STATE_NAME:
  22912. return name->state;
  22913. case ASN_STREET_ADDR:
  22914. return name->street;
  22915. case ASN_LOCALITY_NAME:
  22916. return name->locality;
  22917. #ifdef WOLFSSL_CERT_NAME_ALL
  22918. case ASN_NAME:
  22919. return name->dnName;
  22920. case ASN_GIVEN_NAME:
  22921. return name->givenName;
  22922. case ASN_INITIALS:
  22923. return name->initials;
  22924. case ASN_DNQUALIFIER:
  22925. return name->dnQualifier;
  22926. #endif /* WOLFSSL_CERT_NAME_ALL */
  22927. case ASN_SUR_NAME:
  22928. return name->sur;
  22929. case ASN_ORG_NAME:
  22930. return name->org;
  22931. case ASN_ORGUNIT_NAME:
  22932. return name->unit;
  22933. case ASN_COMMON_NAME:
  22934. return name->commonName;
  22935. case ASN_SERIAL_NUMBER:
  22936. return name->serialDev;
  22937. case ASN_USER_ID:
  22938. return name->userId;
  22939. case ASN_POSTAL_CODE:
  22940. return name->postalCode;
  22941. case ASN_EMAIL_NAME:
  22942. return name->email;
  22943. #ifdef WOLFSSL_CERT_EXT
  22944. case ASN_BUS_CAT:
  22945. return name->busCat;
  22946. #endif
  22947. #ifdef WOLFSSL_CUSTOM_OID
  22948. case ASN_CUSTOM_NAME:
  22949. return (const char*)name->custom.val;
  22950. #endif
  22951. default:
  22952. return NULL;
  22953. }
  22954. }
  22955. /* Get Which Name Encoding from index */
  22956. static char GetNameType(CertName* name, int idx)
  22957. {
  22958. byte type = GetCertNameId(idx);
  22959. switch (type) {
  22960. case ASN_COUNTRY_NAME:
  22961. return name->countryEnc;
  22962. case ASN_STATE_NAME:
  22963. return name->stateEnc;
  22964. case ASN_STREET_ADDR:
  22965. return name->streetEnc;
  22966. case ASN_LOCALITY_NAME:
  22967. return name->localityEnc;
  22968. #ifdef WOLFSSL_CERT_NAME_ALL
  22969. case ASN_NAME:
  22970. return name->dnNameEnc;
  22971. case ASN_GIVEN_NAME:
  22972. return name->givenNameEnc;
  22973. case ASN_INITIALS:
  22974. return name->initialsEnc;
  22975. case ASN_DNQUALIFIER:
  22976. return name->dnQualifierEnc;
  22977. #endif /* WOLFSSL_CERT_NAME_ALL */
  22978. case ASN_SUR_NAME:
  22979. return name->surEnc;
  22980. case ASN_ORG_NAME:
  22981. return name->orgEnc;
  22982. case ASN_ORGUNIT_NAME:
  22983. return name->unitEnc;
  22984. case ASN_COMMON_NAME:
  22985. return name->commonNameEnc;
  22986. case ASN_SERIAL_NUMBER:
  22987. return name->serialDevEnc;
  22988. case ASN_USER_ID:
  22989. return name->userIdEnc;
  22990. case ASN_POSTAL_CODE:
  22991. return name->postalCodeEnc;
  22992. case ASN_EMAIL_NAME:
  22993. return 0; /* special */
  22994. #ifdef WOLFSSL_CERT_EXT
  22995. case ASN_BUS_CAT:
  22996. return name->busCatEnc;
  22997. #endif
  22998. #ifdef WOLFSSL_CUSTOM_OID
  22999. case ASN_CUSTOM_NAME:
  23000. return name->custom.enc;
  23001. #endif
  23002. default:
  23003. return 0;
  23004. }
  23005. }
  23006. #ifndef WOLFSSL_ASN_TEMPLATE
  23007. /*
  23008. Extensions ::= SEQUENCE OF Extension
  23009. Extension ::= SEQUENCE {
  23010. extnId OBJECT IDENTIFIER,
  23011. critical BOOLEAN DEFAULT FALSE,
  23012. extnValue OCTET STRING }
  23013. */
  23014. /* encode all extensions, return total bytes written */
  23015. static int SetExtensions(byte* out, word32 outSz, int *IdxInOut,
  23016. const byte* ext, int extSz)
  23017. {
  23018. if (out == NULL || IdxInOut == NULL || ext == NULL)
  23019. return BAD_FUNC_ARG;
  23020. if (outSz < (word32)(*IdxInOut+extSz))
  23021. return BUFFER_E;
  23022. XMEMCPY(&out[*IdxInOut], ext, (size_t)extSz); /* extensions */
  23023. *IdxInOut += extSz;
  23024. return *IdxInOut;
  23025. }
  23026. /* encode extensions header, return total bytes written */
  23027. static int SetExtensionsHeader(byte* out, word32 outSz, word32 extSz)
  23028. {
  23029. byte sequence[MAX_SEQ_SZ];
  23030. byte len[MAX_LENGTH_SZ];
  23031. word32 seqSz, lenSz, idx = 0;
  23032. if (out == NULL)
  23033. return BAD_FUNC_ARG;
  23034. if (outSz < 3)
  23035. return BUFFER_E;
  23036. seqSz = SetSequence(extSz, sequence);
  23037. /* encode extensions length provided */
  23038. lenSz = SetLength(extSz+seqSz, len);
  23039. if (outSz < (word32)(lenSz+seqSz+1))
  23040. return BUFFER_E;
  23041. out[idx++] = ASN_EXTENSIONS; /* extensions id */
  23042. XMEMCPY(&out[idx], len, lenSz); /* length */
  23043. idx += lenSz;
  23044. XMEMCPY(&out[idx], sequence, seqSz); /* sequence */
  23045. idx += seqSz;
  23046. return (int)idx;
  23047. }
  23048. /* encode CA basic constraints true with path length
  23049. * return total bytes written */
  23050. static int SetCaWithPathLen(byte* out, word32 outSz, byte pathLen)
  23051. {
  23052. /* ASN1->DER sequence for Basic Constraints True and path length */
  23053. const byte caPathLenBasicConstASN1[] = {
  23054. 0x30, 0x0F, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04,
  23055. 0x08, 0x30, 0x06, 0x01, 0x01, 0xFF, 0x02, 0x01,
  23056. 0x00
  23057. };
  23058. if (out == NULL)
  23059. return BAD_FUNC_ARG;
  23060. if (outSz < sizeof(caPathLenBasicConstASN1))
  23061. return BUFFER_E;
  23062. XMEMCPY(out, caPathLenBasicConstASN1, sizeof(caPathLenBasicConstASN1));
  23063. out[sizeof(caPathLenBasicConstASN1)-1] = pathLen;
  23064. return (int)sizeof(caPathLenBasicConstASN1);
  23065. }
  23066. /* encode CA basic constraints true
  23067. * return total bytes written */
  23068. static int SetCa(byte* out, word32 outSz)
  23069. {
  23070. /* ASN1->DER sequence for Basic Constraints True */
  23071. const byte caBasicConstASN1[] = {
  23072. 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  23073. 0x05, 0x30, 0x03, 0x01, 0x01, 0xff
  23074. };
  23075. if (out == NULL)
  23076. return BAD_FUNC_ARG;
  23077. if (outSz < sizeof(caBasicConstASN1))
  23078. return BUFFER_E;
  23079. XMEMCPY(out, caBasicConstASN1, sizeof(caBasicConstASN1));
  23080. return (int)sizeof(caBasicConstASN1);
  23081. }
  23082. /* encode basic constraints without CA Boolean
  23083. * return total bytes written */
  23084. static int SetBC(byte* out, word32 outSz)
  23085. {
  23086. /* ASN1->DER sequence for Basic Constraint without CA Boolean */
  23087. const byte BasicConstASN1[] = {
  23088. 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  23089. 0x02, 0x30, 0x00
  23090. };
  23091. if (out == NULL)
  23092. return BAD_FUNC_ARG;
  23093. if (outSz < sizeof(BasicConstASN1))
  23094. return BUFFER_E;
  23095. XMEMCPY(out, BasicConstASN1, sizeof(BasicConstASN1));
  23096. return (int)sizeof(BasicConstASN1);
  23097. }
  23098. #endif
  23099. #ifdef WOLFSSL_CERT_EXT
  23100. #ifndef WOLFSSL_ASN_TEMPLATE
  23101. /* encode OID and associated value, return total bytes written */
  23102. static int SetOidValue(byte* out, word32 outSz, const byte *oid, word32 oidSz,
  23103. byte *in, word32 inSz)
  23104. {
  23105. word32 idx = 0;
  23106. if (out == NULL || oid == NULL || in == NULL)
  23107. return BAD_FUNC_ARG;
  23108. if (outSz < 3)
  23109. return BUFFER_E;
  23110. /* sequence, + 1 => byte to put value size */
  23111. idx = SetSequence(inSz + oidSz + 1, out);
  23112. if ((idx + inSz + oidSz + 1) > outSz)
  23113. return BUFFER_E;
  23114. XMEMCPY(out+idx, oid, oidSz);
  23115. idx += oidSz;
  23116. out[idx++] = (byte)inSz;
  23117. XMEMCPY(out+idx, in, inSz);
  23118. return (int)(idx+inSz);
  23119. }
  23120. /* encode Subject Key Identifier, return total bytes written
  23121. * RFC5280 : non-critical */
  23122. static int SetSKID(byte* output, word32 outSz, const byte *input, word32 length)
  23123. {
  23124. byte skid_len[1 + MAX_LENGTH_SZ];
  23125. byte skid_enc_len[MAX_LENGTH_SZ];
  23126. word32 idx = 0, skid_lenSz, skid_enc_lenSz;
  23127. const byte skid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04 };
  23128. if (output == NULL || input == NULL)
  23129. return BAD_FUNC_ARG;
  23130. /* Octet String header */
  23131. skid_lenSz = SetOctetString(length, skid_len);
  23132. /* length of encoded value */
  23133. skid_enc_lenSz = SetLength(length + skid_lenSz, skid_enc_len);
  23134. if (outSz < 3)
  23135. return BUFFER_E;
  23136. idx = SetSequence(length + (word32)sizeof(skid_oid) + skid_lenSz +
  23137. skid_enc_lenSz, output);
  23138. if ((length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz) > outSz)
  23139. return BUFFER_E;
  23140. /* put oid */
  23141. XMEMCPY(output+idx, skid_oid, sizeof(skid_oid));
  23142. idx += sizeof(skid_oid);
  23143. /* put encoded len */
  23144. XMEMCPY(output+idx, skid_enc_len, skid_enc_lenSz);
  23145. idx += skid_enc_lenSz;
  23146. /* put octet header */
  23147. XMEMCPY(output+idx, skid_len, skid_lenSz);
  23148. idx += skid_lenSz;
  23149. /* put value */
  23150. XMEMCPY(output+idx, input, length);
  23151. idx += length;
  23152. return (int)idx;
  23153. }
  23154. /* encode Authority Key Identifier, return total bytes written
  23155. * RFC5280 : non-critical */
  23156. static int SetAKID(byte* output, word32 outSz, byte *input, word32 length,
  23157. byte rawAkid)
  23158. {
  23159. int enc_valSz;
  23160. byte enc_val_buf[MAX_KID_SZ];
  23161. byte* enc_val;
  23162. const byte akid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x23 };
  23163. const byte akid_cs[] = { 0x80 };
  23164. word32 inSeqSz, idx;
  23165. (void)rawAkid;
  23166. if (output == NULL || input == NULL)
  23167. return BAD_FUNC_ARG;
  23168. #ifdef WOLFSSL_AKID_NAME
  23169. if (rawAkid) {
  23170. enc_val = input;
  23171. enc_valSz = length;
  23172. }
  23173. else
  23174. #endif
  23175. {
  23176. enc_val = enc_val_buf;
  23177. enc_valSz = (int)length + 3 + (int)sizeof(akid_cs);
  23178. if (enc_valSz > (int)sizeof(enc_val_buf))
  23179. return BAD_FUNC_ARG;
  23180. /* sequence for ContentSpec & value */
  23181. enc_valSz = SetOidValue(enc_val, (word32)enc_valSz, akid_cs,
  23182. sizeof(akid_cs), input, length);
  23183. if (enc_valSz <= 0)
  23184. return enc_valSz;
  23185. }
  23186. /* The size of the extension sequence contents */
  23187. inSeqSz = (word32)sizeof(akid_oid) +
  23188. SetOctetString((word32)enc_valSz, NULL) + (word32)enc_valSz;
  23189. if (SetSequence(inSeqSz, NULL) + inSeqSz > outSz)
  23190. return BAD_FUNC_ARG;
  23191. /* Write out the sequence header */
  23192. idx = SetSequence(inSeqSz, output);
  23193. /* Write out OID */
  23194. XMEMCPY(output + idx, akid_oid, sizeof(akid_oid));
  23195. idx += sizeof(akid_oid);
  23196. /* Write out AKID */
  23197. idx += SetOctetString((word32)enc_valSz, output + idx);
  23198. XMEMCPY(output + idx, enc_val, (size_t)enc_valSz);
  23199. return (int)idx + enc_valSz;
  23200. }
  23201. /* encode Key Usage, return total bytes written
  23202. * RFC5280 : critical */
  23203. static int SetKeyUsage(byte* output, word32 outSz, word16 input)
  23204. {
  23205. byte ku[5];
  23206. word32 idx;
  23207. const byte keyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0f,
  23208. 0x01, 0x01, 0xff, 0x04};
  23209. if (output == NULL)
  23210. return BAD_FUNC_ARG;
  23211. idx = SetBitString16Bit(input, ku);
  23212. return SetOidValue(output, outSz, keyusage_oid, sizeof(keyusage_oid),
  23213. ku, idx);
  23214. }
  23215. static int SetOjectIdValue(byte* output, word32 outSz, word32* idx,
  23216. const byte* oid, word32 oidSz)
  23217. {
  23218. /* verify room */
  23219. if (*idx + 2 + oidSz >= outSz)
  23220. return ASN_PARSE_E;
  23221. *idx += (word32)SetObjectId((int)oidSz, &output[*idx]);
  23222. XMEMCPY(&output[*idx], oid, oidSz);
  23223. *idx += oidSz;
  23224. return 0;
  23225. }
  23226. #endif
  23227. #ifdef WOLFSSL_ASN_TEMPLATE
  23228. /* ASN.1 template for extended key usage.
  23229. * X.509: RFC 5280, 4.2.12 - Extended Key Usage
  23230. * Dynamic creation of template for encoding.
  23231. */
  23232. static const ASNItem ekuASN[] = {
  23233. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  23234. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  23235. };
  23236. enum {
  23237. EKUASN_IDX_SEQ = 0,
  23238. EKUASN_IDX_OID
  23239. };
  23240. /* OIDs corresponding to extended key usage. */
  23241. struct {
  23242. const byte* oid;
  23243. word32 oidSz;
  23244. } ekuOid[] = {
  23245. { extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid) },
  23246. { extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid) },
  23247. { extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid) },
  23248. { extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid) },
  23249. { extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid) },
  23250. { extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid) },
  23251. };
  23252. #define EKU_OID_LO 1
  23253. #define EKU_OID_HI 6
  23254. #endif /* WOLFSSL_ASN_TEMPLATE */
  23255. /* encode Extended Key Usage (RFC 5280 4.2.1.12), return total bytes written */
  23256. static int SetExtKeyUsage(Cert* cert, byte* output, word32 outSz, byte input)
  23257. {
  23258. #ifndef WOLFSSL_ASN_TEMPLATE
  23259. word32 idx = 0, oidListSz = 0, totalSz;
  23260. int ret = 0;
  23261. const byte extkeyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x25 };
  23262. if (output == NULL)
  23263. return BAD_FUNC_ARG;
  23264. /* Skip to OID List */
  23265. totalSz = 2 + sizeof(extkeyusage_oid) + 4;
  23266. idx = totalSz;
  23267. /* Build OID List */
  23268. /* If any set, then just use it */
  23269. if (input & EXTKEYUSE_ANY) {
  23270. ret |= SetOjectIdValue(output, outSz, &idx,
  23271. extExtKeyUsageAnyOid, sizeof(extExtKeyUsageAnyOid));
  23272. }
  23273. else {
  23274. if (input & EXTKEYUSE_SERVER_AUTH)
  23275. ret |= SetOjectIdValue(output, outSz, &idx,
  23276. extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid));
  23277. if (input & EXTKEYUSE_CLIENT_AUTH)
  23278. ret |= SetOjectIdValue(output, outSz, &idx,
  23279. extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid));
  23280. if (input & EXTKEYUSE_CODESIGN)
  23281. ret |= SetOjectIdValue(output, outSz, &idx,
  23282. extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid));
  23283. if (input & EXTKEYUSE_EMAILPROT)
  23284. ret |= SetOjectIdValue(output, outSz, &idx,
  23285. extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid));
  23286. if (input & EXTKEYUSE_TIMESTAMP)
  23287. ret |= SetOjectIdValue(output, outSz, &idx,
  23288. extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid));
  23289. if (input & EXTKEYUSE_OCSP_SIGN)
  23290. ret |= SetOjectIdValue(output, outSz, &idx,
  23291. extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid));
  23292. #ifdef WOLFSSL_EKU_OID
  23293. /* iterate through OID values */
  23294. if (input & EXTKEYUSE_USER) {
  23295. int i, sz;
  23296. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  23297. sz = cert->extKeyUsageOIDSz[i];
  23298. if (sz > 0) {
  23299. ret |= SetOjectIdValue(output, outSz, &idx,
  23300. cert->extKeyUsageOID[i], sz);
  23301. }
  23302. }
  23303. }
  23304. #endif /* WOLFSSL_EKU_OID */
  23305. }
  23306. if (ret != 0)
  23307. return ASN_PARSE_E;
  23308. /* Calculate Sizes */
  23309. oidListSz = idx - totalSz;
  23310. totalSz = idx - 2; /* exclude first seq/len (2) */
  23311. /* 1. Seq + Total Len (2) */
  23312. idx = SetSequence(totalSz, output);
  23313. /* 2. Object ID (2) */
  23314. XMEMCPY(&output[idx], extkeyusage_oid, sizeof(extkeyusage_oid));
  23315. idx += sizeof(extkeyusage_oid);
  23316. /* 3. Octet String (2) */
  23317. idx += SetOctetString(totalSz - idx, &output[idx]);
  23318. /* 4. Seq + OidListLen (2) */
  23319. idx += SetSequence(oidListSz, &output[idx]);
  23320. /* 5. Oid List (already set in-place above) */
  23321. idx += oidListSz;
  23322. (void)cert;
  23323. return (int)idx;
  23324. #else
  23325. /* TODO: consider calculating size of OBJECT_IDs, setting length into
  23326. * SEQUENCE, encode SEQUENCE, encode OBJECT_IDs into buffer. */
  23327. ASNSetData* dataASN;
  23328. ASNItem* extKuASN = NULL;
  23329. int asnIdx = 1;
  23330. size_t cnt = 1 + EKU_OID_HI;
  23331. int i;
  23332. int ret = 0;
  23333. int sz = 0;
  23334. #ifdef WOLFSSL_EKU_OID
  23335. cnt += CTC_MAX_EKU_NB;
  23336. #endif
  23337. /* Allocate memory for dynamic data items. */
  23338. dataASN = (ASNSetData*)XMALLOC(cnt * sizeof(ASNSetData), cert->heap,
  23339. DYNAMIC_TYPE_TMP_BUFFER);
  23340. if (dataASN == NULL) {
  23341. ret = MEMORY_E;
  23342. }
  23343. if (ret == 0) {
  23344. /* Allocate memory for dynamic ASN.1 template. */
  23345. extKuASN = (ASNItem*)XMALLOC(cnt * sizeof(ASNItem), cert->heap,
  23346. DYNAMIC_TYPE_TMP_BUFFER);
  23347. if (extKuASN == NULL) {
  23348. ret = MEMORY_E;
  23349. }
  23350. }
  23351. if (ret == 0) {
  23352. /* Copy Sequence into dynamic ASN.1 template. */
  23353. XMEMCPY(&extKuASN[EKUASN_IDX_SEQ], ekuASN, sizeof(ASNItem));
  23354. /* Clear dynamic data. */
  23355. XMEMSET(dataASN, 0, cnt * sizeof(ASNSetData));
  23356. /* Build up the template and data. */
  23357. /* If 'any' set, then just use it. */
  23358. if ((input & EXTKEYUSE_ANY) == EXTKEYUSE_ANY) {
  23359. /* Set template item. */
  23360. XMEMCPY(&extKuASN[EKUASN_IDX_OID], &ekuASN[EKUASN_IDX_OID],
  23361. sizeof(ASNItem));
  23362. /* Set data item. */
  23363. SetASN_Buffer(&dataASN[asnIdx], extExtKeyUsageAnyOid,
  23364. sizeof(extExtKeyUsageAnyOid));
  23365. asnIdx++;
  23366. }
  23367. else {
  23368. /* Step through the flagged purposes. */
  23369. for (i = EKU_OID_LO; i <= EKU_OID_HI; i++) {
  23370. if ((input & (1 << i)) != 0) {
  23371. /* Set template item. */
  23372. XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
  23373. sizeof(ASNItem));
  23374. /* Set data item. */
  23375. SetASN_Buffer(&dataASN[asnIdx], ekuOid[i - 1].oid,
  23376. ekuOid[i - 1].oidSz);
  23377. asnIdx++;
  23378. }
  23379. }
  23380. #ifdef WOLFSSL_EKU_OID
  23381. if (input & EXTKEYUSE_USER) {
  23382. /* Iterate through OID values */
  23383. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  23384. sz = cert->extKeyUsageOIDSz[i];
  23385. if (sz > 0) {
  23386. /* Set template item. */
  23387. XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
  23388. sizeof(ASNItem));
  23389. /* Set data item. */
  23390. SetASN_Buffer(&dataASN[asnIdx], cert->extKeyUsageOID[i],
  23391. sz);
  23392. asnIdx++;
  23393. }
  23394. }
  23395. }
  23396. #endif /* WOLFSSL_EKU_OID */
  23397. (void)cert;
  23398. }
  23399. /* Calculate size of encoding. */
  23400. sz = 0;
  23401. ret = SizeASN_Items(extKuASN, dataASN, asnIdx, &sz);
  23402. }
  23403. /* When buffer to write to, ensure it's big enough. */
  23404. if ((ret == 0) && (output != NULL) && (sz > (int)outSz)) {
  23405. ret = BUFFER_E;
  23406. }
  23407. if ((ret == 0) && (output != NULL)) {
  23408. /* Encode extended key usage. */
  23409. SetASN_Items(extKuASN, dataASN, asnIdx, output);
  23410. }
  23411. if (ret == 0) {
  23412. /* Return the encoding size. */
  23413. ret = sz;
  23414. }
  23415. /* Dispose of allocated data. */
  23416. if (extKuASN != NULL) {
  23417. XFREE(extKuASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23418. }
  23419. if (dataASN != NULL) {
  23420. XFREE(dataASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23421. }
  23422. return ret;
  23423. #endif
  23424. }
  23425. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  23426. #ifndef WOLFSSL_ASN_TEMPLATE
  23427. static int SetNsCertType(Cert* cert, byte* output, word32 outSz, byte input)
  23428. {
  23429. word32 idx;
  23430. byte unusedBits = 0;
  23431. byte nsCertType = input;
  23432. word32 totalSz;
  23433. word32 bitStrSz;
  23434. const byte nscerttype_oid[] = { 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
  23435. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  23436. if (cert == NULL || output == NULL ||
  23437. input == 0)
  23438. return BAD_FUNC_ARG;
  23439. totalSz = sizeof(nscerttype_oid);
  23440. /* Get amount of lsb zero's */
  23441. for (;(input & 1) == 0; input >>= 1)
  23442. unusedBits++;
  23443. /* 1 byte of NS Cert Type extension */
  23444. bitStrSz = SetBitString(1, unusedBits, NULL) + 1;
  23445. totalSz += SetOctetString(bitStrSz, NULL) + bitStrSz;
  23446. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  23447. return BAD_FUNC_ARG;
  23448. /* 1. Seq + Total Len */
  23449. idx = SetSequence(totalSz, output);
  23450. /* 2. Object ID */
  23451. XMEMCPY(&output[idx], nscerttype_oid, sizeof(nscerttype_oid));
  23452. idx += sizeof(nscerttype_oid);
  23453. /* 3. Octet String */
  23454. idx += SetOctetString(bitStrSz, &output[idx]);
  23455. /* 4. Bit String */
  23456. idx += SetBitString(1, unusedBits, &output[idx]);
  23457. output[idx++] = nsCertType;
  23458. return (int)idx;
  23459. }
  23460. #endif
  23461. #endif
  23462. #ifndef WOLFSSL_ASN_TEMPLATE
  23463. static int SetCRLInfo(Cert* cert, byte* output, word32 outSz, byte* input,
  23464. int inSz)
  23465. {
  23466. word32 idx;
  23467. word32 totalSz;
  23468. const byte crlinfo_oid[] = { 0x06, 0x03, 0x55, 0x1D, 0x1F };
  23469. if (cert == NULL || output == NULL ||
  23470. input == 0 || inSz <= 0)
  23471. return BAD_FUNC_ARG;
  23472. totalSz = (word32)sizeof(crlinfo_oid) + SetOctetString((word32)inSz, NULL) +
  23473. (word32)inSz;
  23474. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  23475. return BAD_FUNC_ARG;
  23476. /* 1. Seq + Total Len */
  23477. idx = SetSequence(totalSz, output);
  23478. /* 2. Object ID */
  23479. XMEMCPY(&output[idx], crlinfo_oid, sizeof(crlinfo_oid));
  23480. idx += sizeof(crlinfo_oid);
  23481. /* 3. Octet String */
  23482. idx += SetOctetString((word32)inSz, &output[idx]);
  23483. /* 4. CRL Info */
  23484. XMEMCPY(&output[idx], input, (size_t)inSz);
  23485. idx += (word32)inSz;
  23486. return (int)idx;
  23487. }
  23488. #endif
  23489. /* encode Certificate Policies, return total bytes written
  23490. * each input value must be ITU-T X.690 formatted : a.b.c...
  23491. * input must be an array of values with a NULL terminated for the latest
  23492. * RFC5280 : non-critical */
  23493. static int SetCertificatePolicies(byte *output,
  23494. word32 outputSz,
  23495. char input[MAX_CERTPOL_NB][MAX_CERTPOL_SZ],
  23496. word16 nb_certpol,
  23497. void* heap)
  23498. {
  23499. #ifndef WOLFSSL_ASN_TEMPLATE
  23500. byte oid[MAX_OID_SZ];
  23501. byte der_oid[MAX_CERTPOL_NB][MAX_OID_SZ];
  23502. byte out[MAX_CERTPOL_SZ];
  23503. word32 oidSz;
  23504. word32 outSz;
  23505. word32 i = 0;
  23506. word32 der_oidSz[MAX_CERTPOL_NB];
  23507. int ret;
  23508. const byte certpol_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x20, 0x04 };
  23509. const byte oid_oid[] = { 0x06 };
  23510. if (output == NULL || input == NULL || nb_certpol > MAX_CERTPOL_NB)
  23511. return BAD_FUNC_ARG;
  23512. for (i = 0; i < nb_certpol; i++) {
  23513. oidSz = sizeof(oid);
  23514. XMEMSET(oid, 0, oidSz);
  23515. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  23516. if (ret != 0)
  23517. return ret;
  23518. /* compute sequence value for the oid */
  23519. ret = SetOidValue(der_oid[i], MAX_OID_SZ, oid_oid,
  23520. sizeof(oid_oid), oid, oidSz);
  23521. if (ret <= 0)
  23522. return ret;
  23523. else
  23524. der_oidSz[i] = (word32)ret;
  23525. }
  23526. /* concatenate oid, keep two byte for sequence/size of the created value */
  23527. for (i = 0, outSz = 2; i < nb_certpol; i++) {
  23528. XMEMCPY(out+outSz, der_oid[i], der_oidSz[i]);
  23529. outSz += der_oidSz[i];
  23530. }
  23531. /* add sequence */
  23532. ret = (int)SetSequence(outSz-2, out);
  23533. if (ret <= 0)
  23534. return ret;
  23535. /* add Policy OID to compute final value */
  23536. return SetOidValue(output, outputSz, certpol_oid, sizeof(certpol_oid),
  23537. out, outSz);
  23538. #else
  23539. int i;
  23540. int ret = 0;
  23541. byte oid[MAX_OID_SZ];
  23542. word32 oidSz;
  23543. word32 sz = 0;
  23544. int piSz;
  23545. if ((input == NULL) || (nb_certpol > MAX_CERTPOL_NB)) {
  23546. ret = BAD_FUNC_ARG;
  23547. }
  23548. /* Put in policyIdentifier but not policyQualifiers. */
  23549. for (i = 0; (ret == 0) && (i < nb_certpol); i++) {
  23550. ASNSetData dataASN[policyInfoASN_Length];
  23551. oidSz = sizeof(oid);
  23552. XMEMSET(oid, 0, oidSz);
  23553. dataASN[POLICYINFOASN_IDX_QUALI].noOut = 1;
  23554. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  23555. if (ret == 0) {
  23556. XMEMSET(dataASN, 0, sizeof(dataASN));
  23557. SetASN_Buffer(&dataASN[POLICYINFOASN_IDX_ID], oid, oidSz);
  23558. ret = SizeASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  23559. &piSz);
  23560. }
  23561. if ((ret == 0) && (output != NULL) && (sz + (word32)piSz > outputSz)) {
  23562. ret = BUFFER_E;
  23563. }
  23564. if (ret == 0) {
  23565. if (output != NULL) {
  23566. SetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  23567. output);
  23568. output += piSz;
  23569. }
  23570. sz += (word32)piSz;
  23571. }
  23572. }
  23573. if (ret == 0) {
  23574. ret = (int)sz;
  23575. }
  23576. return ret;
  23577. #endif
  23578. }
  23579. #endif /* WOLFSSL_CERT_EXT */
  23580. #ifdef WOLFSSL_ALT_NAMES
  23581. #ifndef WOLFSSL_ASN_TEMPLATE
  23582. /* encode Alternative Names, return total bytes written */
  23583. static int SetAltNames(byte *output, word32 outSz,
  23584. const byte *input, word32 length, int critical)
  23585. {
  23586. byte san_len[1 + MAX_LENGTH_SZ];
  23587. const byte san_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x11 };
  23588. const byte san_crit[] = { 0x01, 0x01, 0xff };
  23589. word32 seqSz, san_lenSz, idx = 0;
  23590. if (output == NULL || input == NULL)
  23591. return BAD_FUNC_ARG;
  23592. if (outSz < length)
  23593. return BUFFER_E;
  23594. /* Octet String header */
  23595. san_lenSz = SetOctetString(length, san_len);
  23596. if (outSz < MAX_SEQ_SZ)
  23597. return BUFFER_E;
  23598. seqSz = length + (word32)sizeof(san_oid) + san_lenSz;
  23599. if (critical)
  23600. seqSz += sizeof(san_crit);
  23601. idx = SetSequence(seqSz, output);
  23602. if (seqSz > outSz)
  23603. return BUFFER_E;
  23604. /* put oid */
  23605. XMEMCPY(output+idx, san_oid, sizeof(san_oid));
  23606. idx += sizeof(san_oid);
  23607. if (critical) {
  23608. XMEMCPY(output+idx, san_crit, sizeof(san_crit));
  23609. idx += sizeof(san_crit);
  23610. }
  23611. /* put octet header */
  23612. XMEMCPY(output+idx, san_len, san_lenSz);
  23613. idx += san_lenSz;
  23614. /* put value */
  23615. XMEMCPY(output+idx, input, length);
  23616. idx += length;
  23617. return (int)idx;
  23618. }
  23619. #endif /* WOLFSSL_ASN_TEMPLATE */
  23620. int FlattenAltNames(byte* output, word32 outputSz, const DNS_entry* names)
  23621. {
  23622. word32 idx;
  23623. const DNS_entry* curName;
  23624. word32 namesSz = 0;
  23625. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23626. word32 i;
  23627. #endif
  23628. if (output == NULL)
  23629. return BAD_FUNC_ARG;
  23630. if (names == NULL)
  23631. return 0;
  23632. curName = names;
  23633. do {
  23634. namesSz += (word32)curName->len + 2 +
  23635. ((curName->len < ASN_LONG_LENGTH) ? 0
  23636. : BytePrecision((word32)curName->len));
  23637. curName = curName->next;
  23638. } while (curName != NULL);
  23639. if (outputSz < MAX_SEQ_SZ + namesSz)
  23640. return BUFFER_E;
  23641. idx = SetSequence(namesSz, output);
  23642. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23643. namesSz += idx;
  23644. i = namesSz;
  23645. #endif
  23646. curName = names;
  23647. do {
  23648. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23649. word32 len = SetLength(curName->len, NULL);
  23650. idx = i - curName->len - len - 1;
  23651. i = idx;
  23652. #endif
  23653. output[idx] = (byte) (ASN_CONTEXT_SPECIFIC | curName->type);
  23654. if (curName->type == ASN_DIR_TYPE || curName->type == ASN_OTHER_TYPE) {
  23655. output[idx] |= ASN_CONSTRUCTED;
  23656. }
  23657. idx++;
  23658. idx += SetLength((word32)curName->len, output + idx);
  23659. XMEMCPY(output + idx, curName->name, (size_t)curName->len);
  23660. #ifndef WOLFSSL_ALT_NAMES_NO_REV
  23661. idx += (word32)curName->len;
  23662. #endif
  23663. curName = curName->next;
  23664. } while (curName != NULL);
  23665. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23666. idx = namesSz;
  23667. #endif
  23668. return (int)idx;
  23669. }
  23670. #endif /* WOLFSSL_ALT_NAMES */
  23671. #endif /* WOLFSSL_CERT_GEN */
  23672. #if defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  23673. /* Simple domain name OID size. */
  23674. #define DN_OID_SZ 3
  23675. /* Encodes one attribute of the name (issuer/subject)
  23676. *
  23677. * name structure to hold result of encoding
  23678. * nameStr value to be encoded
  23679. * nameTag tag of encoding i.e CTC_UTF8
  23680. * type id of attribute i.e ASN_COMMON_NAME
  23681. * emailTag tag of email i.e CTC_UTF8
  23682. * returns length on success
  23683. */
  23684. static int EncodeName(EncodedName* name, const char* nameStr,
  23685. byte nameTag, byte type, byte emailTag, CertName* cname)
  23686. {
  23687. #if !defined(WOLFSSL_ASN_TEMPLATE)
  23688. word32 idx = 0;
  23689. /* bottom up */
  23690. byte firstLen[1 + MAX_LENGTH_SZ];
  23691. byte secondLen[MAX_LENGTH_SZ];
  23692. byte sequence[MAX_SEQ_SZ];
  23693. byte set[MAX_SET_SZ];
  23694. word32 strLen;
  23695. word32 thisLen;
  23696. word32 firstSz, secondSz, seqSz, setSz;
  23697. if (nameStr == NULL) {
  23698. name->used = 0;
  23699. return 0;
  23700. }
  23701. thisLen = strLen = (word32)XSTRLEN(nameStr);
  23702. #ifdef WOLFSSL_CUSTOM_OID
  23703. if (type == ASN_CUSTOM_NAME) {
  23704. if (cname == NULL || cname->custom.oidSz == 0) {
  23705. name->used = 0;
  23706. return 0;
  23707. }
  23708. thisLen = strLen = (word32)cname->custom.valSz;
  23709. }
  23710. #else
  23711. (void)cname;
  23712. #endif
  23713. if (strLen == 0) { /* no user data for this item */
  23714. name->used = 0;
  23715. return 0;
  23716. }
  23717. /* Restrict country code size */
  23718. if (type == ASN_COUNTRY_NAME && strLen != CTC_COUNTRY_SIZE) {
  23719. WOLFSSL_MSG("Country code size error");
  23720. WOLFSSL_ERROR_VERBOSE(ASN_COUNTRY_SIZE_E);
  23721. return ASN_COUNTRY_SIZE_E;
  23722. }
  23723. secondSz = SetLength(strLen, secondLen);
  23724. thisLen += secondSz;
  23725. switch (type) {
  23726. case ASN_EMAIL_NAME: /* email */
  23727. thisLen += (int)sizeof(attrEmailOid);
  23728. firstSz = (int)sizeof(attrEmailOid);
  23729. break;
  23730. case ASN_DOMAIN_COMPONENT:
  23731. thisLen += (int)sizeof(dcOid);
  23732. firstSz = (int)sizeof(dcOid);
  23733. break;
  23734. case ASN_USER_ID:
  23735. thisLen += (int)sizeof(uidOid);
  23736. firstSz = (int)sizeof(uidOid);
  23737. break;
  23738. case ASN_FAVOURITE_DRINK:
  23739. thisLen += (int)sizeof(fvrtDrk);
  23740. firstSz = (int)sizeof(fvrtDrk);
  23741. break;
  23742. #ifdef WOLFSSL_CUSTOM_OID
  23743. case ASN_CUSTOM_NAME:
  23744. thisLen += cname->custom.oidSz;
  23745. firstSz = cname->custom.oidSz;
  23746. break;
  23747. #endif
  23748. default:
  23749. thisLen += DN_OID_SZ;
  23750. firstSz = DN_OID_SZ;
  23751. }
  23752. thisLen++; /* id type */
  23753. firstSz = (word32)SetObjectId((int)firstSz, firstLen);
  23754. thisLen += firstSz;
  23755. seqSz = SetSequence(thisLen, sequence);
  23756. thisLen += seqSz;
  23757. setSz = SetSet(thisLen, set);
  23758. thisLen += setSz;
  23759. if (thisLen > (int)sizeof(name->encoded)) {
  23760. return BUFFER_E;
  23761. }
  23762. /* store it */
  23763. idx = 0;
  23764. /* set */
  23765. XMEMCPY(name->encoded, set, setSz);
  23766. idx += setSz;
  23767. /* seq */
  23768. XMEMCPY(name->encoded + idx, sequence, seqSz);
  23769. idx += seqSz;
  23770. /* asn object id */
  23771. XMEMCPY(name->encoded + idx, firstLen, firstSz);
  23772. idx += firstSz;
  23773. switch (type) {
  23774. case ASN_EMAIL_NAME:
  23775. /* email joint id */
  23776. XMEMCPY(name->encoded + idx, attrEmailOid, sizeof(attrEmailOid));
  23777. idx += (int)sizeof(attrEmailOid);
  23778. name->encoded[idx++] = emailTag;
  23779. break;
  23780. case ASN_DOMAIN_COMPONENT:
  23781. XMEMCPY(name->encoded + idx, dcOid, sizeof(dcOid)-1);
  23782. idx += (int)sizeof(dcOid)-1;
  23783. /* id type */
  23784. name->encoded[idx++] = type;
  23785. /* str type */
  23786. name->encoded[idx++] = nameTag;
  23787. break;
  23788. case ASN_USER_ID:
  23789. XMEMCPY(name->encoded + idx, uidOid, sizeof(uidOid));
  23790. idx += (int)sizeof(uidOid);
  23791. /* str type */
  23792. name->encoded[idx++] = nameTag;
  23793. break;
  23794. case ASN_FAVOURITE_DRINK:
  23795. XMEMCPY(name->encoded + idx, fvrtDrk, sizeof(fvrtDrk));
  23796. idx += (int)sizeof(fvrtDrk);
  23797. /* str type */
  23798. name->encoded[idx++] = nameTag;
  23799. break;
  23800. #ifdef WOLFSSL_CUSTOM_OID
  23801. case ASN_CUSTOM_NAME:
  23802. XMEMCPY(name->encoded + idx, cname->custom.oid,
  23803. cname->custom.oidSz);
  23804. idx += cname->custom.oidSz;
  23805. /* str type */
  23806. name->encoded[idx++] = nameTag;
  23807. break;
  23808. #endif
  23809. default:
  23810. name->encoded[idx++] = 0x55;
  23811. name->encoded[idx++] = 0x04;
  23812. /* id type */
  23813. name->encoded[idx++] = type;
  23814. /* str type */
  23815. name->encoded[idx++] = nameTag;
  23816. }
  23817. /* second length */
  23818. XMEMCPY(name->encoded + idx, secondLen, secondSz);
  23819. idx += secondSz;
  23820. /* str value */
  23821. XMEMCPY(name->encoded + idx, nameStr, strLen);
  23822. idx += strLen;
  23823. name->type = type;
  23824. name->totalLen = (int)idx;
  23825. name->used = 1;
  23826. return (int)idx;
  23827. #else
  23828. DECL_ASNSETDATA(dataASN, rdnASN_Length);
  23829. ASNItem namesASN[rdnASN_Length];
  23830. byte dnOid[DN_OID_SZ] = { 0x55, 0x04, 0x00 };
  23831. int ret = 0;
  23832. int sz = 0;
  23833. const byte* oid;
  23834. word32 oidSz;
  23835. word32 nameSz;
  23836. /* Validate input parameters. */
  23837. if ((name == NULL) || (nameStr == NULL)) {
  23838. ret = BAD_FUNC_ARG;
  23839. }
  23840. CALLOC_ASNSETDATA(dataASN, rdnASN_Length, ret, NULL);
  23841. if (ret == 0) {
  23842. nameSz = (word32)XSTRLEN(nameStr);
  23843. /* Copy the RDN encoding template. ASN.1 tag for the name string is set
  23844. * based on type. */
  23845. XMEMCPY(namesASN, rdnASN, sizeof(namesASN));
  23846. /* Set OID and ASN.1 tag for name depending on type. */
  23847. switch (type) {
  23848. case ASN_EMAIL_NAME:
  23849. /* email OID different to standard types. */
  23850. oid = attrEmailOid;
  23851. oidSz = sizeof(attrEmailOid);
  23852. /* Use email specific type/tag. */
  23853. nameTag = emailTag;
  23854. break;
  23855. case ASN_DOMAIN_COMPONENT:
  23856. /* Domain component OID different to standard types. */
  23857. oid = dcOid;
  23858. oidSz = sizeof(dcOid);
  23859. break;
  23860. case ASN_USER_ID:
  23861. /* Domain component OID different to standard types. */
  23862. oid = uidOid;
  23863. oidSz = sizeof(uidOid);
  23864. break;
  23865. case ASN_FAVOURITE_DRINK:
  23866. oid = fvrtDrk;
  23867. oidSz = sizeof(fvrtDrk);
  23868. break;
  23869. #ifdef WOLFSSL_CUSTOM_OID
  23870. case ASN_CUSTOM_NAME:
  23871. nameSz = cname->custom.valSz;
  23872. oid = cname->custom.oid;
  23873. oidSz = cname->custom.oidSz;
  23874. break;
  23875. #endif
  23876. default:
  23877. /* Construct OID using type. */
  23878. dnOid[2] = type;
  23879. oid = dnOid;
  23880. oidSz = DN_OID_SZ;
  23881. break;
  23882. }
  23883. /* Set OID corresponding to the name type. */
  23884. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
  23885. /* Set name string. */
  23886. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], (const byte *)nameStr, nameSz);
  23887. /* Set the ASN.1 tag for the name string. */
  23888. namesASN[RDNASN_IDX_ATTR_VAL].tag = nameTag;
  23889. /* Calculate size of encoded name and indexes of components. */
  23890. ret = SizeASN_Items(namesASN, dataASN, rdnASN_Length, &sz);
  23891. }
  23892. /* Check if name's buffer is big enough. */
  23893. if ((ret == 0) && (sz > (int)sizeof(name->encoded))) {
  23894. ret = BUFFER_E;
  23895. }
  23896. if (ret == 0) {
  23897. /* Encode name into the buffer. */
  23898. SetASN_Items(namesASN, dataASN, rdnASN_Length, name->encoded);
  23899. /* Cache the type and size, and set that it is used. */
  23900. name->type = type;
  23901. name->totalLen = sz;
  23902. name->used = 1;
  23903. /* Return size of encoding. */
  23904. ret = sz;
  23905. }
  23906. (void)cname;
  23907. FREE_ASNSETDATA(dataASN, NULL);
  23908. return ret;
  23909. #endif /* WOLFSSL_ASN_TEMPLATE */
  23910. }
  23911. /* canonical encoding one attribute of the name (issuer/subject)
  23912. * call EncodeName with CTC_UTF8 for email type
  23913. *
  23914. * name structure to hold result of encoding
  23915. * nameStr value to be encoded
  23916. * nameType type of encoding i.e CTC_UTF8
  23917. * type id of attribute i.e ASN_COMMON_NAME
  23918. *
  23919. * returns length on success
  23920. */
  23921. int wc_EncodeNameCanonical(EncodedName* name, const char* nameStr,
  23922. char nameType, byte type)
  23923. {
  23924. return EncodeName(name, nameStr, (byte)nameType, type,
  23925. ASN_UTF8STRING, NULL);
  23926. }
  23927. #endif /* WOLFSSL_CERT_GEN || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  23928. #ifdef WOLFSSL_CERT_GEN
  23929. /* Encodes one attribute of the name (issuer/subject)
  23930. * call we_EncodeName_ex with 0x16, IA5String for email type
  23931. * name structure to hold result of encoding
  23932. * nameStr value to be encoded
  23933. * nameType type of encoding i.e CTC_UTF8
  23934. * type id of attribute i.e ASN_COMMON_NAME
  23935. *
  23936. * returns length on success
  23937. */
  23938. int wc_EncodeName(EncodedName* name, const char* nameStr, char nameType,
  23939. byte type)
  23940. {
  23941. return EncodeName(name, nameStr, (byte)nameType, type,
  23942. ASN_IA5_STRING, NULL);
  23943. }
  23944. #ifdef WOLFSSL_ASN_TEMPLATE
  23945. static void SetRdnItems(ASNItem* namesASN, ASNSetData* dataASN, const byte* oid,
  23946. word32 oidSz, byte tag, const byte* data, word32 sz)
  23947. {
  23948. XMEMCPY(namesASN, rdnASN, sizeof(rdnASN));
  23949. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
  23950. namesASN[RDNASN_IDX_ATTR_VAL].tag = tag;
  23951. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], data, sz);
  23952. }
  23953. #ifdef WOLFSSL_MULTI_ATTRIB
  23954. static int FindMultiAttrib(CertName* name, int id, int* idx)
  23955. {
  23956. int i;
  23957. for (i = *idx + 1; i < CTC_MAX_ATTRIB; i++) {
  23958. if (name->name[i].sz > 0 && name->name[i].id == id) {
  23959. break;
  23960. }
  23961. }
  23962. if (i == CTC_MAX_ATTRIB) {
  23963. i = -1;
  23964. }
  23965. *idx = i;
  23966. return i >= 0;
  23967. }
  23968. #endif
  23969. /* ASN.1 template for the SEQUENCE around the RDNs.
  23970. * X.509: RFC 5280, 4.1.2.4 - RDNSequence
  23971. */
  23972. static const ASNItem nameASN[] = {
  23973. { 0, ASN_SEQUENCE, 1, 1, 0 },
  23974. };
  23975. enum {
  23976. NAMEASN_IDX_SEQ = 0
  23977. };
  23978. /* Number of items in ASN.1 template for the SEQUENCE around the RDNs. */
  23979. #define nameASN_Length (sizeof(nameASN) / sizeof(ASNItem))
  23980. static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN,
  23981. int maxIdx, CertName* name)
  23982. {
  23983. int i;
  23984. int idx;
  23985. int ret = 0;
  23986. word32 nameLen[NAME_ENTRIES];
  23987. #ifdef WOLFSSL_MULTI_ATTRIB
  23988. int j;
  23989. #endif
  23990. for (i = 0; i < NAME_ENTRIES; i++) {
  23991. /* Keep name length to identify component is to be encoded. */
  23992. const char* nameStr = GetOneCertName(name, i);
  23993. nameLen[i] = nameStr ? (word32)XSTRLEN(nameStr) : 0;
  23994. }
  23995. idx = nameASN_Length;
  23996. for (i = 0; i < NAME_ENTRIES; i++) {
  23997. int type = GetCertNameId(i);
  23998. #ifdef WOLFSSL_MULTI_ATTRIB
  23999. j = -1;
  24000. /* Put DomainComponents before OrgUnitName. */
  24001. while (FindMultiAttrib(name, type, &j)) {
  24002. if (GetCertNameId(i) != ASN_DOMAIN_COMPONENT) {
  24003. continue;
  24004. }
  24005. if (dataASN != NULL && namesASN != NULL) {
  24006. if (idx > maxIdx - (int)rdnASN_Length) {
  24007. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  24008. ret = BUFFER_E;
  24009. break;
  24010. }
  24011. /* Copy data into dynamic vars. */
  24012. SetRdnItems(namesASN + idx, dataASN + idx, dcOid,
  24013. sizeof(dcOid), (byte)name->name[j].type,
  24014. (byte*)name->name[j].value,
  24015. (word32)name->name[j].sz);
  24016. }
  24017. idx += (int)rdnASN_Length;
  24018. }
  24019. if (ret != 0)
  24020. break;
  24021. #endif
  24022. if (nameLen[i] > 0) {
  24023. if (dataASN != NULL) {
  24024. if (idx > maxIdx - (int)rdnASN_Length) {
  24025. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  24026. ret = BUFFER_E;
  24027. break;
  24028. }
  24029. /* Write out first instance of attribute type. */
  24030. if (type == ASN_EMAIL_NAME) {
  24031. /* Copy email data into dynamic vars. */
  24032. SetRdnItems(namesASN + idx, dataASN + idx, attrEmailOid,
  24033. sizeof(attrEmailOid), ASN_IA5_STRING,
  24034. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24035. }
  24036. else if (type == ASN_USER_ID) {
  24037. /* Copy userID data into dynamic vars. */
  24038. SetRdnItems(namesASN + idx, dataASN + idx, uidOid,
  24039. sizeof(uidOid), (byte)GetNameType(name, i),
  24040. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24041. }
  24042. else if (type == ASN_FAVOURITE_DRINK) {
  24043. /* Copy favourite drink data into dynamic vars. */
  24044. SetRdnItems(namesASN + idx, dataASN + idx, fvrtDrk,
  24045. sizeof(fvrtDrk), (byte)GetNameType(name, i),
  24046. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24047. }
  24048. else if (type == ASN_CUSTOM_NAME) {
  24049. #ifdef WOLFSSL_CUSTOM_OID
  24050. SetRdnItems(namesASN + idx, dataASN + idx, name->custom.oid,
  24051. name->custom.oidSz, name->custom.enc,
  24052. name->custom.val, name->custom.valSz);
  24053. #endif
  24054. }
  24055. else {
  24056. /* Copy name data into dynamic vars. */
  24057. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
  24058. NAME_OID_SZ, (byte)GetNameType(name, i),
  24059. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24060. }
  24061. }
  24062. idx += (int)rdnASN_Length;
  24063. }
  24064. #ifdef WOLFSSL_MULTI_ATTRIB
  24065. j = -1;
  24066. /* Write all other attributes of this type. */
  24067. while (FindMultiAttrib(name, type, &j)) {
  24068. if (GetCertNameId(i) == ASN_DOMAIN_COMPONENT) {
  24069. continue;
  24070. }
  24071. if (dataASN != NULL && namesASN != NULL) {
  24072. if (idx > maxIdx - (int)rdnASN_Length) {
  24073. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  24074. ret = BUFFER_E;
  24075. break;
  24076. }
  24077. /* Copy data into dynamic vars. */
  24078. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
  24079. NAME_OID_SZ, (byte)name->name[j].type,
  24080. (byte*)name->name[j].value, (word32)name->name[j].sz);
  24081. }
  24082. idx += (int)rdnASN_Length;
  24083. }
  24084. if (ret != 0)
  24085. break;
  24086. #endif
  24087. }
  24088. if (ret == 0)
  24089. ret = idx;
  24090. return ret;
  24091. }
  24092. #endif
  24093. /* encode CertName into output, return total bytes written */
  24094. int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap)
  24095. {
  24096. #ifndef WOLFSSL_ASN_TEMPLATE
  24097. int ret;
  24098. int i;
  24099. word32 idx, totalBytes = 0;
  24100. #ifdef WOLFSSL_SMALL_STACK
  24101. EncodedName* names = NULL;
  24102. #else
  24103. EncodedName names[NAME_ENTRIES];
  24104. #endif
  24105. #ifdef WOLFSSL_MULTI_ATTRIB
  24106. EncodedName addNames[CTC_MAX_ATTRIB];
  24107. int j, type;
  24108. #endif
  24109. if (output == NULL || name == NULL)
  24110. return BAD_FUNC_ARG;
  24111. if (outputSz < 3)
  24112. return BUFFER_E;
  24113. #ifdef WOLFSSL_SMALL_STACK
  24114. names = (EncodedName*)XMALLOC(sizeof(EncodedName) * NAME_ENTRIES, NULL,
  24115. DYNAMIC_TYPE_TMP_BUFFER);
  24116. if (names == NULL)
  24117. return MEMORY_E;
  24118. #endif
  24119. for (i = 0; i < NAME_ENTRIES; i++) {
  24120. const char* nameStr = GetOneCertName(name, i);
  24121. ret = EncodeName(&names[i], nameStr, (byte)GetNameType(name, i),
  24122. GetCertNameId(i), ASN_IA5_STRING, name);
  24123. if (ret < 0) {
  24124. #ifdef WOLFSSL_SMALL_STACK
  24125. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24126. #endif
  24127. WOLFSSL_MSG("EncodeName failed");
  24128. return BUFFER_E;
  24129. }
  24130. totalBytes += (word32)ret;
  24131. }
  24132. #ifdef WOLFSSL_MULTI_ATTRIB
  24133. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  24134. if (name->name[i].sz > 0) {
  24135. ret = EncodeName(&addNames[i], name->name[i].value,
  24136. (byte)name->name[i].type, (byte)name->name[i].id,
  24137. ASN_IA5_STRING, NULL);
  24138. if (ret < 0) {
  24139. #ifdef WOLFSSL_SMALL_STACK
  24140. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24141. #endif
  24142. WOLFSSL_MSG("EncodeName on multiple attributes failed");
  24143. return BUFFER_E;
  24144. }
  24145. totalBytes += (word32)ret;
  24146. }
  24147. else {
  24148. addNames[i].used = 0;
  24149. }
  24150. }
  24151. #endif /* WOLFSSL_MULTI_ATTRIB */
  24152. /* header */
  24153. idx = SetSequence(totalBytes, output);
  24154. totalBytes += idx;
  24155. if (totalBytes > WC_ASN_NAME_MAX) {
  24156. #ifdef WOLFSSL_SMALL_STACK
  24157. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24158. #endif
  24159. WOLFSSL_MSG("Total Bytes is greater than WC_ASN_NAME_MAX");
  24160. return BUFFER_E;
  24161. }
  24162. for (i = 0; i < NAME_ENTRIES; i++) {
  24163. #ifdef WOLFSSL_MULTI_ATTRIB
  24164. type = GetCertNameId(i);
  24165. for (j = 0; j < CTC_MAX_ATTRIB; j++) {
  24166. if (name->name[j].sz > 0 && type == name->name[j].id) {
  24167. if (outputSz < idx + (word32)addNames[j].totalLen) {
  24168. #ifdef WOLFSSL_SMALL_STACK
  24169. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24170. #endif
  24171. WOLFSSL_MSG("Not enough space left for DC value");
  24172. return BUFFER_E;
  24173. }
  24174. XMEMCPY(output + idx, addNames[j].encoded,
  24175. (size_t)addNames[j].totalLen);
  24176. idx += (word32)addNames[j].totalLen;
  24177. }
  24178. }
  24179. #endif /* WOLFSSL_MULTI_ATTRIB */
  24180. if (names[i].used) {
  24181. if (outputSz < idx + (word32)names[i].totalLen) {
  24182. #ifdef WOLFSSL_SMALL_STACK
  24183. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24184. #endif
  24185. return BUFFER_E;
  24186. }
  24187. XMEMCPY(output + idx, names[i].encoded, (size_t)names[i].totalLen);
  24188. idx += (word32)names[i].totalLen;
  24189. }
  24190. }
  24191. #ifdef WOLFSSL_SMALL_STACK
  24192. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24193. #endif
  24194. (void)heap;
  24195. return (int)totalBytes;
  24196. #else
  24197. /* TODO: consider calculating size of entries, putting length into
  24198. * SEQUENCE, encode SEQUENCE, encode entries into buffer. */
  24199. ASNSetData* dataASN = NULL; /* Can't use DECL_ASNSETDATA. Always dynamic. */
  24200. ASNItem* namesASN = NULL;
  24201. word32 items = 0;
  24202. int ret = 0;
  24203. int sz = 0;
  24204. /* Calculate length of name entries and size for allocating. */
  24205. ret = SetNameRdnItems(NULL, NULL, 0, name);
  24206. if (ret > 0) {
  24207. items = (word32)ret;
  24208. ret = 0;
  24209. }
  24210. /* Allocate dynamic data items. */
  24211. dataASN = (ASNSetData*)XMALLOC(items * sizeof(ASNSetData), heap,
  24212. DYNAMIC_TYPE_TMP_BUFFER);
  24213. if (dataASN == NULL) {
  24214. ret = MEMORY_E;
  24215. }
  24216. else {
  24217. /* Allocate dynamic ASN.1 template items. */
  24218. namesASN = (ASNItem*)XMALLOC(items * sizeof(ASNItem), heap,
  24219. DYNAMIC_TYPE_TMP_BUFFER);
  24220. if (namesASN == NULL) {
  24221. ret = MEMORY_E;
  24222. }
  24223. }
  24224. if (ret == 0) {
  24225. /* Clear the dynamic data. */
  24226. XMEMSET(dataASN, 0, items * sizeof(ASNSetData));
  24227. /* Copy in the outer sequence. */
  24228. XMEMCPY(namesASN, nameASN, sizeof(nameASN));
  24229. ret = SetNameRdnItems(dataASN, namesASN, (int)items, name);
  24230. if (ret == (int)items)
  24231. ret = 0;
  24232. else if (ret > 0) {
  24233. WOLFSSL_MSG("SetNameRdnItems returned different length");
  24234. ret = BUFFER_E;
  24235. }
  24236. }
  24237. if (ret == 0) {
  24238. /* Calculate size of encoding. */
  24239. ret = SizeASN_Items(namesASN, dataASN, (int)items, &sz);
  24240. }
  24241. /* Check buffer size if passed in. */
  24242. if (ret == 0 && output != NULL && sz > (int)outputSz) {
  24243. ret = BUFFER_E;
  24244. }
  24245. if (ret == 0) {
  24246. if (output != NULL) {
  24247. /* Encode Name. */
  24248. ret = SetASN_Items(namesASN, dataASN, (int)items, output);
  24249. }
  24250. else {
  24251. /* Return the encoding size. */
  24252. ret = sz;
  24253. }
  24254. }
  24255. if (namesASN != NULL)
  24256. XFREE(namesASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24257. if (dataASN != NULL)
  24258. XFREE(dataASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24259. (void)heap;
  24260. return ret;
  24261. #endif
  24262. }
  24263. int SetName(byte* output, word32 outputSz, CertName* name)
  24264. {
  24265. return SetNameEx(output, outputSz, name, NULL);
  24266. }
  24267. #ifdef WOLFSSL_ASN_TEMPLATE
  24268. static int EncodePublicKey(int keyType, byte* output, int outLen,
  24269. RsaKey* rsaKey, ecc_key* eccKey,
  24270. ed25519_key* ed25519Key, ed448_key* ed448Key,
  24271. DsaKey* dsaKey)
  24272. {
  24273. int ret = 0;
  24274. (void)outLen;
  24275. (void)rsaKey;
  24276. (void)eccKey;
  24277. (void)ed25519Key;
  24278. (void)ed448Key;
  24279. (void)dsaKey;
  24280. switch (keyType) {
  24281. #ifndef NO_RSA
  24282. case RSA_KEY:
  24283. ret = SetRsaPublicKey(output, rsaKey, outLen, 1);
  24284. if (ret <= 0) {
  24285. ret = PUBLIC_KEY_E;
  24286. }
  24287. break;
  24288. #endif
  24289. #ifdef HAVE_ECC
  24290. case ECC_KEY:
  24291. ret = SetEccPublicKey(output, eccKey, outLen, 1, 0);
  24292. if (ret <= 0) {
  24293. ret = PUBLIC_KEY_E;
  24294. }
  24295. break;
  24296. #endif /* HAVE_ECC */
  24297. #ifdef HAVE_ED25519
  24298. case ED25519_KEY:
  24299. ret = wc_Ed25519PublicKeyToDer(ed25519Key, output,
  24300. (word32)outLen, 1);
  24301. if (ret <= 0) {
  24302. ret = PUBLIC_KEY_E;
  24303. }
  24304. break;
  24305. #endif
  24306. #ifdef HAVE_ED448
  24307. case ED448_KEY:
  24308. ret = wc_Ed448PublicKeyToDer(ed448Key, output, (word32)outLen, 1);
  24309. if (ret <= 0) {
  24310. ret = PUBLIC_KEY_E;
  24311. }
  24312. break;
  24313. #endif
  24314. default:
  24315. ret = PUBLIC_KEY_E;
  24316. break;
  24317. }
  24318. return ret;
  24319. }
  24320. /* ASN.1 template for certificate extensions.
  24321. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  24322. * All extensions supported for encoding are described.
  24323. */
  24324. static const ASNItem static_certExtsASN[] = {
  24325. /* Basic Constraints Extension - 4.2.1.9 */
  24326. /* BC_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24327. /* BC_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24328. /* BC_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24329. /* BC_STR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  24330. /* cA */
  24331. /* BC_CA */ { 3, ASN_BOOLEAN, 0, 0, 0 },
  24332. /* pathLenConstraint */
  24333. /* BC_PATHLEN */ { 3, ASN_INTEGER, 0, 0, 1 },
  24334. /* Subject Alternative Name - 4.2.1.6 */
  24335. /* SAN_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24336. /* SAN_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24337. /* SAN_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24338. /* SAN_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24339. /* Subject Key Identifier - 4.2.1.2 */
  24340. /* SKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24341. /* SKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24342. /* SKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24343. /* SKID_KEYID */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  24344. /* Authority Key Identifier - 4.2.1.1 */
  24345. /* AKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24346. /* AKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24347. /* AKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24348. /* AKID_STR_SEQ, */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  24349. /* AKID_KEYID */ { 3, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  24350. /* Key Usage - 4.2.1.3 */
  24351. /* KU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24352. /* KU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24353. /* KU_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24354. /* KU_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24355. /* KU_USAGE */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  24356. /* Extended Key Usage - 4,2,1,12 */
  24357. /* EKU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24358. /* EKU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24359. /* EKU_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24360. /* Certificate Policies - 4.2.1.4 */
  24361. /* POLICIES_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24362. /* POLICIES_OID, */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24363. /* POLICIES_STR, */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24364. /* POLICIES_INFO */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  24365. /* Netscape Certificate Type */
  24366. /* NSTYPE_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24367. /* NSTYPE_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24368. /* NSTYPE_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24369. /* NSTYPE_USAGE, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  24370. /* CRLINFO_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24371. /* CRLINFO_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24372. /* CRLINFO_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24373. /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24374. /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24375. /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24376. };
  24377. enum {
  24378. CERTEXTSASN_IDX_BC_SEQ = 0,
  24379. CERTEXTSASN_IDX_BC_OID,
  24380. CERTEXTSASN_IDX_BC_STR,
  24381. CERTEXTSASN_IDX_BC_STR_SEQ,
  24382. CERTEXTSASN_IDX_BC_CA,
  24383. CERTEXTSASN_IDX_BC_PATHLEN,
  24384. CERTEXTSASN_IDX_SAN_SEQ,
  24385. CERTEXTSASN_IDX_SAN_OID,
  24386. CERTEXTSASN_IDX_SAN_CRIT,
  24387. CERTEXTSASN_IDX_SAN_STR,
  24388. CERTEXTSASN_IDX_SKID_SEQ,
  24389. CERTEXTSASN_IDX_SKID_OID,
  24390. CERTEXTSASN_IDX_SKID_STR,
  24391. CERTEXTSASN_IDX_SKID_KEYID,
  24392. CERTEXTSASN_IDX_AKID_SEQ,
  24393. CERTEXTSASN_IDX_AKID_OID,
  24394. CERTEXTSASN_IDX_AKID_STR,
  24395. CERTEXTSASN_IDX_AKID_STR_SEQ,
  24396. CERTEXTSASN_IDX_AKID_KEYID,
  24397. CERTEXTSASN_IDX_KU_SEQ,
  24398. CERTEXTSASN_IDX_KU_OID,
  24399. CERTEXTSASN_IDX_KU_CRIT,
  24400. CERTEXTSASN_IDX_KU_STR,
  24401. CERTEXTSASN_IDX_KU_USAGE,
  24402. CERTEXTSASN_IDX_EKU_SEQ,
  24403. CERTEXTSASN_IDX_EKU_OID,
  24404. CERTEXTSASN_IDX_EKU_STR,
  24405. CERTEXTSASN_IDX_POLICIES_SEQ,
  24406. CERTEXTSASN_IDX_POLICIES_OID,
  24407. CERTEXTSASN_IDX_POLICIES_STR,
  24408. CERTEXTSASN_IDX_POLICIES_INFO,
  24409. CERTEXTSASN_IDX_NSTYPE_SEQ,
  24410. CERTEXTSASN_IDX_NSTYPE_OID,
  24411. CERTEXTSASN_IDX_NSTYPE_STR,
  24412. CERTEXTSASN_IDX_NSTYPE_USAGE,
  24413. CERTEXTSASN_IDX_CRLINFO_SEQ,
  24414. CERTEXTSASN_IDX_CRLINFO_OID,
  24415. CERTEXTSASN_IDX_CRLINFO_STR,
  24416. CERTEXTSASN_IDX_CUSTOM_SEQ,
  24417. CERTEXTSASN_IDX_CUSTOM_OID,
  24418. CERTEXTSASN_IDX_CUSTOM_STR,
  24419. CERTEXTSASN_IDX_START_CUSTOM
  24420. };
  24421. /* Number of items in ASN.1 template for certificate extensions. We multiply
  24422. * by 4 because there are 4 things (seq, OID, crit flag, octet string). */
  24423. #define certExtsASN_Length ((sizeof(static_certExtsASN) / sizeof(ASNItem)) \
  24424. + (NUM_CUSTOM_EXT * 4))
  24425. static const ASNItem customExtASN[] = {
  24426. /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24427. /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24428. /* CUSTOM_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24429. /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24430. };
  24431. static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz,
  24432. int forRequest)
  24433. {
  24434. DECL_ASNSETDATA(dataASN, certExtsASN_Length);
  24435. int sz;
  24436. int ret = 0;
  24437. int i = 0;
  24438. static const byte bcOID[] = { 0x55, 0x1d, 0x13 };
  24439. #ifdef WOLFSSL_ALT_NAMES
  24440. static const byte sanOID[] = { 0x55, 0x1d, 0x11 };
  24441. #endif
  24442. #ifdef WOLFSSL_CERT_EXT
  24443. static const byte skidOID[] = { 0x55, 0x1d, 0x0e };
  24444. static const byte akidOID[] = { 0x55, 0x1d, 0x23 };
  24445. static const byte kuOID[] = { 0x55, 0x1d, 0x0f };
  24446. static const byte ekuOID[] = { 0x55, 0x1d, 0x25 };
  24447. static const byte cpOID[] = { 0x55, 0x1d, 0x20 };
  24448. static const byte nsCertOID[] = { 0x60, 0x86, 0x48, 0x01,
  24449. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  24450. static const byte crlInfoOID[] = { 0x55, 0x1D, 0x1F };
  24451. #endif
  24452. #ifdef WOLFSSL_SMALL_STACK
  24453. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24454. byte *encodedOids;
  24455. #endif
  24456. ASNItem *certExtsASN = (ASNItem *)XMALLOC(certExtsASN_Length *
  24457. sizeof(ASNItem), cert->heap,
  24458. DYNAMIC_TYPE_TMP_BUFFER);
  24459. if (certExtsASN == NULL) {
  24460. return MEMORY_E;
  24461. }
  24462. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24463. encodedOids = (byte *)XMALLOC(NUM_CUSTOM_EXT * MAX_OID_SZ, cert->heap,
  24464. DYNAMIC_TYPE_TMP_BUFFER);
  24465. if (encodedOids == NULL) {
  24466. XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24467. return MEMORY_E;
  24468. }
  24469. #endif
  24470. #else
  24471. ASNItem certExtsASN[certExtsASN_Length];
  24472. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24473. byte encodedOids[NUM_CUSTOM_EXT * MAX_OID_SZ];
  24474. #endif
  24475. #endif
  24476. /* Clone static_certExtsASN into a certExtsASN and then fill the rest of it
  24477. * with (NUM_CUSTOM_EXT*4) more ASNItems specifying extensions. See comment
  24478. * above definition of certExtsASN_Length. */
  24479. XMEMCPY(certExtsASN, static_certExtsASN, sizeof(static_certExtsASN));
  24480. for (i = sizeof(static_certExtsASN) / sizeof(ASNItem);
  24481. i < (int)certExtsASN_Length; i += 4) {
  24482. XMEMCPY(&certExtsASN[i], customExtASN, sizeof(customExtASN));
  24483. }
  24484. (void)forRequest;
  24485. CALLOC_ASNSETDATA(dataASN, certExtsASN_Length, ret, cert->heap);
  24486. if (ret == 0) {
  24487. if (cert->isCA) {
  24488. /* Set Basic Constraints to be a Certificate Authority. */
  24489. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_BC_CA], 1);
  24490. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
  24491. if (cert->pathLenSet
  24492. #ifdef WOLFSSL_CERT_EXT
  24493. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  24494. #endif
  24495. ) {
  24496. SetASN_Int8Bit(&dataASN[CERTEXTSASN_IDX_BC_PATHLEN],
  24497. cert->pathLen);
  24498. }
  24499. else {
  24500. dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
  24501. }
  24502. }
  24503. else if (cert->basicConstSet) {
  24504. /* Set Basic Constraints to be a non Certificate Authority. */
  24505. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
  24506. dataASN[CERTEXTSASN_IDX_BC_CA].noOut = 1;
  24507. dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
  24508. }
  24509. else {
  24510. /* Don't write out Basic Constraints extension items. */
  24511. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_BC_SEQ,
  24512. CERTEXTSASN_IDX_BC_PATHLEN);
  24513. }
  24514. #ifdef WOLFSSL_ALT_NAMES
  24515. if (cert->altNamesSz > 0) {
  24516. /* Set Subject Alternative Name OID and data. */
  24517. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_OID],
  24518. sanOID, sizeof(sanOID));
  24519. if (cert->altNamesCrit) {
  24520. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_SAN_CRIT], 1);
  24521. }
  24522. else {
  24523. dataASN[CERTEXTSASN_IDX_SAN_CRIT].noOut = 1;
  24524. }
  24525. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_STR],
  24526. cert->altNames, (word32)cert->altNamesSz);
  24527. }
  24528. else
  24529. #endif
  24530. {
  24531. /* Don't write out Subject Alternative Name extension items. */
  24532. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SAN_SEQ,
  24533. CERTEXTSASN_IDX_SAN_STR);
  24534. }
  24535. #ifdef WOLFSSL_CERT_EXT
  24536. if (cert->skidSz > 0) {
  24537. /* Set Subject Key Identifier OID and data. */
  24538. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_OID],
  24539. skidOID, sizeof(skidOID));
  24540. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_KEYID],
  24541. cert->skid, (word32)cert->skidSz);
  24542. }
  24543. else
  24544. #endif
  24545. {
  24546. /* Don't write out Subject Key Identifier extension items. */
  24547. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SKID_SEQ,
  24548. CERTEXTSASN_IDX_SKID_KEYID);
  24549. }
  24550. #ifdef WOLFSSL_CERT_EXT
  24551. if (cert->akidSz > 0) {
  24552. /* Set Authority Key Identifier OID and data. */
  24553. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_OID],
  24554. akidOID, sizeof(akidOID));
  24555. #ifdef WOLFSSL_AKID_NAME
  24556. if (cert->rawAkid) {
  24557. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_STR],
  24558. cert->akid, cert->akidSz);
  24559. /* cert->akid contains the internal ext structure */
  24560. SetASNItem_NoOutBelow(dataASN, certExtsASN,
  24561. CERTEXTSASN_IDX_AKID_STR, certExtsASN_Length);
  24562. }
  24563. else
  24564. #endif
  24565. {
  24566. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_KEYID],
  24567. cert->akid, (word32)cert->akidSz);
  24568. }
  24569. }
  24570. else
  24571. #endif
  24572. {
  24573. /* Don't write out Authority Key Identifier extension items. */
  24574. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_AKID_SEQ,
  24575. CERTEXTSASN_IDX_AKID_KEYID);
  24576. }
  24577. #ifdef WOLFSSL_CERT_EXT
  24578. if (cert->keyUsage != 0) {
  24579. /* Set Key Usage OID, critical and value. */
  24580. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_KU_OID],
  24581. kuOID, sizeof(kuOID));
  24582. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_KU_CRIT], 1);
  24583. SetASN_Int16Bit(&dataASN[CERTEXTSASN_IDX_KU_USAGE],
  24584. cert->keyUsage);
  24585. }
  24586. else
  24587. #endif
  24588. {
  24589. /* Don't write out Key Usage extension items. */
  24590. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_KU_SEQ,
  24591. CERTEXTSASN_IDX_KU_USAGE);
  24592. }
  24593. #ifdef WOLFSSL_CERT_EXT
  24594. if (cert->extKeyUsage != 0) {
  24595. /* Calculate size of Extended Key Usage data. */
  24596. sz = SetExtKeyUsage(cert, NULL, 0, cert->extKeyUsage);
  24597. if (sz <= 0) {
  24598. ret = KEYUSAGE_E;
  24599. }
  24600. /* Set Extended Key Usage OID and data. */
  24601. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_OID],
  24602. ekuOID, sizeof(ekuOID));
  24603. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_STR],
  24604. NULL, (word32)sz);
  24605. }
  24606. else
  24607. #endif
  24608. {
  24609. /* Don't write out Extended Key Usage extension items. */
  24610. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_EKU_SEQ,
  24611. CERTEXTSASN_IDX_EKU_STR);
  24612. }
  24613. #ifdef WOLFSSL_CERT_EXT
  24614. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  24615. /* Calculate size of certificate policies. */
  24616. sz = SetCertificatePolicies(NULL, 0, cert->certPolicies,
  24617. cert->certPoliciesNb, cert->heap);
  24618. if (sz > 0) {
  24619. /* Set Certificate Policies OID. */
  24620. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_OID],
  24621. cpOID, sizeof(cpOID));
  24622. /* Make space for data. */
  24623. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_INFO],
  24624. NULL, (word32)sz);
  24625. }
  24626. else {
  24627. ret = CERTPOLICIES_E;
  24628. }
  24629. }
  24630. else
  24631. #endif
  24632. {
  24633. /* Don't write out Certificate Policies extension items. */
  24634. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_POLICIES_SEQ,
  24635. CERTEXTSASN_IDX_POLICIES_INFO);
  24636. }
  24637. #if defined(WOLFSSL_CERT_EXT) && !defined(IGNORE_NETSCAPE_CERT_TYPE)
  24638. /* Netscape Certificate Type */
  24639. if (cert->nsCertType != 0) {
  24640. /* Set Netscape Certificate Type OID and data. */
  24641. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_OID],
  24642. nsCertOID, sizeof(nsCertOID));
  24643. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_USAGE],
  24644. &cert->nsCertType, 1);
  24645. }
  24646. else
  24647. #endif
  24648. {
  24649. /* Don't write out Netscape Certificate Type. */
  24650. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_NSTYPE_SEQ,
  24651. CERTEXTSASN_IDX_NSTYPE_USAGE);
  24652. }
  24653. #ifdef WOLFSSL_CERT_EXT
  24654. if (cert->crlInfoSz > 0) {
  24655. /* Set CRL Distribution Points OID and data. */
  24656. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_OID],
  24657. crlInfoOID, sizeof(crlInfoOID));
  24658. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_STR],
  24659. cert->crlInfo, (word32)cert->crlInfoSz);
  24660. }
  24661. else
  24662. #endif
  24663. {
  24664. /* Don't write out CRL Distribution Points. */
  24665. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CRLINFO_SEQ,
  24666. CERTEXTSASN_IDX_CRLINFO_STR);
  24667. }
  24668. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
  24669. /* encode a custom oid and value */
  24670. if (cert->extCustom.oidSz > 0) {
  24671. /* Set CRL Distribution Points OID and data. */
  24672. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_OID],
  24673. cert->extCustom.oid, cert->extCustom.oidSz);
  24674. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_STR],
  24675. cert->extCustom.val, cert->extCustom.valSz);
  24676. }
  24677. else
  24678. #endif
  24679. {
  24680. /* Don't write out custom OID. */
  24681. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CUSTOM_SEQ,
  24682. CERTEXTSASN_IDX_CUSTOM_STR);
  24683. }
  24684. i = 0;
  24685. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
  24686. for (; i < cert->customCertExtCount; i++) {
  24687. int idx = CERTEXTSASN_IDX_START_CUSTOM + (i * 4);
  24688. word32 encodedOidSz = MAX_OID_SZ;
  24689. idx++; /* Skip one for for SEQ. */
  24690. /* EncodePolicyOID() will never return error since we parsed this
  24691. * OID when it was set. */
  24692. EncodePolicyOID(&encodedOids[i * MAX_OID_SZ], &encodedOidSz,
  24693. cert->customCertExt[i].oid, NULL);
  24694. SetASN_Buffer(&dataASN[idx], &encodedOids[i * MAX_OID_SZ],
  24695. encodedOidSz);
  24696. idx++;
  24697. if (cert->customCertExt[i].crit) {
  24698. SetASN_Boolean(&dataASN[idx], 1);
  24699. } else {
  24700. dataASN[idx].noOut = 1;
  24701. }
  24702. idx++;
  24703. SetASN_Buffer(&dataASN[idx], cert->customCertExt[i].val,
  24704. cert->customCertExt[i].valSz);
  24705. }
  24706. #endif
  24707. while (i < NUM_CUSTOM_EXT) {
  24708. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_START_CUSTOM + (i * 4),
  24709. CERTEXTSASN_IDX_START_CUSTOM + (i * 4) + 3);
  24710. i++;
  24711. }
  24712. }
  24713. if (ret == 0) {
  24714. /* Calculate size of encoded extensions. */
  24715. ret = SizeASN_Items(certExtsASN, dataASN, certExtsASN_Length, &sz);
  24716. }
  24717. if (ret == 0) {
  24718. /* Only SEQUENCE - don't encode extensions. */
  24719. if (sz == 2) {
  24720. sz = 0;
  24721. }
  24722. /* Check buffer is big enough. */
  24723. else if ((output != NULL) && (sz > (int)maxSz)) {
  24724. ret = BUFFER_E;
  24725. }
  24726. }
  24727. if ((ret == 0) && (output != NULL) && (sz > 0)) {
  24728. /* Encode certificate extensions into buffer. */
  24729. SetASN_Items(certExtsASN, dataASN, certExtsASN_Length, output);
  24730. #ifdef WOLFSSL_CERT_EXT
  24731. if (cert->extKeyUsage != 0){
  24732. /* Encode Extended Key Usage into space provided. */
  24733. if (SetExtKeyUsage(cert,
  24734. (byte*)dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.data,
  24735. dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.length,
  24736. cert->extKeyUsage) <= 0) {
  24737. ret = KEYUSAGE_E;
  24738. }
  24739. }
  24740. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  24741. /* Encode Certificate Policies into space provided. */
  24742. if (SetCertificatePolicies(
  24743. (byte*)dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.data,
  24744. dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.length,
  24745. cert->certPolicies, cert->certPoliciesNb, cert->heap) <= 0) {
  24746. ret = CERTPOLICIES_E;
  24747. }
  24748. }
  24749. #endif
  24750. }
  24751. if (ret == 0) {
  24752. /* Return the encoding size. */
  24753. ret = sz;
  24754. }
  24755. FREE_ASNSETDATA(dataASN, cert->heap);
  24756. #ifdef WOLFSSL_SMALL_STACK
  24757. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24758. XFREE(encodedOids, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24759. #endif
  24760. XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24761. #endif
  24762. return ret;
  24763. }
  24764. #endif /* WOLFSSL_ASN_TEMPLATE */
  24765. #ifndef WOLFSSL_ASN_TEMPLATE
  24766. /* Set Date validity from now until now + daysValid
  24767. * return size in bytes written to output, 0 on error */
  24768. /* TODO https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.5
  24769. * "MUST always encode certificate validity dates through the year 2049 as
  24770. * UTCTime; certificate validity dates in 2050 or later MUST be encoded as
  24771. * GeneralizedTime." */
  24772. static int SetValidity(byte* output, int daysValid)
  24773. {
  24774. #ifndef NO_ASN_TIME
  24775. byte before[MAX_DATE_SIZE];
  24776. byte after[MAX_DATE_SIZE];
  24777. word32 beforeSz, afterSz, seqSz;
  24778. time_t now;
  24779. time_t then;
  24780. struct tm* tmpTime;
  24781. struct tm* expandedTime;
  24782. struct tm localTime;
  24783. #if defined(NEED_TMP_TIME)
  24784. /* for use with gmtime_r */
  24785. struct tm tmpTimeStorage;
  24786. tmpTime = &tmpTimeStorage;
  24787. #else
  24788. tmpTime = NULL;
  24789. #endif
  24790. (void)tmpTime;
  24791. now = wc_Time(0);
  24792. /* before now */
  24793. before[0] = ASN_GENERALIZED_TIME;
  24794. beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
  24795. /* subtract 1 day of seconds for more compliance */
  24796. then = now - 86400;
  24797. expandedTime = XGMTIME(&then, tmpTime);
  24798. if (expandedTime == NULL) {
  24799. WOLFSSL_MSG("XGMTIME failed");
  24800. return 0; /* error */
  24801. }
  24802. localTime = *expandedTime;
  24803. /* adjust */
  24804. localTime.tm_year += 1900;
  24805. localTime.tm_mon += 1;
  24806. SetTime(&localTime, before + beforeSz);
  24807. beforeSz += ASN_GEN_TIME_SZ;
  24808. after[0] = ASN_GENERALIZED_TIME;
  24809. afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
  24810. /* add daysValid of seconds */
  24811. then = now + (daysValid * (time_t)86400);
  24812. expandedTime = XGMTIME(&then, tmpTime);
  24813. if (expandedTime == NULL) {
  24814. WOLFSSL_MSG("XGMTIME failed");
  24815. return 0; /* error */
  24816. }
  24817. localTime = *expandedTime;
  24818. /* adjust */
  24819. localTime.tm_year += 1900;
  24820. localTime.tm_mon += 1;
  24821. SetTime(&localTime, after + afterSz);
  24822. afterSz += ASN_GEN_TIME_SZ;
  24823. /* headers and output */
  24824. seqSz = SetSequence(beforeSz + afterSz, output);
  24825. XMEMCPY(output + seqSz, before, beforeSz);
  24826. XMEMCPY(output + seqSz + beforeSz, after, afterSz);
  24827. return (int)(seqSz + beforeSz + afterSz);
  24828. #else
  24829. (void)output;
  24830. (void)daysValid;
  24831. return NOT_COMPILED_IN;
  24832. #endif
  24833. }
  24834. #else
  24835. static int SetValidity(byte* before, byte* after, int daysValid)
  24836. {
  24837. #ifndef NO_ASN_TIME
  24838. int ret = 0;
  24839. time_t now;
  24840. time_t then;
  24841. struct tm* tmpTime;
  24842. struct tm* expandedTime;
  24843. struct tm localTime;
  24844. #if defined(NEED_TMP_TIME)
  24845. /* for use with gmtime_r */
  24846. struct tm tmpTimeStorage;
  24847. tmpTime = &tmpTimeStorage;
  24848. #else
  24849. tmpTime = NULL;
  24850. #endif
  24851. (void)tmpTime;
  24852. now = wc_Time(0);
  24853. /* subtract 1 day of seconds for more compliance */
  24854. then = now - 86400;
  24855. expandedTime = XGMTIME(&then, tmpTime);
  24856. if (expandedTime == NULL) {
  24857. WOLFSSL_MSG("XGMTIME failed");
  24858. ret = DATE_E;
  24859. }
  24860. if (ret == 0) {
  24861. localTime = *expandedTime;
  24862. /* adjust */
  24863. localTime.tm_year += 1900;
  24864. localTime.tm_mon += 1;
  24865. SetTime(&localTime, before);
  24866. /* add daysValid of seconds */
  24867. then = now + (daysValid * (time_t)86400);
  24868. expandedTime = XGMTIME(&then, tmpTime);
  24869. if (expandedTime == NULL) {
  24870. WOLFSSL_MSG("XGMTIME failed");
  24871. ret = DATE_E;
  24872. }
  24873. }
  24874. if (ret == 0) {
  24875. localTime = *expandedTime;
  24876. /* adjust */
  24877. localTime.tm_year += 1900;
  24878. localTime.tm_mon += 1;
  24879. SetTime(&localTime, after);
  24880. }
  24881. return ret;
  24882. #else
  24883. (void)before;
  24884. (void)after;
  24885. (void)daysValid;
  24886. return NOT_COMPILED_IN;
  24887. #endif
  24888. }
  24889. #endif /* WOLFSSL_ASN_TEMPLATE */
  24890. #ifndef WOLFSSL_ASN_TEMPLATE
  24891. /* encode info from cert into DER encoded format */
  24892. static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey,
  24893. WC_RNG* rng, DsaKey* dsaKey, ed25519_key* ed25519Key,
  24894. ed448_key* ed448Key, falcon_key* falconKey,
  24895. dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
  24896. {
  24897. int ret;
  24898. if (cert == NULL || der == NULL || rng == NULL)
  24899. return BAD_FUNC_ARG;
  24900. /* make sure at least one key type is provided */
  24901. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  24902. dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
  24903. dilithiumKey == NULL && sphincsKey == NULL) {
  24904. return PUBLIC_KEY_E;
  24905. }
  24906. /* init */
  24907. XMEMSET(der, 0, sizeof(DerCert));
  24908. /* version */
  24909. der->versionSz = SetMyVersion((word32)cert->version, der->version, TRUE);
  24910. /* serial number (must be positive) */
  24911. if (cert->serialSz == 0) {
  24912. /* generate random serial */
  24913. cert->serialSz = CTC_GEN_SERIAL_SZ;
  24914. ret = wc_RNG_GenerateBlock(rng, cert->serial, (word32)cert->serialSz);
  24915. if (ret != 0)
  24916. return ret;
  24917. /* Clear the top bit to avoid a negative value */
  24918. cert->serial[0] &= 0x7f;
  24919. }
  24920. der->serialSz = SetSerialNumber(cert->serial, (word32)cert->serialSz,
  24921. der->serial, sizeof(der->serial),
  24922. CTC_SERIAL_SIZE);
  24923. if (der->serialSz < 0)
  24924. return der->serialSz;
  24925. /* signature algo */
  24926. der->sigAlgoSz = (int)SetAlgoID(cert->sigType, der->sigAlgo, oidSigType, 0);
  24927. if (der->sigAlgoSz <= 0)
  24928. return ALGO_ID_E;
  24929. /* public key */
  24930. #ifndef NO_RSA
  24931. if (cert->keyType == RSA_KEY) {
  24932. if (rsaKey == NULL)
  24933. return PUBLIC_KEY_E;
  24934. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  24935. sizeof(der->publicKey), 1);
  24936. }
  24937. #endif
  24938. #ifdef HAVE_ECC
  24939. if (cert->keyType == ECC_KEY) {
  24940. if (eccKey == NULL)
  24941. return PUBLIC_KEY_E;
  24942. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  24943. sizeof(der->publicKey), 1, 0);
  24944. }
  24945. #endif
  24946. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  24947. if (cert->keyType == DSA_KEY) {
  24948. if (dsaKey == NULL)
  24949. return PUBLIC_KEY_E;
  24950. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  24951. sizeof(der->publicKey), 1);
  24952. }
  24953. #endif
  24954. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  24955. if (cert->keyType == ED25519_KEY) {
  24956. if (ed25519Key == NULL)
  24957. return PUBLIC_KEY_E;
  24958. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  24959. (word32)sizeof(der->publicKey), 1);
  24960. }
  24961. #endif
  24962. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  24963. if (cert->keyType == ED448_KEY) {
  24964. if (ed448Key == NULL)
  24965. return PUBLIC_KEY_E;
  24966. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  24967. (word32)sizeof(der->publicKey), 1);
  24968. }
  24969. #endif
  24970. #if defined(HAVE_PQC)
  24971. #if defined(HAVE_FALCON)
  24972. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  24973. (cert->keyType == FALCON_LEVEL5_KEY)) {
  24974. if (falconKey == NULL)
  24975. return PUBLIC_KEY_E;
  24976. der->publicKeySz =
  24977. wc_Falcon_PublicKeyToDer(falconKey, der->publicKey,
  24978. (word32)sizeof(der->publicKey), 1);
  24979. }
  24980. #endif /* HAVE_FALCON */
  24981. #if defined(HAVE_DILITHIUM)
  24982. if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
  24983. (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
  24984. (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
  24985. if (dilithiumKey == NULL)
  24986. return PUBLIC_KEY_E;
  24987. der->publicKeySz =
  24988. wc_Dilithium_PublicKeyToDer(dilithiumKey, der->publicKey,
  24989. (word32)sizeof(der->publicKey), 1);
  24990. }
  24991. #endif /* HAVE_DILITHIUM */
  24992. #if defined(HAVE_SPHINCS)
  24993. if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
  24994. (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
  24995. (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
  24996. (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
  24997. (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
  24998. (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
  24999. if (sphincsKey == NULL)
  25000. return PUBLIC_KEY_E;
  25001. der->publicKeySz =
  25002. wc_Sphincs_PublicKeyToDer(sphincsKey, der->publicKey,
  25003. (word32)sizeof(der->publicKey), 1);
  25004. }
  25005. #endif /* HAVE_SPHINCS */
  25006. #endif /* HAVE_PQC */
  25007. if (der->publicKeySz <= 0)
  25008. return PUBLIC_KEY_E;
  25009. der->validitySz = 0;
  25010. /* copy date validity if already set in cert struct */
  25011. if (cert->beforeDateSz && cert->afterDateSz) {
  25012. der->validitySz = CopyValidity(der->validity, cert);
  25013. if (der->validitySz <= 0)
  25014. return DATE_E;
  25015. }
  25016. /* set date validity using daysValid if not set already */
  25017. if (der->validitySz == 0) {
  25018. der->validitySz = SetValidity(der->validity, cert->daysValid);
  25019. if (der->validitySz <= 0)
  25020. return DATE_E;
  25021. }
  25022. /* subject name */
  25023. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  25024. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  25025. /* Use the raw subject */
  25026. word32 idx;
  25027. der->subjectSz = (int)min((word32)sizeof(der->subject),
  25028. (word32)XSTRLEN((const char*)cert->sbjRaw));
  25029. /* header */
  25030. idx = SetSequence((word32)der->subjectSz, der->subject);
  25031. if ((word32)der->subjectSz + idx > (word32)sizeof(der->subject)) {
  25032. return SUBJECT_E;
  25033. }
  25034. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  25035. (size_t)der->subjectSz);
  25036. der->subjectSz += (int)idx;
  25037. }
  25038. else
  25039. #endif
  25040. {
  25041. /* Use the name structure */
  25042. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  25043. &cert->subject, cert->heap);
  25044. }
  25045. if (der->subjectSz <= 0)
  25046. return SUBJECT_E;
  25047. /* issuer name */
  25048. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  25049. if (XSTRLEN((const char*)cert->issRaw) > 0) {
  25050. /* Use the raw issuer */
  25051. word32 idx;
  25052. der->issuerSz = (int)min((word32)sizeof(der->issuer),
  25053. (word32)XSTRLEN((const char*)cert->issRaw));
  25054. /* header */
  25055. idx = SetSequence((word32)der->issuerSz, der->issuer);
  25056. if ((word32)der->issuerSz + idx > (word32)sizeof(der->issuer)) {
  25057. return ISSUER_E;
  25058. }
  25059. XMEMCPY((char*)der->issuer + idx, (const char*)cert->issRaw,
  25060. (size_t)der->issuerSz);
  25061. der->issuerSz += (int)idx;
  25062. }
  25063. else
  25064. #endif
  25065. {
  25066. /* Use the name structure */
  25067. der->issuerSz = SetNameEx(der->issuer, sizeof(der->issuer),
  25068. cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
  25069. }
  25070. if (der->issuerSz <= 0)
  25071. return ISSUER_E;
  25072. /* set the extensions */
  25073. der->extensionsSz = 0;
  25074. /* RFC 5280 : 4.2.1.9. Basic Constraints
  25075. * The pathLenConstraint field is meaningful only if the CA boolean is
  25076. * asserted and the key usage extension, if present, asserts the
  25077. * keyCertSign bit */
  25078. /* Set CA and path length */
  25079. if ((cert->isCA) && (cert->pathLenSet)
  25080. #ifdef WOLFSSL_CERT_EXT
  25081. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  25082. #endif
  25083. ) {
  25084. der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
  25085. if (der->caSz <= 0)
  25086. return CA_TRUE_E;
  25087. der->extensionsSz += der->caSz;
  25088. }
  25089. /* Set CA */
  25090. else if (cert->isCA) {
  25091. der->caSz = SetCa(der->ca, sizeof(der->ca));
  25092. if (der->caSz <= 0)
  25093. return CA_TRUE_E;
  25094. der->extensionsSz += der->caSz;
  25095. }
  25096. /* Set Basic Constraint */
  25097. else if (cert->basicConstSet) {
  25098. der->caSz = SetBC(der->ca, sizeof(der->ca));
  25099. if (der->caSz <= 0)
  25100. return EXTENSIONS_E;
  25101. der->extensionsSz += der->caSz;
  25102. }
  25103. else
  25104. der->caSz = 0;
  25105. #ifdef WOLFSSL_ALT_NAMES
  25106. /* Alternative Name */
  25107. if (cert->altNamesSz) {
  25108. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  25109. cert->altNames, (word32)cert->altNamesSz,
  25110. cert->altNamesCrit);
  25111. if (der->altNamesSz <= 0)
  25112. return ALT_NAME_E;
  25113. der->extensionsSz += der->altNamesSz;
  25114. }
  25115. else
  25116. der->altNamesSz = 0;
  25117. #endif
  25118. #ifdef WOLFSSL_CERT_EXT
  25119. /* SKID */
  25120. if (cert->skidSz) {
  25121. /* check the provided SKID size */
  25122. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  25123. return SKID_E;
  25124. /* Note: different skid buffers sizes for der (MAX_KID_SZ) and
  25125. cert (CTC_MAX_SKID_SIZE). */
  25126. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  25127. cert->skid, (word32)cert->skidSz);
  25128. if (der->skidSz <= 0)
  25129. return SKID_E;
  25130. der->extensionsSz += der->skidSz;
  25131. }
  25132. else
  25133. der->skidSz = 0;
  25134. /* AKID */
  25135. if (cert->akidSz) {
  25136. /* check the provided AKID size */
  25137. if ((
  25138. #ifdef WOLFSSL_AKID_NAME
  25139. !cert->rawAkid &&
  25140. #endif
  25141. cert->akidSz > (int)min(CTC_MAX_AKID_SIZE, sizeof(der->akid)))
  25142. #ifdef WOLFSSL_AKID_NAME
  25143. || (cert->rawAkid && cert->akidSz > (int)sizeof(der->akid))
  25144. #endif
  25145. )
  25146. return AKID_E;
  25147. der->akidSz = SetAKID(der->akid, sizeof(der->akid), cert->akid,
  25148. (word32)cert->akidSz,
  25149. #ifdef WOLFSSL_AKID_NAME
  25150. cert->rawAkid
  25151. #else
  25152. 0
  25153. #endif
  25154. );
  25155. if (der->akidSz <= 0)
  25156. return AKID_E;
  25157. der->extensionsSz += der->akidSz;
  25158. }
  25159. else
  25160. der->akidSz = 0;
  25161. /* Key Usage */
  25162. if (cert->keyUsage != 0){
  25163. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  25164. cert->keyUsage);
  25165. if (der->keyUsageSz <= 0)
  25166. return KEYUSAGE_E;
  25167. der->extensionsSz += der->keyUsageSz;
  25168. }
  25169. else
  25170. der->keyUsageSz = 0;
  25171. /* Extended Key Usage */
  25172. if (cert->extKeyUsage != 0){
  25173. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  25174. sizeof(der->extKeyUsage), cert->extKeyUsage);
  25175. if (der->extKeyUsageSz <= 0)
  25176. return EXTKEYUSAGE_E;
  25177. der->extensionsSz += der->extKeyUsageSz;
  25178. }
  25179. else
  25180. der->extKeyUsageSz = 0;
  25181. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  25182. /* Netscape Certificate Type */
  25183. if (cert->nsCertType != 0) {
  25184. der->nsCertTypeSz = SetNsCertType(cert, der->nsCertType,
  25185. sizeof(der->nsCertType), cert->nsCertType);
  25186. if (der->nsCertTypeSz <= 0)
  25187. return EXTENSIONS_E;
  25188. der->extensionsSz += der->nsCertTypeSz;
  25189. }
  25190. else
  25191. der->nsCertTypeSz = 0;
  25192. #endif
  25193. if (cert->crlInfoSz > 0) {
  25194. der->crlInfoSz = SetCRLInfo(cert, der->crlInfo, sizeof(der->crlInfo),
  25195. cert->crlInfo, cert->crlInfoSz);
  25196. if (der->crlInfoSz <= 0)
  25197. return EXTENSIONS_E;
  25198. der->extensionsSz += der->crlInfoSz;
  25199. }
  25200. else
  25201. der->crlInfoSz = 0;
  25202. /* Certificate Policies */
  25203. if (cert->certPoliciesNb != 0) {
  25204. der->certPoliciesSz = SetCertificatePolicies(der->certPolicies,
  25205. sizeof(der->certPolicies),
  25206. cert->certPolicies,
  25207. cert->certPoliciesNb,
  25208. cert->heap);
  25209. if (der->certPoliciesSz <= 0)
  25210. return CERTPOLICIES_E;
  25211. der->extensionsSz += der->certPoliciesSz;
  25212. }
  25213. else
  25214. der->certPoliciesSz = 0;
  25215. #endif /* WOLFSSL_CERT_EXT */
  25216. /* put extensions */
  25217. if (der->extensionsSz > 0) {
  25218. /* put the start of extensions sequence (ID, Size) */
  25219. der->extensionsSz = SetExtensionsHeader(der->extensions,
  25220. sizeof(der->extensions),
  25221. (word32)der->extensionsSz);
  25222. if (der->extensionsSz <= 0)
  25223. return EXTENSIONS_E;
  25224. /* put CA */
  25225. if (der->caSz) {
  25226. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25227. &der->extensionsSz,
  25228. der->ca, der->caSz);
  25229. if (ret == 0)
  25230. return EXTENSIONS_E;
  25231. }
  25232. #ifdef WOLFSSL_ALT_NAMES
  25233. /* put Alternative Names */
  25234. if (der->altNamesSz) {
  25235. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25236. &der->extensionsSz,
  25237. der->altNames, der->altNamesSz);
  25238. if (ret <= 0)
  25239. return EXTENSIONS_E;
  25240. }
  25241. #endif
  25242. #ifdef WOLFSSL_CERT_EXT
  25243. /* put SKID */
  25244. if (der->skidSz) {
  25245. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25246. &der->extensionsSz,
  25247. der->skid, der->skidSz);
  25248. if (ret <= 0)
  25249. return EXTENSIONS_E;
  25250. }
  25251. /* put AKID */
  25252. if (der->akidSz) {
  25253. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25254. &der->extensionsSz,
  25255. der->akid, der->akidSz);
  25256. if (ret <= 0)
  25257. return EXTENSIONS_E;
  25258. }
  25259. /* put CRL Distribution Points */
  25260. if (der->crlInfoSz) {
  25261. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25262. &der->extensionsSz,
  25263. der->crlInfo, der->crlInfoSz);
  25264. if (ret <= 0)
  25265. return EXTENSIONS_E;
  25266. }
  25267. /* put KeyUsage */
  25268. if (der->keyUsageSz) {
  25269. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25270. &der->extensionsSz,
  25271. der->keyUsage, der->keyUsageSz);
  25272. if (ret <= 0)
  25273. return EXTENSIONS_E;
  25274. }
  25275. /* put ExtendedKeyUsage */
  25276. if (der->extKeyUsageSz) {
  25277. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25278. &der->extensionsSz,
  25279. der->extKeyUsage, der->extKeyUsageSz);
  25280. if (ret <= 0)
  25281. return EXTENSIONS_E;
  25282. }
  25283. /* put Netscape Cert Type */
  25284. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  25285. if (der->nsCertTypeSz) {
  25286. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25287. &der->extensionsSz,
  25288. der->nsCertType, der->nsCertTypeSz);
  25289. if (ret <= 0)
  25290. return EXTENSIONS_E;
  25291. }
  25292. #endif
  25293. /* put Certificate Policies */
  25294. if (der->certPoliciesSz) {
  25295. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25296. &der->extensionsSz,
  25297. der->certPolicies, der->certPoliciesSz);
  25298. if (ret <= 0)
  25299. return EXTENSIONS_E;
  25300. }
  25301. #endif /* WOLFSSL_CERT_EXT */
  25302. }
  25303. der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
  25304. der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
  25305. der->extensionsSz;
  25306. return 0;
  25307. }
  25308. /* write DER encoded cert to buffer, size already checked */
  25309. static int WriteCertBody(DerCert* der, byte* buf)
  25310. {
  25311. word32 idx;
  25312. /* signed part header */
  25313. idx = SetSequence((word32)der->total, buf);
  25314. /* version */
  25315. XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
  25316. idx += (word32)der->versionSz;
  25317. /* serial */
  25318. XMEMCPY(buf + idx, der->serial, (size_t)der->serialSz);
  25319. idx += (word32)der->serialSz;
  25320. /* sig algo */
  25321. XMEMCPY(buf + idx, der->sigAlgo, (size_t)der->sigAlgoSz);
  25322. idx += (word32)der->sigAlgoSz;
  25323. /* issuer */
  25324. XMEMCPY(buf + idx, der->issuer, (size_t)der->issuerSz);
  25325. idx += (word32)der->issuerSz;
  25326. /* validity */
  25327. XMEMCPY(buf + idx, der->validity, (size_t)der->validitySz);
  25328. idx += (word32)der->validitySz;
  25329. /* subject */
  25330. XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
  25331. idx += (word32)der->subjectSz;
  25332. /* public key */
  25333. XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
  25334. idx += (word32)der->publicKeySz;
  25335. if (der->extensionsSz) {
  25336. /* extensions */
  25337. XMEMCPY(buf + idx, der->extensions,
  25338. min((word32)der->extensionsSz,
  25339. (word32)sizeof(der->extensions)));
  25340. idx += (word32)der->extensionsSz;
  25341. }
  25342. return (int)idx;
  25343. }
  25344. #endif /* !WOLFSSL_ASN_TEMPLATE */
  25345. /* Make signature from buffer (sz), write to sig (sigSz) */
  25346. static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz,
  25347. byte* sig, word32 sigSz, RsaKey* rsaKey, ecc_key* eccKey,
  25348. ed25519_key* ed25519Key, ed448_key* ed448Key, falcon_key* falconKey,
  25349. dilithium_key* dilithiumKey, sphincs_key* sphincsKey, WC_RNG* rng,
  25350. word32 sigAlgoType, void* heap)
  25351. {
  25352. int digestSz = 0, typeH = 0, ret = 0;
  25353. (void)digestSz;
  25354. (void)typeH;
  25355. (void)buf;
  25356. (void)sz;
  25357. (void)sig;
  25358. (void)sigSz;
  25359. (void)rsaKey;
  25360. (void)eccKey;
  25361. (void)ed25519Key;
  25362. (void)ed448Key;
  25363. (void)falconKey;
  25364. (void)dilithiumKey;
  25365. (void)sphincsKey;
  25366. (void)rng;
  25367. (void)heap;
  25368. switch (certSignCtx->state) {
  25369. case CERTSIGN_STATE_BEGIN:
  25370. case CERTSIGN_STATE_DIGEST:
  25371. certSignCtx->state = CERTSIGN_STATE_DIGEST;
  25372. certSignCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, heap,
  25373. DYNAMIC_TYPE_TMP_BUFFER);
  25374. if (certSignCtx->digest == NULL) {
  25375. ret = MEMORY_E; goto exit_ms;
  25376. }
  25377. ret = HashForSignature(buf, sz, sigAlgoType, certSignCtx->digest,
  25378. &typeH, &digestSz, 0);
  25379. /* set next state, since WC_PENDING_E rentry for these are not "call again" */
  25380. certSignCtx->state = CERTSIGN_STATE_ENCODE;
  25381. if (ret != 0) {
  25382. goto exit_ms;
  25383. }
  25384. FALL_THROUGH;
  25385. case CERTSIGN_STATE_ENCODE:
  25386. #ifndef NO_RSA
  25387. if (rsaKey) {
  25388. certSignCtx->encSig = (byte*)XMALLOC(MAX_DER_DIGEST_SZ, heap,
  25389. DYNAMIC_TYPE_TMP_BUFFER);
  25390. if (certSignCtx->encSig == NULL) {
  25391. ret = MEMORY_E; goto exit_ms;
  25392. }
  25393. /* signature */
  25394. certSignCtx->encSigSz = (int)wc_EncodeSignature(certSignCtx->encSig,
  25395. certSignCtx->digest, (word32)digestSz, typeH);
  25396. }
  25397. #endif /* !NO_RSA */
  25398. FALL_THROUGH;
  25399. case CERTSIGN_STATE_DO:
  25400. certSignCtx->state = CERTSIGN_STATE_DO;
  25401. ret = ALGO_ID_E; /* default to error */
  25402. #ifndef NO_RSA
  25403. if (rsaKey) {
  25404. /* signature */
  25405. ret = wc_RsaSSL_Sign(certSignCtx->encSig,
  25406. (word32)certSignCtx->encSigSz,
  25407. sig, sigSz, rsaKey, rng);
  25408. }
  25409. #endif /* !NO_RSA */
  25410. #if defined(HAVE_ECC) && defined(HAVE_ECC_SIGN)
  25411. if (!rsaKey && eccKey) {
  25412. word32 outSz = sigSz;
  25413. ret = wc_ecc_sign_hash(certSignCtx->digest, (word32)digestSz,
  25414. sig, &outSz, rng, eccKey);
  25415. if (ret == 0)
  25416. ret = (int)outSz;
  25417. }
  25418. #endif /* HAVE_ECC && HAVE_ECC_SIGN */
  25419. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_SIGN)
  25420. if (!rsaKey && !eccKey && ed25519Key) {
  25421. word32 outSz = sigSz;
  25422. ret = wc_ed25519_sign_msg(buf, sz, sig, &outSz, ed25519Key);
  25423. if (ret == 0)
  25424. ret = (int)outSz;
  25425. }
  25426. #endif /* HAVE_ED25519 && HAVE_ED25519_SIGN */
  25427. #if defined(HAVE_ED448) && defined(HAVE_ED448_SIGN)
  25428. if (!rsaKey && !eccKey && !ed25519Key && ed448Key) {
  25429. word32 outSz = sigSz;
  25430. ret = wc_ed448_sign_msg(buf, sz, sig, &outSz, ed448Key, NULL, 0);
  25431. if (ret == 0)
  25432. ret = (int)outSz;
  25433. }
  25434. #endif /* HAVE_ED448 && HAVE_ED448_SIGN */
  25435. #if defined(HAVE_PQC)
  25436. #if defined(HAVE_FALCON)
  25437. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && falconKey) {
  25438. word32 outSz = sigSz;
  25439. ret = wc_falcon_sign_msg(buf, sz, sig, &outSz, falconKey);
  25440. if (ret == 0)
  25441. ret = outSz;
  25442. }
  25443. #endif /* HAVE_FALCON */
  25444. #if defined(HAVE_DILITHIUM)
  25445. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
  25446. dilithiumKey) {
  25447. word32 outSz = sigSz;
  25448. ret = wc_dilithium_sign_msg(buf, sz, sig, &outSz, dilithiumKey);
  25449. if (ret == 0)
  25450. ret = outSz;
  25451. }
  25452. #endif /* HAVE_DILITHIUM */
  25453. #if defined(HAVE_SPHINCS)
  25454. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
  25455. !dilithiumKey && sphincsKey) {
  25456. word32 outSz = sigSz;
  25457. ret = wc_sphincs_sign_msg(buf, sz, sig, &outSz, sphincsKey);
  25458. if (ret == 0)
  25459. ret = outSz;
  25460. }
  25461. #endif /* HAVE_SPHINCS */
  25462. #endif /* HAVE_PQC */
  25463. break;
  25464. }
  25465. exit_ms:
  25466. #ifdef WOLFSSL_ASYNC_CRYPT
  25467. if (ret == WC_PENDING_E) {
  25468. return ret;
  25469. }
  25470. #endif
  25471. #ifndef NO_RSA
  25472. if (rsaKey) {
  25473. XFREE(certSignCtx->encSig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25474. }
  25475. #endif /* !NO_RSA */
  25476. XFREE(certSignCtx->digest, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25477. certSignCtx->digest = NULL;
  25478. /* reset state */
  25479. certSignCtx->state = CERTSIGN_STATE_BEGIN;
  25480. if (ret < 0) {
  25481. WOLFSSL_ERROR_VERBOSE(ret);
  25482. }
  25483. return ret;
  25484. }
  25485. #ifdef WOLFSSL_ASN_TEMPLATE
  25486. /* Generate a random integer value of at most len bytes.
  25487. *
  25488. * Most-significant bit will not be set when maximum size.
  25489. * Random value may be smaller than maximum size in bytes.
  25490. *
  25491. * @param [in] rng Random number generator.
  25492. * @param [out] out Buffer to hold integer value.
  25493. * @param [in] len Maximum number of bytes of integer.
  25494. * @return 0 on success.
  25495. * @return -ve when random number generation failed.
  25496. */
  25497. static int GenerateInteger(WC_RNG* rng, byte* out, word32 len)
  25498. {
  25499. int ret;
  25500. /* Generate random number. */
  25501. ret = wc_RNG_GenerateBlock(rng, out, len);
  25502. if (ret == 0) {
  25503. int i;
  25504. /* Clear the top bit to make positive. */
  25505. out[0] &= 0x7f;
  25506. /* Find first non-zero byte. One zero byte is valid though. */
  25507. for (i = 0; i < (int)len - 1; i++) {
  25508. if (out[i] != 0) {
  25509. break;
  25510. }
  25511. }
  25512. if (i != 0) {
  25513. /* Remove leading zeros. */
  25514. XMEMMOVE(out, out + i, (size_t)len - (size_t)i);
  25515. }
  25516. }
  25517. return ret;
  25518. }
  25519. /* ASN.1 template for a Certificate.
  25520. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  25521. */
  25522. static const ASNItem sigASN[] = {
  25523. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25524. /* tbsCertificate */
  25525. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  25526. /* signatureAlgorithm */
  25527. /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  25528. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  25529. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  25530. /* signatureValue */
  25531. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  25532. };
  25533. enum {
  25534. SIGASN_IDX_SEQ = 0,
  25535. SIGASN_IDX_TBS_SEQ,
  25536. SIGASN_IDX_SIGALGO_SEQ,
  25537. SIGASN_IDX_SIGALGO_OID,
  25538. SIGASN_IDX_SIGALGO_NULL,
  25539. SIGASN_IDX_SIGNATURE
  25540. };
  25541. /* Number of items in ASN.1 template for a Certificate. */
  25542. #define sigASN_Length (sizeof(sigASN) / sizeof(ASNItem))
  25543. #endif
  25544. /* add signature to end of buffer, size of buffer assumed checked, return
  25545. new length */
  25546. int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz,
  25547. int sigAlgoType)
  25548. {
  25549. #ifndef WOLFSSL_ASN_TEMPLATE
  25550. byte seq[MAX_SEQ_SZ];
  25551. word32 idx, seqSz;
  25552. if ((bodySz < 0) || (sigSz < 0))
  25553. return BUFFER_E;
  25554. idx = (word32)bodySz;
  25555. /* algo */
  25556. idx += SetAlgoID(sigAlgoType, buf ? buf + idx : NULL, oidSigType, 0);
  25557. /* bit string */
  25558. idx += SetBitString((word32)sigSz, 0, buf ? buf + idx : NULL);
  25559. /* signature */
  25560. if (buf)
  25561. XMEMCPY(buf + idx, sig, (size_t)sigSz);
  25562. idx += (word32)sigSz;
  25563. /* make room for overall header */
  25564. seqSz = SetSequence(idx, seq);
  25565. if (buf) {
  25566. XMEMMOVE(buf + seqSz, buf, idx);
  25567. XMEMCPY(buf, seq, seqSz);
  25568. }
  25569. return (int)(idx + seqSz);
  25570. #else
  25571. DECL_ASNSETDATA(dataASN, sigASN_Length);
  25572. word32 seqSz;
  25573. int sz;
  25574. int ret = 0;
  25575. CALLOC_ASNSETDATA(dataASN, sigASN_Length, ret, NULL);
  25576. /* In place, put body between SEQUENCE and signature. */
  25577. if (ret == 0) {
  25578. /* Set signature OID and signature data. */
  25579. SetASN_OID(&dataASN[SIGASN_IDX_SIGALGO_OID], (word32)sigAlgoType,
  25580. oidSigType);
  25581. if (IsSigAlgoECC((word32)sigAlgoType)) {
  25582. /* ECDSA and EdDSA doesn't have NULL tagged item. */
  25583. dataASN[SIGASN_IDX_SIGALGO_NULL].noOut = 1;
  25584. }
  25585. SetASN_Buffer(&dataASN[SIGASN_IDX_SIGNATURE], sig, (word32)sigSz);
  25586. /* Calculate size of signature data. */
  25587. ret = SizeASN_Items(&sigASN[SIGASN_IDX_SIGALGO_SEQ],
  25588. &dataASN[SIGASN_IDX_SIGALGO_SEQ], sigASN_Length - 2, &sz);
  25589. }
  25590. if (ret == 0) {
  25591. /* Calculate size of outer sequence by calculating size of the encoded
  25592. * length and adding 1 for tag. */
  25593. seqSz = SizeASNHeader((word32)bodySz + (word32)sz);
  25594. if (buf != NULL) {
  25595. /* Move body to after sequence. */
  25596. XMEMMOVE(buf + seqSz, buf, (size_t)bodySz);
  25597. }
  25598. /* Leave space for body in encoding. */
  25599. SetASN_ReplaceBuffer(&dataASN[SIGASN_IDX_TBS_SEQ], NULL,
  25600. (word32)bodySz);
  25601. /* Calculate overall size and put in offsets and lengths. */
  25602. ret = SizeASN_Items(sigASN, dataASN, sigASN_Length, &sz);
  25603. }
  25604. if ((ret == 0) && (buf != NULL)) {
  25605. /* Write SEQUENCE and signature around body. */
  25606. SetASN_Items(sigASN, dataASN, sigASN_Length, buf);
  25607. }
  25608. if (ret == 0) {
  25609. /* Return the encoding size. */
  25610. ret = sz;
  25611. }
  25612. FREE_ASNSETDATA(dataASN, NULL);
  25613. return ret;
  25614. #endif /* WOLFSSL_ASN_TEMPLATE */
  25615. }
  25616. /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
  25617. static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
  25618. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng,
  25619. DsaKey* dsaKey, ed25519_key* ed25519Key,
  25620. ed448_key* ed448Key, falcon_key* falconKey,
  25621. dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
  25622. {
  25623. #ifndef WOLFSSL_ASN_TEMPLATE
  25624. int ret;
  25625. #ifdef WOLFSSL_SMALL_STACK
  25626. DerCert* der;
  25627. #else
  25628. DerCert der[1];
  25629. #endif
  25630. if (derBuffer == NULL)
  25631. return BAD_FUNC_ARG;
  25632. if (eccKey)
  25633. cert->keyType = ECC_KEY;
  25634. else if (rsaKey)
  25635. cert->keyType = RSA_KEY;
  25636. else if (dsaKey)
  25637. cert->keyType = DSA_KEY;
  25638. else if (ed25519Key)
  25639. cert->keyType = ED25519_KEY;
  25640. else if (ed448Key)
  25641. cert->keyType = ED448_KEY;
  25642. #ifdef HAVE_PQC
  25643. #ifdef HAVE_FALCON
  25644. else if ((falconKey != NULL) && (falconKey->level == 1))
  25645. cert->keyType = FALCON_LEVEL1_KEY;
  25646. else if ((falconKey != NULL) && (falconKey->level == 5))
  25647. cert->keyType = FALCON_LEVEL5_KEY;
  25648. #endif /* HAVE_FALCON */
  25649. #ifdef HAVE_DILITHIUM
  25650. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
  25651. cert->keyType = DILITHIUM_LEVEL2_KEY;
  25652. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
  25653. cert->keyType = DILITHIUM_LEVEL3_KEY;
  25654. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
  25655. cert->keyType = DILITHIUM_LEVEL5_KEY;
  25656. #endif /* HAVE_DILITHIUM */
  25657. #ifdef HAVE_SPHINCS
  25658. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25659. && (sphincsKey->optim == FAST_VARIANT))
  25660. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  25661. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25662. && (sphincsKey->optim == FAST_VARIANT))
  25663. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  25664. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25665. && (sphincsKey->optim == FAST_VARIANT))
  25666. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  25667. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25668. && (sphincsKey->optim == SMALL_VARIANT))
  25669. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  25670. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25671. && (sphincsKey->optim == SMALL_VARIANT))
  25672. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  25673. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25674. && (sphincsKey->optim == SMALL_VARIANT))
  25675. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  25676. #endif /* HAVE_SPHINCS */
  25677. #endif /* HAVE_PQC */
  25678. else
  25679. return BAD_FUNC_ARG;
  25680. #ifdef WOLFSSL_SMALL_STACK
  25681. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25682. if (der == NULL)
  25683. return MEMORY_E;
  25684. #endif
  25685. ret = EncodeCert(cert, der, rsaKey, eccKey, rng, dsaKey, ed25519Key,
  25686. ed448Key, falconKey, dilithiumKey, sphincsKey);
  25687. if (ret == 0) {
  25688. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  25689. ret = BUFFER_E;
  25690. else
  25691. ret = cert->bodySz = WriteCertBody(der, derBuffer);
  25692. }
  25693. #ifdef WOLFSSL_SMALL_STACK
  25694. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25695. #endif
  25696. return ret;
  25697. #else
  25698. /* TODO: issRaw and sbjRaw should be NUL terminated. */
  25699. DECL_ASNSETDATA(dataASN, x509CertASN_Length);
  25700. word32 publicKeySz = 0;
  25701. word32 issuerSz = 0;
  25702. word32 subjectSz = 0;
  25703. word32 extSz = 0;
  25704. int sz = 0;
  25705. int ret = 0;
  25706. word32 issRawLen = 0;
  25707. word32 sbjRawLen = 0;
  25708. /* Unused without OQS */
  25709. (void)falconKey;
  25710. (void)dilithiumKey;
  25711. (void)sphincsKey;
  25712. CALLOC_ASNSETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  25713. if (ret == 0) {
  25714. /* Set key type into certificate object based on key passed in. */
  25715. if (rsaKey) {
  25716. cert->keyType = RSA_KEY;
  25717. }
  25718. else if (eccKey) {
  25719. cert->keyType = ECC_KEY;
  25720. }
  25721. else if (dsaKey) {
  25722. cert->keyType = DSA_KEY;
  25723. }
  25724. else if (ed25519Key) {
  25725. cert->keyType = ED25519_KEY;
  25726. }
  25727. else if (ed448Key) {
  25728. cert->keyType = ED448_KEY;
  25729. }
  25730. #ifdef HAVE_PQC
  25731. #ifdef HAVE_FALCON
  25732. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  25733. cert->keyType = FALCON_LEVEL1_KEY;
  25734. }
  25735. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  25736. cert->keyType = FALCON_LEVEL5_KEY;
  25737. }
  25738. #endif /* HAVE_FALCON */
  25739. #ifdef HAVE_DILITHIUM
  25740. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
  25741. cert->keyType = DILITHIUM_LEVEL2_KEY;
  25742. }
  25743. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
  25744. cert->keyType = DILITHIUM_LEVEL3_KEY;
  25745. }
  25746. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
  25747. cert->keyType = DILITHIUM_LEVEL5_KEY;
  25748. }
  25749. #endif /* HAVE_DILITHIUM */
  25750. #ifdef HAVE_SPHINCS
  25751. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25752. && (sphincsKey->optim == FAST_VARIANT)) {
  25753. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  25754. }
  25755. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25756. && (sphincsKey->optim == FAST_VARIANT)) {
  25757. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  25758. }
  25759. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25760. && (sphincsKey->optim == FAST_VARIANT)) {
  25761. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  25762. }
  25763. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25764. && (sphincsKey->optim == SMALL_VARIANT)) {
  25765. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  25766. }
  25767. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25768. && (sphincsKey->optim == SMALL_VARIANT)) {
  25769. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  25770. }
  25771. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25772. && (sphincsKey->optim == SMALL_VARIANT)) {
  25773. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  25774. }
  25775. #endif /* HAVE_SPHINCS */
  25776. #endif /* HAVE_PQC */
  25777. else {
  25778. ret = BAD_FUNC_ARG;
  25779. }
  25780. }
  25781. if ((ret == 0) && (cert->serialSz == 0)) {
  25782. /* Generate random serial number. */
  25783. cert->serialSz = CTC_GEN_SERIAL_SZ;
  25784. ret = GenerateInteger(rng, cert->serial, CTC_GEN_SERIAL_SZ);
  25785. }
  25786. if (ret == 0) {
  25787. /* Determine issuer name size. */
  25788. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25789. defined(WOLFSSL_CERT_REQ)
  25790. issRawLen = (word32)XSTRLEN((const char*)cert->issRaw);
  25791. if (issRawLen > 0) {
  25792. issuerSz = min(sizeof(cert->issRaw), issRawLen);
  25793. }
  25794. else
  25795. #endif
  25796. {
  25797. /* Calculate issuer name encoding size. If the cert is self-signed
  25798. * use the subject instead of the issuer. */
  25799. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, cert->selfSigned ?
  25800. &cert->subject : &cert->issuer, cert->heap);
  25801. issuerSz = (word32)ret;
  25802. }
  25803. }
  25804. if (ret >= 0) {
  25805. /* Determine subject name size. */
  25806. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25807. defined(WOLFSSL_CERT_REQ)
  25808. sbjRawLen = (word32)XSTRLEN((const char*)cert->sbjRaw);
  25809. if (sbjRawLen > 0) {
  25810. subjectSz = min(sizeof(cert->sbjRaw), sbjRawLen);
  25811. }
  25812. else
  25813. #endif
  25814. {
  25815. /* Calculate subject name encoding size. */
  25816. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject,
  25817. cert->heap);
  25818. subjectSz = (word32)ret;
  25819. }
  25820. }
  25821. if (ret >= 0) {
  25822. /* Calculate public key encoding size. */
  25823. ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  25824. eccKey, ed25519Key, ed448Key, dsaKey);
  25825. publicKeySz = (word32)ret;
  25826. }
  25827. if (ret >= 0) {
  25828. /* Calculate extensions encoding size - may be 0. */
  25829. ret = EncodeExtensions(cert, NULL, 0, 0);
  25830. extSz = (word32)ret;
  25831. }
  25832. if (ret >= 0) {
  25833. /* Don't write out outer sequence - only doing body. */
  25834. dataASN[X509CERTASN_IDX_SEQ].noOut = 1;
  25835. /* Set version, serial number and signature OID */
  25836. SetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT],
  25837. (byte)cert->version);
  25838. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
  25839. (word32)cert->serialSz);
  25840. SetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID],
  25841. (word32)cert->sigType, oidSigType);
  25842. if (IsSigAlgoECC((word32)cert->sigType)) {
  25843. /* No NULL tagged item with ECDSA and EdDSA signature OIDs. */
  25844. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL].noOut = 1;
  25845. }
  25846. #ifdef WC_RSA_PSS
  25847. /* TODO: Encode RSA PSS parameters. */
  25848. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].noOut = 1;
  25849. #endif
  25850. if (issRawLen > 0) {
  25851. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25852. defined(WOLFSSL_CERT_REQ)
  25853. /* Put in encoded issuer name. */
  25854. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  25855. cert->issRaw, issuerSz);
  25856. #endif
  25857. }
  25858. else {
  25859. /* Leave space for issuer name. */
  25860. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  25861. NULL, issuerSz);
  25862. }
  25863. if (cert->beforeDateSz && cert->afterDateSz) {
  25864. if (cert->beforeDate[0] == ASN_UTC_TIME) {
  25865. /* Make space for before date data. */
  25866. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC],
  25867. cert->beforeDate + 2, ASN_UTC_TIME_SIZE - 1);
  25868. /* Don't put out Generalized Time before data. */
  25869. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT].noOut = 1;
  25870. }
  25871. else {
  25872. /* Don't put out UTC before data. */
  25873. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
  25874. /* Make space for before date data. */
  25875. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
  25876. cert->beforeDate + 2, ASN_GEN_TIME_SZ);
  25877. }
  25878. if (cert->afterDate[0] == ASN_UTC_TIME) {
  25879. /* Make space for after date data. */
  25880. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC],
  25881. cert->afterDate + 2, ASN_UTC_TIME_SIZE - 1);
  25882. /* Don't put out UTC Generalized Time after data. */
  25883. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT].noOut = 1;
  25884. }
  25885. else {
  25886. /* Don't put out UTC after data. */
  25887. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
  25888. /* Make space for after date data. */
  25889. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
  25890. cert->afterDate + 2, ASN_GEN_TIME_SZ);
  25891. }
  25892. }
  25893. else
  25894. {
  25895. /* Don't put out UTC before data. */
  25896. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
  25897. /* Make space for before date data. */
  25898. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
  25899. NULL, ASN_GEN_TIME_SZ);
  25900. /* Don't put out UTC after data. */
  25901. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
  25902. /* Make space for after date data. */
  25903. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
  25904. NULL, ASN_GEN_TIME_SZ);
  25905. }
  25906. if (sbjRawLen > 0) {
  25907. /* Put in encoded subject name. */
  25908. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25909. defined(WOLFSSL_CERT_REQ)
  25910. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
  25911. cert->sbjRaw, subjectSz);
  25912. #endif
  25913. }
  25914. else {
  25915. /* Leave space for subject name. */
  25916. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
  25917. NULL, subjectSz);
  25918. }
  25919. /* Leave space for public key. */
  25920. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ],
  25921. NULL, publicKeySz);
  25922. /* Replacement buffer instead of algorithm identifier items. */
  25923. SetASNItem_NoOut(dataASN,
  25924. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
  25925. X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY);
  25926. /* issuerUniqueID and subjectUniqueID not supported. */
  25927. dataASN[X509CERTASN_IDX_TBS_ISSUERUID].noOut = 1;
  25928. dataASN[X509CERTASN_IDX_TBS_SUBJECTUID].noOut = 1;
  25929. /* Leave space for extensions if any set into certificate object. */
  25930. if (extSz > 0) {
  25931. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_EXT_SEQ], NULL, extSz);
  25932. }
  25933. else {
  25934. SetASNItem_NoOutNode(dataASN, x509CertASN,
  25935. X509CERTASN_IDX_TBS_EXT, x509CertASN_Length);
  25936. }
  25937. /* No signature - added later. */
  25938. SetASNItem_NoOut(dataASN, X509CERTASN_IDX_SIGALGO_SEQ,
  25939. X509CERTASN_IDX_SIGNATURE);
  25940. /* Calculate encoded certificate body size. */
  25941. ret = SizeASN_Items(x509CertASN, dataASN, x509CertASN_Length, &sz);
  25942. }
  25943. /* Check buffer is big enough for encoded data. */
  25944. if ((ret == 0) && (sz > (int)derSz)) {
  25945. ret = BUFFER_E;
  25946. }
  25947. if (ret == 0) {
  25948. /* Encode certificate body into buffer. */
  25949. SetASN_Items(x509CertASN, dataASN, x509CertASN_Length, derBuffer);
  25950. if (issRawLen == 0) {
  25951. /* Encode issuer name into buffer. Use the subject as the issuer
  25952. * if it is self-signed. Size will be correct because we did the
  25953. * same for size. */
  25954. ret = SetNameEx(
  25955. (byte*)dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.data,
  25956. dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.length,
  25957. cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
  25958. }
  25959. }
  25960. if ((ret >= 0) && (sbjRawLen == 0)) {
  25961. /* Encode subject name into buffer. */
  25962. ret = SetNameEx(
  25963. (byte*)dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.data,
  25964. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.length,
  25965. &cert->subject, cert->heap);
  25966. }
  25967. if (ret >= 0) {
  25968. if (cert->beforeDateSz == 0 || cert->afterDateSz == 0)
  25969. {
  25970. /* Encode validity into buffer. */
  25971. ret = SetValidity(
  25972. (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT]
  25973. .data.buffer.data,
  25974. (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT]
  25975. .data.buffer.data, cert->daysValid);
  25976. }
  25977. }
  25978. if (ret >= 0) {
  25979. /* Encode public key into buffer. */
  25980. ret = EncodePublicKey(cert->keyType,
  25981. (byte*)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
  25982. .data.buffer.data,
  25983. (int)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
  25984. .data.buffer.length,
  25985. rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
  25986. }
  25987. if ((ret >= 0) && (!dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].noOut)) {
  25988. /* Encode extensions into buffer. */
  25989. ret = EncodeExtensions(cert,
  25990. (byte*)dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.data,
  25991. dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.length, 0);
  25992. }
  25993. if (ret >= 0) {
  25994. /* Store encoded certificate body size. */
  25995. cert->bodySz = sz;
  25996. /* Return the encoding size. */
  25997. ret = sz;
  25998. }
  25999. FREE_ASNSETDATA(dataASN, cert->heap);
  26000. return ret;
  26001. #endif
  26002. }
  26003. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  26004. int wc_MakeCert_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  26005. void* key, WC_RNG* rng)
  26006. {
  26007. RsaKey* rsaKey = NULL;
  26008. DsaKey* dsaKey = NULL;
  26009. ecc_key* eccKey = NULL;
  26010. ed25519_key* ed25519Key = NULL;
  26011. ed448_key* ed448Key = NULL;
  26012. falcon_key* falconKey = NULL;
  26013. dilithium_key* dilithiumKey = NULL;
  26014. sphincs_key* sphincsKey = NULL;
  26015. if (keyType == RSA_TYPE)
  26016. rsaKey = (RsaKey*)key;
  26017. else if (keyType == DSA_TYPE)
  26018. dsaKey = (DsaKey*)key;
  26019. else if (keyType == ECC_TYPE)
  26020. eccKey = (ecc_key*)key;
  26021. else if (keyType == ED25519_TYPE)
  26022. ed25519Key = (ed25519_key*)key;
  26023. else if (keyType == ED448_TYPE)
  26024. ed448Key = (ed448_key*)key;
  26025. else if (keyType == FALCON_LEVEL1_TYPE)
  26026. falconKey = (falcon_key*)key;
  26027. else if (keyType == FALCON_LEVEL5_TYPE)
  26028. falconKey = (falcon_key*)key;
  26029. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  26030. dilithiumKey = (dilithium_key*)key;
  26031. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  26032. dilithiumKey = (dilithium_key*)key;
  26033. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  26034. dilithiumKey = (dilithium_key*)key;
  26035. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  26036. sphincsKey = (sphincs_key*)key;
  26037. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  26038. sphincsKey = (sphincs_key*)key;
  26039. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  26040. sphincsKey = (sphincs_key*)key;
  26041. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  26042. sphincsKey = (sphincs_key*)key;
  26043. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  26044. sphincsKey = (sphincs_key*)key;
  26045. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  26046. sphincsKey = (sphincs_key*)key;
  26047. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, dsaKey,
  26048. ed25519Key, ed448Key, falconKey, dilithiumKey,
  26049. sphincsKey);
  26050. }
  26051. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  26052. WOLFSSL_ABI
  26053. int wc_MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,
  26054. ecc_key* eccKey, WC_RNG* rng)
  26055. {
  26056. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, NULL,
  26057. NULL, NULL, NULL, NULL);
  26058. }
  26059. #ifdef WOLFSSL_CERT_REQ
  26060. #ifndef WOLFSSL_ASN_TEMPLATE
  26061. /* return size of data set on success
  26062. * if getting size only then attr and oid should be NULL
  26063. */
  26064. static word32 SetReqAttribSingle(byte* output, word32* idx, char* attr,
  26065. word32 attrSz, const byte* oid, word32 oidSz, byte printable,
  26066. word32 extSz)
  26067. {
  26068. word32 totalSz = 0;
  26069. word32 seqSz = 0;
  26070. word32 setSz = 0;
  26071. word32 strSz = 0;
  26072. byte seq[MAX_SEQ_SZ];
  26073. byte set[MAX_SET_SZ];
  26074. byte str[MAX_PRSTR_SZ];
  26075. totalSz = (word32)SetObjectId((int)oidSz, NULL);
  26076. totalSz += oidSz;
  26077. if (extSz > 0) {
  26078. totalSz += setSz = SetSet(extSz, set);
  26079. totalSz += seqSz = SetSequence(totalSz + extSz, seq);
  26080. totalSz += extSz;
  26081. }
  26082. else {
  26083. if (printable) {
  26084. strSz = SetPrintableString(attrSz, str);
  26085. totalSz += strSz;
  26086. }
  26087. else {
  26088. totalSz += strSz = SetUTF8String(attrSz, str);
  26089. }
  26090. totalSz += setSz = SetSet(strSz + attrSz, set);
  26091. totalSz += seqSz = SetSequence(totalSz + attrSz, seq);
  26092. totalSz += attrSz;
  26093. }
  26094. if (oid) {
  26095. XMEMCPY(&output[*idx], seq, seqSz);
  26096. *idx += seqSz;
  26097. *idx += (word32)SetObjectId((int)oidSz, output + *idx);
  26098. XMEMCPY(&output[*idx], oid, oidSz);
  26099. *idx += oidSz;
  26100. XMEMCPY(&output[*idx], set, setSz);
  26101. *idx += setSz;
  26102. if (strSz > 0) {
  26103. XMEMCPY(&output[*idx], str, strSz);
  26104. *idx += strSz;
  26105. if (attrSz > 0) {
  26106. XMEMCPY(&output[*idx], attr, attrSz);
  26107. *idx += attrSz;
  26108. }
  26109. }
  26110. }
  26111. return totalSz;
  26112. }
  26113. static int SetReqAttrib(byte* output, Cert* cert, word32 extSz)
  26114. {
  26115. word32 sz = 0; /* overall size */
  26116. word32 setSz = 0;
  26117. output[0] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  26118. sz++;
  26119. if (cert->challengePw[0]) {
  26120. setSz += SetReqAttribSingle(output, &sz, NULL,
  26121. (word32)XSTRLEN(cert->challengePw), NULL,
  26122. sizeof(attrChallengePasswordOid),
  26123. (byte)cert->challengePwPrintableString, 0);
  26124. }
  26125. if (cert->unstructuredName[0]) {
  26126. setSz += SetReqAttribSingle(output, &sz, NULL,
  26127. (word32)XSTRLEN(cert->unstructuredName), NULL,
  26128. sizeof(attrUnstructuredNameOid), 1, 0);
  26129. }
  26130. if (extSz) {
  26131. setSz += SetReqAttribSingle(output, &sz, NULL, 0, NULL,
  26132. sizeof(attrExtensionRequestOid), 1, extSz);
  26133. }
  26134. /* Put the pieces together. */
  26135. sz += SetLength(setSz, &output[sz]);
  26136. if (sz + setSz - extSz > MAX_ATTRIB_SZ) {
  26137. WOLFSSL_MSG("Attribute Buffer is not big enough!");
  26138. return REQ_ATTRIBUTE_E;
  26139. }
  26140. if (cert->challengePw[0]) {
  26141. SetReqAttribSingle(output, &sz, cert->challengePw,
  26142. (word32)XSTRLEN(cert->challengePw),
  26143. &attrChallengePasswordOid[0],
  26144. sizeof(attrChallengePasswordOid),
  26145. (byte)cert->challengePwPrintableString, 0);
  26146. }
  26147. if (cert->unstructuredName[0]) {
  26148. SetReqAttribSingle(output, &sz, cert->unstructuredName,
  26149. (word32)XSTRLEN(cert->unstructuredName),
  26150. &attrUnstructuredNameOid[0],
  26151. sizeof(attrUnstructuredNameOid), 1, 0);
  26152. }
  26153. if (extSz) {
  26154. SetReqAttribSingle(output, &sz, NULL, 0, &attrExtensionRequestOid[0],
  26155. sizeof(attrExtensionRequestOid), 1, extSz);
  26156. /* The actual extension data will be tacked onto the output later. */
  26157. }
  26158. return (int)sz;
  26159. }
  26160. #ifdef WOLFSSL_CUSTOM_OID
  26161. /* encode a custom oid and value */
  26162. static int SetCustomObjectId(Cert* cert, byte* output, word32 outSz,
  26163. CertOidField* custom)
  26164. {
  26165. int idx = 0, cust_lenSz, cust_oidSz;
  26166. if (cert == NULL || output == NULL || custom == NULL) {
  26167. return BAD_FUNC_ARG;
  26168. }
  26169. if (custom->oid == NULL || custom->oidSz <= 0) {
  26170. return 0; /* none set */
  26171. }
  26172. /* Octet String header */
  26173. cust_lenSz = SetOctetString(custom->valSz, NULL);
  26174. cust_oidSz = SetObjectId(custom->oidSz, NULL);
  26175. /* check for output buffer room */
  26176. if ((word32)(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz) >
  26177. outSz) {
  26178. return BUFFER_E;
  26179. }
  26180. /* put sequence with total */
  26181. idx = SetSequence(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz,
  26182. output);
  26183. /* put oid header */
  26184. idx += SetObjectId(custom->oidSz, output+idx);
  26185. XMEMCPY(output+idx, custom->oid, custom->oidSz);
  26186. idx += custom->oidSz;
  26187. /* put value */
  26188. idx += SetOctetString(custom->valSz, output+idx);
  26189. XMEMCPY(output+idx, custom->val, custom->valSz);
  26190. idx += custom->valSz;
  26191. return idx;
  26192. }
  26193. #endif /* WOLFSSL_CUSTOM_OID */
  26194. /* encode info from cert into DER encoded format */
  26195. static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey,
  26196. DsaKey* dsaKey, ecc_key* eccKey,
  26197. ed25519_key* ed25519Key, ed448_key* ed448Key,
  26198. falcon_key* falconKey, dilithium_key* dilithiumKey,
  26199. sphincs_key* sphincsKey)
  26200. {
  26201. int ret;
  26202. (void)eccKey;
  26203. (void)ed25519Key;
  26204. (void)ed448Key;
  26205. (void)falconKey;
  26206. (void)dilithiumKey;
  26207. (void)sphincsKey;
  26208. if (cert == NULL || der == NULL)
  26209. return BAD_FUNC_ARG;
  26210. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  26211. dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
  26212. falconKey == NULL) {
  26213. return PUBLIC_KEY_E;
  26214. }
  26215. /* init */
  26216. XMEMSET(der, 0, sizeof(DerCert));
  26217. /* version */
  26218. der->versionSz = SetMyVersion((word32)cert->version, der->version, FALSE);
  26219. /* subject name */
  26220. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26221. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  26222. /* Use the raw subject */
  26223. int idx;
  26224. der->subjectSz = (int)min(sizeof(der->subject),
  26225. (word32)XSTRLEN((const char*)cert->sbjRaw));
  26226. /* header */
  26227. idx = (int)SetSequence((word32)der->subjectSz, der->subject);
  26228. if (der->subjectSz + idx > (int)sizeof(der->subject)) {
  26229. return SUBJECT_E;
  26230. }
  26231. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  26232. (size_t)der->subjectSz);
  26233. der->subjectSz += idx;
  26234. }
  26235. else
  26236. #endif
  26237. {
  26238. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  26239. &cert->subject, cert->heap);
  26240. }
  26241. if (der->subjectSz <= 0)
  26242. return SUBJECT_E;
  26243. /* public key */
  26244. #ifndef NO_RSA
  26245. if (cert->keyType == RSA_KEY) {
  26246. if (rsaKey == NULL)
  26247. return PUBLIC_KEY_E;
  26248. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  26249. sizeof(der->publicKey), 1);
  26250. }
  26251. #endif
  26252. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  26253. if (cert->keyType == DSA_KEY) {
  26254. if (dsaKey == NULL)
  26255. return PUBLIC_KEY_E;
  26256. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  26257. sizeof(der->publicKey), 1);
  26258. }
  26259. #endif
  26260. #ifdef HAVE_ECC
  26261. if (cert->keyType == ECC_KEY) {
  26262. if (eccKey == NULL)
  26263. return PUBLIC_KEY_E;
  26264. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  26265. sizeof(der->publicKey), 1, 0);
  26266. }
  26267. #endif
  26268. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  26269. if (cert->keyType == ED25519_KEY) {
  26270. if (ed25519Key == NULL)
  26271. return PUBLIC_KEY_E;
  26272. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  26273. (word32)sizeof(der->publicKey), 1);
  26274. }
  26275. #endif
  26276. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  26277. if (cert->keyType == ED448_KEY) {
  26278. if (ed448Key == NULL)
  26279. return PUBLIC_KEY_E;
  26280. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  26281. (word32)sizeof(der->publicKey), 1);
  26282. }
  26283. #endif
  26284. #if defined(HAVE_PQC)
  26285. #if defined(HAVE_FALCON)
  26286. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  26287. (cert->keyType == FALCON_LEVEL5_KEY)) {
  26288. if (falconKey == NULL)
  26289. return PUBLIC_KEY_E;
  26290. der->publicKeySz = wc_Falcon_PublicKeyToDer(falconKey,
  26291. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26292. }
  26293. #endif
  26294. #if defined(HAVE_DILITHIUM)
  26295. if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
  26296. (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
  26297. (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
  26298. if (dilithiumKey == NULL)
  26299. return PUBLIC_KEY_E;
  26300. der->publicKeySz = wc_Dilithium_PublicKeyToDer(dilithiumKey,
  26301. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26302. }
  26303. #endif
  26304. #if defined(HAVE_SPHINCS)
  26305. if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
  26306. (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
  26307. (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
  26308. (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
  26309. (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
  26310. (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
  26311. if (sphincsKey == NULL)
  26312. return PUBLIC_KEY_E;
  26313. der->publicKeySz = wc_Sphincs_PublicKeyToDer(sphincsKey,
  26314. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26315. }
  26316. #endif
  26317. #endif /* HAVE_PQC */
  26318. if (der->publicKeySz <= 0)
  26319. return PUBLIC_KEY_E;
  26320. /* set the extensions */
  26321. der->extensionsSz = 0;
  26322. /* RFC 5280 : 4.2.1.9. Basic Constraints
  26323. * The pathLenConstraint field is meaningful only if the CA boolean is
  26324. * asserted and the key usage extension, if present, asserts the
  26325. * keyCertSign bit */
  26326. /* Set CA and path length */
  26327. if ((cert->isCA) && (cert->pathLenSet)
  26328. #ifdef WOLFSSL_CERT_EXT
  26329. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  26330. #endif
  26331. ) {
  26332. der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
  26333. if (der->caSz <= 0)
  26334. return CA_TRUE_E;
  26335. der->extensionsSz += der->caSz;
  26336. }
  26337. /* Set CA */
  26338. else if (cert->isCA) {
  26339. der->caSz = SetCa(der->ca, sizeof(der->ca));
  26340. if (der->caSz <= 0)
  26341. return CA_TRUE_E;
  26342. der->extensionsSz += der->caSz;
  26343. }
  26344. /* Set Basic Constraint */
  26345. else if (cert->basicConstSet) {
  26346. der->caSz = SetBC(der->ca, sizeof(der->ca));
  26347. if (der->caSz <= 0)
  26348. return EXTENSIONS_E;
  26349. der->extensionsSz += der->caSz;
  26350. }
  26351. else
  26352. der->caSz = 0;
  26353. #ifdef WOLFSSL_ALT_NAMES
  26354. /* Alternative Name */
  26355. if (cert->altNamesSz) {
  26356. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  26357. cert->altNames, (word32)cert->altNamesSz,
  26358. cert->altNamesCrit);
  26359. if (der->altNamesSz <= 0)
  26360. return ALT_NAME_E;
  26361. der->extensionsSz += der->altNamesSz;
  26362. }
  26363. else
  26364. der->altNamesSz = 0;
  26365. #endif
  26366. #ifdef WOLFSSL_CERT_EXT
  26367. /* SKID */
  26368. if (cert->skidSz) {
  26369. /* check the provided SKID size */
  26370. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  26371. return SKID_E;
  26372. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  26373. cert->skid, (word32)cert->skidSz);
  26374. if (der->skidSz <= 0)
  26375. return SKID_E;
  26376. der->extensionsSz += der->skidSz;
  26377. }
  26378. else
  26379. der->skidSz = 0;
  26380. /* Key Usage */
  26381. if (cert->keyUsage != 0) {
  26382. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  26383. cert->keyUsage);
  26384. if (der->keyUsageSz <= 0)
  26385. return KEYUSAGE_E;
  26386. der->extensionsSz += der->keyUsageSz;
  26387. }
  26388. else
  26389. der->keyUsageSz = 0;
  26390. /* Extended Key Usage */
  26391. if (cert->extKeyUsage != 0) {
  26392. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  26393. sizeof(der->extKeyUsage), cert->extKeyUsage);
  26394. if (der->extKeyUsageSz <= 0)
  26395. return EXTKEYUSAGE_E;
  26396. der->extensionsSz += der->extKeyUsageSz;
  26397. }
  26398. else
  26399. der->extKeyUsageSz = 0;
  26400. #endif /* WOLFSSL_CERT_EXT */
  26401. #ifdef WOLFSSL_CUSTOM_OID
  26402. /* encode a custom oid and value */
  26403. /* zero returns, means none set */
  26404. ret = SetCustomObjectId(cert, der->extCustom,
  26405. sizeof(der->extCustom), &cert->extCustom);
  26406. if (ret < 0)
  26407. return ret;
  26408. der->extCustomSz = ret;
  26409. der->extensionsSz += der->extCustomSz;
  26410. #endif
  26411. /* put extensions */
  26412. if (der->extensionsSz > 0) {
  26413. /* put the start of sequence (ID, Size) */
  26414. der->extensionsSz = (int)SetSequence((word32)der->extensionsSz,
  26415. der->extensions);
  26416. if (der->extensionsSz <= 0)
  26417. return EXTENSIONS_E;
  26418. /* put CA */
  26419. if (der->caSz) {
  26420. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26421. &der->extensionsSz,
  26422. der->ca, der->caSz);
  26423. if (ret <= 0)
  26424. return EXTENSIONS_E;
  26425. }
  26426. #ifdef WOLFSSL_ALT_NAMES
  26427. /* put Alternative Names */
  26428. if (der->altNamesSz) {
  26429. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26430. &der->extensionsSz,
  26431. der->altNames, der->altNamesSz);
  26432. if (ret <= 0)
  26433. return EXTENSIONS_E;
  26434. }
  26435. #endif
  26436. #ifdef WOLFSSL_CERT_EXT
  26437. /* put SKID */
  26438. if (der->skidSz) {
  26439. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26440. &der->extensionsSz,
  26441. der->skid, der->skidSz);
  26442. if (ret <= 0)
  26443. return EXTENSIONS_E;
  26444. }
  26445. /* put AKID */
  26446. if (der->akidSz) {
  26447. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26448. &der->extensionsSz,
  26449. der->akid, der->akidSz);
  26450. if (ret <= 0)
  26451. return EXTENSIONS_E;
  26452. }
  26453. /* put KeyUsage */
  26454. if (der->keyUsageSz) {
  26455. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26456. &der->extensionsSz,
  26457. der->keyUsage, der->keyUsageSz);
  26458. if (ret <= 0)
  26459. return EXTENSIONS_E;
  26460. }
  26461. /* put ExtendedKeyUsage */
  26462. if (der->extKeyUsageSz) {
  26463. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26464. &der->extensionsSz,
  26465. der->extKeyUsage, der->extKeyUsageSz);
  26466. if (ret <= 0)
  26467. return EXTENSIONS_E;
  26468. }
  26469. #ifdef WOLFSSL_CUSTOM_OID
  26470. if (der->extCustomSz) {
  26471. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26472. &der->extensionsSz,
  26473. der->extCustom, der->extCustomSz);
  26474. if (ret <= 0)
  26475. return EXTENSIONS_E;
  26476. }
  26477. #endif
  26478. #endif /* WOLFSSL_CERT_EXT */
  26479. }
  26480. der->attribSz = SetReqAttrib(der->attrib, cert, (word32)der->extensionsSz);
  26481. if (der->attribSz <= 0)
  26482. return REQ_ATTRIBUTE_E;
  26483. der->total = der->versionSz + der->subjectSz + der->publicKeySz +
  26484. der->extensionsSz + der->attribSz;
  26485. return 0;
  26486. }
  26487. /* write DER encoded cert req to buffer, size already checked */
  26488. static int WriteCertReqBody(DerCert* der, byte* buf)
  26489. {
  26490. int idx;
  26491. /* signed part header */
  26492. idx = (int)SetSequence((word32)der->total, buf);
  26493. /* version */
  26494. if (buf)
  26495. XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
  26496. idx += der->versionSz;
  26497. /* subject */
  26498. if (buf)
  26499. XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
  26500. idx += der->subjectSz;
  26501. /* public key */
  26502. if (buf)
  26503. XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
  26504. idx += der->publicKeySz;
  26505. /* attributes */
  26506. if (buf)
  26507. XMEMCPY(buf + idx, der->attrib, (size_t)der->attribSz);
  26508. idx += der->attribSz;
  26509. /* extensions */
  26510. if (der->extensionsSz) {
  26511. if (buf)
  26512. XMEMCPY(buf + idx, der->extensions, min((word32)der->extensionsSz,
  26513. sizeof(der->extensions)));
  26514. idx += der->extensionsSz;
  26515. }
  26516. return idx;
  26517. }
  26518. #endif
  26519. #ifdef WOLFSSL_ASN_TEMPLATE
  26520. /* ASN.1 template for Certificate Request body.
  26521. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  26522. */
  26523. static const ASNItem certReqBodyASN[] = {
  26524. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  26525. /* version */
  26526. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  26527. /* subject */
  26528. /* SUBJ_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  26529. /* subjectPKInfo */
  26530. /* SPUBKEYINFO_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  26531. /* attributes*/
  26532. /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  26533. /* Challenge Password Attribute */
  26534. /* ATTRS_CPW_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  26535. /* ATTRS_CPW_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  26536. /* ATTRS_CPW_SET */ { 3, ASN_SET, 1, 1, 0 },
  26537. /* ATTRS_CPW_PS */ { 4, ASN_PRINTABLE_STRING, 0, 0, 0 },
  26538. /* ATTRS_CPW_UTF */ { 4, ASN_UTF8STRING, 0, 0, 0 },
  26539. /* Extensions Attribute */
  26540. /* EXT_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  26541. /* EXT_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  26542. /* EXT_SET */ { 3, ASN_SET, 1, 1, 0 },
  26543. /* EXT_BODY */ { 4, ASN_SEQUENCE, 1, 0, 0 },
  26544. };
  26545. enum {
  26546. CERTREQBODYASN_IDX_SEQ = 0,
  26547. CERTREQBODYASN_IDX_VER,
  26548. CERTREQBODYASN_IDX_SUBJ_SEQ,
  26549. CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ,
  26550. CERTREQBODYASN_IDX_ATTRS,
  26551. CERTREQBODYASN_IDX_ATTRS_CPW_SEQ,
  26552. CERTREQBODYASN_IDX_ATTRS_CPW_OID,
  26553. CERTREQBODYASN_IDX_ATTRS_CPW_SET,
  26554. CERTREQBODYASN_IDX_ATTRS_CPW_PS,
  26555. CERTREQBODYASN_IDX_ATTRS_CPW_UTF,
  26556. CERTREQBODYASN_IDX_EXT_SEQ,
  26557. CERTREQBODYASN_IDX_EXT_OID,
  26558. CERTREQBODYASN_IDX_EXT_SET,
  26559. CERTREQBODYASN_IDX_EXT_BODY
  26560. };
  26561. /* Number of items in ASN.1 template for Certificate Request body. */
  26562. #define certReqBodyASN_Length (sizeof(certReqBodyASN) / sizeof(ASNItem))
  26563. #endif
  26564. static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  26565. RsaKey* rsaKey, DsaKey* dsaKey, ecc_key* eccKey,
  26566. ed25519_key* ed25519Key, ed448_key* ed448Key,
  26567. falcon_key* falconKey, dilithium_key* dilithiumKey,
  26568. sphincs_key* sphincsKey)
  26569. {
  26570. #ifndef WOLFSSL_ASN_TEMPLATE
  26571. int ret;
  26572. #ifdef WOLFSSL_SMALL_STACK
  26573. DerCert* der;
  26574. #else
  26575. DerCert der[1];
  26576. #endif
  26577. if (eccKey)
  26578. cert->keyType = ECC_KEY;
  26579. else if (rsaKey)
  26580. cert->keyType = RSA_KEY;
  26581. else if (dsaKey)
  26582. cert->keyType = DSA_KEY;
  26583. else if (ed25519Key)
  26584. cert->keyType = ED25519_KEY;
  26585. else if (ed448Key)
  26586. cert->keyType = ED448_KEY;
  26587. #ifdef HAVE_PQC
  26588. #ifdef HAVE_FALCON
  26589. else if ((falconKey != NULL) && (falconKey->level == 1))
  26590. cert->keyType = FALCON_LEVEL1_KEY;
  26591. else if ((falconKey != NULL) && (falconKey->level == 5))
  26592. cert->keyType = FALCON_LEVEL5_KEY;
  26593. #endif /* HAVE_FALCON */
  26594. #ifdef HAVE_DILITHIUM
  26595. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
  26596. cert->keyType = DILITHIUM_LEVEL2_KEY;
  26597. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
  26598. cert->keyType = DILITHIUM_LEVEL3_KEY;
  26599. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
  26600. cert->keyType = DILITHIUM_LEVEL5_KEY;
  26601. #endif /* HAVE_DILITHIUM */
  26602. #ifdef HAVE_SPHINCS
  26603. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26604. && (sphincsKey->optim == FAST_VARIANT))
  26605. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  26606. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26607. && (sphincsKey->optim == FAST_VARIANT))
  26608. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  26609. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26610. && (sphincsKey->optim == FAST_VARIANT))
  26611. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  26612. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26613. && (sphincsKey->optim == SMALL_VARIANT))
  26614. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  26615. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26616. && (sphincsKey->optim == SMALL_VARIANT))
  26617. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  26618. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26619. && (sphincsKey->optim == SMALL_VARIANT))
  26620. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  26621. #endif /* HAVE_SPHINCS */
  26622. #endif /* HAVE_PQC */
  26623. else
  26624. return BAD_FUNC_ARG;
  26625. #ifdef WOLFSSL_SMALL_STACK
  26626. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap,
  26627. DYNAMIC_TYPE_TMP_BUFFER);
  26628. if (der == NULL)
  26629. return MEMORY_E;
  26630. #endif
  26631. ret = EncodeCertReq(cert, der, rsaKey, dsaKey, eccKey, ed25519Key, ed448Key,
  26632. falconKey, dilithiumKey, sphincsKey);
  26633. if (ret == 0) {
  26634. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  26635. ret = BUFFER_E;
  26636. else
  26637. ret = cert->bodySz = WriteCertReqBody(der, derBuffer);
  26638. }
  26639. #ifdef WOLFSSL_SMALL_STACK
  26640. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  26641. #endif
  26642. return ret;
  26643. #else
  26644. DECL_ASNSETDATA(dataASN, certReqBodyASN_Length);
  26645. word32 publicKeySz = 0;
  26646. word32 subjectSz = 0;
  26647. word32 extSz = 0;
  26648. int sz = 0;
  26649. int ret = 0;
  26650. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26651. word32 sbjRawSz = 0;
  26652. #endif
  26653. /* Unused without OQS */
  26654. (void)falconKey;
  26655. (void)dilithiumKey;
  26656. (void)sphincsKey;
  26657. CALLOC_ASNSETDATA(dataASN, certReqBodyASN_Length, ret, cert->heap);
  26658. if (ret == 0) {
  26659. /* Set key type into certificate object based on key passed in. */
  26660. if (rsaKey != NULL) {
  26661. cert->keyType = RSA_KEY;
  26662. }
  26663. else if (eccKey != NULL) {
  26664. cert->keyType = ECC_KEY;
  26665. }
  26666. else if (dsaKey != NULL) {
  26667. cert->keyType = DSA_KEY;
  26668. }
  26669. else if (ed25519Key != NULL) {
  26670. cert->keyType = ED25519_KEY;
  26671. }
  26672. else if (ed448Key != NULL) {
  26673. cert->keyType = ED448_KEY;
  26674. }
  26675. #ifdef HAVE_PQC
  26676. #ifdef HAVE_FALCON
  26677. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  26678. cert->keyType = FALCON_LEVEL1_KEY;
  26679. }
  26680. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  26681. cert->keyType = FALCON_LEVEL5_KEY;
  26682. }
  26683. #endif /* HAVE_FALCON */
  26684. #ifdef HAVE_DILITHIUM
  26685. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
  26686. cert->keyType = DILITHIUM_LEVEL2_KEY;
  26687. }
  26688. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
  26689. cert->keyType = DILITHIUM_LEVEL3_KEY;
  26690. }
  26691. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
  26692. cert->keyType = DILITHIUM_LEVEL5_KEY;
  26693. }
  26694. #endif /* HAVE_DILITHIUM */
  26695. #ifdef HAVE_SPHINCS
  26696. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26697. && (sphincsKey->optim == FAST_VARIANT)) {
  26698. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  26699. }
  26700. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26701. && (sphincsKey->optim == FAST_VARIANT)) {
  26702. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  26703. }
  26704. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26705. && (sphincsKey->optim == FAST_VARIANT)) {
  26706. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  26707. }
  26708. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26709. && (sphincsKey->optim == SMALL_VARIANT)) {
  26710. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  26711. }
  26712. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26713. && (sphincsKey->optim == SMALL_VARIANT)) {
  26714. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  26715. }
  26716. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26717. && (sphincsKey->optim == SMALL_VARIANT)) {
  26718. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  26719. }
  26720. #endif /* HAVE_SPHINCS */
  26721. #endif /* HAVE_PQC */
  26722. else {
  26723. ret = BAD_FUNC_ARG;
  26724. }
  26725. }
  26726. if (ret == 0) {
  26727. /* Determine subject name size. */
  26728. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26729. sbjRawSz = (word32)XSTRLEN((const char*)cert->sbjRaw);
  26730. if (sbjRawSz > 0) {
  26731. subjectSz = min(sizeof(cert->sbjRaw), sbjRawSz);
  26732. }
  26733. else
  26734. #endif
  26735. {
  26736. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject, cert->heap);
  26737. subjectSz = (word32)ret;
  26738. }
  26739. }
  26740. if (ret >= 0) {
  26741. /* Determine encode public key size. */
  26742. ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  26743. eccKey, ed25519Key, ed448Key, dsaKey);
  26744. publicKeySz = (word32)ret;
  26745. }
  26746. if (ret >= 0) {
  26747. /* Determine encode extensions size. */
  26748. ret = EncodeExtensions(cert, NULL, 0, 1);
  26749. extSz = (word32)ret;
  26750. }
  26751. if (ret >= 0) {
  26752. /* Set version. */
  26753. SetASN_Int8Bit(&dataASN[CERTREQBODYASN_IDX_VER], (byte)cert->version);
  26754. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26755. if (sbjRawSz > 0) {
  26756. /* Put in encoded subject name. */
  26757. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], cert->sbjRaw,
  26758. subjectSz);
  26759. }
  26760. else
  26761. #endif
  26762. {
  26763. /* Leave space for subject name. */
  26764. SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], NULL,
  26765. subjectSz);
  26766. }
  26767. /* Leave space for public key. */
  26768. SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ],
  26769. NULL, publicKeySz);
  26770. if (cert->challengePw[0] != '\0') {
  26771. /* Add challenge password attribute. */
  26772. /* Set challenge password OID. */
  26773. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_OID],
  26774. attrChallengePasswordOid, sizeof(attrChallengePasswordOid));
  26775. /* Enable the ASN template item with the appropriate tag. */
  26776. if (cert->challengePwPrintableString) {
  26777. /* PRINTABLE_STRING - set buffer */
  26778. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS],
  26779. (byte*)cert->challengePw,
  26780. (word32)XSTRLEN(cert->challengePw));
  26781. /* UTF8STRING - don't encode */
  26782. dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF].noOut = 1;
  26783. }
  26784. else {
  26785. /* PRINTABLE_STRING - don't encode */
  26786. dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS].noOut = 1;
  26787. /* UTF8STRING - set buffer */
  26788. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF],
  26789. (byte*)cert->challengePw,
  26790. (word32)XSTRLEN(cert->challengePw));
  26791. }
  26792. }
  26793. else {
  26794. /* Leave out challenge password attribute items. */
  26795. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  26796. CERTREQBODYASN_IDX_ATTRS_CPW_SEQ, certReqBodyASN_Length);
  26797. }
  26798. if (extSz > 0) {
  26799. /* Set extension attribute OID. */
  26800. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_OID], attrExtensionRequestOid,
  26801. sizeof(attrExtensionRequestOid));
  26802. /* Leave space for data. */
  26803. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_BODY], NULL, extSz);
  26804. }
  26805. else {
  26806. /* Leave out extension attribute items. */
  26807. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  26808. CERTREQBODYASN_IDX_EXT_SEQ, certReqBodyASN_Length);
  26809. }
  26810. /* Calculate size of encoded certificate request body. */
  26811. ret = SizeASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length,
  26812. &sz);
  26813. }
  26814. /* Check buffer is big enough for encoded data. */
  26815. if ((ret == 0) && (sz > (int)derSz)) {
  26816. ret = BUFFER_E;
  26817. }
  26818. if (ret == 0 && derBuffer != NULL) {
  26819. /* Encode certificate request body into buffer. */
  26820. SetASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length, derBuffer);
  26821. /* Put in generated data */
  26822. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26823. if (sbjRawSz == 0)
  26824. #endif
  26825. {
  26826. /* Encode subject name into space in buffer. */
  26827. ret = SetNameEx(
  26828. (byte*)dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.data,
  26829. dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.length,
  26830. &cert->subject, cert->heap);
  26831. }
  26832. }
  26833. if (ret >= 0 && derBuffer != NULL) {
  26834. /* Encode public key into space in buffer. */
  26835. ret = EncodePublicKey(cert->keyType,
  26836. (byte*)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.data,
  26837. (int)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.length,
  26838. rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
  26839. }
  26840. if ((ret >= 0 && derBuffer != NULL) &&
  26841. (!dataASN[CERTREQBODYASN_IDX_EXT_BODY].noOut)) {
  26842. /* Encode extensions into space in buffer. */
  26843. ret = EncodeExtensions(cert,
  26844. (byte*)dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.data,
  26845. dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.length, 1);
  26846. }
  26847. if (ret >= 0) {
  26848. /* Store encoded certificate request body size. */
  26849. cert->bodySz = sz;
  26850. /* Return the encoding size. */
  26851. ret = sz;
  26852. }
  26853. FREE_ASNSETDATA(dataASN, cert->heap);
  26854. return ret;
  26855. #endif /* WOLFSSL_ASN_TEMPLATE */
  26856. }
  26857. int wc_MakeCertReq_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  26858. void* key)
  26859. {
  26860. RsaKey* rsaKey = NULL;
  26861. DsaKey* dsaKey = NULL;
  26862. ecc_key* eccKey = NULL;
  26863. ed25519_key* ed25519Key = NULL;
  26864. ed448_key* ed448Key = NULL;
  26865. falcon_key* falconKey = NULL;
  26866. dilithium_key* dilithiumKey = NULL;
  26867. sphincs_key* sphincsKey = NULL;
  26868. if (keyType == RSA_TYPE)
  26869. rsaKey = (RsaKey*)key;
  26870. else if (keyType == DSA_TYPE)
  26871. dsaKey = (DsaKey*)key;
  26872. else if (keyType == ECC_TYPE)
  26873. eccKey = (ecc_key*)key;
  26874. else if (keyType == ED25519_TYPE)
  26875. ed25519Key = (ed25519_key*)key;
  26876. else if (keyType == ED448_TYPE)
  26877. ed448Key = (ed448_key*)key;
  26878. else if (keyType == FALCON_LEVEL1_TYPE)
  26879. falconKey = (falcon_key*)key;
  26880. else if (keyType == FALCON_LEVEL5_TYPE)
  26881. falconKey = (falcon_key*)key;
  26882. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  26883. dilithiumKey = (dilithium_key*)key;
  26884. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  26885. dilithiumKey = (dilithium_key*)key;
  26886. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  26887. dilithiumKey = (dilithium_key*)key;
  26888. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  26889. sphincsKey = (sphincs_key*)key;
  26890. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  26891. sphincsKey = (sphincs_key*)key;
  26892. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  26893. sphincsKey = (sphincs_key*)key;
  26894. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  26895. sphincsKey = (sphincs_key*)key;
  26896. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  26897. sphincsKey = (sphincs_key*)key;
  26898. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  26899. sphincsKey = (sphincs_key*)key;
  26900. return MakeCertReq(cert, derBuffer, derSz, rsaKey, dsaKey, eccKey,
  26901. ed25519Key, ed448Key, falconKey, dilithiumKey,
  26902. sphincsKey);
  26903. }
  26904. WOLFSSL_ABI
  26905. int wc_MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  26906. RsaKey* rsaKey, ecc_key* eccKey)
  26907. {
  26908. return MakeCertReq(cert, derBuffer, derSz, rsaKey, NULL, eccKey, NULL,
  26909. NULL, NULL, NULL, NULL);
  26910. }
  26911. #endif /* WOLFSSL_CERT_REQ */
  26912. static int SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  26913. RsaKey* rsaKey, ecc_key* eccKey, ed25519_key* ed25519Key,
  26914. ed448_key* ed448Key, falcon_key* falconKey,
  26915. dilithium_key* dilithiumKey, sphincs_key* sphincsKey,
  26916. WC_RNG* rng)
  26917. {
  26918. int sigSz = 0;
  26919. void* heap = NULL;
  26920. CertSignCtx certSignCtx_lcl;
  26921. CertSignCtx* certSignCtx = &certSignCtx_lcl;
  26922. XMEMSET(certSignCtx, 0, sizeof(*certSignCtx));
  26923. if (requestSz < 0)
  26924. return requestSz;
  26925. /* locate ctx */
  26926. if (rsaKey) {
  26927. #ifndef NO_RSA
  26928. #ifdef WOLFSSL_ASYNC_CRYPT
  26929. certSignCtx = &rsaKey->certSignCtx;
  26930. #endif
  26931. heap = rsaKey->heap;
  26932. #else
  26933. return NOT_COMPILED_IN;
  26934. #endif /* NO_RSA */
  26935. }
  26936. else if (eccKey) {
  26937. #ifdef HAVE_ECC
  26938. #ifdef WOLFSSL_ASYNC_CRYPT
  26939. certSignCtx = &eccKey->certSignCtx;
  26940. #endif
  26941. heap = eccKey->heap;
  26942. #else
  26943. return NOT_COMPILED_IN;
  26944. #endif /* HAVE_ECC */
  26945. }
  26946. if (certSignCtx->sig == NULL) {
  26947. certSignCtx->sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, heap,
  26948. DYNAMIC_TYPE_TMP_BUFFER);
  26949. if (certSignCtx->sig == NULL)
  26950. return MEMORY_E;
  26951. }
  26952. sigSz = MakeSignature(certSignCtx, buf, (word32)requestSz, certSignCtx->sig,
  26953. MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key,
  26954. falconKey, dilithiumKey, sphincsKey, rng, (word32)sType, heap);
  26955. #ifdef WOLFSSL_ASYNC_CRYPT
  26956. if (sigSz == WC_PENDING_E) {
  26957. /* Not free'ing certSignCtx->sig here because it could still be in use
  26958. * with async operations. */
  26959. return sigSz;
  26960. }
  26961. #endif
  26962. if (sigSz >= 0) {
  26963. if (requestSz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
  26964. sigSz = BUFFER_E;
  26965. else
  26966. sigSz = AddSignature(buf, requestSz, certSignCtx->sig, sigSz,
  26967. sType);
  26968. }
  26969. XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  26970. certSignCtx->sig = NULL;
  26971. return sigSz;
  26972. }
  26973. int wc_SignCert_ex(int requestSz, int sType, byte* buf, word32 buffSz,
  26974. int keyType, void* key, WC_RNG* rng)
  26975. {
  26976. RsaKey* rsaKey = NULL;
  26977. ecc_key* eccKey = NULL;
  26978. ed25519_key* ed25519Key = NULL;
  26979. ed448_key* ed448Key = NULL;
  26980. falcon_key* falconKey = NULL;
  26981. dilithium_key* dilithiumKey = NULL;
  26982. sphincs_key* sphincsKey = NULL;
  26983. if (keyType == RSA_TYPE)
  26984. rsaKey = (RsaKey*)key;
  26985. else if (keyType == ECC_TYPE)
  26986. eccKey = (ecc_key*)key;
  26987. else if (keyType == ED25519_TYPE)
  26988. ed25519Key = (ed25519_key*)key;
  26989. else if (keyType == ED448_TYPE)
  26990. ed448Key = (ed448_key*)key;
  26991. else if (keyType == FALCON_LEVEL1_TYPE)
  26992. falconKey = (falcon_key*)key;
  26993. else if (keyType == FALCON_LEVEL5_TYPE)
  26994. falconKey = (falcon_key*)key;
  26995. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  26996. dilithiumKey = (dilithium_key*)key;
  26997. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  26998. dilithiumKey = (dilithium_key*)key;
  26999. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27000. dilithiumKey = (dilithium_key*)key;
  27001. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27002. sphincsKey = (sphincs_key*)key;
  27003. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27004. sphincsKey = (sphincs_key*)key;
  27005. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27006. sphincsKey = (sphincs_key*)key;
  27007. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27008. sphincsKey = (sphincs_key*)key;
  27009. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27010. sphincsKey = (sphincs_key*)key;
  27011. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27012. sphincsKey = (sphincs_key*)key;
  27013. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, ed25519Key,
  27014. ed448Key, falconKey, dilithiumKey, sphincsKey, rng);
  27015. }
  27016. int wc_SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  27017. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng)
  27018. {
  27019. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, NULL, NULL,
  27020. NULL, NULL, NULL, rng);
  27021. }
  27022. WOLFSSL_ABI
  27023. int wc_MakeSelfCert(Cert* cert, byte* buf, word32 buffSz,
  27024. RsaKey* key, WC_RNG* rng)
  27025. {
  27026. int ret;
  27027. ret = wc_MakeCert(cert, buf, buffSz, key, NULL, rng);
  27028. if (ret < 0)
  27029. return ret;
  27030. return wc_SignCert(cert->bodySz, cert->sigType,
  27031. buf, buffSz, key, NULL, rng);
  27032. }
  27033. #ifdef WOLFSSL_CERT_EXT
  27034. /* Get raw subject from cert, which may contain OIDs not parsed by Decode.
  27035. The raw subject pointer will only be valid while "cert" is valid. */
  27036. WOLFSSL_ABI
  27037. int wc_GetSubjectRaw(byte **subjectRaw, Cert *cert)
  27038. {
  27039. int rc = BAD_FUNC_ARG;
  27040. if ((subjectRaw != NULL) && (cert != NULL)) {
  27041. *subjectRaw = cert->sbjRaw;
  27042. rc = 0;
  27043. }
  27044. return rc;
  27045. }
  27046. /* Set KID from public key */
  27047. static int SetKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey,
  27048. ed25519_key* ed25519Key, ed448_key* ed448Key,
  27049. falcon_key* falconKey,
  27050. dilithium_key* dilithiumKey,
  27051. sphincs_key *sphincsKey, int kid_type)
  27052. {
  27053. byte *buf;
  27054. int bufferSz, ret;
  27055. if (cert == NULL ||
  27056. (rsakey == NULL && eckey == NULL && ed25519Key == NULL &&
  27057. ed448Key == NULL && falconKey == NULL && dilithiumKey == NULL &&
  27058. sphincsKey == NULL) ||
  27059. (kid_type != SKID_TYPE && kid_type != AKID_TYPE))
  27060. return BAD_FUNC_ARG;
  27061. buf = (byte *)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap,
  27062. DYNAMIC_TYPE_TMP_BUFFER);
  27063. if (buf == NULL)
  27064. return MEMORY_E;
  27065. /* Public Key */
  27066. bufferSz = -1;
  27067. #ifndef NO_RSA
  27068. /* RSA public key */
  27069. if (rsakey != NULL)
  27070. bufferSz = SetRsaPublicKey(buf, rsakey, MAX_PUBLIC_KEY_SZ, 0);
  27071. #endif
  27072. #ifdef HAVE_ECC
  27073. /* ECC public key */
  27074. if (eckey != NULL)
  27075. bufferSz = SetEccPublicKey(buf, eckey, MAX_PUBLIC_KEY_SZ, 0, 0);
  27076. #endif
  27077. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  27078. /* ED25519 public key */
  27079. if (ed25519Key != NULL) {
  27080. bufferSz = wc_Ed25519PublicKeyToDer(ed25519Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  27081. }
  27082. #endif
  27083. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  27084. /* ED448 public key */
  27085. if (ed448Key != NULL) {
  27086. bufferSz = wc_Ed448PublicKeyToDer(ed448Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  27087. }
  27088. #endif
  27089. #if defined(HAVE_PQC)
  27090. #if defined(HAVE_FALCON)
  27091. if (falconKey != NULL) {
  27092. bufferSz = wc_Falcon_PublicKeyToDer(falconKey, buf, MAX_PUBLIC_KEY_SZ,
  27093. 0);
  27094. }
  27095. #endif
  27096. #if defined(HAVE_DILITHIUM)
  27097. if (dilithiumKey != NULL) {
  27098. bufferSz = wc_Dilithium_PublicKeyToDer(dilithiumKey, buf,
  27099. MAX_PUBLIC_KEY_SZ, 0);
  27100. }
  27101. #endif
  27102. #if defined(HAVE_SPHINCS)
  27103. if (sphincsKey != NULL) {
  27104. bufferSz = wc_Sphincs_PublicKeyToDer(sphincsKey, buf,
  27105. MAX_PUBLIC_KEY_SZ, 0);
  27106. }
  27107. #endif
  27108. #endif /* HAVE_PQC */
  27109. if (bufferSz <= 0) {
  27110. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27111. return PUBLIC_KEY_E;
  27112. }
  27113. /* Compute SKID by hashing public key */
  27114. if (kid_type == SKID_TYPE) {
  27115. ret = CalcHashId(buf, (word32)bufferSz, cert->skid);
  27116. cert->skidSz = KEYID_SIZE;
  27117. }
  27118. else if (kid_type == AKID_TYPE) {
  27119. ret = CalcHashId(buf, (word32)bufferSz, cert->akid);
  27120. cert->akidSz = KEYID_SIZE;
  27121. }
  27122. else
  27123. ret = BAD_FUNC_ARG;
  27124. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27125. return ret;
  27126. }
  27127. int wc_SetSubjectKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  27128. {
  27129. RsaKey* rsaKey = NULL;
  27130. ecc_key* eccKey = NULL;
  27131. ed25519_key* ed25519Key = NULL;
  27132. ed448_key* ed448Key = NULL;
  27133. falcon_key* falconKey = NULL;
  27134. dilithium_key* dilithiumKey = NULL;
  27135. sphincs_key* sphincsKey = NULL;
  27136. if (keyType == RSA_TYPE)
  27137. rsaKey = (RsaKey*)key;
  27138. else if (keyType == ECC_TYPE)
  27139. eccKey = (ecc_key*)key;
  27140. else if (keyType == ED25519_TYPE)
  27141. ed25519Key = (ed25519_key*)key;
  27142. else if (keyType == ED448_TYPE)
  27143. ed448Key = (ed448_key*)key;
  27144. else if (keyType == FALCON_LEVEL1_TYPE)
  27145. falconKey = (falcon_key*)key;
  27146. else if (keyType == FALCON_LEVEL5_TYPE)
  27147. falconKey = (falcon_key*)key;
  27148. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27149. dilithiumKey = (dilithium_key*)key;
  27150. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27151. dilithiumKey = (dilithium_key*)key;
  27152. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27153. dilithiumKey = (dilithium_key*)key;
  27154. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27155. sphincsKey = (sphincs_key*)key;
  27156. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27157. sphincsKey = (sphincs_key*)key;
  27158. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27159. sphincsKey = (sphincs_key*)key;
  27160. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27161. sphincsKey = (sphincs_key*)key;
  27162. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27163. sphincsKey = (sphincs_key*)key;
  27164. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27165. sphincsKey = (sphincs_key*)key;
  27166. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  27167. falconKey, dilithiumKey, sphincsKey,
  27168. SKID_TYPE);
  27169. }
  27170. /* Set SKID from RSA or ECC public key */
  27171. int wc_SetSubjectKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  27172. {
  27173. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
  27174. NULL, SKID_TYPE);
  27175. }
  27176. int wc_SetAuthKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  27177. {
  27178. RsaKey* rsaKey = NULL;
  27179. ecc_key* eccKey = NULL;
  27180. ed25519_key* ed25519Key = NULL;
  27181. ed448_key* ed448Key = NULL;
  27182. falcon_key* falconKey = NULL;
  27183. dilithium_key* dilithiumKey = NULL;
  27184. sphincs_key* sphincsKey = NULL;
  27185. if (keyType == RSA_TYPE)
  27186. rsaKey = (RsaKey*)key;
  27187. else if (keyType == ECC_TYPE)
  27188. eccKey = (ecc_key*)key;
  27189. else if (keyType == ED25519_TYPE)
  27190. ed25519Key = (ed25519_key*)key;
  27191. else if (keyType == ED448_TYPE)
  27192. ed448Key = (ed448_key*)key;
  27193. else if (keyType == FALCON_LEVEL1_TYPE)
  27194. falconKey = (falcon_key*)key;
  27195. else if (keyType == FALCON_LEVEL5_TYPE)
  27196. falconKey = (falcon_key*)key;
  27197. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27198. dilithiumKey = (dilithium_key*)key;
  27199. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27200. dilithiumKey = (dilithium_key*)key;
  27201. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27202. dilithiumKey = (dilithium_key*)key;
  27203. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27204. sphincsKey = (sphincs_key*)key;
  27205. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27206. sphincsKey = (sphincs_key*)key;
  27207. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27208. sphincsKey = (sphincs_key*)key;
  27209. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27210. sphincsKey = (sphincs_key*)key;
  27211. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27212. sphincsKey = (sphincs_key*)key;
  27213. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27214. sphincsKey = (sphincs_key*)key;
  27215. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  27216. falconKey, dilithiumKey, sphincsKey,
  27217. AKID_TYPE);
  27218. }
  27219. /* Set SKID from RSA or ECC public key */
  27220. int wc_SetAuthKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  27221. {
  27222. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
  27223. NULL, AKID_TYPE);
  27224. }
  27225. #if !defined(NO_FILESYSTEM) && !defined(NO_ASN_CRYPT)
  27226. /* Set SKID from public key file in PEM */
  27227. int wc_SetSubjectKeyId(Cert *cert, const char* file)
  27228. {
  27229. int ret, derSz;
  27230. byte* der;
  27231. word32 idx;
  27232. RsaKey *rsakey = NULL;
  27233. ecc_key *eckey = NULL;
  27234. if (cert == NULL || file == NULL)
  27235. return BAD_FUNC_ARG;
  27236. der = (byte*)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap, DYNAMIC_TYPE_CERT);
  27237. if (der == NULL) {
  27238. WOLFSSL_MSG("wc_SetSubjectKeyId memory Problem");
  27239. return MEMORY_E;
  27240. }
  27241. derSz = MAX_PUBLIC_KEY_SZ;
  27242. XMEMSET(der, 0, (size_t)derSz);
  27243. derSz = wc_PemPubKeyToDer(file, der, derSz);
  27244. if (derSz <= 0) {
  27245. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27246. return derSz;
  27247. }
  27248. /* Load PubKey in internal structure */
  27249. #ifndef NO_RSA
  27250. rsakey = (RsaKey*) XMALLOC(sizeof(RsaKey), cert->heap, DYNAMIC_TYPE_RSA);
  27251. if (rsakey == NULL) {
  27252. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27253. return MEMORY_E;
  27254. }
  27255. if (wc_InitRsaKey(rsakey, cert->heap) != 0) {
  27256. WOLFSSL_MSG("wc_InitRsaKey failure");
  27257. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27258. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27259. return MEMORY_E;
  27260. }
  27261. idx = 0;
  27262. ret = wc_RsaPublicKeyDecode(der, &idx, rsakey, (word32)derSz);
  27263. if (ret != 0)
  27264. #endif
  27265. {
  27266. #ifndef NO_RSA
  27267. WOLFSSL_MSG("wc_RsaPublicKeyDecode failed");
  27268. wc_FreeRsaKey(rsakey);
  27269. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27270. rsakey = NULL;
  27271. #endif
  27272. #ifdef HAVE_ECC
  27273. /* Check to load ecc public key */
  27274. eckey = (ecc_key*) XMALLOC(sizeof(ecc_key), cert->heap,
  27275. DYNAMIC_TYPE_ECC);
  27276. if (eckey == NULL) {
  27277. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27278. return MEMORY_E;
  27279. }
  27280. if (wc_ecc_init(eckey) != 0) {
  27281. WOLFSSL_MSG("wc_ecc_init failure");
  27282. wc_ecc_free(eckey);
  27283. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27284. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27285. return MEMORY_E;
  27286. }
  27287. idx = 0;
  27288. ret = wc_EccPublicKeyDecode(der, &idx, eckey, (word32)derSz);
  27289. if (ret != 0) {
  27290. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  27291. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27292. wc_ecc_free(eckey);
  27293. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27294. return PUBLIC_KEY_E;
  27295. }
  27296. #else
  27297. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27298. return PUBLIC_KEY_E;
  27299. #endif /* HAVE_ECC */
  27300. }
  27301. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27302. ret = wc_SetSubjectKeyIdFromPublicKey(cert, rsakey, eckey);
  27303. #ifndef NO_RSA
  27304. wc_FreeRsaKey(rsakey);
  27305. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27306. #endif
  27307. #ifdef HAVE_ECC
  27308. wc_ecc_free(eckey);
  27309. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27310. #endif
  27311. return ret;
  27312. }
  27313. #endif /* !NO_FILESYSTEM && !NO_ASN_CRYPT */
  27314. static int SetAuthKeyIdFromDcert(Cert* cert, DecodedCert* decoded)
  27315. {
  27316. int ret = 0;
  27317. /* Subject Key Id not found !! */
  27318. if (decoded->extSubjKeyIdSet == 0) {
  27319. ret = ASN_NO_SKID;
  27320. }
  27321. /* SKID invalid size */
  27322. else if (sizeof(cert->akid) < sizeof(decoded->extSubjKeyId)) {
  27323. ret = MEMORY_E;
  27324. }
  27325. else {
  27326. /* Put the SKID of CA to AKID of certificate */
  27327. XMEMCPY(cert->akid, decoded->extSubjKeyId, KEYID_SIZE);
  27328. cert->akidSz = KEYID_SIZE;
  27329. }
  27330. return ret;
  27331. }
  27332. /* Set AKID from certificate contains in buffer (DER encoded) */
  27333. int wc_SetAuthKeyIdFromCert(Cert *cert, const byte *der, int derSz)
  27334. {
  27335. int ret = 0;
  27336. if (cert == NULL) {
  27337. ret = BAD_FUNC_ARG;
  27338. }
  27339. else {
  27340. /* Check if decodedCert is cached */
  27341. if (cert->der != der) {
  27342. /* Allocate cache for the decoded cert */
  27343. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27344. }
  27345. if (ret >= 0) {
  27346. ret = SetAuthKeyIdFromDcert(cert, (DecodedCert*)cert->decodedCert);
  27347. #ifndef WOLFSSL_CERT_GEN_CACHE
  27348. wc_SetCert_Free(cert);
  27349. #endif
  27350. }
  27351. }
  27352. return ret;
  27353. }
  27354. #ifndef NO_FILESYSTEM
  27355. /* Set AKID from certificate file in PEM */
  27356. int wc_SetAuthKeyId(Cert *cert, const char* file)
  27357. {
  27358. int ret;
  27359. DerBuffer* der = NULL;
  27360. if (cert == NULL || file == NULL)
  27361. return BAD_FUNC_ARG;
  27362. ret = wc_PemCertToDer_ex(file, &der);
  27363. if (ret == 0)
  27364. {
  27365. ret = wc_SetAuthKeyIdFromCert(cert, der->buffer, (int)der->length);
  27366. FreeDer(&der);
  27367. }
  27368. return ret;
  27369. }
  27370. #endif /* !NO_FILESYSTEM */
  27371. /* Set KeyUsage from human readable string */
  27372. int wc_SetKeyUsage(Cert *cert, const char *value)
  27373. {
  27374. int ret = 0;
  27375. char *token, *str, *ptr;
  27376. word32 len;
  27377. if (cert == NULL || value == NULL)
  27378. return BAD_FUNC_ARG;
  27379. cert->keyUsage = 0;
  27380. /* duplicate string (including terminator) */
  27381. len = (word32)XSTRLEN(value);
  27382. str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27383. if (str == NULL)
  27384. return MEMORY_E;
  27385. XMEMCPY(str, value, len+1);
  27386. /* parse value, and set corresponding Key Usage value */
  27387. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  27388. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27389. return KEYUSAGE_E;
  27390. }
  27391. while (token != NULL)
  27392. {
  27393. if (!XSTRCASECMP(token, "digitalSignature"))
  27394. cert->keyUsage |= KEYUSE_DIGITAL_SIG;
  27395. else if (!XSTRCASECMP(token, "nonRepudiation") ||
  27396. !XSTRCASECMP(token, "contentCommitment"))
  27397. cert->keyUsage |= KEYUSE_CONTENT_COMMIT;
  27398. else if (!XSTRCASECMP(token, "keyEncipherment"))
  27399. cert->keyUsage |= KEYUSE_KEY_ENCIPHER;
  27400. else if (!XSTRCASECMP(token, "dataEncipherment"))
  27401. cert->keyUsage |= KEYUSE_DATA_ENCIPHER;
  27402. else if (!XSTRCASECMP(token, "keyAgreement"))
  27403. cert->keyUsage |= KEYUSE_KEY_AGREE;
  27404. else if (!XSTRCASECMP(token, "keyCertSign"))
  27405. cert->keyUsage |= KEYUSE_KEY_CERT_SIGN;
  27406. else if (!XSTRCASECMP(token, "cRLSign"))
  27407. cert->keyUsage |= KEYUSE_CRL_SIGN;
  27408. else if (!XSTRCASECMP(token, "encipherOnly"))
  27409. cert->keyUsage |= KEYUSE_ENCIPHER_ONLY;
  27410. else if (!XSTRCASECMP(token, "decipherOnly"))
  27411. cert->keyUsage |= KEYUSE_DECIPHER_ONLY;
  27412. else {
  27413. ret = KEYUSAGE_E;
  27414. break;
  27415. }
  27416. token = XSTRTOK(NULL, ",", &ptr);
  27417. }
  27418. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27419. return ret;
  27420. }
  27421. /* Set ExtendedKeyUsage from human readable string */
  27422. int wc_SetExtKeyUsage(Cert *cert, const char *value)
  27423. {
  27424. int ret = 0;
  27425. char *token, *str, *ptr;
  27426. word32 len;
  27427. if (cert == NULL || value == NULL)
  27428. return BAD_FUNC_ARG;
  27429. cert->extKeyUsage = 0;
  27430. /* duplicate string (including terminator) */
  27431. len = (word32)XSTRLEN(value);
  27432. str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27433. if (str == NULL)
  27434. return MEMORY_E;
  27435. XMEMCPY(str, value, len+1);
  27436. /* parse value, and set corresponding Key Usage value */
  27437. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  27438. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27439. return EXTKEYUSAGE_E;
  27440. }
  27441. while (token != NULL)
  27442. {
  27443. if (!XSTRCASECMP(token, "any"))
  27444. cert->extKeyUsage |= EXTKEYUSE_ANY;
  27445. else if (!XSTRCASECMP(token, "serverAuth"))
  27446. cert->extKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  27447. else if (!XSTRCASECMP(token, "clientAuth"))
  27448. cert->extKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  27449. else if (!XSTRCASECMP(token, "codeSigning"))
  27450. cert->extKeyUsage |= EXTKEYUSE_CODESIGN;
  27451. else if (!XSTRCASECMP(token, "emailProtection"))
  27452. cert->extKeyUsage |= EXTKEYUSE_EMAILPROT;
  27453. else if (!XSTRCASECMP(token, "timeStamping"))
  27454. cert->extKeyUsage |= EXTKEYUSE_TIMESTAMP;
  27455. else if (!XSTRCASECMP(token, "OCSPSigning"))
  27456. cert->extKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  27457. else {
  27458. ret = EXTKEYUSAGE_E;
  27459. break;
  27460. }
  27461. token = XSTRTOK(NULL, ",", &ptr);
  27462. }
  27463. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27464. return ret;
  27465. }
  27466. #ifdef WOLFSSL_EKU_OID
  27467. /*
  27468. * cert structure to set EKU oid in
  27469. * oid the oid in byte representation
  27470. * sz size of oid buffer
  27471. * idx index of array to place oid
  27472. *
  27473. * returns 0 on success
  27474. */
  27475. int wc_SetExtKeyUsageOID(Cert *cert, const char *in, word32 sz, byte idx,
  27476. void* heap)
  27477. {
  27478. byte oid[MAX_OID_SZ];
  27479. word32 oidSz = MAX_OID_SZ;
  27480. if (idx >= CTC_MAX_EKU_NB || sz >= CTC_MAX_EKU_OID_SZ) {
  27481. WOLFSSL_MSG("Either idx or sz was too large");
  27482. return BAD_FUNC_ARG;
  27483. }
  27484. if (EncodePolicyOID(oid, &oidSz, in, heap) != 0) {
  27485. return BUFFER_E;
  27486. }
  27487. XMEMCPY(cert->extKeyUsageOID[idx], oid, oidSz);
  27488. cert->extKeyUsageOIDSz[idx] = oidSz;
  27489. cert->extKeyUsage |= EXTKEYUSE_USER;
  27490. return 0;
  27491. }
  27492. #endif /* WOLFSSL_EKU_OID */
  27493. #if defined(WOLFSSL_ASN_TEMPLATE) && defined(WOLFSSL_CERT_GEN) && \
  27494. defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_ENCODING) && \
  27495. defined(WOLFSSL_CERT_EXT)
  27496. int wc_SetCustomExtension(Cert *cert, int critical, const char *oid,
  27497. const byte *der, word32 derSz) {
  27498. CertExtension *ext;
  27499. byte encodedOid[MAX_OID_SZ];
  27500. word32 encodedOidSz = MAX_OID_SZ;
  27501. int ret;
  27502. if (cert == NULL || oid == NULL || der == NULL || derSz == 0) {
  27503. return BAD_FUNC_ARG;
  27504. }
  27505. if (cert->customCertExtCount >= NUM_CUSTOM_EXT) {
  27506. return MEMORY_E;
  27507. }
  27508. /* Make sure we can properly parse the OID. */
  27509. ret = EncodePolicyOID(encodedOid, &encodedOidSz, oid, NULL);
  27510. if (ret != 0) {
  27511. return ret;
  27512. }
  27513. ext = &cert->customCertExt[cert->customCertExtCount];
  27514. ext->oid = oid;
  27515. ext->crit = (critical == 0) ? 0 : 1;
  27516. ext->val = der;
  27517. ext->valSz = derSz;
  27518. cert->customCertExtCount++;
  27519. return 0;
  27520. }
  27521. #endif
  27522. #endif /* WOLFSSL_CERT_EXT */
  27523. #ifdef WOLFSSL_ALT_NAMES
  27524. static int SetAltNamesFromDcert(Cert* cert, DecodedCert* decoded)
  27525. {
  27526. int ret = 0;
  27527. cert->altNamesSz = 0;
  27528. if (decoded->altNames) {
  27529. ret = FlattenAltNames(cert->altNames,
  27530. sizeof(cert->altNames), decoded->altNames);
  27531. if (ret >= 0) {
  27532. cert->altNamesSz = ret;
  27533. ret = 0;
  27534. }
  27535. }
  27536. return ret;
  27537. }
  27538. #ifndef NO_FILESYSTEM
  27539. /* Set Alt Names from der cert, return 0 on success */
  27540. static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz,
  27541. int devId)
  27542. {
  27543. int ret;
  27544. #ifdef WOLFSSL_SMALL_STACK
  27545. DecodedCert* decoded;
  27546. #else
  27547. DecodedCert decoded[1];
  27548. #endif
  27549. if (derSz < 0)
  27550. return derSz;
  27551. #ifdef WOLFSSL_SMALL_STACK
  27552. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), cert->heap,
  27553. DYNAMIC_TYPE_TMP_BUFFER);
  27554. if (decoded == NULL)
  27555. return MEMORY_E;
  27556. #endif
  27557. InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
  27558. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  27559. if (ret < 0) {
  27560. WOLFSSL_MSG("ParseCertRelative error");
  27561. }
  27562. else {
  27563. ret = SetAltNamesFromDcert(cert, decoded);
  27564. }
  27565. FreeDecodedCert(decoded);
  27566. #ifdef WOLFSSL_SMALL_STACK
  27567. XFREE(decoded, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27568. #endif
  27569. return ret < 0 ? ret : 0;
  27570. }
  27571. #endif
  27572. static int SetDatesFromDcert(Cert* cert, DecodedCert* decoded)
  27573. {
  27574. int ret = 0;
  27575. if (decoded->beforeDate == NULL || decoded->afterDate == NULL) {
  27576. WOLFSSL_MSG("Couldn't extract dates");
  27577. ret = -1;
  27578. }
  27579. else if (decoded->beforeDateLen > MAX_DATE_SIZE ||
  27580. decoded->afterDateLen > MAX_DATE_SIZE) {
  27581. WOLFSSL_MSG("Bad date size");
  27582. ret = -1;
  27583. }
  27584. else {
  27585. XMEMCPY(cert->beforeDate, decoded->beforeDate,
  27586. (size_t)decoded->beforeDateLen);
  27587. XMEMCPY(cert->afterDate, decoded->afterDate,
  27588. (size_t)decoded->afterDateLen);
  27589. cert->beforeDateSz = decoded->beforeDateLen;
  27590. cert->afterDateSz = decoded->afterDateLen;
  27591. }
  27592. return ret;
  27593. }
  27594. #endif /* WOLFSSL_ALT_NAMES */
  27595. static void SetNameFromDcert(CertName* cn, DecodedCert* decoded)
  27596. {
  27597. int sz;
  27598. if (decoded->subjectCN) {
  27599. sz = (decoded->subjectCNLen < CTC_NAME_SIZE) ? decoded->subjectCNLen
  27600. : CTC_NAME_SIZE - 1;
  27601. XSTRNCPY(cn->commonName, decoded->subjectCN, (size_t)sz);
  27602. cn->commonName[sz] = '\0';
  27603. cn->commonNameEnc = decoded->subjectCNEnc;
  27604. }
  27605. if (decoded->subjectC) {
  27606. sz = (decoded->subjectCLen < CTC_NAME_SIZE) ? decoded->subjectCLen
  27607. : CTC_NAME_SIZE - 1;
  27608. XSTRNCPY(cn->country, decoded->subjectC, (size_t)sz);
  27609. cn->country[sz] = '\0';
  27610. cn->countryEnc = decoded->subjectCEnc;
  27611. }
  27612. if (decoded->subjectST) {
  27613. sz = (decoded->subjectSTLen < CTC_NAME_SIZE) ? decoded->subjectSTLen
  27614. : CTC_NAME_SIZE - 1;
  27615. XSTRNCPY(cn->state, decoded->subjectST, (size_t)sz);
  27616. cn->state[sz] = '\0';
  27617. cn->stateEnc = decoded->subjectSTEnc;
  27618. }
  27619. if (decoded->subjectL) {
  27620. sz = (decoded->subjectLLen < CTC_NAME_SIZE) ? decoded->subjectLLen
  27621. : CTC_NAME_SIZE - 1;
  27622. XSTRNCPY(cn->locality, decoded->subjectL, (size_t)sz);
  27623. cn->locality[sz] = '\0';
  27624. cn->localityEnc = decoded->subjectLEnc;
  27625. }
  27626. if (decoded->subjectO) {
  27627. sz = (decoded->subjectOLen < CTC_NAME_SIZE) ? decoded->subjectOLen
  27628. : CTC_NAME_SIZE - 1;
  27629. XSTRNCPY(cn->org, decoded->subjectO, (size_t)sz);
  27630. cn->org[sz] = '\0';
  27631. cn->orgEnc = decoded->subjectOEnc;
  27632. }
  27633. if (decoded->subjectOU) {
  27634. sz = (decoded->subjectOULen < CTC_NAME_SIZE) ? decoded->subjectOULen
  27635. : CTC_NAME_SIZE - 1;
  27636. XSTRNCPY(cn->unit, decoded->subjectOU, (size_t)sz);
  27637. cn->unit[sz] = '\0';
  27638. cn->unitEnc = decoded->subjectOUEnc;
  27639. }
  27640. if (decoded->subjectSN) {
  27641. sz = (decoded->subjectSNLen < CTC_NAME_SIZE) ? decoded->subjectSNLen
  27642. : CTC_NAME_SIZE - 1;
  27643. XSTRNCPY(cn->sur, decoded->subjectSN, (size_t)sz);
  27644. cn->sur[sz] = '\0';
  27645. cn->surEnc = decoded->subjectSNEnc;
  27646. }
  27647. if (decoded->subjectSND) {
  27648. sz = (decoded->subjectSNDLen < CTC_NAME_SIZE) ? decoded->subjectSNDLen
  27649. : CTC_NAME_SIZE - 1;
  27650. XSTRNCPY(cn->serialDev, decoded->subjectSND, (size_t)sz);
  27651. cn->serialDev[sz] = '\0';
  27652. cn->serialDevEnc = decoded->subjectSNDEnc;
  27653. }
  27654. if (decoded->subjectUID) {
  27655. sz = (decoded->subjectUIDLen < CTC_NAME_SIZE) ? decoded->subjectUIDLen
  27656. : CTC_NAME_SIZE - 1;
  27657. XSTRNCPY(cn->userId, decoded->subjectUID, (size_t)sz);
  27658. cn->userId[sz] = '\0';
  27659. cn->userIdEnc = decoded->subjectUIDEnc;
  27660. }
  27661. #ifdef WOLFSSL_CERT_EXT
  27662. if (decoded->subjectBC) {
  27663. sz = (decoded->subjectBCLen < CTC_NAME_SIZE) ? decoded->subjectBCLen
  27664. : CTC_NAME_SIZE - 1;
  27665. XSTRNCPY(cn->busCat, decoded->subjectBC, (size_t)sz);
  27666. cn->busCat[sz] = '\0';
  27667. cn->busCatEnc = decoded->subjectBCEnc;
  27668. }
  27669. if (decoded->subjectJC) {
  27670. sz = (decoded->subjectJCLen < CTC_NAME_SIZE) ? decoded->subjectJCLen
  27671. : CTC_NAME_SIZE - 1;
  27672. XSTRNCPY(cn->joiC, decoded->subjectJC, (size_t)sz);
  27673. cn->joiC[sz] = '\0';
  27674. cn->joiCEnc = decoded->subjectJCEnc;
  27675. }
  27676. if (decoded->subjectJS) {
  27677. sz = (decoded->subjectJSLen < CTC_NAME_SIZE) ? decoded->subjectJSLen
  27678. : CTC_NAME_SIZE - 1;
  27679. XSTRNCPY(cn->joiSt, decoded->subjectJS, (size_t)sz);
  27680. cn->joiSt[sz] = '\0';
  27681. cn->joiStEnc = decoded->subjectJSEnc;
  27682. }
  27683. #endif
  27684. if (decoded->subjectEmail) {
  27685. sz = (decoded->subjectEmailLen < CTC_NAME_SIZE)
  27686. ? decoded->subjectEmailLen : CTC_NAME_SIZE - 1;
  27687. XSTRNCPY(cn->email, decoded->subjectEmail, (size_t)sz);
  27688. cn->email[sz] = '\0';
  27689. }
  27690. #if defined(WOLFSSL_CERT_NAME_ALL) && \
  27691. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
  27692. if (decoded->subjectN) {
  27693. sz = (decoded->subjectNLen < CTC_NAME_SIZE) ? decoded->subjectNLen
  27694. : CTC_NAME_SIZE - 1;
  27695. XSTRNCPY(cn->dnName, decoded->subjectN, (size_t)sz);
  27696. cn->dnName[sz] = '\0';
  27697. cn->dnNameEnc = decoded->subjectNEnc;
  27698. }
  27699. if (decoded->subjectI) {
  27700. sz = (decoded->subjectILen < CTC_NAME_SIZE) ? decoded->subjectILen
  27701. : CTC_NAME_SIZE - 1;
  27702. XSTRNCPY(cn->initials, decoded->subjectI, (size_t)sz);
  27703. cn->initials[sz] = '\0';
  27704. cn->initialsEnc = decoded->subjectIEnc;
  27705. }
  27706. if (decoded->subjectGN) {
  27707. sz = (decoded->subjectGNLen < CTC_NAME_SIZE) ? decoded->subjectGNLen
  27708. : CTC_NAME_SIZE - 1;
  27709. XSTRNCPY(cn->givenName, decoded->subjectGN, (size_t)sz);
  27710. cn->givenName[sz] = '\0';
  27711. cn->givenNameEnc = decoded->subjectGNEnc;
  27712. }
  27713. if (decoded->subjectDNQ) {
  27714. sz = (decoded->subjectDNQLen < CTC_NAME_SIZE) ? decoded->subjectDNQLen
  27715. : CTC_NAME_SIZE - 1;
  27716. XSTRNCPY(cn->dnQualifier, decoded->subjectDNQ, (size_t)sz);
  27717. cn->dnQualifier[sz] = '\0';
  27718. cn->dnQualifierEnc = decoded->subjectDNQEnc;
  27719. }
  27720. #endif /* WOLFSSL_CERT_NAME_ALL */
  27721. }
  27722. #ifndef NO_FILESYSTEM
  27723. /* Set cn name from der buffer, return 0 on success */
  27724. static int SetNameFromCert(CertName* cn, const byte* der, int derSz, int devId)
  27725. {
  27726. int ret;
  27727. #ifdef WOLFSSL_SMALL_STACK
  27728. DecodedCert* decoded;
  27729. #else
  27730. DecodedCert decoded[1];
  27731. #endif
  27732. if (derSz < 0)
  27733. return derSz;
  27734. #ifdef WOLFSSL_SMALL_STACK
  27735. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  27736. DYNAMIC_TYPE_TMP_BUFFER);
  27737. if (decoded == NULL)
  27738. return MEMORY_E;
  27739. #endif
  27740. InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
  27741. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  27742. if (ret < 0) {
  27743. WOLFSSL_MSG("ParseCertRelative error");
  27744. }
  27745. else {
  27746. SetNameFromDcert(cn, decoded);
  27747. }
  27748. FreeDecodedCert(decoded);
  27749. #ifdef WOLFSSL_SMALL_STACK
  27750. XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  27751. #endif
  27752. return ret < 0 ? ret : 0;
  27753. }
  27754. /* Set cert issuer from issuerFile in PEM */
  27755. WOLFSSL_ABI
  27756. int wc_SetIssuer(Cert* cert, const char* issuerFile)
  27757. {
  27758. int ret;
  27759. DerBuffer* der = NULL;
  27760. if (cert == NULL || issuerFile == NULL)
  27761. return BAD_FUNC_ARG;
  27762. ret = wc_PemCertToDer_ex(issuerFile, &der);
  27763. if (ret == 0) {
  27764. cert->selfSigned = 0;
  27765. ret = SetNameFromCert(&cert->issuer, der->buffer, (int)der->length,
  27766. INVALID_DEVID);
  27767. FreeDer(&der);
  27768. }
  27769. return ret;
  27770. }
  27771. /* Set cert subject from subjectFile in PEM */
  27772. WOLFSSL_ABI
  27773. int wc_SetSubject(Cert* cert, const char* subjectFile)
  27774. {
  27775. int ret;
  27776. DerBuffer* der = NULL;
  27777. if (cert == NULL || subjectFile == NULL)
  27778. return BAD_FUNC_ARG;
  27779. ret = wc_PemCertToDer_ex(subjectFile, &der);
  27780. if (ret == 0) {
  27781. ret = SetNameFromCert(&cert->subject, der->buffer, (int)der->length,
  27782. INVALID_DEVID);
  27783. FreeDer(&der);
  27784. }
  27785. return ret;
  27786. }
  27787. #ifdef WOLFSSL_ALT_NAMES
  27788. /* Set alt names from file in PEM */
  27789. WOLFSSL_ABI
  27790. int wc_SetAltNames(Cert* cert, const char* file)
  27791. {
  27792. int ret;
  27793. DerBuffer* der = NULL;
  27794. if (cert == NULL) {
  27795. return BAD_FUNC_ARG;
  27796. }
  27797. ret = wc_PemCertToDer_ex(file, &der);
  27798. if (ret == 0) {
  27799. ret = SetAltNamesFromCert(cert, der->buffer, (int)der->length,
  27800. INVALID_DEVID);
  27801. FreeDer(&der);
  27802. }
  27803. return ret;
  27804. }
  27805. #endif /* WOLFSSL_ALT_NAMES */
  27806. #endif /* !NO_FILESYSTEM */
  27807. /* Set cert issuer from DER buffer */
  27808. WOLFSSL_ABI
  27809. int wc_SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
  27810. {
  27811. int ret = 0;
  27812. if (cert == NULL) {
  27813. ret = BAD_FUNC_ARG;
  27814. }
  27815. else {
  27816. cert->selfSigned = 0;
  27817. /* Check if decodedCert is cached */
  27818. if (cert->der != der) {
  27819. /* Allocate cache for the decoded cert */
  27820. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27821. }
  27822. if (ret >= 0) {
  27823. SetNameFromDcert(&cert->issuer, (DecodedCert*)cert->decodedCert);
  27824. #ifndef WOLFSSL_CERT_GEN_CACHE
  27825. wc_SetCert_Free(cert);
  27826. #endif
  27827. }
  27828. }
  27829. return ret;
  27830. }
  27831. /* Set cert subject from DER buffer */
  27832. WOLFSSL_ABI
  27833. int wc_SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
  27834. {
  27835. int ret = 0;
  27836. if (cert == NULL) {
  27837. ret = BAD_FUNC_ARG;
  27838. }
  27839. else {
  27840. /* Check if decodedCert is cached */
  27841. if (cert->der != der) {
  27842. /* Allocate cache for the decoded cert */
  27843. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27844. }
  27845. if (ret >= 0) {
  27846. SetNameFromDcert(&cert->subject, (DecodedCert*)cert->decodedCert);
  27847. #ifndef WOLFSSL_CERT_GEN_CACHE
  27848. wc_SetCert_Free(cert);
  27849. #endif
  27850. }
  27851. }
  27852. return ret;
  27853. }
  27854. #ifdef WOLFSSL_CERT_EXT
  27855. /* Set cert raw subject from DER buffer */
  27856. WOLFSSL_ABI
  27857. int wc_SetSubjectRaw(Cert* cert, const byte* der, int derSz)
  27858. {
  27859. int ret = 0;
  27860. if (cert == NULL) {
  27861. ret = BAD_FUNC_ARG;
  27862. }
  27863. else {
  27864. /* Check if decodedCert is cached */
  27865. if (cert->der != der) {
  27866. /* Allocate cache for the decoded cert */
  27867. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27868. }
  27869. if (ret >= 0) {
  27870. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  27871. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  27872. (int)sizeof(CertName))) {
  27873. XMEMCPY(cert->sbjRaw,
  27874. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  27875. (size_t)((DecodedCert*)cert->decodedCert)->
  27876. subjectRawLen);
  27877. }
  27878. #ifndef WOLFSSL_CERT_GEN_CACHE
  27879. wc_SetCert_Free(cert);
  27880. #endif
  27881. }
  27882. }
  27883. return ret;
  27884. }
  27885. /* Set cert raw issuer from DER buffer */
  27886. WOLFSSL_ABI
  27887. int wc_SetIssuerRaw(Cert* cert, const byte* der, int derSz)
  27888. {
  27889. int ret = 0;
  27890. if (cert == NULL) {
  27891. ret = BAD_FUNC_ARG;
  27892. }
  27893. else {
  27894. /* Check if decodedCert is cached */
  27895. if (cert->der != der) {
  27896. /* Allocate cache for the decoded cert */
  27897. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27898. }
  27899. if (ret >= 0) {
  27900. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  27901. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  27902. (int)sizeof(CertName))) {
  27903. /* Copy the subject to the issuer field */
  27904. XMEMCPY(cert->issRaw,
  27905. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  27906. (size_t)((DecodedCert*)cert->decodedCert)->
  27907. subjectRawLen);
  27908. }
  27909. #ifndef WOLFSSL_CERT_GEN_CACHE
  27910. wc_SetCert_Free(cert);
  27911. #endif
  27912. }
  27913. }
  27914. return ret;
  27915. }
  27916. #endif
  27917. #ifdef WOLFSSL_ALT_NAMES
  27918. /* Set cert alt names from DER buffer */
  27919. WOLFSSL_ABI
  27920. int wc_SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
  27921. {
  27922. int ret = 0;
  27923. if (cert == NULL) {
  27924. ret = BAD_FUNC_ARG;
  27925. }
  27926. else {
  27927. /* Check if decodedCert is cached */
  27928. if (cert->der != der) {
  27929. /* Allocate cache for the decoded cert */
  27930. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27931. }
  27932. if (ret >= 0) {
  27933. ret = SetAltNamesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  27934. #ifndef WOLFSSL_CERT_GEN_CACHE
  27935. wc_SetCert_Free(cert);
  27936. #endif
  27937. }
  27938. }
  27939. return(ret);
  27940. }
  27941. /* Set cert dates from DER buffer */
  27942. WOLFSSL_ABI
  27943. int wc_SetDatesBuffer(Cert* cert, const byte* der, int derSz)
  27944. {
  27945. int ret = 0;
  27946. if (cert == NULL) {
  27947. ret = BAD_FUNC_ARG;
  27948. }
  27949. else {
  27950. /* Check if decodedCert is cached */
  27951. if (cert->der != der) {
  27952. /* Allocate cache for the decoded cert */
  27953. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27954. }
  27955. if (ret >= 0) {
  27956. ret = SetDatesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  27957. #ifndef WOLFSSL_CERT_GEN_CACHE
  27958. wc_SetCert_Free(cert);
  27959. #endif
  27960. }
  27961. }
  27962. return(ret);
  27963. }
  27964. #endif /* WOLFSSL_ALT_NAMES */
  27965. #endif /* WOLFSSL_CERT_GEN */
  27966. #if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) \
  27967. || defined(OPENSSL_EXTRA)
  27968. /* Encode OID string representation to ITU-T X.690 format */
  27969. int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap)
  27970. {
  27971. word32 idx = 0, nb_val;
  27972. char *token, *str, *ptr;
  27973. word32 len;
  27974. (void)heap;
  27975. if (out == NULL || outSz == NULL || *outSz < 2 || in == NULL)
  27976. return BAD_FUNC_ARG;
  27977. /* duplicate string (including terminator) */
  27978. len = (word32)XSTRLEN(in);
  27979. str = (char *)XMALLOC(len+1, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27980. if (str == NULL)
  27981. return MEMORY_E;
  27982. XMEMCPY(str, in, len+1);
  27983. nb_val = 0;
  27984. /* parse value, and set corresponding Policy OID value */
  27985. token = XSTRTOK(str, ".", &ptr);
  27986. while (token != NULL)
  27987. {
  27988. word32 val = (word32)XATOI(token);
  27989. if (nb_val == 0) {
  27990. if (val > 2) {
  27991. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27992. return ASN_OBJECT_ID_E;
  27993. }
  27994. out[idx] = (byte)(40 * val);
  27995. }
  27996. else if (nb_val == 1) {
  27997. if (val > 127) {
  27998. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27999. return ASN_OBJECT_ID_E;
  28000. }
  28001. if (idx > *outSz) {
  28002. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28003. return BUFFER_E;
  28004. }
  28005. out[idx++] += (byte)val;
  28006. }
  28007. else {
  28008. word32 tb = 0;
  28009. int i = 0;
  28010. byte oid[MAX_OID_SZ];
  28011. while (val >= 128) {
  28012. word32 x = val % 128;
  28013. val /= 128;
  28014. oid[i++] = (byte) (((tb++) ? 0x80 : 0) | x);
  28015. }
  28016. if ((idx+(word32)i) >= *outSz) {
  28017. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28018. return BUFFER_E;
  28019. }
  28020. oid[i] = (byte) (((tb++) ? 0x80 : 0) | val);
  28021. /* push value in the right order */
  28022. while (i >= 0)
  28023. out[idx++] = oid[i--];
  28024. }
  28025. token = XSTRTOK(NULL, ".", &ptr);
  28026. nb_val++;
  28027. }
  28028. *outSz = idx;
  28029. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28030. return 0;
  28031. }
  28032. #endif /* WOLFSSL_CERT_EXT || OPENSSL_EXTRA */
  28033. #endif /* !NO_CERTS */
  28034. #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
  28035. /* Helper function for wolfSSL_i2d_DHparams */
  28036. int StoreDHparams(byte* out, word32* outLen, mp_int* p, mp_int* g)
  28037. {
  28038. #ifndef WOLFSSL_ASN_TEMPLATE
  28039. word32 idx = 0;
  28040. word32 total;
  28041. WOLFSSL_ENTER("StoreDHparams");
  28042. if (out == NULL) {
  28043. WOLFSSL_MSG("Null buffer error");
  28044. return BUFFER_E;
  28045. }
  28046. /* determine size */
  28047. /* integer - g */
  28048. idx = SetASNIntMP(g, -1, NULL);
  28049. /* integer - p */
  28050. idx += SetASNIntMP(p, -1, NULL);
  28051. total = idx;
  28052. /* sequence */
  28053. idx += SetSequence(idx, NULL);
  28054. /* make sure output fits in buffer */
  28055. if (idx > *outLen) {
  28056. return BUFFER_E;
  28057. }
  28058. /* write DH parameters */
  28059. /* sequence - for P and G only */
  28060. idx = SetSequence(total, out);
  28061. /* integer - p */
  28062. idx += SetASNIntMP(p, -1, out + idx);
  28063. /* integer - g */
  28064. idx += SetASNIntMP(g, -1, out + idx);
  28065. *outLen = idx;
  28066. return 0;
  28067. #else
  28068. ASNSetData dataASN[dhParamASN_Length];
  28069. int ret = 0;
  28070. int sz = 0;
  28071. WOLFSSL_ENTER("StoreDHparams");
  28072. if (out == NULL) {
  28073. ret = BUFFER_E;
  28074. }
  28075. if (ret == 0) {
  28076. XMEMSET(dataASN, 0, sizeof(dataASN));
  28077. /* Set mp_int containing p and g. */
  28078. SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], p);
  28079. SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], g);
  28080. /* privateValueLength not encoded. */
  28081. dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
  28082. /* Calculate the size of the DH parameters. */
  28083. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  28084. }
  28085. /* Check buffer is big enough for encoding. */
  28086. if ((ret == 0) && ((int)*outLen < sz)) {
  28087. ret = BUFFER_E;
  28088. }
  28089. if (ret == 0) {
  28090. /* Encode the DH parameters into buffer. */
  28091. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, out);
  28092. /* Set the actual encoding size. */
  28093. *outLen = sz;
  28094. }
  28095. return ret;
  28096. #endif /* WOLFSSL_ASN_TEMPLATE */
  28097. }
  28098. #endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
  28099. #if defined(HAVE_ECC) || !defined(NO_DSA)
  28100. #ifdef WOLFSSL_ASN_TEMPLATE
  28101. /* ASN.1 template for DSA signature.
  28102. * RFC 5912, 6 - DSA-Sig-Value
  28103. */
  28104. static const ASNItem dsaSigASN[] = {
  28105. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28106. /* r */
  28107. /* R */ { 1, ASN_INTEGER, 0, 0, 0 },
  28108. /* s */
  28109. /* S */ { 1, ASN_INTEGER, 0, 0, 0 },
  28110. };
  28111. enum {
  28112. DSASIGASN_IDX_SEQ = 0,
  28113. DSASIGASN_IDX_R,
  28114. DSASIGASN_IDX_S
  28115. };
  28116. #define dsaSigASN_Length (sizeof(dsaSigASN) / sizeof(ASNItem))
  28117. #endif
  28118. /* Der Encode r & s ints into out, outLen is (in/out) size */
  28119. int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
  28120. {
  28121. #ifndef WOLFSSL_ASN_TEMPLATE
  28122. word32 idx = 0;
  28123. int rSz; /* encoding size */
  28124. int sSz;
  28125. int headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  28126. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  28127. int rLeadingZero = mp_leading_bit(r);
  28128. int sLeadingZero = mp_leading_bit(s);
  28129. int rLen = mp_unsigned_bin_size(r); /* big int size */
  28130. int sLen = mp_unsigned_bin_size(s);
  28131. if (*outLen < (word32)((rLen + rLeadingZero + sLen + sLeadingZero +
  28132. headerSz + 2))) /* SEQ_TAG + LEN(ENUM) */
  28133. return BUFFER_E;
  28134. idx = SetSequence((word32)(rLen + rLeadingZero + sLen + sLeadingZero +
  28135. headerSz), out);
  28136. /* store r */
  28137. rSz = SetASNIntMP(r, (int)(*outLen - idx), &out[idx]);
  28138. if (rSz < 0)
  28139. return rSz;
  28140. idx += (word32)rSz;
  28141. /* store s */
  28142. sSz = SetASNIntMP(s, (int)(*outLen - idx), &out[idx]);
  28143. if (sSz < 0)
  28144. return sSz;
  28145. idx += (word32)sSz;
  28146. *outLen = idx;
  28147. return 0;
  28148. #else
  28149. ASNSetData dataASN[dsaSigASN_Length];
  28150. int ret;
  28151. int sz;
  28152. /* Clear dynamic data and set mp_ints r and s */
  28153. XMEMSET(dataASN, 0, sizeof(dataASN));
  28154. SetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
  28155. SetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
  28156. /* Calculate size of encoding. */
  28157. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  28158. /* Check buffer is big enough for encoding. */
  28159. if ((ret == 0) && ((int)*outLen < sz)) {
  28160. ret = BUFFER_E;
  28161. }
  28162. if (ret == 0) {
  28163. /* Encode DSA signature into buffer. */
  28164. SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  28165. /* Set the actual encoding size. */
  28166. *outLen = (word32)sz;
  28167. }
  28168. return ret;
  28169. #endif /* WOLFSSL_ASN_TEMPLATE */
  28170. }
  28171. #ifndef WOLFSSL_ASN_TEMPLATE
  28172. /* determine if leading bit is set */
  28173. static word32 is_leading_bit_set(const byte* input, word32 sz)
  28174. {
  28175. byte c = 0;
  28176. if (sz > 0)
  28177. c = input[0];
  28178. return (c & 0x80) != 0;
  28179. }
  28180. static word32 trim_leading_zeros(const byte** input, word32 sz)
  28181. {
  28182. int i;
  28183. word32 leadingZeroCount = 0;
  28184. const byte* tmp = *input;
  28185. for (i=0; i<(int)sz; i++) {
  28186. if (tmp[i] != 0)
  28187. break;
  28188. leadingZeroCount++;
  28189. }
  28190. /* catch all zero case */
  28191. if (sz > 0 && leadingZeroCount == sz) {
  28192. leadingZeroCount--;
  28193. }
  28194. *input += leadingZeroCount;
  28195. sz -= leadingZeroCount;
  28196. return sz;
  28197. }
  28198. #endif
  28199. /* Der Encode r & s ints into out, outLen is (in/out) size */
  28200. /* All input/outputs are assumed to be big-endian */
  28201. int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen,
  28202. const byte* s, word32 sLen)
  28203. {
  28204. #ifndef WOLFSSL_ASN_TEMPLATE
  28205. int ret;
  28206. word32 idx;
  28207. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  28208. word32 rAddLeadZero, sAddLeadZero;
  28209. if ((out == NULL) || (outLen == NULL) || (r == NULL) || (s == NULL))
  28210. return BAD_FUNC_ARG;
  28211. /* Trim leading zeros */
  28212. rLen = trim_leading_zeros(&r, rLen);
  28213. sLen = trim_leading_zeros(&s, sLen);
  28214. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  28215. /* Add leading zero if MSB is set */
  28216. rAddLeadZero = is_leading_bit_set(r, rLen);
  28217. sAddLeadZero = is_leading_bit_set(s, sLen);
  28218. if (*outLen < (rLen + rAddLeadZero + sLen + sAddLeadZero +
  28219. headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
  28220. return BUFFER_E;
  28221. idx = SetSequence(rLen+rAddLeadZero + sLen+sAddLeadZero + headerSz, out);
  28222. /* store r */
  28223. ret = SetASNInt((int)rLen, (byte)(rAddLeadZero ? 0x80U : 0x00U), &out[idx]);
  28224. if (ret < 0)
  28225. return ret;
  28226. idx += (word32)ret;
  28227. XMEMCPY(&out[idx], r, rLen);
  28228. idx += rLen;
  28229. /* store s */
  28230. ret = SetASNInt((int)sLen, (byte)(sAddLeadZero ? 0x80U : 0x00U), &out[idx]);
  28231. if (ret < 0)
  28232. return ret;
  28233. idx += (word32)ret;
  28234. XMEMCPY(&out[idx], s, sLen);
  28235. idx += sLen;
  28236. *outLen = idx;
  28237. return 0;
  28238. #else
  28239. ASNSetData dataASN[dsaSigASN_Length];
  28240. int ret;
  28241. int sz;
  28242. /* Clear dynamic data and set buffers for r and s */
  28243. XMEMSET(dataASN, 0, sizeof(dataASN));
  28244. SetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
  28245. SetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
  28246. /* Calculate size of encoding. */
  28247. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  28248. /* Check buffer is big enough for encoding. */
  28249. if ((ret == 0) && ((int)*outLen < sz)) {
  28250. ret = BUFFER_E;
  28251. }
  28252. if (ret == 0) {
  28253. /* Encode DSA signature into buffer. */
  28254. SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  28255. /* Set the actual encoding size. */
  28256. *outLen = (word32)sz;
  28257. }
  28258. return ret;
  28259. #endif /* WOLFSSL_ASN_TEMPLATE */
  28260. }
  28261. /* Der Decode ECC-DSA Signature with R/S as unsigned bin */
  28262. /* All input/outputs are assumed to be big-endian */
  28263. int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen,
  28264. byte* s, word32* sLen)
  28265. {
  28266. #ifndef WOLFSSL_ASN_TEMPLATE
  28267. int ret;
  28268. word32 idx = 0;
  28269. int len = 0;
  28270. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  28271. return ASN_ECC_KEY_E;
  28272. }
  28273. #ifndef NO_STRICT_ECDSA_LEN
  28274. /* enable strict length checking for signature */
  28275. if (sigLen != idx + (word32)len) {
  28276. return ASN_ECC_KEY_E;
  28277. }
  28278. #else
  28279. /* allow extra signature bytes at end */
  28280. if ((word32)len > (sigLen - idx)) {
  28281. return ASN_ECC_KEY_E;
  28282. }
  28283. #endif
  28284. ret = GetASNInt(sig, &idx, &len, sigLen);
  28285. if (ret != 0)
  28286. return ret;
  28287. if (rLen)
  28288. *rLen = (word32)len;
  28289. if (r)
  28290. XMEMCPY(r, (byte*)sig + idx, (size_t)len);
  28291. idx += (word32)len;
  28292. ret = GetASNInt(sig, &idx, &len, sigLen);
  28293. if (ret != 0)
  28294. return ret;
  28295. if (sLen)
  28296. *sLen = (word32)len;
  28297. if (s)
  28298. XMEMCPY(s, (byte*)sig + idx, (size_t)len);
  28299. #ifndef NO_STRICT_ECDSA_LEN
  28300. /* sanity check that the index has been advanced all the way to the end of
  28301. * the buffer */
  28302. if (idx + (word32)len != sigLen) {
  28303. ret = ASN_ECC_KEY_E;
  28304. }
  28305. #endif
  28306. return ret;
  28307. #else
  28308. ASNGetData dataASN[dsaSigASN_Length];
  28309. word32 idx = 0;
  28310. /* Clear dynamic data and set buffers to put r and s into. */
  28311. XMEMSET(dataASN, 0, sizeof(dataASN));
  28312. GetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
  28313. GetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
  28314. /* Decode the DSA signature. */
  28315. return GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 1, sig, &idx,
  28316. sigLen);
  28317. #endif /* WOLFSSL_ASN_TEMPLATE */
  28318. }
  28319. int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
  28320. {
  28321. return DecodeECC_DSA_Sig_Ex(sig, sigLen, r, s, 1);
  28322. }
  28323. int DecodeECC_DSA_Sig_Ex(const byte* sig, word32 sigLen, mp_int* r, mp_int* s,
  28324. int init)
  28325. {
  28326. #ifndef WOLFSSL_ASN_TEMPLATE
  28327. word32 idx = 0;
  28328. int len = 0;
  28329. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  28330. return ASN_ECC_KEY_E;
  28331. }
  28332. #ifndef NO_STRICT_ECDSA_LEN
  28333. /* enable strict length checking for signature */
  28334. if (sigLen != idx + (word32)len) {
  28335. return ASN_ECC_KEY_E;
  28336. }
  28337. #else
  28338. /* allow extra signature bytes at end */
  28339. if ((word32)len > (sigLen - idx)) {
  28340. return ASN_ECC_KEY_E;
  28341. }
  28342. #endif
  28343. if (GetIntPositive(r, sig, &idx, sigLen, init) < 0) {
  28344. return ASN_ECC_KEY_E;
  28345. }
  28346. if (GetIntPositive(s, sig, &idx, sigLen, init) < 0) {
  28347. mp_clear(r);
  28348. return ASN_ECC_KEY_E;
  28349. }
  28350. #ifndef NO_STRICT_ECDSA_LEN
  28351. /* sanity check that the index has been advanced all the way to the end of
  28352. * the buffer */
  28353. if (idx != sigLen) {
  28354. mp_clear(r);
  28355. mp_clear(s);
  28356. return ASN_ECC_KEY_E;
  28357. }
  28358. #endif
  28359. return 0;
  28360. #else
  28361. ASNGetData dataASN[dsaSigASN_Length];
  28362. word32 idx = 0;
  28363. int ret;
  28364. /* Clear dynamic data and set mp_ints to put r and s into. */
  28365. XMEMSET(dataASN, 0, sizeof(dataASN));
  28366. if (init) {
  28367. GetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
  28368. GetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
  28369. }
  28370. else {
  28371. GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_R], r);
  28372. GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_S], s);
  28373. }
  28374. /* Decode the DSA signature. */
  28375. ret = GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 0, sig, &idx,
  28376. sigLen);
  28377. #ifndef NO_STRICT_ECDSA_LEN
  28378. /* sanity check that the index has been advanced all the way to the end of
  28379. * the buffer */
  28380. if ((ret == 0) && (idx != sigLen)) {
  28381. ret = ASN_ECC_KEY_E;
  28382. }
  28383. #endif
  28384. if (ret != 0) {
  28385. mp_clear(r);
  28386. mp_clear(s);
  28387. }
  28388. return ret;
  28389. #endif /* WOLFSSL_ASN_TEMPLATE */
  28390. }
  28391. #endif
  28392. #ifdef WOLFSSL_ASN_TEMPLATE
  28393. #ifdef WOLFSSL_CUSTOM_CURVES
  28394. /* Convert data to hex string.
  28395. *
  28396. * Big-endian byte array is converted to big-endian hexadecimal string.
  28397. *
  28398. * @param [in] input Buffer containing data.
  28399. * @param [in] inSz Size of data in buffer.
  28400. * @param [out] out Buffer to hold hex string.
  28401. */
  28402. static void DataToHexString(const byte* input, word32 inSz, char* out)
  28403. {
  28404. static const char hexChar[] = { '0', '1', '2', '3', '4', '5', '6', '7',
  28405. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  28406. word32 i;
  28407. /* Converting a byte of data at a time to two hex characters. */
  28408. for (i = 0; i < inSz; i++) {
  28409. out[i*2 + 0] = hexChar[input[i] >> 4];
  28410. out[i*2 + 1] = hexChar[input[i] & 0xf];
  28411. }
  28412. /* NUL terminate string. */
  28413. out[i * 2] = '\0';
  28414. }
  28415. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28416. /* Convert data to hex string and place in allocated buffer.
  28417. *
  28418. * Big-endian byte array is converted to big-endian hexadecimal string.
  28419. *
  28420. * @param [in] input Buffer containing data.
  28421. * @param [in] inSz Size of data in buffer.
  28422. * @param [out] out Allocated buffer holding hex string.
  28423. * @param [in] heap Dynamic memory allocation hint.
  28424. * @param [in] heapType Type of heap to use.
  28425. * @return 0 on success.
  28426. * @return MEMORY_E when dynamic memory allocation fails.
  28427. */
  28428. static int DataToHexStringAlloc(const byte* input, word32 inSz, char** out,
  28429. void* heap, int heapType)
  28430. {
  28431. int ret = 0;
  28432. char* str;
  28433. /* Allocate for 2 string characters ber byte plus NUL. */
  28434. str = (char*)XMALLOC(inSz * 2 + 1, heap, heapType);
  28435. if (str == NULL) {
  28436. ret = MEMORY_E;
  28437. }
  28438. else {
  28439. /* Convert to hex string. */
  28440. DataToHexString(input, inSz, str);
  28441. *out = str;
  28442. }
  28443. (void)heap;
  28444. (void)heapType;
  28445. return ret;
  28446. }
  28447. #endif /* WOLFSSL_ECC_CURVE_STATIC */
  28448. /* ASN.1 template for SpecifiedECDomain.
  28449. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  28450. * NOTE: characteristic-two-field not supported. */
  28451. static const ASNItem eccSpecifiedASN[] = {
  28452. /* version */
  28453. /* VER */ { 0, ASN_INTEGER, 0, 0, 0 },
  28454. /* fieldID */
  28455. /* PRIME_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28456. /* prime-field or characteristic-two-field */
  28457. /* PRIME_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  28458. /* Prime-p */
  28459. /* PRIME_P */ { 1, ASN_INTEGER, 0, 0, 0 },
  28460. /* fieldID */
  28461. /* PARAM_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28462. /* a */
  28463. /* PARAM_A */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28464. /* b */
  28465. /* PARAM_B */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28466. /* seed */
  28467. /* PARAM_SEED */ { 1, ASN_BIT_STRING, 0, 0, 1 },
  28468. /* base */
  28469. /* BASE */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  28470. /* order */
  28471. /* ORDER */ { 0, ASN_INTEGER, 0, 0, 0 },
  28472. /* cofactor */
  28473. /* COFACTOR */ { 0, ASN_INTEGER, 0, 0, 1 },
  28474. /* hash */
  28475. /* HASH_SEQ */ { 0, ASN_SEQUENCE, 0, 0, 1 },
  28476. };
  28477. enum {
  28478. ECCSPECIFIEDASN_IDX_VER = 0,
  28479. ECCSPECIFIEDASN_IDX_PRIME_SEQ,
  28480. ECCSPECIFIEDASN_IDX_PRIME_OID,
  28481. ECCSPECIFIEDASN_IDX_PRIME_P,
  28482. ECCSPECIFIEDASN_IDX_PARAM_SEQ,
  28483. ECCSPECIFIEDASN_IDX_PARAM_A,
  28484. ECCSPECIFIEDASN_IDX_PARAM_B,
  28485. ECCSPECIFIEDASN_IDX_PARAM_SEED,
  28486. ECCSPECIFIEDASN_IDX_BASE,
  28487. ECCSPECIFIEDASN_IDX_ORDER,
  28488. ECCSPECIFIEDASN_IDX_COFACTOR,
  28489. ECCSPECIFIEDASN_IDX_HASH_SEQ
  28490. };
  28491. /* Number of items in ASN.1 template for SpecifiedECDomain. */
  28492. #define eccSpecifiedASN_Length (sizeof(eccSpecifiedASN) / sizeof(ASNItem))
  28493. /* OID indicating the prime field is explicitly defined. */
  28494. static const byte primeFieldOID[] = {
  28495. 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01
  28496. };
  28497. static const char ecSetCustomName[] = "Custom";
  28498. /* Explicit EC parameter values. */
  28499. static int EccSpecifiedECDomainDecode(const byte* input, word32 inSz,
  28500. ecc_key* key)
  28501. {
  28502. DECL_ASNGETDATA(dataASN, eccSpecifiedASN_Length);
  28503. int ret = 0;
  28504. ecc_set_type* curve;
  28505. word32 idx = 0;
  28506. byte version;
  28507. byte cofactor;
  28508. const byte *base;
  28509. word32 baseLen;
  28510. /* Allocate a new parameter set. */
  28511. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  28512. DYNAMIC_TYPE_ECC_BUFFER);
  28513. if (curve == NULL) {
  28514. ret = MEMORY_E;
  28515. }
  28516. else {
  28517. /* Clear out parameters and set fields to indicate it is custom. */
  28518. XMEMSET(curve, 0, sizeof(*curve));
  28519. }
  28520. CALLOC_ASNGETDATA(dataASN, eccSpecifiedASN_Length, ret, key->heap);
  28521. if (ret == 0) {
  28522. /* Set name to be: "Custom" */
  28523. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28524. curve->name = ecSetCustomName;
  28525. #else
  28526. XMEMCPY((void*)curve->name, ecSetCustomName, sizeof(ecSetCustomName));
  28527. #endif
  28528. curve->id = ECC_CURVE_CUSTOM;
  28529. /* Get version, must have prime field OID and get co-factor. */
  28530. GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_VER], &version);
  28531. GetASN_ExpBuffer(&dataASN[ECCSPECIFIEDASN_IDX_PRIME_OID],
  28532. primeFieldOID, sizeof(primeFieldOID));
  28533. GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_COFACTOR], &cofactor);
  28534. /* Decode the explicit parameters. */
  28535. ret = GetASN_Items(eccSpecifiedASN, dataASN, eccSpecifiedASN_Length, 1,
  28536. input, &idx, inSz);
  28537. }
  28538. /* Version must be 1 or 2 for supporting explicit parameters. */
  28539. if ((ret == 0) && (version < 1 || version > 3)) {
  28540. ret = ASN_PARSE_E;
  28541. }
  28542. #ifndef WOLFSSL_NO_ASN_STRICT
  28543. /* Only version 2 and above can have a seed. */
  28544. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_PARAM_SEED].tag != 0) &&
  28545. (version < 2)) {
  28546. ret = ASN_PARSE_E;
  28547. }
  28548. #endif
  28549. /* Only version 2 and above can have a hash algorithm. */
  28550. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_HASH_SEQ].tag != 0) &&
  28551. (version < 2)) {
  28552. ret = ASN_PARSE_E;
  28553. }
  28554. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_COFACTOR].tag != 0)) {
  28555. /* Store optional co-factor. */
  28556. curve->cofactor = cofactor;
  28557. }
  28558. if (ret == 0) {
  28559. /* Length of the prime in bytes is the curve size. */
  28560. curve->size =
  28561. (int)dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length;
  28562. /* Base point: 0x04 <x> <y> (must be uncompressed). */
  28563. GetASN_GetConstRef(&dataASN[ECCSPECIFIEDASN_IDX_BASE], &base,
  28564. &baseLen);
  28565. if ((baseLen < (word32)curve->size * 2 + 1) || (base[0] != 0x4)) {
  28566. ret = ASN_PARSE_E;
  28567. }
  28568. }
  28569. /* Put the curve parameters into the set.
  28570. * Convert the big-endian number byte array to a big-endian string.
  28571. */
  28572. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28573. /* Allocate buffer to put hex strings into. */
  28574. if (ret == 0) {
  28575. /* Base X-ordinate */
  28576. ret = DataToHexStringAlloc(base + 1, (word32)curve->size,
  28577. (char**)&curve->Gx, key->heap,
  28578. DYNAMIC_TYPE_ECC_BUFFER);
  28579. }
  28580. if (ret == 0) {
  28581. /* Base Y-ordinate */
  28582. ret = DataToHexStringAlloc(base + 1 + curve->size, (word32)curve->size,
  28583. (char**)&curve->Gy, key->heap,
  28584. DYNAMIC_TYPE_ECC_BUFFER);
  28585. }
  28586. if (ret == 0) {
  28587. /* Prime */
  28588. ret = DataToHexStringAlloc(
  28589. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
  28590. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
  28591. (char**)&curve->prime, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28592. }
  28593. if (ret == 0) {
  28594. /* Parameter A */
  28595. ret = DataToHexStringAlloc(
  28596. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
  28597. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
  28598. (char**)&curve->Af, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28599. }
  28600. if (ret == 0) {
  28601. /* Parameter B */
  28602. ret = DataToHexStringAlloc(
  28603. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
  28604. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
  28605. (char**)&curve->Bf, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28606. }
  28607. if (ret == 0) {
  28608. /* Order of curve */
  28609. ret = DataToHexStringAlloc(
  28610. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
  28611. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
  28612. (char**)&curve->order, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28613. }
  28614. #else
  28615. if (ret == 0) {
  28616. /* Base X-ordinate */
  28617. DataToHexString(base + 1, curve->size, curve->Gx);
  28618. /* Base Y-ordinate */
  28619. DataToHexString(base + 1 + curve->size, curve->size, curve->Gy);
  28620. /* Prime */
  28621. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
  28622. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
  28623. curve->prime);
  28624. /* Parameter A */
  28625. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
  28626. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
  28627. curve->Af);
  28628. /* Parameter B */
  28629. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
  28630. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
  28631. curve->Bf);
  28632. /* Order of curve */
  28633. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
  28634. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
  28635. curve->order);
  28636. }
  28637. #endif /* WOLFSSL_ECC_CURVE_STATIC */
  28638. /* Store parameter set in key. */
  28639. if ((ret == 0) && (wc_ecc_set_custom_curve(key, curve) < 0)) {
  28640. ret = ASN_PARSE_E;
  28641. }
  28642. if (ret == 0) {
  28643. /* The parameter set was allocated.. */
  28644. key->deallocSet = 1;
  28645. }
  28646. if ((ret != 0) && (curve != NULL)) {
  28647. /* Failed to set parameters so free parameter set. */
  28648. wc_ecc_free_curve(curve, key->heap);
  28649. }
  28650. FREE_ASNGETDATA(dataASN, key->heap);
  28651. return ret;
  28652. }
  28653. #endif /* WOLFSSL_CUSTOM_CURVES */
  28654. #endif /* WOLFSSL_ASN_TEMPLATE */
  28655. #ifdef HAVE_ECC
  28656. #ifdef WOLFSSL_ASN_TEMPLATE
  28657. /* ASN.1 template for ECC private key.
  28658. * SEC.1 Ver 2.0, C.4 - Syntax for Elliptic Curve Private Keys
  28659. */
  28660. static const ASNItem eccKeyASN[] = {
  28661. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28662. /* version */
  28663. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  28664. /* privateKey */
  28665. /* PKEY */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28666. /* parameters */
  28667. /* PARAMS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PARAMS, 1, 1, 1 },
  28668. /* named */
  28669. /* CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  28670. /* specified */
  28671. /* CURVEPARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  28672. /* publicKey */
  28673. /* PUBKEY */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PUBKEY, 1, 1, 1 },
  28674. /* Uncompressed point - X9.62. */
  28675. /* PUBKEY_VAL, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  28676. };
  28677. enum {
  28678. ECCKEYASN_IDX_SEQ = 0,
  28679. ECCKEYASN_IDX_VER,
  28680. ECCKEYASN_IDX_PKEY,
  28681. ECCKEYASN_IDX_PARAMS,
  28682. ECCKEYASN_IDX_CURVEID,
  28683. ECCKEYASN_IDX_CURVEPARAMS,
  28684. ECCKEYASN_IDX_PUBKEY,
  28685. ECCKEYASN_IDX_PUBKEY_VAL
  28686. };
  28687. /* Number of items in ASN.1 template for ECC private key. */
  28688. #define eccKeyASN_Length (sizeof(eccKeyASN) / sizeof(ASNItem))
  28689. #endif
  28690. WOLFSSL_ABI
  28691. int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
  28692. word32 inSz)
  28693. {
  28694. #ifndef WOLFSSL_ASN_TEMPLATE
  28695. word32 oidSum;
  28696. int version, length;
  28697. int privSz, pubSz = 0;
  28698. byte b;
  28699. int ret = 0;
  28700. int curve_id = ECC_CURVE_DEF;
  28701. #ifdef WOLFSSL_SMALL_STACK
  28702. byte* priv;
  28703. byte* pub = NULL;
  28704. #else
  28705. byte priv[ECC_MAXSIZE+1];
  28706. byte pub[2*(ECC_MAXSIZE+1)]; /* public key has two parts plus header */
  28707. #endif
  28708. word32 algId = 0;
  28709. byte* pubData = NULL;
  28710. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  28711. return BAD_FUNC_ARG;
  28712. /* if has pkcs8 header skip it */
  28713. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  28714. /* ignore error, did not have pkcs8 header */
  28715. }
  28716. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28717. return ASN_PARSE_E;
  28718. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  28719. return ASN_PARSE_E;
  28720. if (*inOutIdx >= inSz)
  28721. return ASN_PARSE_E;
  28722. b = input[*inOutIdx];
  28723. *inOutIdx += 1;
  28724. /* priv type */
  28725. if (b != 4 && b != 6 && b != 7)
  28726. return ASN_PARSE_E;
  28727. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  28728. return ASN_PARSE_E;
  28729. privSz = length;
  28730. if (privSz > ECC_MAXSIZE)
  28731. return BUFFER_E;
  28732. #ifdef WOLFSSL_SMALL_STACK
  28733. priv = (byte*)XMALLOC(privSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28734. if (priv == NULL)
  28735. return MEMORY_E;
  28736. #endif
  28737. /* priv key */
  28738. XMEMCPY(priv, &input[*inOutIdx], (size_t)privSz);
  28739. *inOutIdx += (word32)length;
  28740. if ((*inOutIdx + 1) < inSz) {
  28741. /* prefix 0, may have */
  28742. b = input[*inOutIdx];
  28743. if (b == ECC_PREFIX_0) {
  28744. *inOutIdx += 1;
  28745. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  28746. ret = ASN_PARSE_E;
  28747. else {
  28748. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType,
  28749. inSz);
  28750. if (ret == 0) {
  28751. if ((ret = CheckCurve(oidSum)) < 0)
  28752. ret = ECC_CURVE_OID_E;
  28753. else {
  28754. curve_id = ret;
  28755. ret = 0;
  28756. }
  28757. }
  28758. }
  28759. }
  28760. }
  28761. if (ret == 0 && (*inOutIdx + 1) < inSz) {
  28762. /* prefix 1 */
  28763. b = input[*inOutIdx];
  28764. *inOutIdx += 1;
  28765. if (b != ECC_PREFIX_1) {
  28766. ret = ASN_ECC_KEY_E;
  28767. }
  28768. else if (GetLength(input, inOutIdx, &length, inSz) <= 0) {
  28769. ret = ASN_PARSE_E;
  28770. }
  28771. else {
  28772. /* key header */
  28773. ret = CheckBitString(input, inOutIdx, &length, inSz, 0, NULL);
  28774. if (ret == 0) {
  28775. /* pub key */
  28776. pubSz = length;
  28777. if (pubSz > 2*(ECC_MAXSIZE+1))
  28778. ret = BUFFER_E;
  28779. else {
  28780. #ifdef WOLFSSL_SMALL_STACK
  28781. pub = (byte*)XMALLOC(pubSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28782. if (pub == NULL)
  28783. ret = MEMORY_E;
  28784. else
  28785. #endif
  28786. {
  28787. XMEMCPY(pub, &input[*inOutIdx], (size_t)pubSz);
  28788. *inOutIdx += (word32)length;
  28789. pubData = pub;
  28790. }
  28791. }
  28792. }
  28793. }
  28794. }
  28795. if (ret == 0) {
  28796. ret = wc_ecc_import_private_key_ex(priv, (word32)privSz, pubData,
  28797. (word32)pubSz, key, curve_id);
  28798. }
  28799. #ifdef WOLFSSL_SMALL_STACK
  28800. XFREE(priv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28801. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28802. #endif
  28803. return ret;
  28804. #else
  28805. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  28806. byte version;
  28807. int ret = 0;
  28808. int curve_id = ECC_CURVE_DEF;
  28809. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  28810. word32 algId = 0;
  28811. #endif
  28812. /* Validate parameters. */
  28813. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  28814. ret = BAD_FUNC_ARG;
  28815. }
  28816. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  28817. /* if has pkcs8 header skip it */
  28818. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  28819. /* ignore error, did not have pkcs8 header */
  28820. }
  28821. #endif
  28822. CALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  28823. if (ret == 0) {
  28824. /* Get the version and set the expected OID type. */
  28825. GetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], &version);
  28826. GetASN_OID(&dataASN[ECCKEYASN_IDX_CURVEID], oidCurveType);
  28827. /* Decode the private ECC key. */
  28828. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  28829. inOutIdx, inSz);
  28830. }
  28831. /* Only version 1 supported. */
  28832. if ((ret == 0) && (version != 1)) {
  28833. ret = ASN_PARSE_E;
  28834. }
  28835. /* Curve Parameters are optional. */
  28836. if ((ret == 0) && (dataASN[ECCKEYASN_IDX_PARAMS].tag != 0)) {
  28837. if (dataASN[ECCKEYASN_IDX_CURVEID].tag != 0) {
  28838. /* Named curve - check and get id. */
  28839. curve_id = CheckCurve(dataASN[ECCKEYASN_IDX_CURVEID].data.oid.sum);
  28840. if (curve_id < 0) {
  28841. ret = ECC_CURVE_OID_E;
  28842. }
  28843. }
  28844. else {
  28845. #ifdef WOLFSSL_CUSTOM_CURVES
  28846. /* Parse explicit parameters. */
  28847. ret = EccSpecifiedECDomainDecode(
  28848. dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.data,
  28849. dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.length, key);
  28850. #else
  28851. /* Explicit parameters not supported in build configuration. */
  28852. ret = ASN_PARSE_E;
  28853. #endif
  28854. }
  28855. }
  28856. if (ret == 0) {
  28857. /* Import private key value and public point (may be NULL). */
  28858. ret = wc_ecc_import_private_key_ex(
  28859. dataASN[ECCKEYASN_IDX_PKEY].data.ref.data,
  28860. dataASN[ECCKEYASN_IDX_PKEY].data.ref.length,
  28861. dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.data,
  28862. dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.length,
  28863. key, curve_id);
  28864. }
  28865. FREE_ASNGETDATA(dataASN, key->heap);
  28866. return ret;
  28867. #endif
  28868. }
  28869. #ifdef WOLFSSL_CUSTOM_CURVES
  28870. #ifndef WOLFSSL_ASN_TEMPLATE
  28871. /* returns 0 on success */
  28872. static int ASNToHexString(const byte* input, word32* inOutIdx, char** out,
  28873. word32 inSz, void* heap, int heapType)
  28874. {
  28875. int len;
  28876. int i;
  28877. char* str;
  28878. word32 localIdx;
  28879. byte tag;
  28880. if (*inOutIdx >= inSz) {
  28881. return BUFFER_E;
  28882. }
  28883. localIdx = *inOutIdx;
  28884. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 && tag == ASN_INTEGER) {
  28885. if (GetASNInt(input, inOutIdx, &len, inSz) < 0)
  28886. return ASN_PARSE_E;
  28887. }
  28888. else {
  28889. if (GetOctetString(input, inOutIdx, &len, inSz) < 0)
  28890. return ASN_PARSE_E;
  28891. }
  28892. str = (char*)XMALLOC((size_t)len * 2 + 1, heap, heapType);
  28893. if (str == NULL) {
  28894. return MEMORY_E;
  28895. }
  28896. for (i=0; i<len; i++)
  28897. ByteToHexStr(input[*inOutIdx + (word32)i], str + i*2);
  28898. str[len*2] = '\0';
  28899. *inOutIdx += (word32)len;
  28900. *out = str;
  28901. (void)heap;
  28902. (void)heapType;
  28903. return 0;
  28904. }
  28905. static int EccKeyParamCopy(char** dst, char* src)
  28906. {
  28907. int ret = 0;
  28908. #ifdef WOLFSSL_ECC_CURVE_STATIC
  28909. word32 length;
  28910. #endif
  28911. if (dst == NULL || src == NULL)
  28912. return BAD_FUNC_ARG;
  28913. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28914. *dst = src;
  28915. #else
  28916. length = (int)XSTRLEN(src) + 1;
  28917. if (length > MAX_ECC_STRING) {
  28918. WOLFSSL_MSG("ECC Param too large for buffer");
  28919. ret = BUFFER_E;
  28920. }
  28921. else {
  28922. XSTRNCPY(*dst, src, MAX_ECC_STRING);
  28923. }
  28924. XFREE(src, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28925. #endif
  28926. return ret;
  28927. }
  28928. #endif /* !WOLFSSL_ASN_TEMPLATE */
  28929. #endif /* WOLFSSL_CUSTOM_CURVES */
  28930. WOLFSSL_ABI
  28931. int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx,
  28932. ecc_key* key, word32 inSz)
  28933. {
  28934. #ifndef WOLFSSL_ASN_TEMPLATE
  28935. int ret;
  28936. int version, length;
  28937. int curve_id = ECC_CURVE_DEF;
  28938. word32 oidSum, localIdx;
  28939. byte tag, isPrivFormat = 0;
  28940. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  28941. return BAD_FUNC_ARG;
  28942. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28943. return ASN_PARSE_E;
  28944. /* Check if ECC private key is being used and skip private portion */
  28945. if (GetMyVersion(input, inOutIdx, &version, inSz) >= 0) {
  28946. isPrivFormat = 1;
  28947. /* Type private key */
  28948. if (*inOutIdx >= inSz)
  28949. return ASN_PARSE_E;
  28950. tag = input[*inOutIdx];
  28951. *inOutIdx += 1;
  28952. if (tag != 4 && tag != 6 && tag != 7)
  28953. return ASN_PARSE_E;
  28954. /* Skip Private Key */
  28955. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  28956. return ASN_PARSE_E;
  28957. if (length > ECC_MAXSIZE)
  28958. return BUFFER_E;
  28959. *inOutIdx += (word32)length;
  28960. /* Private Curve Header */
  28961. if (*inOutIdx >= inSz)
  28962. return ASN_PARSE_E;
  28963. tag = input[*inOutIdx];
  28964. *inOutIdx += 1;
  28965. if (tag != ECC_PREFIX_0)
  28966. return ASN_ECC_KEY_E;
  28967. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  28968. return ASN_PARSE_E;
  28969. }
  28970. /* Standard ECC public key */
  28971. else {
  28972. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28973. return ASN_PARSE_E;
  28974. ret = SkipObjectId(input, inOutIdx, inSz);
  28975. if (ret != 0)
  28976. return ret;
  28977. }
  28978. if (*inOutIdx >= inSz) {
  28979. return BUFFER_E;
  28980. }
  28981. localIdx = *inOutIdx;
  28982. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 &&
  28983. tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  28984. #ifdef WOLFSSL_CUSTOM_CURVES
  28985. ecc_set_type* curve;
  28986. int len;
  28987. char* point = NULL;
  28988. ret = 0;
  28989. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  28990. DYNAMIC_TYPE_ECC_BUFFER);
  28991. if (curve == NULL)
  28992. ret = MEMORY_E;
  28993. if (ret == 0) {
  28994. static const char customName[] = "Custom";
  28995. XMEMSET(curve, 0, sizeof(*curve));
  28996. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28997. curve->name = customName;
  28998. #else
  28999. XMEMCPY((void*)curve->name, customName, sizeof(customName));
  29000. #endif
  29001. curve->id = ECC_CURVE_CUSTOM;
  29002. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29003. ret = ASN_PARSE_E;
  29004. }
  29005. if (ret == 0) {
  29006. GetInteger7Bit(input, inOutIdx, inSz);
  29007. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29008. ret = ASN_PARSE_E;
  29009. }
  29010. if (ret == 0) {
  29011. char* p = NULL;
  29012. SkipObjectId(input, inOutIdx, inSz);
  29013. ret = ASNToHexString(input, inOutIdx, &p, inSz,
  29014. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29015. if (ret == 0) {
  29016. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29017. ret = EccKeyParamCopy((char**)&curve->prime, p);
  29018. #else
  29019. const char *_tmp_ptr = &curve->prime[0];
  29020. ret = EccKeyParamCopy((char**)&_tmp_ptr, p);
  29021. #endif
  29022. }
  29023. }
  29024. if (ret == 0) {
  29025. curve->size = (int)XSTRLEN(curve->prime) / 2;
  29026. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29027. ret = ASN_PARSE_E;
  29028. }
  29029. if (ret == 0) {
  29030. char* af = NULL;
  29031. ret = ASNToHexString(input, inOutIdx, &af, inSz,
  29032. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29033. if (ret == 0) {
  29034. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29035. ret = EccKeyParamCopy((char**)&curve->Af, af);
  29036. #else
  29037. const char *_tmp_ptr = &curve->Af[0];
  29038. ret = EccKeyParamCopy((char**)&_tmp_ptr, af);
  29039. #endif
  29040. }
  29041. }
  29042. if (ret == 0) {
  29043. char* bf = NULL;
  29044. ret = ASNToHexString(input, inOutIdx, &bf, inSz,
  29045. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29046. if (ret == 0) {
  29047. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29048. ret = EccKeyParamCopy((char**)&curve->Bf, bf);
  29049. #else
  29050. const char *_tmp_ptr = &curve->Bf[0];
  29051. ret = EccKeyParamCopy((char**)&_tmp_ptr, bf);
  29052. #endif
  29053. }
  29054. }
  29055. if (ret == 0) {
  29056. localIdx = *inOutIdx;
  29057. if (*inOutIdx < inSz && GetASNTag(input, &localIdx, &tag, inSz)
  29058. == 0 && tag == ASN_BIT_STRING) {
  29059. len = 0;
  29060. ret = GetASNHeader(input, ASN_BIT_STRING, inOutIdx, &len, inSz);
  29061. if (ret > 0)
  29062. ret = 0; /* reset on success */
  29063. *inOutIdx += (word32)len;
  29064. }
  29065. }
  29066. if (ret == 0) {
  29067. ret = ASNToHexString(input, inOutIdx, (char**)&point, inSz,
  29068. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29069. /* sanity check that point buffer is not smaller than the expected
  29070. * size to hold ( 0 4 || Gx || Gy )
  29071. * where Gx and Gy are each the size of curve->size * 2 */
  29072. if (ret == 0 && (int)XSTRLEN(point) < (curve->size * 4) + 2) {
  29073. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29074. ret = BUFFER_E;
  29075. }
  29076. }
  29077. if (ret == 0) {
  29078. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29079. curve->Gx = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
  29080. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29081. curve->Gy = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
  29082. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29083. if (curve->Gx == NULL || curve->Gy == NULL) {
  29084. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29085. ret = MEMORY_E;
  29086. }
  29087. #else
  29088. if (curve->size * 2 + 2 > MAX_ECC_STRING) {
  29089. WOLFSSL_MSG("curve size is too large to fit in buffer");
  29090. ret = BUFFER_E;
  29091. }
  29092. #endif
  29093. }
  29094. if (ret == 0) {
  29095. char* o = NULL;
  29096. XMEMCPY((char*)curve->Gx, point + 2, (size_t)curve->size * 2);
  29097. XMEMCPY((char*)curve->Gy, point + curve->size * 2 + 2,
  29098. (size_t)curve->size * 2);
  29099. ((char*)curve->Gx)[curve->size * 2] = '\0';
  29100. ((char*)curve->Gy)[curve->size * 2] = '\0';
  29101. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29102. ret = ASNToHexString(input, inOutIdx, &o, inSz,
  29103. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29104. if (ret == 0) {
  29105. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29106. ret = EccKeyParamCopy((char**)&curve->order, o);
  29107. #else
  29108. const char *_tmp_ptr = &curve->order[0];
  29109. ret = EccKeyParamCopy((char**)&_tmp_ptr, o);
  29110. #endif
  29111. }
  29112. }
  29113. if (ret == 0) {
  29114. curve->cofactor = GetInteger7Bit(input, inOutIdx, inSz);
  29115. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29116. curve->oid = NULL;
  29117. #else
  29118. XMEMSET((void*)curve->oid, 0, sizeof(curve->oid));
  29119. #endif
  29120. curve->oidSz = 0;
  29121. curve->oidSum = 0;
  29122. if (wc_ecc_set_custom_curve(key, curve) < 0) {
  29123. ret = ASN_PARSE_E;
  29124. }
  29125. key->deallocSet = 1;
  29126. curve = NULL;
  29127. }
  29128. if (curve != NULL)
  29129. wc_ecc_free_curve(curve, key->heap);
  29130. if (ret < 0)
  29131. return ret;
  29132. #else
  29133. return ASN_PARSE_E;
  29134. #endif /* WOLFSSL_CUSTOM_CURVES */
  29135. }
  29136. else {
  29137. /* ecc params information */
  29138. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType, inSz);
  29139. if (ret != 0)
  29140. return ret;
  29141. /* get curve id */
  29142. if ((ret = CheckCurve(oidSum)) < 0)
  29143. return ECC_CURVE_OID_E;
  29144. else {
  29145. curve_id = ret;
  29146. }
  29147. }
  29148. if (isPrivFormat) {
  29149. /* Public Curve Header - skip */
  29150. if (*inOutIdx >= inSz)
  29151. return ASN_PARSE_E;
  29152. tag = input[*inOutIdx];
  29153. *inOutIdx += 1;
  29154. if (tag != ECC_PREFIX_1)
  29155. return ASN_ECC_KEY_E;
  29156. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  29157. return ASN_PARSE_E;
  29158. }
  29159. /* key header */
  29160. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  29161. if (ret != 0)
  29162. return ret;
  29163. /* This is the raw point data compressed or uncompressed. */
  29164. if (wc_ecc_import_x963_ex(input + *inOutIdx, (word32)length, key,
  29165. curve_id) != 0) {
  29166. return ASN_ECC_KEY_E;
  29167. }
  29168. *inOutIdx += (word32)length;
  29169. return 0;
  29170. #else
  29171. /* eccKeyASN is longer than eccPublicKeyASN. */
  29172. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  29173. int ret = 0;
  29174. int curve_id = ECC_CURVE_DEF;
  29175. int oidIdx = ECCPUBLICKEYASN_IDX_ALGOID_CURVEID;
  29176. #ifdef WOLFSSL_CUSTOM_CURVES
  29177. int specIdx = ECCPUBLICKEYASN_IDX_ALGOID_PARAMS;
  29178. #endif
  29179. int pubIdx = ECCPUBLICKEYASN_IDX_PUBKEY;
  29180. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  29181. ret = BAD_FUNC_ARG;
  29182. }
  29183. ALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  29184. if (ret == 0) {
  29185. /* Clear dynamic data for ECC public key. */
  29186. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccPublicKeyASN_Length);
  29187. /* Set required ECDSA OID and ignore the curve OID type. */
  29188. GetASN_ExpBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], keyEcdsaOid,
  29189. sizeof(keyEcdsaOid));
  29190. GetASN_OID(&dataASN[oidIdx], oidIgnoreType);
  29191. /* Decode the public ECC key. */
  29192. ret = GetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length, 1,
  29193. input, inOutIdx, inSz);
  29194. if (ret != 0) {
  29195. oidIdx = ECCKEYASN_IDX_CURVEID;
  29196. #ifdef WOLFSSL_CUSTOM_CURVES
  29197. specIdx = ECCKEYASN_IDX_CURVEPARAMS;
  29198. #endif
  29199. pubIdx = ECCKEYASN_IDX_PUBKEY_VAL;
  29200. /* Clear dynamic data for ECC private key. */
  29201. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccKeyASN_Length);
  29202. /* Check named curve OID type. */
  29203. GetASN_OID(&dataASN[oidIdx], oidIgnoreType);
  29204. /* Try private key format .*/
  29205. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  29206. inOutIdx, inSz);
  29207. if (ret != 0) {
  29208. ret = ASN_PARSE_E;
  29209. }
  29210. }
  29211. }
  29212. if (ret == 0) {
  29213. if (dataASN[oidIdx].tag != 0) {
  29214. /* Named curve - check and get id. */
  29215. curve_id = CheckCurve(dataASN[oidIdx].data.oid.sum);
  29216. if (curve_id < 0) {
  29217. ret = ASN_OBJECT_ID_E;
  29218. }
  29219. }
  29220. else {
  29221. #ifdef WOLFSSL_CUSTOM_CURVES
  29222. /* Parse explicit parameters. */
  29223. ret = EccSpecifiedECDomainDecode(dataASN[specIdx].data.ref.data,
  29224. dataASN[specIdx].data.ref.length, key);
  29225. #else
  29226. /* Explicit parameters not supported in build configuration. */
  29227. ret = ASN_PARSE_E;
  29228. #endif
  29229. }
  29230. }
  29231. if (ret == 0) {
  29232. /* Import public point. */
  29233. ret = wc_ecc_import_x963_ex(dataASN[pubIdx].data.ref.data,
  29234. dataASN[pubIdx].data.ref.length, key, curve_id);
  29235. if (ret != 0) {
  29236. ret = ASN_ECC_KEY_E;
  29237. }
  29238. }
  29239. FREE_ASNGETDATA(dataASN, key->heap);
  29240. return ret;
  29241. #endif /* WOLFSSL_ASN_TEMPLATE */
  29242. }
  29243. #if defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  29244. /* build DER formatted ECC key, include optional public key if requested,
  29245. * return length on success, negative on error */
  29246. static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen,
  29247. int pubIn, int curveIn)
  29248. {
  29249. #ifndef WOLFSSL_ASN_TEMPLATE
  29250. byte curve[MAX_ALGO_SZ+2];
  29251. byte ver[MAX_VERSION_SZ];
  29252. byte seq[MAX_SEQ_SZ];
  29253. int ret, curveSz, verSz;
  29254. word32 totalSz;
  29255. int privHdrSz = ASN_ECC_HEADER_SZ;
  29256. int pubHdrSz = ASN_ECC_CONTEXT_SZ + ASN_ECC_HEADER_SZ;
  29257. #ifdef WOLFSSL_NO_MALLOC
  29258. byte prv[MAX_ECC_BYTES + ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  29259. byte pub[(MAX_ECC_BYTES * 2) + 1 + ASN_ECC_CONTEXT_SZ +
  29260. ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  29261. #else
  29262. byte *prv = NULL, *pub = NULL;
  29263. #endif
  29264. word32 idx = 0, prvidx = 0, pubidx = 0, curveidx = 0;
  29265. word32 seqSz, privSz, pubSz = ECC_BUFSIZE;
  29266. if (key == NULL || (output == NULL && inLen == NULL))
  29267. return BAD_FUNC_ARG;
  29268. if (curveIn) {
  29269. /* curve */
  29270. curve[curveidx++] = ECC_PREFIX_0;
  29271. curveidx++ /* to put the size after computation */;
  29272. curveSz = SetCurve(key, curve+curveidx, MAX_ALGO_SZ);
  29273. if (curveSz < 0)
  29274. return curveSz;
  29275. /* set computed size */
  29276. curve[1] = (byte)curveSz;
  29277. curveidx += (word32)curveSz;
  29278. }
  29279. /* private */
  29280. privSz = (word32)key->dp->size;
  29281. #ifdef WOLFSSL_QNX_CAAM
  29282. /* check if is a black key, and add MAC size if needed */
  29283. if (key->blackKey > 0 && key->blackKey != CAAM_BLACK_KEY_ECB) {
  29284. privSz = privSz + WC_CAAM_MAC_SZ;
  29285. }
  29286. #endif
  29287. #ifndef WOLFSSL_NO_MALLOC
  29288. prv = (byte*)XMALLOC(privSz + (word32)privHdrSz + MAX_SEQ_SZ,
  29289. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29290. if (prv == NULL) {
  29291. return MEMORY_E;
  29292. }
  29293. #else
  29294. if (sizeof(prv) < privSz + privHdrSz + MAX_SEQ_SZ) {
  29295. return BUFFER_E;
  29296. }
  29297. #endif
  29298. if (privSz < ASN_LONG_LENGTH) {
  29299. prvidx += SetOctetString8Bit(privSz, &prv[prvidx]);
  29300. }
  29301. else {
  29302. prvidx += SetOctetString(privSz, &prv[prvidx]);
  29303. }
  29304. ret = wc_ecc_export_private_only(key, prv + prvidx, &privSz);
  29305. if (ret < 0) {
  29306. #ifndef WOLFSSL_NO_MALLOC
  29307. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29308. #endif
  29309. return ret;
  29310. }
  29311. prvidx += privSz;
  29312. /* pubIn */
  29313. if (pubIn) {
  29314. PRIVATE_KEY_UNLOCK();
  29315. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  29316. PRIVATE_KEY_LOCK();
  29317. if (ret != LENGTH_ONLY_E) {
  29318. #ifndef WOLFSSL_NO_MALLOC
  29319. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29320. #endif
  29321. return ret;
  29322. }
  29323. #ifndef WOLFSSL_NO_MALLOC
  29324. pub = (byte*)XMALLOC(pubSz + (word32)pubHdrSz + MAX_SEQ_SZ,
  29325. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29326. if (pub == NULL) {
  29327. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29328. return MEMORY_E;
  29329. }
  29330. #else
  29331. if (sizeof(pub) < pubSz + pubHdrSz + MAX_SEQ_SZ) {
  29332. return BUFFER_E;
  29333. }
  29334. #endif
  29335. pub[pubidx++] = ECC_PREFIX_1;
  29336. if (pubSz > 128) /* leading zero + extra size byte */
  29337. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 2, pub+pubidx);
  29338. else /* leading zero */
  29339. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 1, pub+pubidx);
  29340. /* SetBitString adds leading zero */
  29341. pubidx += SetBitString(pubSz, 0, pub + pubidx);
  29342. PRIVATE_KEY_UNLOCK();
  29343. ret = wc_ecc_export_x963(key, pub + pubidx, &pubSz);
  29344. PRIVATE_KEY_LOCK();
  29345. if (ret != 0) {
  29346. #ifndef WOLFSSL_NO_MALLOC
  29347. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29348. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29349. #endif
  29350. return ret;
  29351. }
  29352. pubidx += pubSz;
  29353. }
  29354. /* make headers */
  29355. verSz = SetMyVersion(1, ver, FALSE);
  29356. seqSz = SetSequence((word32)verSz + prvidx + pubidx + curveidx, seq);
  29357. totalSz = prvidx + pubidx + curveidx + (word32)verSz + seqSz;
  29358. if (output == NULL) {
  29359. *inLen = totalSz;
  29360. #ifndef WOLFSSL_NO_MALLOC
  29361. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29362. if (pubIn) {
  29363. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29364. }
  29365. #endif
  29366. return LENGTH_ONLY_E;
  29367. }
  29368. if (inLen != NULL && totalSz > *inLen) {
  29369. #ifndef WOLFSSL_NO_MALLOC
  29370. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29371. if (pubIn) {
  29372. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29373. }
  29374. #endif
  29375. return BAD_FUNC_ARG;
  29376. }
  29377. /* write out */
  29378. /* seq */
  29379. XMEMCPY(output + idx, seq, seqSz);
  29380. idx = seqSz;
  29381. /* ver */
  29382. XMEMCPY(output + idx, ver, (size_t)verSz);
  29383. idx += (word32)verSz;
  29384. /* private */
  29385. XMEMCPY(output + idx, prv, prvidx);
  29386. idx += prvidx;
  29387. #ifndef WOLFSSL_NO_MALLOC
  29388. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29389. #endif
  29390. /* curve */
  29391. XMEMCPY(output + idx, curve, curveidx);
  29392. idx += curveidx;
  29393. /* pubIn */
  29394. if (pubIn) {
  29395. XMEMCPY(output + idx, pub, pubidx);
  29396. /* idx += pubidx; not used after write, if more data remove comment */
  29397. #ifndef WOLFSSL_NO_MALLOC
  29398. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29399. #endif
  29400. }
  29401. return (int)totalSz;
  29402. #else
  29403. DECL_ASNSETDATA(dataASN, eccKeyASN_Length);
  29404. word32 privSz, pubSz;
  29405. int sz = 0;
  29406. int ret = 0;
  29407. int curveIdSz = 0;
  29408. /* Check validity of parameters. */
  29409. if ((key == NULL) || ((output == NULL) && (inLen == NULL))) {
  29410. ret = BAD_FUNC_ARG;
  29411. }
  29412. /* Check key has parameters when encoding curve. */
  29413. if ((ret == 0) && curveIn && (key->dp == NULL)) {
  29414. ret = BAD_FUNC_ARG;
  29415. }
  29416. CALLOC_ASNSETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  29417. if (ret == 0) {
  29418. /* Private key size is the curve size. */
  29419. privSz = (word32)key->dp->size;
  29420. if (pubIn) {
  29421. /* Get the length of the public key. */
  29422. PRIVATE_KEY_UNLOCK();
  29423. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  29424. PRIVATE_KEY_LOCK();
  29425. if (ret == LENGTH_ONLY_E)
  29426. ret = 0;
  29427. }
  29428. }
  29429. if (ret == 0) {
  29430. /* Version: 1 */
  29431. SetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], 1);
  29432. /* Leave space for private key. */
  29433. SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PKEY], NULL, privSz);
  29434. if (curveIn) {
  29435. /* Get length of the named curve OID to put into the encoding. */
  29436. curveIdSz = SetCurve(key, NULL, 0);
  29437. if (curveIdSz < 0) {
  29438. ret = curveIdSz;
  29439. }
  29440. /* Curve OID */
  29441. SetASN_ReplaceBuffer(&dataASN[ECCKEYASN_IDX_CURVEID], NULL,
  29442. (word32)curveIdSz);
  29443. /* TODO: add support for SpecifiedECDomain curve. */
  29444. dataASN[ECCKEYASN_IDX_CURVEPARAMS].noOut = 1;
  29445. }
  29446. else {
  29447. SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PARAMS,
  29448. eccKeyASN_Length);
  29449. }
  29450. if (ret == 0) {
  29451. if (pubIn) {
  29452. /* Leave space for public key. */
  29453. SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PUBKEY_VAL], NULL, pubSz);
  29454. }
  29455. else {
  29456. /* Don't write out public key. */
  29457. SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PUBKEY,
  29458. eccKeyASN_Length);
  29459. }
  29460. /* Calculate size of the private key encoding. */
  29461. ret = SizeASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, &sz);
  29462. }
  29463. }
  29464. /* Return the size if no buffer. */
  29465. if ((ret == 0) && (output == NULL)) {
  29466. *inLen = (word32)sz;
  29467. ret = LENGTH_ONLY_E;
  29468. }
  29469. /* Check the buffer is big enough. */
  29470. if ((ret == 0) && (inLen != NULL) && (sz > (int)*inLen)) {
  29471. ret = BAD_FUNC_ARG;
  29472. }
  29473. if ((ret == 0) && (output != NULL)) {
  29474. /* Encode the private key. */
  29475. SetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, output);
  29476. if (curveIn) {
  29477. /* Put named curve OID data into encoding. */
  29478. curveIdSz = SetCurve(key,
  29479. (byte*)dataASN[ECCKEYASN_IDX_CURVEID].data.buffer.data,
  29480. (size_t)curveIdSz);
  29481. if (curveIdSz < 0) {
  29482. ret = curveIdSz;
  29483. }
  29484. }
  29485. if (ret == 0) {
  29486. /* Export the private value into the buffer. */
  29487. ret = wc_ecc_export_private_only(key,
  29488. (byte*)dataASN[ECCKEYASN_IDX_PKEY].data.buffer.data, &privSz);
  29489. }
  29490. if ((ret == 0) && pubIn) {
  29491. /* Export the public point into the buffer. */
  29492. PRIVATE_KEY_UNLOCK();
  29493. ret = wc_ecc_export_x963(key,
  29494. (byte*)dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.buffer.data,
  29495. &pubSz);
  29496. PRIVATE_KEY_LOCK();
  29497. }
  29498. }
  29499. if (ret == 0) {
  29500. /* Return the encoding size. */
  29501. ret = sz;
  29502. }
  29503. FREE_ASNSETDATA(dataASN, key->heap);
  29504. return ret;
  29505. #endif
  29506. }
  29507. /* Write a Private ecc key, including public to DER format,
  29508. * length on success else < 0 */
  29509. WOLFSSL_ABI
  29510. int wc_EccKeyToDer(ecc_key* key, byte* output, word32 inLen)
  29511. {
  29512. return wc_BuildEccKeyDer(key, output, &inLen, 1, 1);
  29513. }
  29514. /* Write only private ecc key to DER format,
  29515. * length on success else < 0 */
  29516. int wc_EccKeyDerSize(ecc_key* key, int pub)
  29517. {
  29518. word32 sz = 0;
  29519. int ret;
  29520. ret = wc_BuildEccKeyDer(key, NULL, &sz, pub, 1);
  29521. if (ret != LENGTH_ONLY_E) {
  29522. return ret;
  29523. }
  29524. return (int)sz;
  29525. }
  29526. /* Write only private ecc key to DER format,
  29527. * length on success else < 0 */
  29528. int wc_EccPrivateKeyToDer(ecc_key* key, byte* output, word32 inLen)
  29529. {
  29530. return wc_BuildEccKeyDer(key, output, &inLen, 0, 1);
  29531. }
  29532. #ifdef HAVE_PKCS8
  29533. /* Write only private ecc key or both private and public parts to unencrypted
  29534. * PKCS#8 format.
  29535. *
  29536. * If output is NULL, places required PKCS#8 buffer size in outLen and
  29537. * returns LENGTH_ONLY_E.
  29538. *
  29539. * return length on success else < 0 */
  29540. static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen,
  29541. int includePublic)
  29542. {
  29543. int ret;
  29544. word32 tmpDerSz;
  29545. int algoID = 0;
  29546. word32 oidSz = 0;
  29547. word32 pkcs8Sz = 0;
  29548. const byte* curveOID = NULL;
  29549. #ifdef WOLFSSL_NO_MALLOC
  29550. byte tmpDer[ECC_BUFSIZE];
  29551. #else
  29552. byte* tmpDer = NULL;
  29553. #endif
  29554. word32 sz = ECC_BUFSIZE;
  29555. if (key == NULL || key->dp == NULL || outLen == NULL)
  29556. return BAD_FUNC_ARG;
  29557. /* set algoID, get curve OID */
  29558. algoID = ECDSAk;
  29559. ret = wc_ecc_get_oid(key->dp->oidSum, &curveOID, &oidSz);
  29560. if (ret < 0)
  29561. return ret;
  29562. #ifndef WOLFSSL_NO_MALLOC
  29563. /* temp buffer for plain DER key */
  29564. tmpDer = (byte*)XMALLOC(ECC_BUFSIZE, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29565. if (tmpDer == NULL)
  29566. return MEMORY_E;
  29567. #endif
  29568. XMEMSET(tmpDer, 0, ECC_BUFSIZE);
  29569. ret = wc_BuildEccKeyDer(key, tmpDer, &sz, includePublic, 0);
  29570. if (ret < 0) {
  29571. #ifndef WOLFSSL_NO_MALLOC
  29572. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29573. #endif
  29574. return ret;
  29575. }
  29576. tmpDerSz = (word32)ret;
  29577. /* get pkcs8 expected output size */
  29578. ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, tmpDer, tmpDerSz, algoID,
  29579. curveOID, oidSz);
  29580. if (ret != LENGTH_ONLY_E) {
  29581. #ifndef WOLFSSL_NO_MALLOC
  29582. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29583. #endif
  29584. return ret;
  29585. }
  29586. if (output == NULL) {
  29587. #ifndef WOLFSSL_NO_MALLOC
  29588. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29589. #endif
  29590. *outLen = pkcs8Sz;
  29591. return LENGTH_ONLY_E;
  29592. }
  29593. else if (*outLen < pkcs8Sz) {
  29594. #ifndef WOLFSSL_NO_MALLOC
  29595. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29596. #endif
  29597. WOLFSSL_MSG("Input buffer too small for ECC PKCS#8 key");
  29598. return BUFFER_E;
  29599. }
  29600. ret = wc_CreatePKCS8Key(output, &pkcs8Sz, tmpDer, tmpDerSz,
  29601. algoID, curveOID, oidSz);
  29602. if (ret < 0) {
  29603. #ifndef WOLFSSL_NO_MALLOC
  29604. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29605. #endif
  29606. return ret;
  29607. }
  29608. #ifndef WOLFSSL_NO_MALLOC
  29609. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29610. #endif
  29611. *outLen = (word32)ret;
  29612. return ret;
  29613. }
  29614. /* Write only private ecc key to unencrypted PKCS#8 format.
  29615. *
  29616. * return length on success else < 0 */
  29617. int wc_EccPrivateKeyToPKCS8(ecc_key* key, byte* output, word32* outLen)
  29618. {
  29619. return eccToPKCS8(key, output, outLen, 0);
  29620. }
  29621. /* Write both private and public ecc keys to unencrypted PKCS#8 format.
  29622. *
  29623. * return length on success else < 0 */
  29624. int wc_EccKeyToPKCS8(ecc_key* key, byte* output,
  29625. word32* outLen)
  29626. {
  29627. return eccToPKCS8(key, output, outLen, 1);
  29628. }
  29629. #endif /* HAVE_PKCS8 */
  29630. #endif /* HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  29631. #endif /* HAVE_ECC */
  29632. #ifdef WC_ENABLE_ASYM_KEY_IMPORT
  29633. #ifdef WOLFSSL_ASN_TEMPLATE
  29634. /* ASN.1 template for Ed25519 and Ed448 private key.
  29635. * RFC 8410, 7 - Private Key Format (but public value is EXPLICIT OCTET_STRING)
  29636. */
  29637. static const ASNItem edKeyASN[] = {
  29638. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  29639. /* Version */
  29640. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  29641. /* privateKeyAlgorithm */
  29642. /* PKEYALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  29643. /* PKEYALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  29644. /* privateKey */
  29645. /* PKEY */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  29646. /* CurvePrivateKey */
  29647. /* PKEY_CURVEPKEY */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  29648. /* attributes */
  29649. /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_ATTRS, 1, 1, 1 },
  29650. /* publicKey */
  29651. /* PUBKEY */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY, 0, 0, 1 },
  29652. };
  29653. enum {
  29654. EDKEYASN_IDX_SEQ = 0,
  29655. EDKEYASN_IDX_VER,
  29656. EDKEYASN_IDX_PKEYALGO_SEQ,
  29657. EDKEYASN_IDX_PKEYALGO_OID,
  29658. EDKEYASN_IDX_PKEY,
  29659. EDKEYASN_IDX_PKEY_CURVEPKEY,
  29660. EDKEYASN_IDX_ATTRS,
  29661. EDKEYASN_IDX_PUBKEY
  29662. };
  29663. /* Number of items in ASN.1 template for Ed25519 and Ed448 private key. */
  29664. #define edKeyASN_Length (sizeof(edKeyASN) / sizeof(ASNItem))
  29665. #endif
  29666. #if ((defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)) \
  29667. || (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)) \
  29668. || (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)) \
  29669. || (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)) \
  29670. || (defined(HAVE_PQC) && defined(HAVE_FALCON)) \
  29671. || (defined(HAVE_PQC) && defined(HAVE_DILITHIUM)) \
  29672. || (defined(HAVE_PQC) && defined(HAVE_SPHINCS)))
  29673. int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz,
  29674. byte* privKey, word32* privKeyLen,
  29675. byte* pubKey, word32* pubKeyLen, int keyType)
  29676. {
  29677. #ifndef WOLFSSL_ASN_TEMPLATE
  29678. word32 oid;
  29679. int version, length, endKeyIdx, privSz, pubSz;
  29680. const byte* priv;
  29681. const byte* pub;
  29682. #else
  29683. int ret = 0;
  29684. DECL_ASNGETDATA(dataASN, edKeyASN_Length);
  29685. CALLOC_ASNGETDATA(dataASN, edKeyASN_Length, ret, NULL);
  29686. #endif
  29687. if (input == NULL || inOutIdx == NULL || inSz == 0 ||
  29688. privKey == NULL || privKeyLen == NULL) {
  29689. return BAD_FUNC_ARG;
  29690. }
  29691. #ifndef WOLFSSL_ASN_TEMPLATE
  29692. if (GetSequence(input, inOutIdx, &length, inSz) >= 0) {
  29693. endKeyIdx = (int)*inOutIdx + length;
  29694. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  29695. return ASN_PARSE_E;
  29696. if (version != 0) {
  29697. WOLFSSL_MSG("Unrecognized version of ED25519 private key");
  29698. return ASN_PARSE_E;
  29699. }
  29700. if (GetAlgoId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  29701. return ASN_PARSE_E;
  29702. if (oid != (word32)keyType)
  29703. return ASN_PARSE_E;
  29704. if (GetOctetString(input, inOutIdx, &length, inSz) < 0)
  29705. return ASN_PARSE_E;
  29706. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  29707. return ASN_PARSE_E;
  29708. priv = input + *inOutIdx;
  29709. *inOutIdx += (word32)privSz;
  29710. }
  29711. else {
  29712. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  29713. return ASN_PARSE_E;
  29714. priv = input + *inOutIdx;
  29715. *inOutIdx += (word32)privSz;
  29716. endKeyIdx = (int)*inOutIdx;
  29717. }
  29718. if ((word32)privSz > *privKeyLen)
  29719. return BUFFER_E;
  29720. if (endKeyIdx == (int)*inOutIdx) {
  29721. *privKeyLen = (word32)privSz;
  29722. XMEMCPY(privKey, priv, *privKeyLen);
  29723. if (pubKeyLen != NULL)
  29724. *pubKeyLen = 0;
  29725. }
  29726. else {
  29727. if (pubKeyLen == NULL) {
  29728. return BAD_FUNC_ARG;
  29729. }
  29730. if (GetASNHeader(input, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY | 1,
  29731. inOutIdx, &pubSz, inSz) < 0) {
  29732. return ASN_PARSE_E;
  29733. }
  29734. if ((word32)pubSz > *pubKeyLen)
  29735. return BUFFER_E;
  29736. pub = input + *inOutIdx;
  29737. *inOutIdx += (word32)pubSz;
  29738. *privKeyLen = (word32)privSz;
  29739. XMEMCPY(privKey, priv, *privKeyLen);
  29740. *pubKeyLen = (word32)pubSz;
  29741. if (pubKey != NULL)
  29742. XMEMCPY(pubKey, pub, *pubKeyLen);
  29743. }
  29744. if (endKeyIdx != (int)*inOutIdx)
  29745. return ASN_PARSE_E;
  29746. return 0;
  29747. #else
  29748. if (ret == 0) {
  29749. /* Require OID. */
  29750. word32 oidSz;
  29751. const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz);
  29752. GetASN_ExpBuffer(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], oid, oidSz);
  29753. /* Parse full private key. */
  29754. ret = GetASN_Items(edKeyASN, dataASN, edKeyASN_Length, 1, input,
  29755. inOutIdx, inSz);
  29756. if (ret != 0) {
  29757. /* Parse just the OCTET_STRING. */
  29758. ret = GetASN_Items(&edKeyASN[EDKEYASN_IDX_PKEY_CURVEPKEY],
  29759. &dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], 1, 0, input,
  29760. inOutIdx, inSz);
  29761. if (ret != 0) {
  29762. ret = ASN_PARSE_E;
  29763. }
  29764. }
  29765. }
  29766. /* Check the private value length is correct. */
  29767. if ((ret == 0) && dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length
  29768. > *privKeyLen) {
  29769. ret = ASN_PARSE_E;
  29770. }
  29771. if ((ret == 0) && dataASN[EDKEYASN_IDX_PUBKEY].tag == 0) {
  29772. *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
  29773. XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
  29774. *privKeyLen);
  29775. if (pubKeyLen != NULL)
  29776. *pubKeyLen = 0;
  29777. }
  29778. else if ((ret == 0) &&
  29779. (pubKeyLen != NULL) &&
  29780. (dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
  29781. ret = ASN_PARSE_E;
  29782. }
  29783. else if (ret == 0) {
  29784. /* Import private and public value. */
  29785. *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
  29786. XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
  29787. *privKeyLen);
  29788. if (pubKeyLen != NULL)
  29789. *pubKeyLen = dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length;
  29790. if (pubKey != NULL && pubKeyLen != NULL)
  29791. XMEMCPY(pubKey, dataASN[EDKEYASN_IDX_PUBKEY].data.ref.data,
  29792. *pubKeyLen);
  29793. }
  29794. FREE_ASNGETDATA(dataASN, NULL);
  29795. return ret;
  29796. #endif /* WOLFSSL_ASN_TEMPLATE */
  29797. }
  29798. int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz,
  29799. byte* pubKey, word32* pubKeyLen, int keyType)
  29800. {
  29801. int ret = 0;
  29802. #ifndef WOLFSSL_ASN_TEMPLATE
  29803. int length;
  29804. word32 oid;
  29805. #else
  29806. word32 len;
  29807. DECL_ASNGETDATA(dataASN, edPubKeyASN_Length);
  29808. #endif
  29809. if (input == NULL || inSz == 0 || inOutIdx == NULL ||
  29810. pubKey == NULL || pubKeyLen == NULL) {
  29811. return BAD_FUNC_ARG;
  29812. }
  29813. #ifndef WOLFSSL_ASN_TEMPLATE
  29814. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29815. return ASN_PARSE_E;
  29816. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29817. return ASN_PARSE_E;
  29818. if (GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  29819. return ASN_PARSE_E;
  29820. if (oid != (word32)keyType)
  29821. return ASN_PARSE_E;
  29822. /* key header */
  29823. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  29824. if (ret != 0)
  29825. return ret;
  29826. /* check that the value found is not too large for pubKey buffer */
  29827. if ((word32)length > *pubKeyLen)
  29828. return ASN_PARSE_E;
  29829. /* check that input buffer is exhausted */
  29830. if (*inOutIdx + (word32)length != inSz)
  29831. return ASN_PARSE_E;
  29832. /* This is the raw point data compressed or uncompressed. */
  29833. *pubKeyLen = (word32)length;
  29834. XMEMCPY(pubKey, input + *inOutIdx, *pubKeyLen);
  29835. #else
  29836. len = inSz - *inOutIdx;
  29837. CALLOC_ASNGETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
  29838. if (ret == 0) {
  29839. /* Require OID. */
  29840. word32 oidSz;
  29841. const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz);
  29842. GetASN_ExpBuffer(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], oid, oidSz);
  29843. /* Decode Ed25519 private key. */
  29844. ret = GetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, 1, input,
  29845. inOutIdx, inSz);
  29846. if (ret != 0)
  29847. ret = ASN_PARSE_E;
  29848. /* check that input buffer is exhausted */
  29849. if (*inOutIdx != inSz)
  29850. ret = ASN_PARSE_E;
  29851. }
  29852. /* Check the public value length is correct. */
  29853. if ((ret == 0) &&
  29854. (dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
  29855. ret = ASN_PARSE_E;
  29856. }
  29857. /* Check that the all the buffer was used. */
  29858. if ((ret == 0) &&
  29859. (GetASNItem_Length(dataASN[EDPUBKEYASN_IDX_SEQ], input) != len)) {
  29860. ret = ASN_PARSE_E;
  29861. }
  29862. if (ret == 0) {
  29863. *pubKeyLen = dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length;
  29864. XMEMCPY(pubKey, dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.data,
  29865. *pubKeyLen);
  29866. }
  29867. FREE_ASNGETDATA(dataASN, NULL);
  29868. #endif /* WOLFSSL_ASN_TEMPLATE */
  29869. return ret;
  29870. }
  29871. #endif
  29872. #endif /* WC_ENABLE_ASYM_KEY_IMPORT */
  29873. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  29874. int wc_Ed25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  29875. ed25519_key* key, word32 inSz)
  29876. {
  29877. int ret;
  29878. byte privKey[ED25519_KEY_SIZE], pubKey[ED25519_PUB_KEY_SIZE];
  29879. word32 privKeyLen = (word32)sizeof(privKey);
  29880. word32 pubKeyLen = (word32)sizeof(pubKey);
  29881. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  29882. return BAD_FUNC_ARG;
  29883. }
  29884. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  29885. pubKey, &pubKeyLen, ED25519k);
  29886. if (ret == 0) {
  29887. if (pubKeyLen == 0) {
  29888. ret = wc_ed25519_import_private_only(privKey, privKeyLen, key);
  29889. }
  29890. else {
  29891. ret = wc_ed25519_import_private_key(privKey, privKeyLen,
  29892. pubKey, pubKeyLen, key);
  29893. }
  29894. }
  29895. return ret;
  29896. }
  29897. int wc_Ed25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  29898. ed25519_key* key, word32 inSz)
  29899. {
  29900. int ret;
  29901. byte pubKey[ED25519_PUB_KEY_SIZE];
  29902. word32 pubKeyLen = (word32)sizeof(pubKey);
  29903. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  29904. return BAD_FUNC_ARG;
  29905. }
  29906. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  29907. pubKey, &pubKeyLen, ED25519k);
  29908. if (ret == 0) {
  29909. ret = wc_ed25519_import_public(pubKey, pubKeyLen, key);
  29910. }
  29911. return ret;
  29912. }
  29913. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */
  29914. #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)
  29915. int wc_Curve25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  29916. curve25519_key* key, word32 inSz)
  29917. {
  29918. int ret;
  29919. byte privKey[CURVE25519_KEYSIZE];
  29920. word32 privKeyLen = CURVE25519_KEYSIZE;
  29921. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  29922. return BAD_FUNC_ARG;
  29923. }
  29924. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  29925. NULL, NULL, X25519k);
  29926. if (ret == 0) {
  29927. ret = wc_curve25519_import_private(privKey, privKeyLen, key);
  29928. }
  29929. return ret;
  29930. }
  29931. int wc_Curve25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  29932. curve25519_key* key, word32 inSz)
  29933. {
  29934. int ret;
  29935. byte pubKey[CURVE25519_KEYSIZE];
  29936. word32 pubKeyLen = (word32)sizeof(pubKey);
  29937. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  29938. return BAD_FUNC_ARG;
  29939. }
  29940. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  29941. pubKey, &pubKeyLen, X25519k);
  29942. if (ret == 0) {
  29943. ret = wc_curve25519_import_public(pubKey, pubKeyLen, key);
  29944. }
  29945. return ret;
  29946. }
  29947. #endif /* HAVE_CURVE25519 && HAVE_ED25519_KEY_IMPORT */
  29948. #ifdef WC_ENABLE_ASYM_KEY_EXPORT
  29949. /* Build ASN.1 formatted key based on RFC 5958 (Asymmetric Key Packages)
  29950. *
  29951. * Pass NULL for output to get the size of the encoding.
  29952. *
  29953. * @param [in] privKey private key buffer
  29954. * @param [in] privKeyLen private key buffer length
  29955. * @param [in] pubKey public key buffer (optional)
  29956. * @param [in] pubKeyLen public key buffer length
  29957. * @param [out] output Buffer to put encoded data in (optional)
  29958. * @param [in] outLen Size of buffer in bytes
  29959. * @param [in] keyType is "enum Key_Sum" like ED25519k
  29960. * @return Size of encoded data in bytes on success
  29961. * @return BAD_FUNC_ARG when key is NULL.
  29962. * @return MEMORY_E when dynamic memory allocation failed.
  29963. */
  29964. int SetAsymKeyDer(const byte* privKey, word32 privKeyLen,
  29965. const byte* pubKey, word32 pubKeyLen,
  29966. byte* output, word32 outLen, int keyType)
  29967. {
  29968. int ret = 0;
  29969. #ifndef WOLFSSL_ASN_TEMPLATE
  29970. word32 idx = 0, seqSz, verSz, algoSz, privSz, pubSz = 0, sz;
  29971. #else
  29972. DECL_ASNSETDATA(dataASN, edKeyASN_Length);
  29973. int sz;
  29974. #endif
  29975. /* Validate parameters. */
  29976. if (privKey == NULL || outLen == 0) {
  29977. return BAD_FUNC_ARG;
  29978. }
  29979. #ifndef WOLFSSL_ASN_TEMPLATE
  29980. /* calculate size */
  29981. if (pubKey) {
  29982. pubSz = 2 + pubKeyLen;
  29983. }
  29984. privSz = 2 + 2 + privKeyLen;
  29985. algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
  29986. verSz = 3; /* version is 3 bytes (enum + id + version(byte)) */
  29987. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, NULL);
  29988. sz = seqSz + verSz + algoSz + privSz + pubSz;
  29989. /* checkout output size */
  29990. if (output != NULL && sz > outLen) {
  29991. ret = BAD_FUNC_ARG;
  29992. }
  29993. if (ret == 0 && output != NULL) {
  29994. /* write out */
  29995. /* seq */
  29996. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, output);
  29997. idx = seqSz;
  29998. /* ver */
  29999. SetMyVersion(0, output + idx, FALSE);
  30000. idx += verSz;
  30001. /* algo */
  30002. algoSz = SetAlgoID(keyType, output + idx, oidKeyType, 0);
  30003. idx += algoSz;
  30004. /* privKey */
  30005. idx += SetOctetString(2 + privKeyLen, output + idx);
  30006. idx += SetOctetString(privKeyLen, output + idx);
  30007. XMEMCPY(output + idx, privKey, privKeyLen);
  30008. idx += privKeyLen;
  30009. /* pubKey */
  30010. if (pubKey) {
  30011. idx += SetHeader(ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY |
  30012. 1, pubKeyLen, output + idx);
  30013. XMEMCPY(output + idx, pubKey, pubKeyLen);
  30014. idx += pubKeyLen;
  30015. }
  30016. sz = idx;
  30017. }
  30018. if (ret == 0) {
  30019. /* Return size of encoding. */
  30020. ret = (int)sz;
  30021. }
  30022. #else
  30023. CALLOC_ASNSETDATA(dataASN, edKeyASN_Length, ret, NULL);
  30024. if (ret == 0) {
  30025. /* Set version = 0 */
  30026. SetASN_Int8Bit(&dataASN[EDKEYASN_IDX_VER], 0);
  30027. /* Set OID. */
  30028. SetASN_OID(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], (word32)keyType,
  30029. oidKeyType);
  30030. /* Leave space for private key. */
  30031. SetASN_Buffer(&dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], NULL, privKeyLen);
  30032. /* Don't write out attributes. */
  30033. dataASN[EDKEYASN_IDX_ATTRS].noOut = 1;
  30034. if (pubKey) {
  30035. /* Leave space for public key. */
  30036. SetASN_Buffer(&dataASN[EDKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
  30037. }
  30038. else {
  30039. /* Don't put out public part. */
  30040. SetASNItem_NoOutNode(dataASN, edKeyASN, EDKEYASN_IDX_PUBKEY,
  30041. edKeyASN_Length);
  30042. }
  30043. /* Calculate the size of encoding. */
  30044. ret = SizeASN_Items(edKeyASN, dataASN, edKeyASN_Length, &sz);
  30045. }
  30046. /* Check buffer is big enough. */
  30047. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  30048. ret = BAD_FUNC_ARG;
  30049. }
  30050. if ((ret == 0) && (output != NULL)) {
  30051. /* Encode private key. */
  30052. SetASN_Items(edKeyASN, dataASN, edKeyASN_Length, output);
  30053. /* Put private value into space provided. */
  30054. XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.buffer.data,
  30055. privKey, privKeyLen);
  30056. if (pubKey != NULL) {
  30057. /* Put public value into space provided. */
  30058. XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PUBKEY].data.buffer.data,
  30059. pubKey, pubKeyLen);
  30060. }
  30061. }
  30062. if (ret == 0) {
  30063. /* Return size of encoding. */
  30064. ret = sz;
  30065. }
  30066. FREE_ASNSETDATA(dataASN, NULL);
  30067. #endif
  30068. return ret;
  30069. }
  30070. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  30071. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  30072. /* Write a Private ED25519 key, including public to DER format,
  30073. * length on success else < 0 */
  30074. int wc_Ed25519KeyToDer(ed25519_key* key, byte* output, word32 inLen)
  30075. {
  30076. if (key == NULL) {
  30077. return BAD_FUNC_ARG;
  30078. }
  30079. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  30080. key->p, ED25519_PUB_KEY_SIZE, output, inLen, ED25519k);
  30081. }
  30082. /* Write only private ED25519 key to DER format,
  30083. * length on success else < 0 */
  30084. int wc_Ed25519PrivateKeyToDer(ed25519_key* key, byte* output, word32 inLen)
  30085. {
  30086. if (key == NULL) {
  30087. return BAD_FUNC_ARG;
  30088. }
  30089. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  30090. NULL, 0, output, inLen, ED25519k);
  30091. }
  30092. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  30093. #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_EXPORT)
  30094. /* Write only private Curve25519 key to DER format,
  30095. * length on success else < 0 */
  30096. int wc_Curve25519PrivateKeyToDer(curve25519_key* key, byte* output, word32 inLen)
  30097. {
  30098. int ret;
  30099. byte privKey[CURVE25519_KEYSIZE];
  30100. word32 privKeyLen = CURVE25519_KEYSIZE;
  30101. if (key == NULL) {
  30102. return BAD_FUNC_ARG;
  30103. }
  30104. ret = wc_curve25519_export_private_raw(key, privKey, &privKeyLen);
  30105. if (ret == 0) {
  30106. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  30107. X25519k);
  30108. }
  30109. return ret;
  30110. }
  30111. /* Write a public Curve25519 key to DER format,
  30112. * length on success else < 0 */
  30113. int wc_Curve25519PublicKeyToDer(curve25519_key* key, byte* output, word32 inLen,
  30114. int withAlg)
  30115. {
  30116. int ret;
  30117. byte pubKey[CURVE25519_PUB_KEY_SIZE];
  30118. word32 pubKeyLen = (word32)sizeof(pubKey);
  30119. if (key == NULL || output == NULL) {
  30120. return BAD_FUNC_ARG;
  30121. }
  30122. ret = wc_curve25519_export_public(key, pubKey, &pubKeyLen);
  30123. if (ret == 0) {
  30124. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  30125. X25519k, withAlg);
  30126. }
  30127. return ret;
  30128. }
  30129. #endif /* HAVE_CURVE25519 && HAVE_CURVE25519_KEY_EXPORT */
  30130. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  30131. int wc_Ed448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30132. ed448_key* key, word32 inSz)
  30133. {
  30134. int ret;
  30135. byte privKey[ED448_KEY_SIZE], pubKey[ED448_PUB_KEY_SIZE];
  30136. word32 privKeyLen = (word32)sizeof(privKey);
  30137. word32 pubKeyLen = (word32)sizeof(pubKey);
  30138. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30139. return BAD_FUNC_ARG;
  30140. }
  30141. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30142. pubKey, &pubKeyLen, ED448k);
  30143. if (ret == 0) {
  30144. if (pubKeyLen == 0) {
  30145. ret = wc_ed448_import_private_only(privKey, privKeyLen, key);
  30146. }
  30147. else {
  30148. ret = wc_ed448_import_private_key(privKey, privKeyLen,
  30149. pubKey, pubKeyLen, key);
  30150. }
  30151. }
  30152. return ret;
  30153. }
  30154. int wc_Ed448PublicKeyDecode(const byte* input, word32* inOutIdx,
  30155. ed448_key* key, word32 inSz)
  30156. {
  30157. int ret;
  30158. byte pubKey[ED448_PUB_KEY_SIZE];
  30159. word32 pubKeyLen = (word32)sizeof(pubKey);
  30160. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30161. return BAD_FUNC_ARG;
  30162. }
  30163. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30164. pubKey, &pubKeyLen, ED448k);
  30165. if (ret == 0) {
  30166. ret = wc_ed448_import_public(pubKey, pubKeyLen, key);
  30167. }
  30168. return ret;
  30169. }
  30170. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */
  30171. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)
  30172. int wc_Curve448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30173. curve448_key* key, word32 inSz)
  30174. {
  30175. int ret;
  30176. byte privKey[CURVE448_KEY_SIZE];
  30177. word32 privKeyLen = CURVE448_KEY_SIZE;
  30178. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30179. return BAD_FUNC_ARG;
  30180. }
  30181. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30182. NULL, NULL, X448k);
  30183. if (ret == 0) {
  30184. ret = wc_curve448_import_private(privKey, privKeyLen, key);
  30185. }
  30186. return ret;
  30187. }
  30188. int wc_Curve448PublicKeyDecode(const byte* input, word32* inOutIdx,
  30189. curve448_key* key, word32 inSz)
  30190. {
  30191. int ret;
  30192. byte pubKey[CURVE448_PUB_KEY_SIZE];
  30193. word32 pubKeyLen = (word32)sizeof(pubKey);
  30194. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30195. return BAD_FUNC_ARG;
  30196. }
  30197. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30198. pubKey, &pubKeyLen, X448k);
  30199. if (ret == 0) {
  30200. ret = wc_curve448_import_public(pubKey, pubKeyLen, key);
  30201. }
  30202. return ret;
  30203. }
  30204. #endif /* HAVE_CURVE448 && HAVE_ED448_KEY_IMPORT */
  30205. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  30206. /* Write a Private ecc key, including public to DER format,
  30207. * length on success else < 0 */
  30208. int wc_Ed448KeyToDer(ed448_key* key, byte* output, word32 inLen)
  30209. {
  30210. if (key == NULL) {
  30211. return BAD_FUNC_ARG;
  30212. }
  30213. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  30214. key->p, ED448_KEY_SIZE, output, inLen, ED448k);
  30215. }
  30216. /* Write only private ecc key to DER format,
  30217. * length on success else < 0 */
  30218. int wc_Ed448PrivateKeyToDer(ed448_key* key, byte* output, word32 inLen)
  30219. {
  30220. if (key == NULL) {
  30221. return BAD_FUNC_ARG;
  30222. }
  30223. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  30224. NULL, 0, output, inLen, ED448k);
  30225. }
  30226. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  30227. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_EXPORT)
  30228. /* Write private Curve448 key to DER format,
  30229. * length on success else < 0 */
  30230. int wc_Curve448PrivateKeyToDer(curve448_key* key, byte* output, word32 inLen)
  30231. {
  30232. int ret;
  30233. byte privKey[CURVE448_KEY_SIZE];
  30234. word32 privKeyLen = CURVE448_KEY_SIZE;
  30235. if (key == NULL) {
  30236. return BAD_FUNC_ARG;
  30237. }
  30238. ret = wc_curve448_export_private_raw(key, privKey, &privKeyLen);
  30239. if (ret == 0) {
  30240. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  30241. X448k);
  30242. }
  30243. return ret;
  30244. }
  30245. /* Write a public Curve448 key to DER format,
  30246. * length on success else < 0 */
  30247. int wc_Curve448PublicKeyToDer(curve448_key* key, byte* output, word32 inLen,
  30248. int withAlg)
  30249. {
  30250. int ret;
  30251. byte pubKey[CURVE448_PUB_KEY_SIZE];
  30252. word32 pubKeyLen = (word32)sizeof(pubKey);
  30253. if (key == NULL || output == NULL) {
  30254. return BAD_FUNC_ARG;
  30255. }
  30256. ret = wc_curve448_export_public(key, pubKey, &pubKeyLen);
  30257. if (ret == 0) {
  30258. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  30259. X448k, withAlg);
  30260. }
  30261. return ret;
  30262. }
  30263. #endif /* HAVE_CURVE448 && HAVE_CURVE448_KEY_EXPORT */
  30264. #ifndef WOLFSSL_ASN_TEMPLATE
  30265. #if (defined(HAVE_OCSP) || defined(HAVE_CRL)) && !defined(WOLFCRYPT_ONLY)
  30266. /* Get raw Date only, no processing, 0 on success */
  30267. static int GetBasicDate(const byte* source, word32* idx, byte* date,
  30268. byte* format, int maxIdx)
  30269. {
  30270. int ret, length;
  30271. const byte *datePtr = NULL;
  30272. WOLFSSL_ENTER("GetBasicDate");
  30273. ret = GetDateInfo(source, idx, &datePtr, format, &length, maxIdx);
  30274. if (ret < 0)
  30275. return ret;
  30276. XMEMCPY(date, datePtr, length);
  30277. return 0;
  30278. }
  30279. #endif /* HAVE_OCSP || HAVE_CRL */
  30280. #endif /* WOLFSSL_ASN_TEMPLATE */
  30281. #if defined(HAVE_OCSP) && !defined(WOLFCRYPT_ONLY)
  30282. #ifndef WOLFSSL_ASN_TEMPLATE
  30283. static int GetEnumerated(const byte* input, word32* inOutIdx, int *value,
  30284. int sz)
  30285. {
  30286. word32 idx = *inOutIdx;
  30287. word32 len;
  30288. byte tag;
  30289. WOLFSSL_ENTER("GetEnumerated");
  30290. *value = 0;
  30291. if (GetASNTag(input, &idx, &tag, sz) < 0)
  30292. return ASN_PARSE_E;
  30293. if (tag != ASN_ENUMERATED)
  30294. return ASN_PARSE_E;
  30295. if ((int)idx >= sz)
  30296. return BUFFER_E;
  30297. len = input[idx++];
  30298. if (len > 4 || (int)(len + idx) > sz)
  30299. return ASN_PARSE_E;
  30300. while (len--) {
  30301. *value = *value << 8 | input[idx++];
  30302. }
  30303. *inOutIdx = idx;
  30304. return *value;
  30305. }
  30306. #endif /* !WOLFSSL_ASN_TEMPLATE */
  30307. #ifdef WOLFSSL_ASN_TEMPLATE
  30308. /* ASN.1 template for OCSP single response.
  30309. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30310. */
  30311. static const ASNItem singleResponseASN[] = {
  30312. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30313. /* certId */
  30314. /* CID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  30315. /* hashAlgorithm */
  30316. /* CID_HASHALGO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  30317. /* CID_HASHALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  30318. /* CID_HASHALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  30319. /* issuerNameHash */
  30320. /* CID_ISSUERHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  30321. /* issuerKeyHash */
  30322. /* CID_ISSUERKEYHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  30323. /* serialNumber */
  30324. /* CID_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
  30325. /* certStatus - CHOICE */
  30326. /* good [0] IMPLICIT NULL */
  30327. /* CS_GOOD */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 2 },
  30328. /* revoked [1] IMPLICIT RevokedInfo */
  30329. /* CS_REVOKED */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 2 },
  30330. /* revocationTime */
  30331. /* CS_REVOKED_TIME */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30332. /* revocationReason [0] EXPLICIT CRLReason OPTIONAL */
  30333. /* CS_REVOKED_REASON */ { 2, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 1 },
  30334. /* crlReason */
  30335. /* CS_REVOKED_REASON_VAL */ { 3, ASN_ENUMERATED, 0, 0, 0 },
  30336. /* unknown [2] IMPLICIT UnknownInfo ::= NULL */
  30337. /* UNKNOWN */ { 1, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 2 },
  30338. /* thisUpdate */
  30339. /* THISUPDATE_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30340. /* nextUpdate */
  30341. /* NEXTUPDATE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  30342. /* NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30343. /* singleExtensions */
  30344. /* EXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  30345. };
  30346. enum {
  30347. SINGLERESPONSEASN_IDX_SEQ = 0,
  30348. SINGLERESPONSEASN_IDX_CID_SEQ,
  30349. SINGLERESPONSEASN_IDX_CID_HASHALGO_SEQ,
  30350. SINGLERESPONSEASN_IDX_CID_HASHALGO_OID,
  30351. SINGLERESPONSEASN_IDX_CID_HASHALGO_NULL,
  30352. SINGLERESPONSEASN_IDX_CID_ISSUERHASH,
  30353. SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH,
  30354. SINGLERESPONSEASN_IDX_CID_SERIAL,
  30355. SINGLERESPONSEASN_IDX_CS_GOOD,
  30356. SINGLERESPONSEASN_IDX_CS_REVOKED,
  30357. SINGLERESPONSEASN_IDX_CS_REVOKED_TIME,
  30358. SINGLERESPONSEASN_IDX_CS_REVOKED_REASON,
  30359. SINGLERESPONSEASN_IDX_CS_REVOKED_REASON_VAL,
  30360. SINGLERESPONSEASN_IDX_UNKNOWN,
  30361. SINGLERESPONSEASN_IDX_THISUPDATE_GT,
  30362. SINGLERESPONSEASN_IDX_NEXTUPDATE,
  30363. SINGLERESPONSEASN_IDX_NEXTUPDATE_GT,
  30364. SINGLERESPONSEASN_IDX_EXT,
  30365. };
  30366. /* Number of items in ASN.1 template for OCSP single response. */
  30367. #define singleResponseASN_Length (sizeof(singleResponseASN) / sizeof(ASNItem))
  30368. #endif
  30369. static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size,
  30370. int wrapperSz, OcspEntry* single)
  30371. {
  30372. #ifndef WOLFSSL_ASN_TEMPLATE
  30373. word32 idx = *ioIndex, prevIndex, oid, localIdx, certIdIdx;
  30374. int length;
  30375. int ret;
  30376. byte tag;
  30377. WOLFSSL_ENTER("DecodeSingleResponse");
  30378. prevIndex = idx;
  30379. /* Wrapper around the Single Response */
  30380. if (GetSequence(source, &idx, &length, size) < 0)
  30381. return ASN_PARSE_E;
  30382. /* Wrapper around the CertID */
  30383. certIdIdx = idx;
  30384. if (GetSequence(source, &idx, &length, size) < 0)
  30385. return ASN_PARSE_E;
  30386. single->rawCertId = source + certIdIdx;
  30387. /* Hash algorithm */
  30388. ret = GetAlgoId(source, &idx, &oid, oidIgnoreType, size);
  30389. if (ret < 0)
  30390. return ret;
  30391. single->hashAlgoOID = oid;
  30392. /* Save reference to the hash of CN */
  30393. ret = GetOctetString(source, &idx, &length, size);
  30394. if (ret < 0)
  30395. return ret;
  30396. if (length > (int)sizeof(single->issuerHash))
  30397. return BUFFER_E;
  30398. XMEMCPY(single->issuerHash, source + idx, length);
  30399. idx += length;
  30400. /* Save reference to the hash of the issuer public key */
  30401. ret = GetOctetString(source, &idx, &length, size);
  30402. if (ret < 0)
  30403. return ret;
  30404. if (length > (int)sizeof(single->issuerKeyHash))
  30405. return BUFFER_E;
  30406. XMEMCPY(single->issuerKeyHash, source + idx, length);
  30407. idx += length;
  30408. /* Get serial number */
  30409. if (wc_GetSerialNumber(source, &idx, single->status->serial,
  30410. &single->status->serialSz, size) < 0)
  30411. return ASN_PARSE_E;
  30412. single->rawCertIdSize = idx - certIdIdx;
  30413. if (idx >= size)
  30414. return BUFFER_E;
  30415. /* CertStatus */
  30416. switch (source[idx++])
  30417. {
  30418. case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
  30419. single->status->status = CERT_GOOD;
  30420. idx++;
  30421. break;
  30422. case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
  30423. single->status->status = CERT_REVOKED;
  30424. if (GetLength(source, &idx, &length, size) < 0)
  30425. return ASN_PARSE_E;
  30426. idx += length;
  30427. break;
  30428. case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
  30429. single->status->status = CERT_UNKNOWN;
  30430. idx++;
  30431. break;
  30432. default:
  30433. return ASN_PARSE_E;
  30434. }
  30435. if (idx >= size)
  30436. return BUFFER_E;
  30437. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  30438. single->status->thisDateAsn = source + idx;
  30439. localIdx = 0;
  30440. if (GetDateInfo(single->status->thisDateAsn, &localIdx, NULL,
  30441. (byte*)&single->status->thisDateParsed.type,
  30442. &single->status->thisDateParsed.length, size - idx) < 0)
  30443. return ASN_PARSE_E;
  30444. if (idx + localIdx >= size)
  30445. return BUFFER_E;
  30446. XMEMCPY(single->status->thisDateParsed.data,
  30447. single->status->thisDateAsn + localIdx - single->status->thisDateParsed.length,
  30448. single->status->thisDateParsed.length);
  30449. #endif
  30450. if (GetBasicDate(source, &idx, single->status->thisDate,
  30451. &single->status->thisDateFormat, size) < 0)
  30452. return ASN_PARSE_E;
  30453. #ifndef NO_ASN_TIME_CHECK
  30454. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  30455. if (!XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, BEFORE))
  30456. return ASN_BEFORE_DATE_E;
  30457. #endif
  30458. #endif
  30459. /* The following items are optional. Only check for them if there is more
  30460. * unprocessed data in the singleResponse wrapper. */
  30461. localIdx = idx;
  30462. if (((int)(idx - prevIndex) < wrapperSz) &&
  30463. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30464. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  30465. {
  30466. idx++;
  30467. if (GetLength(source, &idx, &length, size) < 0)
  30468. return ASN_PARSE_E;
  30469. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  30470. single->status->nextDateAsn = source + idx;
  30471. localIdx = 0;
  30472. if (GetDateInfo(single->status->nextDateAsn, &localIdx, NULL,
  30473. (byte*)&single->status->nextDateParsed.type,
  30474. &single->status->nextDateParsed.length, size - idx) < 0)
  30475. return ASN_PARSE_E;
  30476. if (idx + localIdx >= size)
  30477. return BUFFER_E;
  30478. XMEMCPY(single->status->nextDateParsed.data,
  30479. single->status->nextDateAsn + localIdx - single->status->nextDateParsed.length,
  30480. single->status->nextDateParsed.length);
  30481. #endif
  30482. if (GetBasicDate(source, &idx, single->status->nextDate,
  30483. &single->status->nextDateFormat, size) < 0)
  30484. return ASN_PARSE_E;
  30485. #ifndef NO_ASN_TIME_CHECK
  30486. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  30487. if (!XVALIDATE_DATE(single->status->nextDate, single->status->nextDateFormat, AFTER))
  30488. return ASN_AFTER_DATE_E;
  30489. #endif
  30490. #endif
  30491. }
  30492. /* Skip the optional extensions in singleResponse. */
  30493. localIdx = idx;
  30494. if (((int)(idx - prevIndex) < wrapperSz) &&
  30495. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30496. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  30497. {
  30498. idx++;
  30499. if (GetLength(source, &idx, &length, size) < 0)
  30500. return ASN_PARSE_E;
  30501. idx += length;
  30502. }
  30503. *ioIndex = idx;
  30504. return 0;
  30505. #else
  30506. DECL_ASNGETDATA(dataASN, singleResponseASN_Length);
  30507. int ret = 0;
  30508. CertStatus* cs = NULL;
  30509. word32 serialSz;
  30510. word32 issuerHashLen;
  30511. word32 issuerKeyHashLen;
  30512. word32 thisDateLen;
  30513. word32 nextDateLen;
  30514. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30515. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30516. WOLFSSL_ASN1_TIME *at;
  30517. #endif
  30518. (void)wrapperSz;
  30519. WOLFSSL_ENTER("DecodeSingleResponse");
  30520. CALLOC_ASNGETDATA(dataASN, singleResponseASN_Length, ret, NULL);
  30521. if (ret == 0) {
  30522. /* Certificate Status field. */
  30523. cs = single->status;
  30524. /* Set maximum lengths for data. */
  30525. issuerHashLen = OCSP_DIGEST_SIZE;
  30526. issuerKeyHashLen = OCSP_DIGEST_SIZE;
  30527. serialSz = EXTERNAL_SERIAL_SIZE;
  30528. thisDateLen = MAX_DATE_SIZE;
  30529. nextDateLen = MAX_DATE_SIZE;
  30530. /* Set OID type, buffers to hold data and variables to hold size. */
  30531. GetASN_OID(&dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID],
  30532. oidHashType);
  30533. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERHASH],
  30534. single->issuerHash, &issuerHashLen);
  30535. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH],
  30536. single->issuerKeyHash, &issuerKeyHashLen);
  30537. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_SERIAL], cs->serial,
  30538. &serialSz);
  30539. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT],
  30540. cs->thisDate, &thisDateLen);
  30541. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT],
  30542. cs->nextDate, &nextDateLen);
  30543. /* TODO: decode revoked time and reason. */
  30544. /* Decode OCSP single response. */
  30545. ret = GetASN_Items(singleResponseASN, dataASN, singleResponseASN_Length,
  30546. 1, source, ioIndex, size);
  30547. }
  30548. /* Validate the issuer hash length is the size required. */
  30549. if ((ret == 0) && (issuerHashLen != OCSP_DIGEST_SIZE)) {
  30550. ret = ASN_PARSE_E;
  30551. }
  30552. /* Validate the issuer key hash length is the size required. */
  30553. if ((ret == 0) && (issuerKeyHashLen != OCSP_DIGEST_SIZE)) {
  30554. ret = ASN_PARSE_E;
  30555. }
  30556. if (ret == 0) {
  30557. /* Store serial size. */
  30558. cs->serialSz = serialSz;
  30559. /* Determine status by which item was found. */
  30560. if (dataASN[SINGLERESPONSEASN_IDX_CS_GOOD].tag != 0) {
  30561. cs->status = CERT_GOOD;
  30562. }
  30563. if (dataASN[SINGLERESPONSEASN_IDX_CS_REVOKED].tag != 0) {
  30564. cs->status = CERT_REVOKED;
  30565. }
  30566. if (dataASN[SINGLERESPONSEASN_IDX_UNKNOWN].tag != 0) {
  30567. cs->status = CERT_UNKNOWN;
  30568. }
  30569. /* Store the thisDate format - only one possible. */
  30570. cs->thisDateFormat = ASN_GENERALIZED_TIME;
  30571. #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  30572. /* Check date is a valid string and BEFORE now. */
  30573. if (!XVALIDATE_DATE(cs->thisDate, ASN_GENERALIZED_TIME, BEFORE)) {
  30574. ret = ASN_BEFORE_DATE_E;
  30575. }
  30576. }
  30577. if (ret == 0) {
  30578. #endif
  30579. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30580. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30581. /* Store ASN.1 version of thisDate. */
  30582. cs->thisDateAsn = GetASNItem_Addr(
  30583. dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT], source);
  30584. at = &cs->thisDateParsed;
  30585. at->type = ASN_GENERALIZED_TIME;
  30586. XMEMCPY(at->data, cs->thisDate, thisDateLen);
  30587. at->length = thisDateLen;
  30588. #endif
  30589. }
  30590. if ((ret == 0) &&
  30591. (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
  30592. /* Store the nextDate format - only one possible. */
  30593. cs->nextDateFormat = ASN_GENERALIZED_TIME;
  30594. #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  30595. /* Check date is a valid string and AFTER now. */
  30596. if (!XVALIDATE_DATE(cs->nextDate, ASN_GENERALIZED_TIME, AFTER)) {
  30597. ret = ASN_AFTER_DATE_E;
  30598. }
  30599. }
  30600. if ((ret == 0) &&
  30601. (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
  30602. #endif
  30603. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30604. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30605. /* Store ASN.1 version of thisDate. */
  30606. cs->nextDateAsn = GetASNItem_Addr(
  30607. dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT], source);
  30608. at = &cs->nextDateParsed;
  30609. at->type = ASN_GENERALIZED_TIME;
  30610. XMEMCPY(at->data, cs->nextDate, nextDateLen);
  30611. at->length = nextDateLen;
  30612. #endif
  30613. }
  30614. if (ret == 0) {
  30615. /* OcspEntry now used. */
  30616. single->used = 1;
  30617. }
  30618. FREE_ASNGETDATA(dataASN, NULL);
  30619. return ret;
  30620. #endif
  30621. }
  30622. #ifdef WOLFSSL_ASN_TEMPLATE
  30623. /* ASN.1 template for OCSP response extension header.
  30624. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30625. */
  30626. static const ASNItem respExtHdrASN[] = {
  30627. /* responseExtensions */
  30628. /* EXT */ { 0, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 0 },
  30629. /* extensions */
  30630. /* EXT_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  30631. };
  30632. enum {
  30633. RESPEXTHDRASN_IDX_EXT = 0,
  30634. RESPEXTHDRASN_IDX_EXT_SEQ,
  30635. };
  30636. /* Number of items in ASN.1 template for OCSP response extension header. */
  30637. #define respExtHdrASN_Length (sizeof(respExtHdrASN) / sizeof(ASNItem))
  30638. #endif
  30639. static int DecodeOcspRespExtensions(byte* source, word32* ioIndex,
  30640. OcspResponse* resp, word32 sz)
  30641. {
  30642. #ifndef WOLFSSL_ASN_TEMPLATE
  30643. word32 idx = *ioIndex;
  30644. int length;
  30645. int ext_bound; /* boundary index for the sequence of extensions */
  30646. word32 oid;
  30647. int ret;
  30648. byte tag;
  30649. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  30650. if ((idx + 1) > sz)
  30651. return BUFFER_E;
  30652. if (GetASNTag(source, &idx, &tag, sz) < 0)
  30653. return ASN_PARSE_E;
  30654. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  30655. return ASN_PARSE_E;
  30656. if (GetLength(source, &idx, &length, sz) < 0)
  30657. return ASN_PARSE_E;
  30658. if (GetSequence(source, &idx, &length, sz) < 0)
  30659. return ASN_PARSE_E;
  30660. ext_bound = idx + length;
  30661. while (idx < (word32)ext_bound) {
  30662. word32 localIdx;
  30663. if (GetSequence(source, &idx, &length, sz) < 0) {
  30664. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  30665. return ASN_PARSE_E;
  30666. }
  30667. oid = 0;
  30668. if (GetObjectId(source, &idx, &oid, oidOcspType, sz) < 0) {
  30669. WOLFSSL_MSG("\tfail: OBJECT ID");
  30670. return ASN_PARSE_E;
  30671. }
  30672. /* check for critical flag */
  30673. if ((idx + 1) > (word32)sz) {
  30674. WOLFSSL_MSG("\tfail: malformed buffer");
  30675. return BUFFER_E;
  30676. }
  30677. localIdx = idx;
  30678. if (GetASNTag(source, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  30679. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  30680. ret = GetBoolean(source, &idx, sz);
  30681. if (ret < 0)
  30682. return ret;
  30683. }
  30684. ret = GetOctetString(source, &idx, &length, sz);
  30685. if (ret < 0)
  30686. return ret;
  30687. if (oid == OCSP_NONCE_OID) {
  30688. /* get data inside extra OCTET_STRING */
  30689. ret = GetOctetString(source, &idx, &length, sz);
  30690. if (ret < 0)
  30691. return ret;
  30692. resp->nonce = source + idx;
  30693. resp->nonceSz = length;
  30694. }
  30695. idx += length;
  30696. }
  30697. *ioIndex = idx;
  30698. return 0;
  30699. #else
  30700. /* certExtASN_Length is greater than respExtHdrASN_Length */
  30701. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  30702. int ret = 0;
  30703. word32 idx = *ioIndex;
  30704. word32 maxIdx = 0;
  30705. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  30706. CALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, resp->heap);
  30707. if (ret == 0) {
  30708. /* Check for header and move past. */
  30709. ret = GetASN_Items(respExtHdrASN, dataASN, respExtHdrASN_Length, 0,
  30710. source, &idx, sz);
  30711. }
  30712. if (ret == 0) {
  30713. /* Keep end extensions index for total length check. */
  30714. maxIdx = idx + dataASN[RESPEXTHDRASN_IDX_EXT_SEQ].length;
  30715. }
  30716. /* Step through all extensions. */
  30717. while ((ret == 0) && (idx < maxIdx)) {
  30718. /* Clear dynamic data, set OID type to expect. */
  30719. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  30720. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidOcspType);
  30721. /* TODO: check criticality. */
  30722. /* Decode OCSP response extension. */
  30723. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0,
  30724. source, &idx, sz);
  30725. if (ret == 0) {
  30726. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  30727. int length = dataASN[CERTEXTASN_IDX_VAL].length;
  30728. if (oid == OCSP_NONCE_OID) {
  30729. /* Extract nonce data. */
  30730. ret = GetOctetString(source, &idx, &length, sz);
  30731. if (ret >= 0) {
  30732. ret = 0;
  30733. /* get data inside extra OCTET_STRING */
  30734. resp->nonce = source + idx;
  30735. resp->nonceSz = length;
  30736. }
  30737. }
  30738. /* Ignore all other extension types. */
  30739. /* Skip over rest of extension. */
  30740. idx += length;
  30741. }
  30742. }
  30743. /* Return index after extensions. */
  30744. *ioIndex = idx;
  30745. FREE_ASNGETDATA(dataASN, resp->heap);
  30746. return ret;
  30747. #endif
  30748. }
  30749. #ifdef WOLFSSL_ASN_TEMPLATE
  30750. /* ASN.1 template for OCSP ResponseData.
  30751. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30752. */
  30753. static const ASNItem ocspRespDataASN[] = {
  30754. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30755. /* version DEFAULT v1 */
  30756. /* VER_PRESENT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  30757. /* VER */ { 2, ASN_INTEGER, 1, 0, 0 },
  30758. /* byName */
  30759. /* BYNAME */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  30760. /* byKey */
  30761. /* BYKEY */ { 1, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 2 },
  30762. /* producedAt */
  30763. /* PA */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0, },
  30764. /* responses */
  30765. /* RESP */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  30766. /* responseExtensions */
  30767. /* RESPEXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 }
  30768. };
  30769. enum {
  30770. OCSPRESPDATAASN_IDX_SEQ = 0,
  30771. OCSPRESPDATAASN_IDX_VER_PRESENT,
  30772. OCSPRESPDATAASN_IDX_VER,
  30773. OCSPRESPDATAASN_IDX_BYNAME,
  30774. OCSPRESPDATAASN_IDX_BYKEY,
  30775. OCSPRESPDATAASN_IDX_PA,
  30776. OCSPRESPDATAASN_IDX_RESP,
  30777. OCSPRESPDATAASN_IDX_RESPEXT,
  30778. };
  30779. /* Number of items in ASN.1 template for OCSP ResponseData. */
  30780. #define ocspRespDataASN_Length (sizeof(ocspRespDataASN) / sizeof(ASNItem))
  30781. #endif
  30782. static int DecodeResponseData(byte* source, word32* ioIndex,
  30783. OcspResponse* resp, word32 size)
  30784. {
  30785. #ifndef WOLFSSL_ASN_TEMPLATE
  30786. word32 idx = *ioIndex, prev_idx, localIdx;
  30787. int length;
  30788. int version;
  30789. int ret;
  30790. byte tag;
  30791. int wrapperSz;
  30792. OcspEntry* single;
  30793. WOLFSSL_ENTER("DecodeResponseData");
  30794. resp->response = source + idx;
  30795. prev_idx = idx;
  30796. if (GetSequence(source, &idx, &length, size) < 0)
  30797. return ASN_PARSE_E;
  30798. resp->responseSz = length + idx - prev_idx;
  30799. /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
  30800. * item isn't an EXPLICIT[0], then set version to zero and move
  30801. * onto the next item.
  30802. */
  30803. localIdx = idx;
  30804. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30805. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
  30806. {
  30807. idx += 2; /* Eat the value and length */
  30808. if (GetMyVersion(source, &idx, &version, size) < 0)
  30809. return ASN_PARSE_E;
  30810. } else
  30811. version = 0;
  30812. localIdx = idx;
  30813. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30814. ( tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1) ||
  30815. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2) ))
  30816. {
  30817. idx++; /* advance past ASN tag */
  30818. if (GetLength(source, &idx, &length, size) < 0)
  30819. return ASN_PARSE_E;
  30820. idx += length;
  30821. }
  30822. else
  30823. return ASN_PARSE_E;
  30824. /* save pointer to the producedAt time */
  30825. if (GetBasicDate(source, &idx, resp->producedDate,
  30826. &resp->producedDateFormat, size) < 0)
  30827. return ASN_PARSE_E;
  30828. /* Outer wrapper of the SEQUENCE OF Single Responses. */
  30829. if (GetSequence(source, &idx, &wrapperSz, size) < 0)
  30830. return ASN_PARSE_E;
  30831. localIdx = idx;
  30832. single = resp->single;
  30833. while (idx - localIdx < (word32)wrapperSz) {
  30834. ret = DecodeSingleResponse(source, &idx, size, wrapperSz, single);
  30835. if (ret < 0)
  30836. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  30837. if (idx - localIdx < (word32)wrapperSz) {
  30838. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  30839. DYNAMIC_TYPE_OCSP_ENTRY);
  30840. if (single->next == NULL) {
  30841. return MEMORY_E;
  30842. }
  30843. XMEMSET(single->next, 0, sizeof(OcspEntry));
  30844. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  30845. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  30846. if (single->next->status == NULL) {
  30847. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  30848. single->next = NULL;
  30849. return MEMORY_E;
  30850. }
  30851. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  30852. single->next->isDynamic = 1;
  30853. single = single->next;
  30854. }
  30855. }
  30856. /*
  30857. * Check the length of the ResponseData against the current index to
  30858. * see if there are extensions, they are optional.
  30859. */
  30860. if (idx - prev_idx < resp->responseSz)
  30861. if (DecodeOcspRespExtensions(source, &idx, resp, size) < 0)
  30862. return ASN_PARSE_E;
  30863. *ioIndex = idx;
  30864. return 0;
  30865. #else
  30866. DECL_ASNGETDATA(dataASN, ocspRespDataASN_Length);
  30867. int ret = 0;
  30868. byte version;
  30869. word32 dateSz, idx = *ioIndex;
  30870. OcspEntry* single = NULL;
  30871. WOLFSSL_ENTER("DecodeResponseData");
  30872. CALLOC_ASNGETDATA(dataASN, ocspRespDataASN_Length, ret, resp->heap);
  30873. if (ret == 0) {
  30874. resp->response = source + idx;
  30875. /* Default, not present, is v1 = 0. */
  30876. version = 0;
  30877. /* Max size of date supported. */
  30878. dateSz = MAX_DATE_SIZE;
  30879. /* Set the where to put version an produced date. */
  30880. GetASN_Int8Bit(&dataASN[OCSPRESPDATAASN_IDX_VER], &version);
  30881. GetASN_Buffer(&dataASN[OCSPRESPDATAASN_IDX_PA], resp->producedDate,
  30882. &dateSz);
  30883. /* Decode the ResponseData. */
  30884. ret = GetASN_Items(ocspRespDataASN, dataASN, ocspRespDataASN_Length,
  30885. 1, source, ioIndex, size);
  30886. }
  30887. /* Only support v1 == 0 */
  30888. if ((ret == 0) && (version != 0)) {
  30889. ret = ASN_PARSE_E;
  30890. }
  30891. /* Ensure date is a minimal size. */
  30892. if ((ret == 0) && (dateSz < MIN_DATE_SIZE)) {
  30893. ret = ASN_PARSE_E;
  30894. }
  30895. if (ret == 0) {
  30896. /* TODO: use byName/byKey fields. */
  30897. /* Store size of response. */
  30898. resp->responseSz = *ioIndex - idx;
  30899. /* Store date format/tag. */
  30900. resp->producedDateFormat = dataASN[OCSPRESPDATAASN_IDX_PA].tag;
  30901. /* Get the index of the responses SEQUENCE. */
  30902. idx = GetASNItem_DataIdx(dataASN[OCSPRESPDATAASN_IDX_RESP], source);
  30903. /* Start with the pre-existing OcspEntry. */
  30904. single = resp->single;
  30905. }
  30906. while ((ret == 0) && (idx < dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset)) {
  30907. /* Allocate and use a new OCSP entry if this is used. */
  30908. if (single->used) {
  30909. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  30910. DYNAMIC_TYPE_OCSP_ENTRY);
  30911. if (single->next == NULL) {
  30912. ret = MEMORY_E;
  30913. }
  30914. else {
  30915. XMEMSET(single->next, 0, sizeof(OcspEntry));
  30916. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  30917. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  30918. if (single->next->status == NULL) {
  30919. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  30920. single->next = NULL;
  30921. ret = MEMORY_E;
  30922. }
  30923. else {
  30924. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  30925. /* Entry to be freed. */
  30926. single->next->isDynamic = 1;
  30927. /* used will be 0 (false) */
  30928. single = single->next;
  30929. }
  30930. }
  30931. }
  30932. if (ret == 0) {
  30933. /* Decode SingleResponse into OcspEntry. */
  30934. ret = DecodeSingleResponse(source, &idx,
  30935. dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset,
  30936. dataASN[OCSPRESPDATAASN_IDX_RESP].length, single);
  30937. /* single->used set on successful decode. */
  30938. }
  30939. }
  30940. /* Check if there were extensions. */
  30941. if ((ret == 0) &&
  30942. (dataASN[OCSPRESPDATAASN_IDX_RESPEXT].data.buffer.data != NULL)) {
  30943. /* Get index of [1] */
  30944. idx = dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset;
  30945. /* Decode the response extensions. */
  30946. if (DecodeOcspRespExtensions(source, &idx, resp, *ioIndex) < 0) {
  30947. ret = ASN_PARSE_E;
  30948. }
  30949. }
  30950. FREE_ASNGETDATA(dataASN, resp->heap);
  30951. return ret;
  30952. #endif
  30953. }
  30954. #ifndef WOLFSSL_ASN_TEMPLATE
  30955. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  30956. static int DecodeCerts(byte* source,
  30957. word32* ioIndex, OcspResponse* resp, word32 size)
  30958. {
  30959. word32 idx = *ioIndex;
  30960. byte tag;
  30961. WOLFSSL_ENTER("DecodeCerts");
  30962. if (GetASNTag(source, &idx, &tag, size) < 0)
  30963. return ASN_PARSE_E;
  30964. if (tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
  30965. {
  30966. int length;
  30967. if (GetLength(source, &idx, &length, size) < 0)
  30968. return ASN_PARSE_E;
  30969. if (GetSequence(source, &idx, &length, size) < 0)
  30970. return ASN_PARSE_E;
  30971. resp->cert = source + idx;
  30972. resp->certSz = length;
  30973. idx += length;
  30974. }
  30975. *ioIndex = idx;
  30976. return 0;
  30977. }
  30978. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  30979. #endif /* !WOLFSSL_ASN_TEMPLATE */
  30980. #ifdef WOLFSSL_ASN_TEMPLATE
  30981. /* ASN.1 template for BasicOCSPResponse.
  30982. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30983. */
  30984. static const ASNItem ocspBasicRespASN[] = {
  30985. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30986. /* tbsResponseData */
  30987. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0, },
  30988. /* signatureAlgorithm */
  30989. /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0, },
  30990. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  30991. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  30992. /* parameters */
  30993. #ifdef WC_RSA_PSS
  30994. /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  30995. #endif
  30996. /* signature */
  30997. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  30998. /* certs */
  30999. /* CERTS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  31000. /* CERTS_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0, },
  31001. };
  31002. enum {
  31003. OCSPBASICRESPASN_IDX_SEQ = 0,
  31004. OCSPBASICRESPASN_IDX_TBS_SEQ,
  31005. OCSPBASICRESPASN_IDX_SIGALGO,
  31006. OCSPBASICRESPASN_IDX_SIGALGO_OID,
  31007. OCSPBASICRESPASN_IDX_SIGALGO_NULL,
  31008. #ifdef WC_RSA_PSS
  31009. OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS,
  31010. #endif
  31011. OCSPBASICRESPASN_IDX_SIGNATURE,
  31012. OCSPBASICRESPASN_IDX_CERTS,
  31013. OCSPBASICRESPASN_IDX_CERTS_SEQ,
  31014. };
  31015. /* Number of items in ASN.1 template for BasicOCSPResponse. */
  31016. #define ocspBasicRespASN_Length (sizeof(ocspBasicRespASN) / sizeof(ASNItem))
  31017. #endif /* WOLFSSL_ASN_TEMPLATE */
  31018. static int DecodeBasicOcspResponse(byte* source, word32* ioIndex,
  31019. OcspResponse* resp, word32 size, void* cm, void* heap, int noVerify)
  31020. {
  31021. #ifndef WOLFSSL_ASN_TEMPLATE
  31022. int length;
  31023. word32 idx = *ioIndex;
  31024. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31025. word32 end_index;
  31026. #endif
  31027. int ret;
  31028. int sigLength;
  31029. const byte* sigParams = NULL;
  31030. word32 sigParamsSz = 0;
  31031. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  31032. (void)heap;
  31033. if (GetSequence(source, &idx, &length, size) < 0)
  31034. return ASN_PARSE_E;
  31035. if (idx + length > size)
  31036. return ASN_INPUT_E;
  31037. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31038. end_index = idx + length;
  31039. #endif
  31040. if ((ret = DecodeResponseData(source, &idx, resp, size)) < 0)
  31041. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  31042. /* Get the signature algorithm */
  31043. if (GetAlgoId(source, &idx, &resp->sigOID, oidSigType, size) < 0) {
  31044. return ASN_PARSE_E;
  31045. }
  31046. #ifdef WC_RSA_PSS
  31047. else if (resp->sigOID == CTC_RSASSAPSS) {
  31048. word32 sz;
  31049. int len;
  31050. const byte* params;
  31051. sz = idx;
  31052. params = source + idx;
  31053. if (GetSequence(source, &idx, &len, size) < 0)
  31054. ret = ASN_PARSE_E;
  31055. if (ret == 0) {
  31056. idx += len;
  31057. sigParams = params;
  31058. sigParamsSz = idx - sz;
  31059. }
  31060. }
  31061. #endif
  31062. ret = CheckBitString(source, &idx, &sigLength, size, 1, NULL);
  31063. if (ret != 0)
  31064. return ret;
  31065. resp->sigSz = sigLength;
  31066. resp->sig = source + idx;
  31067. idx += sigLength;
  31068. /*
  31069. * Check the length of the BasicOcspResponse against the current index to
  31070. * see if there are certificates, they are optional.
  31071. */
  31072. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31073. if (idx < end_index)
  31074. {
  31075. int cert_inited = 0;
  31076. #ifdef WOLFSSL_SMALL_STACK
  31077. DecodedCert *cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  31078. DYNAMIC_TYPE_TMP_BUFFER);
  31079. if (cert == NULL)
  31080. return MEMORY_E;
  31081. #else
  31082. DecodedCert cert[1];
  31083. #endif
  31084. do {
  31085. if (DecodeCerts(source, &idx, resp, size) < 0) {
  31086. ret = ASN_PARSE_E;
  31087. break;
  31088. }
  31089. InitDecodedCert(cert, resp->cert, resp->certSz, heap);
  31090. cert_inited = 1;
  31091. /* Don't verify if we don't have access to Cert Manager. */
  31092. ret = ParseCertRelative(cert, CERT_TYPE,
  31093. noVerify ? NO_VERIFY : VERIFY_OCSP_CERT,
  31094. cm);
  31095. if (ret < 0) {
  31096. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  31097. break;
  31098. }
  31099. #ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK
  31100. if ((cert->extExtKeyUsage & EXTKEYUSE_OCSP_SIGN) == 0) {
  31101. if (XMEMCMP(cert->subjectHash,
  31102. resp->single->issuerHash, OCSP_DIGEST_SIZE) == 0) {
  31103. WOLFSSL_MSG("\tOCSP Response signed by issuer");
  31104. }
  31105. else {
  31106. WOLFSSL_MSG("\tOCSP Responder key usage check failed");
  31107. #ifdef OPENSSL_EXTRA
  31108. resp->verifyError = OCSP_BAD_ISSUER;
  31109. #else
  31110. ret = BAD_OCSP_RESPONDER;
  31111. break;
  31112. #endif
  31113. }
  31114. }
  31115. #endif
  31116. /* ConfirmSignature is blocking here */
  31117. ret = ConfirmSignature(
  31118. &cert->sigCtx,
  31119. resp->response, resp->responseSz,
  31120. cert->publicKey, cert->pubKeySize, cert->keyOID,
  31121. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31122. NULL);
  31123. if (ret != 0) {
  31124. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31125. ret = ASN_OCSP_CONFIRM_E;
  31126. break;
  31127. }
  31128. } while(0);
  31129. if (cert_inited)
  31130. FreeDecodedCert(cert);
  31131. #ifdef WOLFSSL_SMALL_STACK
  31132. XFREE(cert, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31133. #endif
  31134. if (ret != 0)
  31135. return ret;
  31136. }
  31137. else
  31138. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  31139. {
  31140. Signer* ca;
  31141. int sigValid = -1;
  31142. #ifndef NO_SKID
  31143. ca = GetCA(cm, resp->single->issuerKeyHash);
  31144. #else
  31145. ca = GetCA(cm, resp->single->issuerHash);
  31146. #endif
  31147. if (ca) {
  31148. SignatureCtx sigCtx;
  31149. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  31150. /* ConfirmSignature is blocking here */
  31151. sigValid = ConfirmSignature(&sigCtx, resp->response,
  31152. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  31153. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31154. NULL);
  31155. }
  31156. if (ca == NULL || sigValid != 0) {
  31157. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31158. return ASN_OCSP_CONFIRM_E;
  31159. }
  31160. (void)noVerify;
  31161. }
  31162. *ioIndex = idx;
  31163. return 0;
  31164. #else
  31165. DECL_ASNGETDATA(dataASN, ocspBasicRespASN_Length);
  31166. int ret = 0;
  31167. word32 idx = *ioIndex;
  31168. const byte* sigParams = NULL;
  31169. word32 sigParamsSz = 0;
  31170. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31171. #ifdef WOLFSSL_SMALL_STACK
  31172. DecodedCert* cert = NULL;
  31173. #else
  31174. DecodedCert cert[1];
  31175. #endif
  31176. int certInit = 0;
  31177. #endif
  31178. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  31179. (void)heap;
  31180. CALLOC_ASNGETDATA(dataASN, ocspBasicRespASN_Length, ret, heap);
  31181. if (ret == 0) {
  31182. /* Set expecting signature OID. */
  31183. GetASN_OID(&dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID], oidSigType);
  31184. /* Decode BasicOCSPResponse. */
  31185. ret = GetASN_Items(ocspBasicRespASN, dataASN, ocspBasicRespASN_Length,
  31186. 1, source, &idx, size);
  31187. }
  31188. if (ret == 0) {
  31189. word32 dataIdx = 0;
  31190. /* Decode the response data. */
  31191. if (DecodeResponseData(
  31192. GetASNItem_Addr(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source),
  31193. &dataIdx, resp,
  31194. GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source)
  31195. ) < 0) {
  31196. ret = ASN_PARSE_E;
  31197. }
  31198. }
  31199. #ifdef WC_RSA_PSS
  31200. if (ret == 0 && (dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS].tag != 0)) {
  31201. sigParams = GetASNItem_Addr(
  31202. dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
  31203. source);
  31204. sigParamsSz =
  31205. GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
  31206. source);
  31207. }
  31208. #endif
  31209. if (ret == 0) {
  31210. /* Get the signature OID and signature. */
  31211. resp->sigOID = dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID].data.oid.sum;
  31212. GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_SIGNATURE], &resp->sig,
  31213. &resp->sigSz);
  31214. }
  31215. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31216. if ((ret == 0) &&
  31217. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31218. /* TODO: support more than one certificate. */
  31219. /* Store reference to certificate BER data. */
  31220. GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ], &resp->cert,
  31221. &resp->certSz);
  31222. /* Allocate a certificate object to decode cert into. */
  31223. #ifdef WOLFSSL_SMALL_STACK
  31224. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), heap,
  31225. DYNAMIC_TYPE_TMP_BUFFER);
  31226. if (cert == NULL) {
  31227. ret = MEMORY_E;
  31228. }
  31229. }
  31230. if ((ret == 0) &&
  31231. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31232. #endif
  31233. /* Initialize the crtificate object. */
  31234. InitDecodedCert(cert, resp->cert, resp->certSz, heap);
  31235. certInit = 1;
  31236. /* Parse the certificate and don't verify if we don't have access to
  31237. * Cert Manager. */
  31238. ret = ParseCertRelative(cert, CERT_TYPE, noVerify ? NO_VERIFY : VERIFY,
  31239. cm);
  31240. if (ret < 0) {
  31241. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  31242. }
  31243. }
  31244. if ((ret == 0) &&
  31245. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31246. /* TODO: ConfirmSignature is blocking here */
  31247. /* Check the signature of the response. */
  31248. ret = ConfirmSignature(&cert->sigCtx, resp->response, resp->responseSz,
  31249. cert->publicKey, cert->pubKeySize, cert->keyOID, resp->sig,
  31250. resp->sigSz, resp->sigOID, NULL, 0, NULL);
  31251. if (ret != 0) {
  31252. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31253. ret = ASN_OCSP_CONFIRM_E;
  31254. }
  31255. }
  31256. if ((ret == 0) &&
  31257. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data == NULL))
  31258. #else
  31259. if (ret == 0)
  31260. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  31261. {
  31262. Signer* ca;
  31263. int sigValid = -1;
  31264. /* Response didn't have a certificate - lookup CA. */
  31265. #ifndef NO_SKID
  31266. ca = GetCA(cm, resp->single->issuerKeyHash);
  31267. #else
  31268. ca = GetCA(cm, resp->single->issuerHash);
  31269. #endif
  31270. if (ca) {
  31271. SignatureCtx sigCtx;
  31272. /* Initialize he signature context. */
  31273. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  31274. /* TODO: ConfirmSignature is blocking here */
  31275. /* Check the signature of the response CA public key. */
  31276. sigValid = ConfirmSignature(&sigCtx, resp->response,
  31277. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  31278. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31279. NULL);
  31280. }
  31281. if ((ca == NULL) || (sigValid != 0)) {
  31282. /* Didn't find certificate or signature verificate failed. */
  31283. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31284. ret = ASN_OCSP_CONFIRM_E;
  31285. }
  31286. }
  31287. if (ret == 0) {
  31288. /* Update the position to after response data. */
  31289. *ioIndex = idx;
  31290. }
  31291. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31292. if (certInit) {
  31293. FreeDecodedCert(cert);
  31294. }
  31295. #ifdef WOLFSSL_SMALL_STACK
  31296. if (cert != NULL) {
  31297. /* Dispose of certificate object. */
  31298. XFREE(cert, heap, DYNAMIC_TYPE_TMP_BUFFER);
  31299. }
  31300. #endif
  31301. #endif
  31302. FREE_ASNGETDATA(dataASN, heap);
  31303. return ret;
  31304. #endif /* WOLFSSL_ASN_TEMPLATE */
  31305. }
  31306. void InitOcspResponse(OcspResponse* resp, OcspEntry* single, CertStatus* status,
  31307. byte* source, word32 inSz, void* heap)
  31308. {
  31309. WOLFSSL_ENTER("InitOcspResponse");
  31310. XMEMSET(status, 0, sizeof(CertStatus));
  31311. XMEMSET(single, 0, sizeof(OcspEntry));
  31312. XMEMSET(resp, 0, sizeof(OcspResponse));
  31313. single->status = status;
  31314. resp->responseStatus = -1;
  31315. resp->single = single;
  31316. resp->source = source;
  31317. resp->maxIdx = inSz;
  31318. resp->heap = heap;
  31319. }
  31320. void FreeOcspResponse(OcspResponse* resp)
  31321. {
  31322. OcspEntry *single, *next;
  31323. if (resp != NULL) {
  31324. for (single = resp->single; single; single = next) {
  31325. next = single->next;
  31326. if (single->isDynamic) {
  31327. XFREE(single->status, resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  31328. XFREE(single, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  31329. }
  31330. }
  31331. }
  31332. }
  31333. #ifdef WOLFSSL_ASN_TEMPLATE
  31334. /* ASN.1 template for OCSPResponse.
  31335. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  31336. */
  31337. static const ASNItem ocspResponseASN[] = {
  31338. /* OCSPResponse ::= SEQUENCE */
  31339. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31340. /* responseStatus OCSPResponseStatus */
  31341. /* STATUS */ { 1, ASN_ENUMERATED, 0, 0, 0, },
  31342. /* responseBytes [0] EXPLICIT ResponseBytes OPTIONAL */
  31343. /* BYTES */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  31344. /* ResponseBytes ::= SEQUENCE */
  31345. /* BYTES_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  31346. /* responseType OBJECT IDENTIFIER */
  31347. /* BYTES_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  31348. /* response OCTET STRING */
  31349. /* BYTES_VAL */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  31350. };
  31351. enum {
  31352. OCSPRESPONSEASN_IDX_SEQ = 0,
  31353. OCSPRESPONSEASN_IDX_STATUS,
  31354. OCSPRESPONSEASN_IDX_BYTES,
  31355. OCSPRESPONSEASN_IDX_BYTES_SEQ,
  31356. OCSPRESPONSEASN_IDX_BYTES_TYPE,
  31357. OCSPRESPONSEASN_IDX_BYTES_VAL,
  31358. };
  31359. /* Number of items in ASN.1 template for OCSPResponse. */
  31360. #define ocspResponseASN_Length (sizeof(ocspResponseASN) / sizeof(ASNItem))
  31361. #endif /* WOLFSSL_ASN_TEMPLATE */
  31362. int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, int noVerify)
  31363. {
  31364. #ifndef WOLFSSL_ASN_TEMPLATE
  31365. int ret;
  31366. int length = 0;
  31367. word32 idx = 0;
  31368. byte* source = resp->source;
  31369. word32 size = resp->maxIdx;
  31370. word32 oid;
  31371. byte tag;
  31372. WOLFSSL_ENTER("OcspResponseDecode");
  31373. /* peel the outer SEQUENCE wrapper */
  31374. if (GetSequence(source, &idx, &length, size) < 0) {
  31375. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31376. return ASN_PARSE_E;
  31377. }
  31378. /* First get the responseStatus, an ENUMERATED */
  31379. if (GetEnumerated(source, &idx, &resp->responseStatus, size) < 0) {
  31380. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31381. return ASN_PARSE_E;
  31382. }
  31383. if (resp->responseStatus != OCSP_SUCCESSFUL) {
  31384. WOLFSSL_LEAVE("OcspResponseDecode", 0);
  31385. return 0;
  31386. }
  31387. /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
  31388. if (idx >= size) {
  31389. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31390. return ASN_PARSE_E;
  31391. }
  31392. if (GetASNTag(source, &idx, &tag, size) < 0) {
  31393. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31394. return ASN_PARSE_E;
  31395. }
  31396. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC)) {
  31397. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31398. return ASN_PARSE_E;
  31399. }
  31400. if (GetLength(source, &idx, &length, size) < 0) {
  31401. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31402. return ASN_PARSE_E;
  31403. }
  31404. /* Get the responseBytes SEQUENCE */
  31405. if (GetSequence(source, &idx, &length, size) < 0) {
  31406. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31407. return ASN_PARSE_E;
  31408. }
  31409. /* Check ObjectID for the resposeBytes */
  31410. if (GetObjectId(source, &idx, &oid, oidOcspType, size) < 0) {
  31411. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31412. return ASN_PARSE_E;
  31413. }
  31414. if (oid != OCSP_BASIC_OID) {
  31415. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31416. return ASN_PARSE_E;
  31417. }
  31418. ret = GetOctetString(source, &idx, &length, size);
  31419. if (ret < 0) {
  31420. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31421. return ret;
  31422. }
  31423. ret = DecodeBasicOcspResponse(source, &idx, resp, size, cm, heap, noVerify);
  31424. if (ret < 0) {
  31425. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31426. return ret;
  31427. }
  31428. WOLFSSL_LEAVE("OcspResponseDecode", 0);
  31429. return 0;
  31430. #else
  31431. DECL_ASNGETDATA(dataASN, ocspResponseASN_Length);
  31432. int ret = 0;
  31433. word32 idx = 0, size = resp->maxIdx;
  31434. byte* source = resp->source;
  31435. byte status;
  31436. byte* basic;
  31437. word32 basicSz;
  31438. WOLFSSL_ENTER("OcspResponseDecode");
  31439. CALLOC_ASNGETDATA(dataASN, ocspResponseASN_Length, ret, resp->heap);
  31440. if (ret == 0) {
  31441. /* Set variable to put status in and expect OCSP OID. */
  31442. GetASN_Int8Bit(&dataASN[OCSPRESPONSEASN_IDX_STATUS], &status);
  31443. GetASN_OID(&dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE], oidOcspType);
  31444. /* Decode OCSPResponse (and ResponseBytes). */
  31445. ret = GetASN_Items(ocspResponseASN, dataASN, ocspResponseASN_Length, 1,
  31446. source, &idx, size);
  31447. }
  31448. if (ret == 0) {
  31449. /* Get response. */
  31450. resp->responseStatus = status;
  31451. if (dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE].data.oid.sum
  31452. == OCSP_BASIC_OID) {
  31453. /* Get reference to BasicOCSPResponse. */
  31454. GetASN_GetRef(&dataASN[OCSPRESPONSEASN_IDX_BYTES_VAL], &basic,
  31455. &basicSz);
  31456. idx = 0;
  31457. /* Decode BasicOCSPResponse. */
  31458. ret = DecodeBasicOcspResponse(basic, &idx, resp, basicSz, cm, heap,
  31459. noVerify);
  31460. }
  31461. /* Only support BasicOCSPResponse. */
  31462. else {
  31463. ret = ASN_PARSE_E;
  31464. }
  31465. }
  31466. FREE_ASNGETDATA(dataASN, resp->heap);
  31467. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31468. return ret;
  31469. #endif /* WOLFSSL_ASN_TEMPLATE */
  31470. }
  31471. #ifdef WOLFSSL_ASN_TEMPLATE
  31472. /* ASN.1 template for OCSP nonce extension.
  31473. * RFC 6960, 4.4.1 - Nonce
  31474. * X.509: RFC 5280, 4.1 - Basic Certificate Fields. (Extension)
  31475. */
  31476. static const ASNItem ocspNonceExtASN[] = {
  31477. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31478. /* Extension */
  31479. /* EXT */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  31480. /* extnId */
  31481. /* EXT_OID */ {2, ASN_OBJECT_ID, 0, 0, 0 },
  31482. /* critical not encoded. */
  31483. /* extnValue */
  31484. /* EXT_VAL */ {2, ASN_OCTET_STRING, 0, 1, 0 },
  31485. /* nonce */
  31486. /* EXT_NONCE */ {3, ASN_OCTET_STRING, 0, 0, 0 },
  31487. };
  31488. enum {
  31489. OCSPNONCEEXTASN_IDX_SEQ = 0,
  31490. OCSPNONCEEXTASN_IDX_EXT,
  31491. OCSPNONCEEXTASN_IDX_EXT_OID,
  31492. OCSPNONCEEXTASN_IDX_EXT_VAL,
  31493. OCSPNONCEEXTASN_IDX_EXT_NONCE,
  31494. };
  31495. /* Number of items in ASN.1 template for OCSP nonce extension. */
  31496. #define ocspNonceExtASN_Length (sizeof(ocspNonceExtASN) / sizeof(ASNItem))
  31497. #endif /* WOLFSSL_ASN_TEMPLATE */
  31498. word32 EncodeOcspRequestExtensions(OcspRequest* req, byte* output, word32 size)
  31499. {
  31500. const byte NonceObjId[] = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07,
  31501. 0x30, 0x01, 0x02 };
  31502. #ifndef WOLFSSL_ASN_TEMPLATE
  31503. byte seqArray[5][MAX_SEQ_SZ];
  31504. word32 seqSz[5], totalSz = (word32)sizeof(NonceObjId);
  31505. WOLFSSL_ENTER("SetOcspReqExtensions");
  31506. if (!req || !output || !req->nonceSz)
  31507. return 0;
  31508. totalSz += req->nonceSz;
  31509. totalSz += seqSz[0] = SetOctetString(req->nonceSz, seqArray[0]);
  31510. totalSz += seqSz[1] = SetOctetString(req->nonceSz + seqSz[0], seqArray[1]);
  31511. totalSz += seqSz[2] = SetObjectId(sizeof(NonceObjId), seqArray[2]);
  31512. totalSz += seqSz[3] = SetSequence(totalSz, seqArray[3]);
  31513. totalSz += seqSz[4] = SetSequence(totalSz, seqArray[4]);
  31514. if (totalSz > size)
  31515. return 0;
  31516. totalSz = 0;
  31517. XMEMCPY(output + totalSz, seqArray[4], seqSz[4]);
  31518. totalSz += seqSz[4];
  31519. XMEMCPY(output + totalSz, seqArray[3], seqSz[3]);
  31520. totalSz += seqSz[3];
  31521. XMEMCPY(output + totalSz, seqArray[2], seqSz[2]);
  31522. totalSz += seqSz[2];
  31523. XMEMCPY(output + totalSz, NonceObjId, sizeof(NonceObjId));
  31524. totalSz += (word32)sizeof(NonceObjId);
  31525. XMEMCPY(output + totalSz, seqArray[1], seqSz[1]);
  31526. totalSz += seqSz[1];
  31527. XMEMCPY(output + totalSz, seqArray[0], seqSz[0]);
  31528. totalSz += seqSz[0];
  31529. XMEMCPY(output + totalSz, req->nonce, req->nonceSz);
  31530. totalSz += req->nonceSz;
  31531. return totalSz;
  31532. #else
  31533. int ret = 0;
  31534. WOLFSSL_ENTER("SetOcspReqExtensions");
  31535. /* Check request has nonce to write in extension. */
  31536. if (req != NULL && req->nonceSz != 0) {
  31537. DECL_ASNSETDATA(dataASN, ocspNonceExtASN_Length);
  31538. int sz;
  31539. CALLOC_ASNSETDATA(dataASN, ocspNonceExtASN_Length, ret, req->heap);
  31540. /* Set nonce extension OID and nonce. */
  31541. SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_OID], NonceObjId,
  31542. sizeof(NonceObjId));
  31543. SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_NONCE], req->nonce,
  31544. req->nonceSz);
  31545. /* Calculate size of nonce extension. */
  31546. ret = SizeASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
  31547. &sz);
  31548. /* Check buffer big enough for encoding if supplied. */
  31549. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  31550. ret = BUFFER_E;
  31551. }
  31552. if ((ret == 0) && (output != NULL)) {
  31553. /* Encode nonce extension. */
  31554. SetASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
  31555. output);
  31556. }
  31557. if (ret == 0) {
  31558. /* Return size of encoding. */
  31559. ret = sz;
  31560. }
  31561. FREE_ASNSETDATA(dataASN, req->heap);
  31562. }
  31563. return ret;
  31564. #endif /* WOLFSSL_ASN_TEMPLATE */
  31565. }
  31566. #ifdef WOLFSSL_ASN_TEMPLATE
  31567. /* ASN.1 template for OCSPRequest.
  31568. * RFC 6960, 4.1.1 - ASN.1 Specification of the OCSP Request
  31569. */
  31570. static const ASNItem ocspRequestASN[] = {
  31571. /* OCSPRequest */
  31572. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31573. /* tbsRequest */
  31574. /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  31575. /* version not written - v1 */
  31576. /* requestorName not written */
  31577. /* requestList */
  31578. /* TBS_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  31579. /* Request */
  31580. /* TBS_LIST */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  31581. /* reqCert */
  31582. /* TBS_REQ_CID */ { 4, ASN_SEQUENCE, 1, 1, 0 },
  31583. /* hashAlgorithm */
  31584. /* TBS_REQ_HASH */ { 5, ASN_SEQUENCE, 1, 1, 0 },
  31585. /* TBS_REQ_HASH_OID */ { 6, ASN_OBJECT_ID, 0, 0, 0 },
  31586. /* issuerNameHash */
  31587. /* TBS_REQ_ISSUER */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  31588. /* issuerKeyHash */
  31589. /* TBS_REQ_ISSUERKEY */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  31590. /* serialNumber */
  31591. /* TBS_REQ_SERIAL */ { 5, ASN_INTEGER, 0, 0, 0 },
  31592. /* requestExtensions */
  31593. /* TBS_REQEXT */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 0 },
  31594. /* optionalSignature not written. */
  31595. };
  31596. enum {
  31597. OCSPREQUESTASN_IDX_SEQ = 0,
  31598. OCSPREQUESTASN_IDX_TBS,
  31599. OCSPREQUESTASN_IDX_TBS_SEQ,
  31600. OCSPREQUESTASN_IDX_TBS_LIST,
  31601. OCSPREQUESTASN_IDX_TBS_REQ_CID,
  31602. OCSPREQUESTASN_IDX_TBS_REQ_HASH,
  31603. OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID,
  31604. OCSPREQUESTASN_IDX_TBS_REQ_ISSUER,
  31605. OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY,
  31606. OCSPREQUESTASN_IDX_TBS_REQ_SERIAL,
  31607. OCSPREQUESTASN_IDX_TBS_REQEXT,
  31608. };
  31609. /* Number of items in ASN.1 template for OCSPRequest. */
  31610. #define ocspRequestASN_Length (sizeof(ocspRequestASN) / sizeof(ASNItem))
  31611. #endif
  31612. int EncodeOcspRequest(OcspRequest* req, byte* output, word32 size)
  31613. {
  31614. #ifndef WOLFSSL_ASN_TEMPLATE
  31615. byte seqArray[5][MAX_SEQ_SZ];
  31616. /* The ASN.1 of the OCSP Request is an onion of sequences */
  31617. byte algoArray[MAX_ALGO_SZ];
  31618. byte issuerArray[MAX_ENCODED_DIG_SZ];
  31619. byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
  31620. byte snArray[MAX_SN_SZ];
  31621. byte extArray[MAX_OCSP_EXT_SZ];
  31622. word32 seqSz[5], algoSz, issuerSz, issuerKeySz, extSz, totalSz;
  31623. int i, snSz;
  31624. WOLFSSL_ENTER("EncodeOcspRequest");
  31625. #ifdef NO_SHA
  31626. algoSz = SetAlgoID(SHA256h, algoArray, oidHashType, 0);
  31627. #else
  31628. algoSz = SetAlgoID(SHAh, algoArray, oidHashType, 0);
  31629. #endif
  31630. issuerSz = SetDigest(req->issuerHash, KEYID_SIZE, issuerArray);
  31631. issuerKeySz = SetDigest(req->issuerKeyHash, KEYID_SIZE, issuerKeyArray);
  31632. snSz = SetSerialNumber(req->serial, req->serialSz, snArray,
  31633. MAX_SN_SZ, MAX_SN_SZ);
  31634. extSz = 0;
  31635. if (snSz < 0)
  31636. return snSz;
  31637. if (req->nonceSz) {
  31638. /* TLS Extensions use this function too - put extensions after
  31639. * ASN.1: Context Specific [2].
  31640. */
  31641. extSz = EncodeOcspRequestExtensions(req, extArray + 2,
  31642. OCSP_NONCE_EXT_SZ);
  31643. extSz += SetExplicit(2, extSz, extArray);
  31644. }
  31645. totalSz = algoSz + issuerSz + issuerKeySz + snSz;
  31646. for (i = 4; i >= 0; i--) {
  31647. seqSz[i] = SetSequence(totalSz, seqArray[i]);
  31648. totalSz += seqSz[i];
  31649. if (i == 2) totalSz += extSz;
  31650. }
  31651. if (output == NULL)
  31652. return totalSz;
  31653. if (totalSz > size)
  31654. return BUFFER_E;
  31655. totalSz = 0;
  31656. for (i = 0; i < 5; i++) {
  31657. XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
  31658. totalSz += seqSz[i];
  31659. }
  31660. XMEMCPY(output + totalSz, algoArray, algoSz);
  31661. totalSz += algoSz;
  31662. XMEMCPY(output + totalSz, issuerArray, issuerSz);
  31663. totalSz += issuerSz;
  31664. XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
  31665. totalSz += issuerKeySz;
  31666. XMEMCPY(output + totalSz, snArray, snSz);
  31667. totalSz += snSz;
  31668. if (extSz != 0) {
  31669. XMEMCPY(output + totalSz, extArray, extSz);
  31670. totalSz += extSz;
  31671. }
  31672. return totalSz;
  31673. #else
  31674. DECL_ASNSETDATA(dataASN, ocspRequestASN_Length);
  31675. word32 extSz = 0;
  31676. int sz = 0;
  31677. int ret = 0;
  31678. WOLFSSL_ENTER("EncodeOcspRequest");
  31679. CALLOC_ASNSETDATA(dataASN, ocspRequestASN_Length, ret, req->heap);
  31680. if (ret == 0) {
  31681. /* Set OID of hash algorithm use on issuer and key. */
  31682. #ifdef NO_SHA
  31683. SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHA256h,
  31684. oidHashType);
  31685. #else
  31686. SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHAh,
  31687. oidHashType);
  31688. #endif
  31689. /* Set issuer, issuer key hash and serial number of certificate being
  31690. * checked. */
  31691. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUER],
  31692. req->issuerHash, KEYID_SIZE);
  31693. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY],
  31694. req->issuerKeyHash, KEYID_SIZE);
  31695. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_SERIAL],
  31696. req->serial, req->serialSz);
  31697. /* Only extension to write is nonce - check if one to encode. */
  31698. if (req->nonceSz) {
  31699. /* Get size of extensions and leave space for them in encoding. */
  31700. ret = extSz = EncodeOcspRequestExtensions(req, NULL, 0);
  31701. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT], NULL, extSz);
  31702. if (ret > 0) {
  31703. ret = 0;
  31704. }
  31705. }
  31706. else {
  31707. /* Don't write out extensions. */
  31708. dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].noOut = 1;
  31709. }
  31710. }
  31711. if (ret == 0) {
  31712. /* Calculate size of encoding. */
  31713. ret = SizeASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length,
  31714. &sz);
  31715. }
  31716. /* Check buffer big enough for encoding if supplied. */
  31717. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  31718. ret = BUFFER_E;
  31719. }
  31720. if ((ret == 0) && (output != NULL)) {
  31721. /* Encode OCSPRequest. */
  31722. SetASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length, output);
  31723. if (req->nonceSz) {
  31724. /* Encode extensions into space provided. */
  31725. ret = EncodeOcspRequestExtensions(req,
  31726. (byte*)dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].data.buffer.data,
  31727. extSz);
  31728. if (ret > 0) {
  31729. ret = 0;
  31730. }
  31731. }
  31732. }
  31733. if (ret == 0) {
  31734. /* Return size of encoding. */
  31735. ret = sz;
  31736. }
  31737. FREE_ASNSETDATA(dataASN, req->heap);
  31738. return ret;
  31739. #endif /* WOLFSSL_ASN_TEMPLATE */
  31740. }
  31741. int InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce,
  31742. void* heap)
  31743. {
  31744. int ret;
  31745. WOLFSSL_ENTER("InitOcspRequest");
  31746. if (req == NULL)
  31747. return BAD_FUNC_ARG;
  31748. XMEMSET(req, 0, sizeof(OcspRequest));
  31749. req->heap = heap;
  31750. if (cert) {
  31751. XMEMCPY(req->issuerHash, cert->issuerHash, KEYID_SIZE);
  31752. XMEMCPY(req->issuerKeyHash, cert->issuerKeyHash, KEYID_SIZE);
  31753. req->serial = (byte*)XMALLOC(cert->serialSz, req->heap,
  31754. DYNAMIC_TYPE_OCSP_REQUEST);
  31755. if (req->serial == NULL)
  31756. return MEMORY_E;
  31757. XMEMCPY(req->serial, cert->serial, cert->serialSz);
  31758. req->serialSz = cert->serialSz;
  31759. if (cert->extAuthInfoSz != 0 && cert->extAuthInfo != NULL) {
  31760. req->url = (byte*)XMALLOC(cert->extAuthInfoSz + 1, req->heap,
  31761. DYNAMIC_TYPE_OCSP_REQUEST);
  31762. if (req->url == NULL) {
  31763. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP);
  31764. req->serial = NULL;
  31765. return MEMORY_E;
  31766. }
  31767. XMEMCPY(req->url, cert->extAuthInfo, cert->extAuthInfoSz);
  31768. req->urlSz = cert->extAuthInfoSz;
  31769. req->url[req->urlSz] = 0;
  31770. }
  31771. }
  31772. if (useNonce) {
  31773. WC_RNG rng;
  31774. #ifndef HAVE_FIPS
  31775. ret = wc_InitRng_ex(&rng, req->heap, INVALID_DEVID);
  31776. #else
  31777. ret = wc_InitRng(&rng);
  31778. #endif
  31779. if (ret != 0) {
  31780. WOLFSSL_MSG("\tCannot initialize RNG. Skipping the OCSP Nonce.");
  31781. } else {
  31782. if (wc_RNG_GenerateBlock(&rng, req->nonce, MAX_OCSP_NONCE_SZ) != 0)
  31783. WOLFSSL_MSG("\tCannot run RNG. Skipping the OCSP Nonce.");
  31784. else
  31785. req->nonceSz = MAX_OCSP_NONCE_SZ;
  31786. wc_FreeRng(&rng);
  31787. }
  31788. }
  31789. return 0;
  31790. }
  31791. void FreeOcspRequest(OcspRequest* req)
  31792. {
  31793. WOLFSSL_ENTER("FreeOcspRequest");
  31794. if (req) {
  31795. if (req->serial)
  31796. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  31797. req->serial = NULL;
  31798. #ifdef OPENSSL_EXTRA
  31799. if (req->serialInt) {
  31800. if (req->serialInt->isDynamic) {
  31801. XFREE(req->serialInt->data, NULL, DYNAMIC_TYPE_OPENSSL);
  31802. }
  31803. XFREE(req->serialInt, NULL, DYNAMIC_TYPE_OPENSSL);
  31804. }
  31805. req->serialInt = NULL;
  31806. #endif
  31807. if (req->url)
  31808. XFREE(req->url, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  31809. req->url = NULL;
  31810. }
  31811. }
  31812. int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
  31813. {
  31814. int cmp = -1; /* default as not matching, cmp gets set on each check */
  31815. OcspEntry *single, *next, *prev = NULL, *top;
  31816. WOLFSSL_ENTER("CompareOcspReqResp");
  31817. if (req == NULL) {
  31818. WOLFSSL_MSG("\tReq missing");
  31819. return -1;
  31820. }
  31821. if (resp == NULL || resp->single == NULL) {
  31822. WOLFSSL_MSG("\tResp missing");
  31823. return 1;
  31824. }
  31825. /* Nonces are not critical. The responder may not necessarily add
  31826. * the nonce to the response. */
  31827. if (req->nonceSz && resp->nonce != NULL
  31828. #ifndef WOLFSSL_FORCE_OCSP_NONCE_CHECK
  31829. && resp->nonceSz != 0
  31830. #endif
  31831. ) {
  31832. cmp = req->nonceSz - resp->nonceSz;
  31833. if (cmp != 0) {
  31834. WOLFSSL_MSG("\tnonceSz mismatch");
  31835. return cmp;
  31836. }
  31837. cmp = XMEMCMP(req->nonce, resp->nonce, req->nonceSz);
  31838. if (cmp != 0) {
  31839. WOLFSSL_MSG("\tnonce mismatch");
  31840. return cmp;
  31841. }
  31842. }
  31843. /* match based on found status and return */
  31844. for (single = resp->single; single; single = next) {
  31845. cmp = req->serialSz - single->status->serialSz;
  31846. if (cmp == 0) {
  31847. cmp = XMEMCMP(req->serial, single->status->serial, req->serialSz)
  31848. || XMEMCMP(req->issuerHash, single->issuerHash, OCSP_DIGEST_SIZE)
  31849. || XMEMCMP(req->issuerKeyHash, single->issuerKeyHash, OCSP_DIGEST_SIZE);
  31850. if (cmp == 0) {
  31851. /* match found */
  31852. if (resp->single != single && prev) {
  31853. /* move to top of list */
  31854. top = resp->single;
  31855. resp->single = single;
  31856. prev->next = single->next;
  31857. single->next = top;
  31858. }
  31859. break;
  31860. }
  31861. }
  31862. next = single->next;
  31863. prev = single;
  31864. }
  31865. if (cmp != 0) {
  31866. WOLFSSL_MSG("\trequest and response mismatch");
  31867. return cmp;
  31868. }
  31869. return 0;
  31870. }
  31871. #endif /* HAVE_OCSP */
  31872. #ifdef WOLFSSL_ASN_TEMPLATE
  31873. /* ASN.1 template for certificate name hash. */
  31874. static const ASNItem nameHashASN[] = {
  31875. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  31876. /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  31877. };
  31878. enum {
  31879. NAMEHASHASN_IDX_OID = 0,
  31880. NAMEHASHASN_IDX_NAME
  31881. };
  31882. /* Number of items in ASN.1 template for certificate name hash. */
  31883. #define nameHashASN_Length (sizeof(nameHashASN) / sizeof(ASNItem))
  31884. #endif /* WOLFSSL_ASN_TEMPLATE */
  31885. /* store WC_SHA hash of NAME */
  31886. int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx)
  31887. {
  31888. #ifndef WOLFSSL_ASN_TEMPLATE
  31889. int length; /* length of all distinguished names */
  31890. int ret;
  31891. word32 dummy;
  31892. byte tag;
  31893. WOLFSSL_ENTER("GetNameHash");
  31894. dummy = *idx;
  31895. if (GetASNTag(source, &dummy, &tag, (word32)maxIdx) == 0 &&
  31896. tag == ASN_OBJECT_ID) {
  31897. WOLFSSL_MSG("Trying optional prefix...");
  31898. if (GetLength(source, idx, &length, (word32)maxIdx) < 0)
  31899. return ASN_PARSE_E;
  31900. *idx += (word32)length;
  31901. WOLFSSL_MSG("Got optional prefix");
  31902. }
  31903. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  31904. * calculated over the entire DER encoding of the Name field, including
  31905. * the tag and length. */
  31906. dummy = *idx;
  31907. if (GetSequence(source, idx, &length, (word32)maxIdx) < 0)
  31908. return ASN_PARSE_E;
  31909. ret = CalcHashId(source + dummy, (word32)length + *idx - dummy, hash);
  31910. *idx += (word32)length;
  31911. return ret;
  31912. #else
  31913. ASNGetData dataASN[nameHashASN_Length];
  31914. int ret;
  31915. XMEMSET(dataASN, 0, sizeof(dataASN));
  31916. /* Ignore the OID even when present. */
  31917. GetASN_OID(&dataASN[NAMEHASHASN_IDX_OID], oidIgnoreType);
  31918. /* Decode certificate name. */
  31919. ret = GetASN_Items(nameHashASN, dataASN, nameHashASN_Length, 0, source, idx,
  31920. (word32)maxIdx);
  31921. if (ret == 0) {
  31922. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  31923. * calculated over the entire DER encoding of the Name field, including
  31924. * the tag and length. */
  31925. /* Calculate hash of complete name including SEQUENCE. */
  31926. ret = CalcHashId(
  31927. GetASNItem_Addr(dataASN[NAMEHASHASN_IDX_NAME], source),
  31928. GetASNItem_Length(dataASN[NAMEHASHASN_IDX_NAME], source),
  31929. hash);
  31930. }
  31931. return ret;
  31932. #endif /* WOLFSSL_ASN_TEMPLATE */
  31933. }
  31934. #if defined(HAVE_CRL) && !defined(WOLFCRYPT_ONLY)
  31935. #ifdef OPENSSL_EXTRA
  31936. static char* GetNameFromDer(const byte* source, int sz)
  31937. {
  31938. char* out;
  31939. out = (char*)XMALLOC(sz, NULL, DYNAMIC_TYPE_OPENSSL);
  31940. if (out == NULL) {
  31941. WOLFSSL_MSG("Name malloc failed");
  31942. return NULL;
  31943. }
  31944. XMEMCPY(out, source, sz);
  31945. return out;
  31946. }
  31947. #endif
  31948. /* initialize decoded CRL */
  31949. void InitDecodedCRL(DecodedCRL* dcrl, void* heap)
  31950. {
  31951. WOLFSSL_MSG("InitDecodedCRL");
  31952. XMEMSET(dcrl, 0, sizeof(DecodedCRL));
  31953. dcrl->heap = heap;
  31954. #ifdef WOLFSSL_HEAP_TEST
  31955. dcrl->heap = (void*)WOLFSSL_HEAP_TEST;
  31956. #endif
  31957. }
  31958. /* free decoded CRL resources */
  31959. void FreeDecodedCRL(DecodedCRL* dcrl)
  31960. {
  31961. RevokedCert* tmp = dcrl->certs;
  31962. WOLFSSL_MSG("FreeDecodedCRL");
  31963. while(tmp) {
  31964. RevokedCert* next = tmp->next;
  31965. XFREE(tmp, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  31966. tmp = next;
  31967. }
  31968. #ifdef OPENSSL_EXTRA
  31969. if (dcrl->issuer != NULL)
  31970. XFREE(dcrl->issuer, NULL, DYNAMIC_TYPE_OPENSSL);
  31971. #endif
  31972. }
  31973. #ifdef WOLFSSL_ASN_TEMPLATE
  31974. /* ASN.1 template for revoked certificates.
  31975. * X.509: RFC 5280, 5.1 - CRL Fields
  31976. */
  31977. static const ASNItem revokedASN[] = {
  31978. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31979. /* userCertificate CertificateSerialNumber */
  31980. /* CERT */ { 1, ASN_INTEGER, 0, 0, 0 },
  31981. /* revocationDate Time */
  31982. /* TIME_UTC */ { 1, ASN_UTC_TIME, 0, 0, 2 },
  31983. /* TIME_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 2 },
  31984. /* crlEntryExensions Extensions */
  31985. /* TIME_EXT */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  31986. };
  31987. enum {
  31988. REVOKEDASN_IDX_SEQ = 0,
  31989. REVOKEDASN_IDX_CERT,
  31990. REVOKEDASN_IDX_TIME_UTC,
  31991. REVOKEDASN_IDX_TIME_GT,
  31992. REVOKEDASN_IDX_TIME_EXT,
  31993. };
  31994. /* Number of items in ASN.1 template for revoked certificates. */
  31995. #define revokedASN_Length (sizeof(revokedASN) / sizeof(ASNItem))
  31996. #endif
  31997. /* Get Revoked Cert list, 0 on success */
  31998. static int GetRevoked(RevokedCert* rcert, const byte* buff, word32* idx,
  31999. DecodedCRL* dcrl, int maxIdx)
  32000. {
  32001. #ifndef WOLFSSL_ASN_TEMPLATE
  32002. int ret;
  32003. int len;
  32004. word32 end;
  32005. RevokedCert* rc;
  32006. #ifdef CRL_STATIC_REVOKED_LIST
  32007. int totalCerts = 0;
  32008. #endif
  32009. WOLFSSL_ENTER("GetRevoked");
  32010. if (GetSequence(buff, idx, &len, maxIdx) < 0)
  32011. return ASN_PARSE_E;
  32012. end = *idx + len;
  32013. #ifdef CRL_STATIC_REVOKED_LIST
  32014. totalCerts = dcrl->totalCerts;
  32015. if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
  32016. return MEMORY_E;
  32017. }
  32018. rc = &rcert[totalCerts];
  32019. ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
  32020. if (ret < 0) {
  32021. WOLFSSL_MSG("wc_GetSerialNumber error");
  32022. return ret;
  32023. }
  32024. #else
  32025. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  32026. DYNAMIC_TYPE_REVOKED);
  32027. if (rc == NULL) {
  32028. WOLFSSL_MSG("Alloc Revoked Cert failed");
  32029. return MEMORY_E;
  32030. }
  32031. ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
  32032. if (ret < 0) {
  32033. WOLFSSL_MSG("wc_GetSerialNumber error");
  32034. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  32035. return ret;
  32036. }
  32037. /* add to list */
  32038. rc->next = dcrl->certs;
  32039. dcrl->certs = rc;
  32040. (void)rcert;
  32041. #endif /* CRL_STATIC_REVOKED_LIST */
  32042. dcrl->totalCerts++;
  32043. /* get date */
  32044. #ifndef NO_ASN_TIME
  32045. ret = GetBasicDate(buff, idx, rc->revDate, &rc->revDateFormat, maxIdx);
  32046. if (ret < 0) {
  32047. WOLFSSL_MSG("Expecting Date");
  32048. return ret;
  32049. }
  32050. #endif
  32051. /* skip extensions */
  32052. *idx = end;
  32053. return 0;
  32054. #else
  32055. DECL_ASNGETDATA(dataASN, revokedASN_Length);
  32056. int ret = 0;
  32057. word32 serialSz = EXTERNAL_SERIAL_SIZE;
  32058. word32 revDateSz = MAX_DATE_SIZE;
  32059. RevokedCert* rc;
  32060. #ifdef CRL_STATIC_REVOKED_LIST
  32061. int totalCerts = dcrl->totalCerts;
  32062. if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
  32063. return MEMORY_E;
  32064. }
  32065. rc = &rcert[totalCerts];
  32066. #else
  32067. /* Allocate a new revoked certificate object. */
  32068. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  32069. DYNAMIC_TYPE_CRL);
  32070. if (rc == NULL) {
  32071. ret = MEMORY_E;
  32072. }
  32073. #endif /* CRL_STATIC_REVOKED_LIST */
  32074. CALLOC_ASNGETDATA(dataASN, revokedASN_Length, ret, dcrl->heap);
  32075. if (ret == 0) {
  32076. /* Set buffer to place serial number into. */
  32077. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_CERT], rc->serialNumber,
  32078. &serialSz);
  32079. /* Set buffer to store revocation date. */
  32080. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_UTC], rc->revDate,
  32081. &revDateSz);
  32082. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_GT], rc->revDate,
  32083. &revDateSz);
  32084. /* Decode the Revoked */
  32085. ret = GetASN_Items(revokedASN, dataASN, revokedASN_Length, 1, buff, idx,
  32086. maxIdx);
  32087. }
  32088. if (ret == 0) {
  32089. /* Store size of serial number. */
  32090. rc->serialSz = serialSz;
  32091. rc->revDateFormat = (dataASN[REVOKEDASN_IDX_TIME_UTC].tag != 0)
  32092. ? dataASN[REVOKEDASN_IDX_TIME_UTC].tag
  32093. : dataASN[REVOKEDASN_IDX_TIME_GT].tag;
  32094. /* TODO: use extensions, only v2 */
  32095. /* Add revoked certificate to chain. */
  32096. #ifndef CRL_STATIC_REVOKED_LIST
  32097. rc->next = dcrl->certs;
  32098. dcrl->certs = rc;
  32099. #endif
  32100. dcrl->totalCerts++;
  32101. }
  32102. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32103. #ifndef CRL_STATIC_REVOKED_LIST
  32104. if ((ret != 0) && (rc != NULL)) {
  32105. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_CRL);
  32106. }
  32107. (void)rcert;
  32108. #endif
  32109. return ret;
  32110. #endif /* WOLFSSL_ASN_TEMPLATE */
  32111. }
  32112. #ifdef WOLFSSL_ASN_TEMPLATE
  32113. /* Parse the revoked certificates of a CRL.
  32114. *
  32115. * @param [in] dcrl Decoded CRL object.
  32116. * @param [in] buff Buffer holding CRL.
  32117. * @param [in] idx Index into buffer of revoked certificates.
  32118. * @param [in] maxIdx Maximum index of revoked cartificates data.
  32119. * @return 0 on success.
  32120. * @return ASN_PARSE_E on failure.
  32121. */
  32122. static int ParseCRL_RevokedCerts(RevokedCert* rcert, DecodedCRL* dcrl,
  32123. const byte* buff, word32 idx, word32 maxIdx)
  32124. {
  32125. int ret = 0;
  32126. /* Parse each revoked certificate. */
  32127. while ((ret == 0) && (idx < maxIdx)) {
  32128. /* Parse a revoked certificate. */
  32129. if (GetRevoked(rcert, buff, &idx, dcrl, maxIdx) < 0) {
  32130. ret = ASN_PARSE_E;
  32131. }
  32132. }
  32133. return ret;
  32134. }
  32135. #endif /* WOLFSSL_ASN_TEMPLATE */
  32136. #ifndef WOLFSSL_ASN_TEMPLATE
  32137. /* Get CRL Signature, 0 on success */
  32138. static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
  32139. int maxIdx)
  32140. {
  32141. int length;
  32142. int ret;
  32143. WOLFSSL_ENTER("GetCRL_Signature");
  32144. ret = CheckBitString(source, idx, &length, maxIdx, 1, NULL);
  32145. if (ret != 0)
  32146. return ret;
  32147. dcrl->sigLength = length;
  32148. dcrl->signature = (byte*)&source[*idx];
  32149. *idx += dcrl->sigLength;
  32150. return 0;
  32151. }
  32152. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32153. int VerifyCRL_Signature(SignatureCtx* sigCtx, const byte* toBeSigned,
  32154. word32 tbsSz, const byte* signature, word32 sigSz,
  32155. word32 signatureOID, Signer *ca, void* heap)
  32156. {
  32157. /* try to confirm/verify signature */
  32158. #ifndef IGNORE_KEY_EXTENSIONS
  32159. if ((ca->keyUsage & KEYUSE_CRL_SIGN) == 0) {
  32160. WOLFSSL_MSG("CA cannot sign CRLs");
  32161. WOLFSSL_ERROR_VERBOSE(ASN_CRL_NO_SIGNER_E);
  32162. return ASN_CRL_NO_SIGNER_E;
  32163. }
  32164. #endif /* IGNORE_KEY_EXTENSIONS */
  32165. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  32166. if (ConfirmSignature(sigCtx, toBeSigned, tbsSz, ca->publicKey,
  32167. ca->pubKeySize, ca->keyOID, signature, sigSz,
  32168. signatureOID, NULL, 0, NULL) != 0) {
  32169. WOLFSSL_MSG("CRL Confirm signature failed");
  32170. WOLFSSL_ERROR_VERBOSE(ASN_CRL_CONFIRM_E);
  32171. return ASN_CRL_CONFIRM_E;
  32172. }
  32173. return 0;
  32174. }
  32175. #ifdef WOLFSSL_ASN_TEMPLATE
  32176. /* Find the signer for the CRL and verify the signature.
  32177. *
  32178. * @param [in] dcrl Decoded CRL object.
  32179. * @param [in] buff Buffer holding CRL.
  32180. * @param [in] cm Certificate manager object.
  32181. * @return 0 on success.
  32182. * @return ASN_CRL_NO_SIGNER_E when no signer found.
  32183. * @return ASN_CRL_CONFIRM_E when signature did not verify.
  32184. */
  32185. static int PaseCRL_CheckSignature(DecodedCRL* dcrl, const byte* buff, void* cm)
  32186. {
  32187. int ret = 0;
  32188. Signer* ca = NULL;
  32189. SignatureCtx sigCtx;
  32190. /* OpenSSL doesn't add skid by default for CRLs cause firefox chokes.
  32191. * If experiencing issues uncomment NO_SKID define in CRL section of
  32192. * wolfssl/wolfcrypt/settings.h */
  32193. #ifndef NO_SKID
  32194. if (dcrl->extAuthKeyIdSet) {
  32195. /* more unique than issuerHash */
  32196. ca = GetCA(cm, dcrl->extAuthKeyId);
  32197. }
  32198. /* Check issuerHash matched CA's subjectNameHash. */
  32199. if ((ca != NULL) && (XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  32200. KEYID_SIZE) != 0)) {
  32201. ca = NULL;
  32202. }
  32203. if (ca == NULL) {
  32204. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  32205. /* If AKID is available then this CA doesn't have the public
  32206. * key required */
  32207. if (ca && dcrl->extAuthKeyIdSet) {
  32208. WOLFSSL_MSG("CA SKID doesn't match AKID");
  32209. ca = NULL;
  32210. }
  32211. }
  32212. #else
  32213. ca = GetCA(cm, dcrl->issuerHash);
  32214. #endif /* !NO_SKID */
  32215. WOLFSSL_MSG("About to verify CRL signature");
  32216. if (ca == NULL) {
  32217. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  32218. ret = ASN_CRL_NO_SIGNER_E;
  32219. WOLFSSL_ERROR_VERBOSE(ret);
  32220. }
  32221. if (ret == 0) {
  32222. WOLFSSL_MSG("Found CRL issuer CA");
  32223. /* Verify CRL signature with CA. */
  32224. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  32225. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  32226. dcrl->signatureOID, ca, dcrl->heap);
  32227. }
  32228. return ret;
  32229. }
  32230. #endif
  32231. #ifndef WOLFSSL_ASN_TEMPLATE
  32232. static int ParseCRL_CertList(RevokedCert* rcert, DecodedCRL* dcrl,
  32233. const byte* buf,word32* inOutIdx, int sz, int verify)
  32234. {
  32235. word32 oid, dateIdx, idx, checkIdx;
  32236. int length;
  32237. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  32238. int doNextDate = 1;
  32239. #endif
  32240. byte tag;
  32241. if (dcrl == NULL || inOutIdx == NULL || buf == NULL) {
  32242. return BAD_FUNC_ARG;
  32243. }
  32244. /* may have version */
  32245. idx = *inOutIdx;
  32246. checkIdx = idx;
  32247. if (GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag == ASN_INTEGER) {
  32248. if (GetMyVersion(buf, &idx, &dcrl->version, sz) < 0)
  32249. return ASN_PARSE_E;
  32250. dcrl->version++;
  32251. }
  32252. if (GetAlgoId(buf, &idx, &oid, oidIgnoreType, sz) < 0)
  32253. return ASN_PARSE_E;
  32254. checkIdx = idx;
  32255. if (GetSequence(buf, &checkIdx, &length, sz) < 0) {
  32256. return ASN_PARSE_E;
  32257. }
  32258. #ifdef OPENSSL_EXTRA
  32259. dcrl->issuerSz = length + (checkIdx - idx);
  32260. dcrl->issuer = (byte*)GetNameFromDer(buf + idx, (int)dcrl->issuerSz);
  32261. #endif
  32262. if (GetNameHash(buf, &idx, dcrl->issuerHash, sz) < 0)
  32263. return ASN_PARSE_E;
  32264. if (GetBasicDate(buf, &idx, dcrl->lastDate, &dcrl->lastDateFormat, sz) < 0)
  32265. return ASN_PARSE_E;
  32266. dateIdx = idx;
  32267. if (GetBasicDate(buf, &idx, dcrl->nextDate, &dcrl->nextDateFormat, sz) < 0)
  32268. {
  32269. #ifndef WOLFSSL_NO_CRL_NEXT_DATE
  32270. (void)dateIdx;
  32271. return ASN_PARSE_E;
  32272. #else
  32273. dcrl->nextDateFormat = ASN_OTHER_TYPE; /* skip flag */
  32274. doNextDate = 0;
  32275. idx = dateIdx;
  32276. #endif
  32277. }
  32278. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  32279. if (doNextDate)
  32280. #endif
  32281. {
  32282. #ifndef NO_ASN_TIME
  32283. if (verify != NO_VERIFY &&
  32284. !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  32285. WOLFSSL_MSG("CRL after date is no longer valid");
  32286. WOLFSSL_ERROR_VERBOSE(CRL_CERT_DATE_ERR);
  32287. return CRL_CERT_DATE_ERR;
  32288. }
  32289. #else
  32290. (void)verify;
  32291. #endif
  32292. }
  32293. checkIdx = idx;
  32294. if (idx != dcrl->sigIndex &&
  32295. GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag != CRL_EXTENSIONS) {
  32296. int len;
  32297. if (GetSequence(buf, &idx, &len, sz) < 0)
  32298. return ASN_PARSE_E;
  32299. len += idx;
  32300. while (idx < (word32)len) {
  32301. if (GetRevoked(rcert, buf, &idx, dcrl, len) < 0)
  32302. return ASN_PARSE_E;
  32303. }
  32304. }
  32305. *inOutIdx = idx;
  32306. return 0;
  32307. }
  32308. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32309. #ifndef NO_SKID
  32310. static int ParseCRL_AuthKeyIdExt(const byte* input, int sz, DecodedCRL* dcrl)
  32311. {
  32312. #ifndef WOLFSSL_ASN_TEMPLATE
  32313. word32 idx = 0;
  32314. int length = 0, ret = 0;
  32315. byte tag;
  32316. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  32317. if (GetSequence(input, &idx, &length, sz) < 0) {
  32318. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  32319. return ASN_PARSE_E;
  32320. }
  32321. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  32322. return ASN_PARSE_E;
  32323. }
  32324. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  32325. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  32326. return 0;
  32327. }
  32328. if (GetLength(input, &idx, &length, sz) <= 0) {
  32329. WOLFSSL_MSG("\tfail: extension data length");
  32330. return ASN_PARSE_E;
  32331. }
  32332. dcrl->extAuthKeyIdSet = 1;
  32333. /* Get the hash or hash of the hash if wrong size. */
  32334. ret = GetHashId(input + idx, length, dcrl->extAuthKeyId);
  32335. return ret;
  32336. #else
  32337. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  32338. int ret = 0;
  32339. word32 idx = 0;
  32340. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  32341. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, dcrl->heap);
  32342. if (ret == 0) {
  32343. /* Parse an authority key identifier. */
  32344. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  32345. &idx, sz);
  32346. }
  32347. if (ret == 0) {
  32348. /* Key id is optional. */
  32349. if (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data == NULL) {
  32350. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  32351. }
  32352. else {
  32353. /* Get the hash or hash of the hash if wrong size. */
  32354. ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  32355. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  32356. dcrl->extAuthKeyId);
  32357. }
  32358. }
  32359. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32360. return ret;
  32361. #endif /* WOLFSSL_ASN_TEMPLATE */
  32362. }
  32363. #endif
  32364. #ifndef WOLFSSL_ASN_TEMPLATE
  32365. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf,
  32366. word32* inOutIdx, word32 sz)
  32367. {
  32368. int length;
  32369. word32 idx;
  32370. word32 ext_bound; /* boundary index for the sequence of extensions */
  32371. word32 oid;
  32372. byte tag;
  32373. WOLFSSL_ENTER("ParseCRL_Extensions");
  32374. (void)dcrl;
  32375. if (inOutIdx == NULL)
  32376. return BAD_FUNC_ARG;
  32377. idx = *inOutIdx;
  32378. /* CRL Extensions are optional */
  32379. if ((idx + 1) > sz)
  32380. return 0;
  32381. /* CRL Extensions are optional */
  32382. if (GetASNTag(buf, &idx, &tag, sz) < 0)
  32383. return 0;
  32384. /* CRL Extensions are optional */
  32385. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  32386. return 0;
  32387. if (GetLength(buf, &idx, &length, sz) < 0)
  32388. return ASN_PARSE_E;
  32389. if (GetSequence(buf, &idx, &length, sz) < 0)
  32390. return ASN_PARSE_E;
  32391. ext_bound = idx + length;
  32392. while (idx < (word32)ext_bound) {
  32393. word32 localIdx;
  32394. int ret;
  32395. if (GetSequence(buf, &idx, &length, sz) < 0) {
  32396. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  32397. return ASN_PARSE_E;
  32398. }
  32399. oid = 0;
  32400. if (GetObjectId(buf, &idx, &oid, oidCrlExtType, sz) < 0) {
  32401. WOLFSSL_MSG("\tfail: OBJECT ID");
  32402. return ASN_PARSE_E;
  32403. }
  32404. /* check for critical flag */
  32405. if ((idx + 1) > (word32)sz) {
  32406. WOLFSSL_MSG("\tfail: malformed buffer");
  32407. return BUFFER_E;
  32408. }
  32409. localIdx = idx;
  32410. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  32411. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  32412. ret = GetBoolean(buf, &idx, sz);
  32413. if (ret < 0)
  32414. return ret;
  32415. }
  32416. ret = GetOctetString(buf, &idx, &length, sz);
  32417. if (ret < 0)
  32418. return ret;
  32419. if (oid == AUTH_KEY_OID) {
  32420. #ifndef NO_SKID
  32421. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  32422. if (ret < 0) {
  32423. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  32424. return ret;
  32425. }
  32426. #endif
  32427. }
  32428. else if (oid == CRL_NUMBER_OID) {
  32429. localIdx = idx;
  32430. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 &&
  32431. tag == ASN_INTEGER) {
  32432. ret = GetASNInt(buf, &idx, &length, sz);
  32433. if (ret < 0) {
  32434. WOLFSSL_MSG("\tcouldn't parse CRL number extension");
  32435. return ret;
  32436. }
  32437. else {
  32438. if (length > 1) {
  32439. int i;
  32440. #ifdef WOLFSSL_SMALL_STACK
  32441. mp_int* m = (mp_int*)XMALLOC(sizeof(*m), NULL,
  32442. DYNAMIC_TYPE_BIGINT);
  32443. if (m == NULL) {
  32444. return MEMORY_E;
  32445. }
  32446. #else
  32447. mp_int m[1];
  32448. #endif
  32449. if (mp_init(m) != MP_OKAY) {
  32450. ret = MP_INIT_E;
  32451. }
  32452. if (ret == 0)
  32453. ret = mp_read_unsigned_bin(m, buf + idx, length);
  32454. if (ret != MP_OKAY)
  32455. ret = BUFFER_E;
  32456. if (ret == 0) {
  32457. dcrl->crlNumber = 0;
  32458. for (i = 0; i < (int)(*m).used; ++i) {
  32459. if (i > (CHAR_BIT *
  32460. (int)sizeof(word32) / DIGIT_BIT)) {
  32461. break;
  32462. }
  32463. dcrl->crlNumber |= ((word32)(*m).dp[i]) <<
  32464. (DIGIT_BIT * i);
  32465. }
  32466. }
  32467. mp_free(m);
  32468. #ifdef WOLFSSL_SMALL_STACK
  32469. XFREE(m, NULL, DYNAMIC_TYPE_BIGINT);
  32470. #endif
  32471. if (ret != 0)
  32472. return ret;
  32473. }
  32474. else if (length == 1) {
  32475. dcrl->crlNumber = buf[idx];
  32476. }
  32477. }
  32478. }
  32479. }
  32480. idx += length;
  32481. }
  32482. *inOutIdx = idx;
  32483. return 0;
  32484. }
  32485. #else
  32486. /* Parse the extensions of a CRL.
  32487. *
  32488. * @param [in] dcrl Decoded CRL object.
  32489. * @param [in] buff Buffer holding CRL.
  32490. * @param [in] idx Index into buffer of extensions.
  32491. * @param [in] maxIdx Maximum index of extension data.
  32492. * @return 0 on success.
  32493. * @return ASN_PARSE_E on failure.
  32494. */
  32495. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf, word32 idx,
  32496. word32 maxIdx)
  32497. {
  32498. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  32499. int ret = 0;
  32500. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, dcrl->heap);
  32501. while ((ret == 0) && (idx < maxIdx)) {
  32502. byte critical = 0;
  32503. /* Clear dynamic data. */
  32504. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  32505. /* Ensure OID is an extension type. */
  32506. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  32507. /* Set criticality variable. */
  32508. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  32509. /* Parse extension wrapper. */
  32510. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, buf, &idx,
  32511. maxIdx);
  32512. if (ret == 0) {
  32513. /* OID in extension. */
  32514. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  32515. /* Length of extension data. */
  32516. int length = dataASN[CERTEXTASN_IDX_VAL].length;
  32517. if (oid == AUTH_KEY_OID) {
  32518. #ifndef NO_SKID
  32519. /* Parse Authority Key Id extension.
  32520. * idx is at start of OCTET_STRING data. */
  32521. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  32522. if (ret != 0) {
  32523. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  32524. }
  32525. #endif
  32526. }
  32527. /* TODO: Parse CRL Number extension */
  32528. /* TODO: check criticality */
  32529. /* Move index on to next extension. */
  32530. idx += length;
  32531. }
  32532. }
  32533. if (ret < 0) {
  32534. ret = ASN_PARSE_E;
  32535. }
  32536. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32537. return ret;
  32538. }
  32539. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32540. #ifdef WOLFSSL_ASN_TEMPLATE
  32541. /* ASN.1 template for a CRL- CertificateList.
  32542. * X.509: RFC 5280, 5.1 - CRL Fields
  32543. */
  32544. static const ASNItem crlASN[] = {
  32545. /* CertificateList */
  32546. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  32547. /* tbsCertList */
  32548. /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  32549. /* version Version OPTIONAL if present must be v2 */
  32550. /* TBS_VER */ { 2, ASN_INTEGER, 0, 0, 1 },
  32551. /* signature */
  32552. /* TBS_SIGALGO */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  32553. /* TBS_SIGALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  32554. /* TBS_SIGALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  32555. /* issuer */
  32556. /* TBS_ISSUER */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  32557. /* thisUpdate */
  32558. /* TBS_THISUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 2 },
  32559. /* TBS_THISUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 2 },
  32560. /* nextUpdate */
  32561. /* TBS_NEXTUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 3 },
  32562. /* TBS_NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 3 },
  32563. /* revokedCertificates */
  32564. /* TBS_REVOKEDCERTS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  32565. /* crlExtensions */
  32566. /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  32567. /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
  32568. /* signatureAlgorithm */
  32569. /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  32570. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  32571. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  32572. /* signatureValue */
  32573. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  32574. };
  32575. enum {
  32576. CRLASN_IDX_SEQ = 0,
  32577. CRLASN_IDX_TBS,
  32578. CRLASN_IDX_TBS_VER,
  32579. CRLASN_IDX_TBS_SIGALGO,
  32580. CRLASN_IDX_TBS_SIGALGO_OID,
  32581. CRLASN_IDX_TBS_SIGALGO_NULL,
  32582. CRLASN_IDX_TBS_ISSUER,
  32583. CRLASN_IDX_TBS_THISUPDATE_UTC,
  32584. CRLASN_IDX_TBS_THISUPDATE_GT,
  32585. CRLASN_IDX_TBS_NEXTUPDATE_UTC,
  32586. CRLASN_IDX_TBS_NEXTUPDATE_GT,
  32587. CRLASN_IDX_TBS_REVOKEDCERTS,
  32588. CRLASN_IDX_TBS_EXT,
  32589. CRLASN_IDX_TBS_EXT_SEQ,
  32590. CRLASN_IDX_SIGALGO,
  32591. CRLASN_IDX_SIGALGO_OID,
  32592. CRLASN_IDX_SIGALGO_NULL,
  32593. CRLASN_IDX_SIGNATURE,
  32594. };
  32595. /* Number of items in ASN.1 template for a CRL- CertificateList. */
  32596. #define crlASN_Length (sizeof(crlASN) / sizeof(ASNItem))
  32597. #endif
  32598. /* parse crl buffer into decoded state, 0 on success */
  32599. int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz,
  32600. int verify, void* cm)
  32601. {
  32602. #ifndef WOLFSSL_ASN_TEMPLATE
  32603. Signer* ca = NULL;
  32604. SignatureCtx sigCtx;
  32605. int ret = 0;
  32606. int len;
  32607. word32 idx = 0;
  32608. WOLFSSL_MSG("ParseCRL");
  32609. /* raw crl hash */
  32610. /* hash here if needed for optimized comparisons
  32611. * wc_Sha sha;
  32612. * wc_InitSha(&sha);
  32613. * wc_ShaUpdate(&sha, buff, sz);
  32614. * wc_ShaFinal(&sha, dcrl->crlHash); */
  32615. if (GetSequence(buff, &idx, &len, sz) < 0)
  32616. return ASN_PARSE_E;
  32617. dcrl->certBegin = idx;
  32618. /* Normalize sz for the length inside the outer sequence. */
  32619. sz = len + idx;
  32620. if (GetSequence(buff, &idx, &len, sz) < 0)
  32621. return ASN_PARSE_E;
  32622. dcrl->sigIndex = len + idx;
  32623. if (ParseCRL_CertList(rcert, dcrl, buff, &idx, dcrl->sigIndex, verify) < 0)
  32624. return ASN_PARSE_E;
  32625. if (ParseCRL_Extensions(dcrl, buff, &idx, dcrl->sigIndex) < 0)
  32626. return ASN_PARSE_E;
  32627. idx = dcrl->sigIndex;
  32628. if (GetAlgoId(buff, &idx, &dcrl->signatureOID, oidSigType, sz) < 0)
  32629. return ASN_PARSE_E;
  32630. if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
  32631. return ASN_PARSE_E;
  32632. /* openssl doesn't add skid by default for CRLs cause firefox chokes
  32633. if experiencing issues uncomment NO_SKID define in CRL section of
  32634. wolfssl/wolfcrypt/settings.h */
  32635. #ifndef NO_SKID
  32636. if (dcrl->extAuthKeyIdSet) {
  32637. ca = GetCA(cm, dcrl->extAuthKeyId); /* more unique than issuerHash */
  32638. }
  32639. if (ca != NULL && XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  32640. KEYID_SIZE) != 0) {
  32641. ca = NULL;
  32642. }
  32643. if (ca == NULL) {
  32644. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  32645. /* If AKID is available then this CA doesn't have the public
  32646. * key required */
  32647. if (ca && dcrl->extAuthKeyIdSet) {
  32648. WOLFSSL_MSG("CA SKID doesn't match AKID");
  32649. ca = NULL;
  32650. }
  32651. }
  32652. #else
  32653. ca = GetCA(cm, dcrl->issuerHash);
  32654. #endif /* !NO_SKID */
  32655. WOLFSSL_MSG("About to verify CRL signature");
  32656. if (ca == NULL) {
  32657. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  32658. ret = ASN_CRL_NO_SIGNER_E;
  32659. WOLFSSL_ERROR_VERBOSE(ret);
  32660. goto end;
  32661. }
  32662. WOLFSSL_MSG("Found CRL issuer CA");
  32663. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  32664. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  32665. dcrl->signatureOID, ca, dcrl->heap);
  32666. end:
  32667. return ret;
  32668. #else
  32669. DECL_ASNGETDATA(dataASN, crlASN_Length);
  32670. int ret = 0;
  32671. /* Default version - v1 = 0 */
  32672. byte version = 0;
  32673. word32 idx = 0;
  32674. /* Size of buffer for date. */
  32675. word32 lastDateSz = MAX_DATE_SIZE;
  32676. word32 nextDateSz = MAX_DATE_SIZE;
  32677. /* When NO_ASN_TIME is defined, verify not used. */
  32678. (void)verify;
  32679. WOLFSSL_MSG("ParseCRL");
  32680. CALLOC_ASNGETDATA(dataASN, crlASN_Length, ret, dcrl->heap);
  32681. if (ret == 0) {
  32682. /* Set variable to store version. */
  32683. GetASN_Int8Bit(&dataASN[CRLASN_IDX_TBS_VER], &version);
  32684. /* Set expecting signature OID. */
  32685. GetASN_OID(&dataASN[CRLASN_IDX_TBS_SIGALGO_OID], oidSigType);
  32686. /* Set buffer to put last and next date into. */
  32687. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC], dcrl->lastDate,
  32688. &lastDateSz);
  32689. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_GT], dcrl->lastDate,
  32690. &lastDateSz);
  32691. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC], dcrl->nextDate,
  32692. &nextDateSz);
  32693. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT], dcrl->nextDate,
  32694. &nextDateSz);
  32695. /* Set expecting signature OID. */
  32696. GetASN_OID(&dataASN[CRLASN_IDX_SIGALGO_OID], oidSigType);
  32697. /* Decode the CRL. */
  32698. ret = GetASN_Items(crlASN, dataASN, crlASN_Length, 1, buff, &idx, sz);
  32699. }
  32700. /* Version must be v2 = 1 if present. */
  32701. if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_VER].tag != 0) &&
  32702. (version != 1)) {
  32703. ret = ASN_PARSE_E;
  32704. }
  32705. /* Check minimum size of last date. */
  32706. if ((ret == 0) && (lastDateSz < MIN_DATE_SIZE)) {
  32707. ret = ASN_PARSE_E;
  32708. }
  32709. /* Check minimum size of next date. */
  32710. if ((ret == 0) && (nextDateSz < MIN_DATE_SIZE)) {
  32711. ret = ASN_PARSE_E;
  32712. }
  32713. /* 'signatureAlgorithm' OID must be the same as 'signature' OID. */
  32714. if ((ret == 0) && (dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum !=
  32715. dataASN[CRLASN_IDX_TBS_SIGALGO_OID].data.oid.sum)) {
  32716. ret = ASN_PARSE_E;
  32717. }
  32718. if (ret == 0) {
  32719. /* Store version */
  32720. dcrl->version = ++version;
  32721. /* Store offset of to be signed part. */
  32722. dcrl->certBegin = dataASN[CRLASN_IDX_TBS].offset;
  32723. /* Store index of signature. */
  32724. dcrl->sigIndex = dataASN[CRLASN_IDX_SIGALGO].offset;
  32725. /* Store address and length of signature data. */
  32726. GetASN_GetRef(&dataASN[CRLASN_IDX_SIGNATURE], &dcrl->signature,
  32727. &dcrl->sigLength);
  32728. /* Get the signature OID. */
  32729. dcrl->signatureOID = dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum;
  32730. /* Get the format/tag of the last and next date. */
  32731. dcrl->lastDateFormat = (dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag != 0)
  32732. ? dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag
  32733. : dataASN[CRLASN_IDX_TBS_THISUPDATE_GT].tag;
  32734. dcrl->nextDateFormat = (dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag != 0)
  32735. ? dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag
  32736. : dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT].tag;
  32737. #ifndef NO_ASN_TIME
  32738. if (dcrl->nextDateFormat != 0) {
  32739. /* Next date was set, so validate it. */
  32740. if (verify != NO_VERIFY &&
  32741. !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  32742. WOLFSSL_MSG("CRL after date is no longer valid");
  32743. ret = CRL_CERT_DATE_ERR;
  32744. WOLFSSL_ERROR_VERBOSE(ret);
  32745. }
  32746. }
  32747. }
  32748. if (ret == 0) {
  32749. #endif
  32750. #ifdef OPENSSL_EXTRA
  32751. /* Parse and store the issuer name. */
  32752. dcrl->issuerSz = GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER],
  32753. buff);
  32754. dcrl->issuer = (byte*)GetNameFromDer((byte*)GetASNItem_Addr(
  32755. dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  32756. (int)dcrl->issuerSz);
  32757. #endif
  32758. /* Calculate the Hash id from the issuer name. */
  32759. ret = CalcHashId(GetASNItem_Addr(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  32760. GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  32761. dcrl->issuerHash);
  32762. if (ret < 0) {
  32763. ret = ASN_PARSE_E;
  32764. }
  32765. }
  32766. if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_REVOKEDCERTS].tag != 0)) {
  32767. /* Parse revoked certificates - starting after SEQUENCE OF. */
  32768. ret = ParseCRL_RevokedCerts(rcert, dcrl, buff,
  32769. GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff),
  32770. GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff));
  32771. }
  32772. if (ret == 0) {
  32773. /* Parse the extensions - starting after SEQUENCE OF. */
  32774. ret = ParseCRL_Extensions(dcrl, buff,
  32775. GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff),
  32776. GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff));
  32777. }
  32778. if (ret == 0) {
  32779. /* Find signer and verify signature. */
  32780. ret = PaseCRL_CheckSignature(dcrl, buff, cm);
  32781. }
  32782. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32783. return ret;
  32784. #endif /* WOLFSSL_ASN_TEMPLATE */
  32785. }
  32786. #endif /* HAVE_CRL */
  32787. #ifdef WOLFSSL_CERT_PIV
  32788. #ifdef WOLFSSL_ASN_TEMPLATE
  32789. /* Template for PIV. */
  32790. static const ASNItem pivASN[] = {
  32791. /* CERT */ { 0, ASN_PIV_CERT, 0, 0, 0 },
  32792. /* NONCE */ { 0, ASN_PIV_NONCE, 0, 0, 1 },
  32793. /* SIGNEDNONCE */ { 0, ASN_PIV_SIGNED_NONCE, 0, 0, 1 },
  32794. };
  32795. enum {
  32796. PIVASN_IDX_CERT = 0,
  32797. PIVASN_IDX_NONCE,
  32798. PIVASN_IDX_SIGNEDNONCE,
  32799. };
  32800. #define pivASN_Length (sizeof(pivASN) / sizeof(ASNItem))
  32801. static const ASNItem pivCertASN[] = {
  32802. /* 0x53 = 0x40 | 0x13 */
  32803. /* CERT */ { 1, ASN_APPLICATION | 0x13, 0, 1, 0 },
  32804. /* 0x70 = 0x40 | 0x10 + 0x20 (CONSTRUCTED) */
  32805. /* X509 */ { 2, ASN_APPLICATION | 0x10, 1, 0, 0 },
  32806. /* 0x71 = 0x40 | 0x11 + 0x20 (CONSTRUCTED) */
  32807. /* INFO */ { 2, ASN_APPLICATION | 0x11, 1, 0, 1 },
  32808. /* 0xFE = 0xC0 | 0x1E + 0x20 (CONSTRUCTED) */
  32809. /* ERR */ { 2, ASN_PRIVATE | 0x1e, 1, 0, 1 },
  32810. };
  32811. enum {
  32812. PIVCERTASN_IDX_CERT,
  32813. PIVCERTASN_IDX_X509,
  32814. PIVCERTASN_IDX_INFO,
  32815. PIVCERTASN_IDX_ERR,
  32816. };
  32817. #define pivCertASN_Length (sizeof(pivCertASN) / sizeof(ASNItem))
  32818. #endif
  32819. int wc_ParseCertPIV(wc_CertPIV* piv, const byte* buf, word32 totalSz)
  32820. {
  32821. #ifndef WOLFSSL_ASN_TEMPLATE
  32822. int length = 0;
  32823. word32 idx = 0;
  32824. WOLFSSL_ENTER("wc_ParseCertPIV");
  32825. if (piv == NULL || buf == NULL || totalSz == 0)
  32826. return BAD_FUNC_ARG;
  32827. XMEMSET(piv, 0, sizeof(wc_CertPIV));
  32828. /* Detect Identiv PIV (with 0x0A, 0x0B and 0x0C sections) */
  32829. /* Certificate (0A 82 05FA) */
  32830. if (GetASNHeader(buf, ASN_PIV_CERT, &idx, &length, totalSz) >= 0) {
  32831. /* Identiv Type PIV card */
  32832. piv->isIdentiv = 1;
  32833. piv->cert = &buf[idx];
  32834. piv->certSz = length;
  32835. idx += length;
  32836. /* Nonce (0B 14) */
  32837. if (GetASNHeader(buf, ASN_PIV_NONCE, &idx, &length, totalSz) >= 0) {
  32838. piv->nonce = &buf[idx];
  32839. piv->nonceSz = length;
  32840. idx += length;
  32841. }
  32842. /* Signed Nonce (0C 82 0100) */
  32843. if (GetASNHeader(buf, ASN_PIV_SIGNED_NONCE, &idx, &length, totalSz) >= 0) {
  32844. piv->signedNonce = &buf[idx];
  32845. piv->signedNonceSz = length;
  32846. }
  32847. idx = 0;
  32848. buf = piv->cert;
  32849. totalSz = piv->certSz;
  32850. }
  32851. /* Certificate Buffer Total Size (53 82 05F6) */
  32852. if (GetASNHeader(buf, ASN_APPLICATION | ASN_PRINTABLE_STRING, &idx,
  32853. &length, totalSz) < 0) {
  32854. return ASN_PARSE_E;
  32855. }
  32856. /* PIV Certificate (70 82 05ED) */
  32857. if (GetASNHeader(buf, ASN_PIV_TAG_CERT, &idx, &length,
  32858. totalSz) < 0) {
  32859. return ASN_PARSE_E;
  32860. }
  32861. /* Capture certificate buffer pointer and length */
  32862. piv->cert = &buf[idx];
  32863. piv->certSz = length;
  32864. idx += length;
  32865. /* PIV Certificate Info (71 01 00) */
  32866. if (GetASNHeader(buf, ASN_PIV_TAG_CERT_INFO, &idx, &length,
  32867. totalSz) >= 0) {
  32868. if (length >= 1) {
  32869. piv->compression = (buf[idx] & ASN_PIV_CERT_INFO_COMPRESSED);
  32870. piv->isX509 = ((buf[idx] & ASN_PIV_CERT_INFO_ISX509) != 0);
  32871. }
  32872. idx += length;
  32873. }
  32874. /* PIV Error Detection (FE 00) */
  32875. if (GetASNHeader(buf, ASN_PIV_TAG_ERR_DET, &idx, &length,
  32876. totalSz) >= 0) {
  32877. piv->certErrDet = &buf[idx];
  32878. piv->certErrDetSz = length;
  32879. idx += length;
  32880. }
  32881. return 0;
  32882. #else
  32883. /* pivCertASN_Length is longer than pivASN_Length */
  32884. DECL_ASNGETDATA(dataASN, pivCertASN_Length);
  32885. int ret = 0;
  32886. word32 idx;
  32887. byte info;
  32888. WOLFSSL_ENTER("wc_ParseCertPIV");
  32889. ALLOC_ASNGETDATA(dataASN, pivCertASN_Length, ret, NULL);
  32890. if (ret == 0) {
  32891. /* Clear dynamic data. */
  32892. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivASN_Length);
  32893. /* Start parsing from start of buffer. */
  32894. idx = 0;
  32895. /* Parse Identiv wrapper. */
  32896. ret = GetASN_Items(pivASN, dataASN, pivASN_Length, 1, buf, &idx,
  32897. totalSz);
  32898. if (ret == 0) {
  32899. /* Identiv wrapper found. */
  32900. piv->isIdentiv = 1;
  32901. /* Get nonce reference. */
  32902. if (dataASN[PIVASN_IDX_NONCE].tag != 0) {
  32903. GetASN_GetConstRef(&dataASN[PIVASN_IDX_NONCE], &piv->nonce,
  32904. &piv->nonceSz);
  32905. }
  32906. /* Get signedNonce reference. */
  32907. if (dataASN[PIVASN_IDX_SIGNEDNONCE].tag != 0) {
  32908. GetASN_GetConstRef(&dataASN[PIVASN_IDX_SIGNEDNONCE],
  32909. &piv->signedNonce, &piv->signedNonceSz);
  32910. }
  32911. /* Get the certificate data for parsing. */
  32912. GetASN_GetConstRef(&dataASN[PIVASN_IDX_CERT], &buf, &totalSz);
  32913. }
  32914. ret = 0;
  32915. }
  32916. if (ret == 0) {
  32917. /* Clear dynamic data and set variable to put cert info into. */
  32918. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivCertASN_Length);
  32919. GetASN_Int8Bit(&dataASN[PIVCERTASN_IDX_INFO], &info);
  32920. /* Start parsing from start of buffer. */
  32921. idx = 0;
  32922. /* Parse PIV cetificate data. */
  32923. ret = GetASN_Items(pivCertASN, dataASN, pivCertASN_Length, 1, buf, &idx,
  32924. totalSz);
  32925. if (ret == 0) {
  32926. /* Get X.509 certificate reference. */
  32927. GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_X509], &piv->cert,
  32928. &piv->certSz);
  32929. /* Set the certificate info if available. */
  32930. if (dataASN[PIVCERTASN_IDX_INFO].tag != 0) {
  32931. /* Bits 1 and 2 are compression. */
  32932. piv->compression = info & ASN_PIV_CERT_INFO_COMPRESSED;
  32933. /* Bits 3 is X509 flag. */
  32934. piv->isX509 = ((info & ASN_PIV_CERT_INFO_ISX509) != 0);
  32935. }
  32936. /* Get X.509 certificate error detection reference. */
  32937. GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_ERR], &piv->certErrDet,
  32938. &piv->certErrDetSz);
  32939. }
  32940. ret = 0;
  32941. }
  32942. FREE_ASNGETDATA(dataASN, NULL);
  32943. return ret;
  32944. #endif /* WOLFSSL_ASN_TEMPLATE */
  32945. }
  32946. #endif /* WOLFSSL_CERT_PIV */
  32947. #ifdef HAVE_SMIME
  32948. /*****************************************************************************
  32949. * wc_MIME_parse_headers - Reads the char array in and parses out MIME headers
  32950. * and parameters into headers. Will continue until in has no more content.
  32951. *
  32952. * RETURNS:
  32953. * returns zero on success, non-zero on error.
  32954. */
  32955. int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers)
  32956. {
  32957. MimeHdr* nextHdr = NULL;
  32958. MimeHdr* curHdr = NULL;
  32959. MimeParam* nextParam = NULL;
  32960. size_t start = 0;
  32961. size_t end = 0;
  32962. char* nameAttr = NULL;
  32963. char* bodyVal = NULL;
  32964. MimeTypes mimeType = MIME_HDR;
  32965. MimeStatus mimeStatus = MIME_NAMEATTR;
  32966. int ret = -1;
  32967. size_t pos = 0;
  32968. size_t lineLen = 0;
  32969. char* curLine = NULL;
  32970. char* ptr = NULL;
  32971. if (in == NULL || inLen <= 0 || in[inLen] != '\0' || headers == NULL) {
  32972. ret = BAD_FUNC_ARG;
  32973. goto error;
  32974. }
  32975. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL, DYNAMIC_TYPE_PKCS7);
  32976. if (nextHdr == NULL) {
  32977. ret = MEMORY_E;
  32978. goto error;
  32979. }
  32980. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  32981. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  32982. DYNAMIC_TYPE_PKCS7);
  32983. if (nextParam == NULL) {
  32984. ret = MEMORY_E;
  32985. goto error;
  32986. }
  32987. XMEMSET(nextParam, 0, sizeof(MimeParam));
  32988. curLine = XSTRTOK(in, "\r\n", &ptr);
  32989. if (curLine == NULL) {
  32990. ret = ASN_PARSE_E;
  32991. goto error;
  32992. }
  32993. while (curLine != NULL) {
  32994. /* Leftover from previous line, add params to previous header. */
  32995. if (curLine[0] == ' ' && curHdr) {
  32996. mimeType = MIME_PARAM;
  32997. }
  32998. else {
  32999. mimeType = MIME_HDR;
  33000. }
  33001. start = 0;
  33002. lineLen = XSTRLEN(curLine);
  33003. if (lineLen == 0) {
  33004. ret = BAD_FUNC_ARG;
  33005. goto error;
  33006. }
  33007. for (pos = 0; pos < lineLen; pos++) {
  33008. char cur = curLine[pos];
  33009. if (mimeStatus == MIME_NAMEATTR && ((cur == ':' &&
  33010. mimeType == MIME_HDR) || (cur == '=' &&
  33011. mimeType == MIME_PARAM)) && pos >= 1) {
  33012. mimeStatus = MIME_BODYVAL;
  33013. end = pos-1;
  33014. if (nameAttr != NULL)
  33015. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  33016. ret = wc_MIME_header_strip(curLine, &nameAttr, start, end);
  33017. if (ret) {
  33018. goto error;
  33019. }
  33020. start = pos+1;
  33021. }
  33022. else if (mimeStatus == MIME_BODYVAL && cur == ';' && pos >= 1) {
  33023. end = pos-1;
  33024. if (bodyVal != NULL)
  33025. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  33026. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  33027. if (ret) {
  33028. goto error;
  33029. }
  33030. if (mimeType == MIME_HDR) {
  33031. nextHdr->name = nameAttr;
  33032. nameAttr = NULL;
  33033. nextHdr->body = bodyVal;
  33034. bodyVal = NULL;
  33035. nextHdr->next = curHdr;
  33036. curHdr = nextHdr;
  33037. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  33038. DYNAMIC_TYPE_PKCS7);
  33039. if (nextHdr == NULL) {
  33040. ret = MEMORY_E;
  33041. goto error;
  33042. }
  33043. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  33044. }
  33045. else {
  33046. nextParam->attribute = nameAttr;
  33047. nameAttr = NULL;
  33048. nextParam->value = bodyVal;
  33049. bodyVal = NULL;
  33050. nextParam->next = curHdr->params;
  33051. curHdr->params = nextParam;
  33052. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  33053. DYNAMIC_TYPE_PKCS7);
  33054. if (nextParam == NULL) {
  33055. ret = MEMORY_E;
  33056. goto error;
  33057. }
  33058. XMEMSET(nextParam, 0, sizeof(MimeParam));
  33059. }
  33060. mimeType = MIME_PARAM;
  33061. mimeStatus = MIME_NAMEATTR;
  33062. start = pos+1;
  33063. }
  33064. }
  33065. end = lineLen-1;
  33066. /* Omit newline characters. */
  33067. while ((curLine[end] == '\r' || curLine[end] == '\n') && end > 0) {
  33068. end--;
  33069. }
  33070. if (end >= start && mimeStatus == MIME_BODYVAL) {
  33071. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  33072. if (ret) {
  33073. goto error;
  33074. }
  33075. if (mimeType == MIME_HDR) {
  33076. nextHdr->name = nameAttr;
  33077. nameAttr = NULL;
  33078. nextHdr->body = bodyVal;
  33079. bodyVal = NULL;
  33080. nextHdr->next = curHdr;
  33081. curHdr = nextHdr;
  33082. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  33083. DYNAMIC_TYPE_PKCS7);
  33084. if (nextHdr == NULL) {
  33085. ret = MEMORY_E;
  33086. goto error;
  33087. }
  33088. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  33089. } else {
  33090. nextParam->attribute = nameAttr;
  33091. nameAttr = NULL;
  33092. nextParam->value = bodyVal;
  33093. bodyVal = NULL;
  33094. nextParam->next = curHdr->params;
  33095. curHdr->params = nextParam;
  33096. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  33097. DYNAMIC_TYPE_PKCS7);
  33098. if (nextParam == NULL) {
  33099. ret = MEMORY_E;
  33100. goto error;
  33101. }
  33102. XMEMSET(nextParam, 0, sizeof(MimeParam));
  33103. }
  33104. }
  33105. curLine = XSTRTOK(NULL, "\r\n", &ptr);
  33106. mimeStatus = MIME_NAMEATTR;
  33107. }
  33108. *headers = curHdr;
  33109. ret = 0; /* success if at this point */
  33110. error:
  33111. if (ret != 0)
  33112. wc_MIME_free_hdrs(curHdr);
  33113. wc_MIME_free_hdrs(nextHdr);
  33114. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  33115. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  33116. XFREE(nextParam, NULL, DYNAMIC_TYPE_PKCS7);
  33117. return ret;
  33118. }
  33119. /*****************************************************************************
  33120. * wc_MIME_header_strip - Reads the string in from indices start to end, strips
  33121. * out disallowed/separator characters and places the rest into *out.
  33122. *
  33123. * RETURNS:
  33124. * returns zero on success, non-zero on error.
  33125. */
  33126. int wc_MIME_header_strip(char* in, char** out, size_t start, size_t end)
  33127. {
  33128. size_t inPos = start;
  33129. size_t outPos = 0;
  33130. size_t inLen = 0;
  33131. if (end < start || in == NULL || out == NULL) {
  33132. return BAD_FUNC_ARG;
  33133. }
  33134. inLen = XSTRLEN(in);
  33135. if (start > inLen || end > inLen) {
  33136. return BAD_FUNC_ARG;
  33137. }
  33138. *out = (char*)XMALLOC(((end-start)+2)*sizeof(char), NULL,
  33139. DYNAMIC_TYPE_PKCS7);
  33140. if (*out == NULL) {
  33141. return MEMORY_E;
  33142. }
  33143. while (inPos <= end) {
  33144. if (in[inPos] >= MIME_HEADER_ASCII_MIN && in[inPos] <=
  33145. MIME_HEADER_ASCII_MAX && in[inPos] != ';' && in[inPos] != '\"') {
  33146. (*out)[outPos] = in[inPos];
  33147. outPos++;
  33148. }
  33149. inPos++;
  33150. }
  33151. (*out)[outPos] = '\0';
  33152. return 0;
  33153. }
  33154. /*****************************************************************************
  33155. * wc_MIME_find_header_name - Searches through all given headers until a header with
  33156. * a name matching the provided name is found.
  33157. *
  33158. * RETURNS:
  33159. * returns a pointer to the found header, if no match was found, returns NULL.
  33160. */
  33161. MimeHdr* wc_MIME_find_header_name(const char* name, MimeHdr* header)
  33162. {
  33163. while (header) {
  33164. if (!XSTRCMP(name, header->name)) {
  33165. return header;
  33166. }
  33167. header = header->next;
  33168. }
  33169. return header;
  33170. }
  33171. /*****************************************************************************
  33172. * wc_MIME_find_param_attr - Searches through all parameters until a parameter
  33173. * with a attribute matching the provided attribute is found.
  33174. *
  33175. * RETURNS:
  33176. * returns a pointer to the found parameter, if no match was found,
  33177. * returns NULL.
  33178. */
  33179. MimeParam* wc_MIME_find_param_attr(const char* attribute,
  33180. MimeParam* param)
  33181. {
  33182. while (param) {
  33183. if (!XSTRCMP(attribute, param->attribute)) {
  33184. return param;
  33185. }
  33186. param = param->next;
  33187. }
  33188. return param;
  33189. }
  33190. /*****************************************************************************
  33191. * wc_MIME_single_canonicalize - Canonicalize a line by converting the trailing
  33192. * line ending to CRLF.
  33193. *
  33194. * line - input line to canonicalize
  33195. * len - length of line in chars on input, length of output array on return
  33196. *
  33197. * RETURNS:
  33198. * returns a pointer to a canonicalized line on success, NULL on error.
  33199. */
  33200. char* wc_MIME_single_canonicalize(const char* line, word32* len)
  33201. {
  33202. size_t end = 0;
  33203. char* canonLine = NULL;
  33204. if (line == NULL || len == NULL || *len == 0) {
  33205. return NULL;
  33206. }
  33207. end = *len;
  33208. while (end >= 1 && ((line[end-1] == '\r') || (line[end-1] == '\n'))) {
  33209. end--;
  33210. }
  33211. /* Need 2 chars for \r\n and 1 for EOL */
  33212. canonLine = (char*)XMALLOC((end+3)*sizeof(char), NULL, DYNAMIC_TYPE_PKCS7);
  33213. if (canonLine == NULL) {
  33214. return NULL;
  33215. }
  33216. XMEMCPY(canonLine, line, end);
  33217. canonLine[end] = '\r';
  33218. canonLine[end+1] = '\n';
  33219. canonLine[end+2] = '\0';
  33220. *len = (word32)(end + 3);
  33221. return canonLine;
  33222. }
  33223. /*****************************************************************************
  33224. * wc_MIME_free_hdrs - Frees all MIME headers, parameters and strings starting from
  33225. * the provided header pointer.
  33226. *
  33227. * RETURNS:
  33228. * returns zero on success, non-zero on error.
  33229. */
  33230. int wc_MIME_free_hdrs(MimeHdr* head)
  33231. {
  33232. MimeHdr* curHdr = NULL;
  33233. MimeParam* curParam = NULL;
  33234. while (head) {
  33235. while (head->params) {
  33236. curParam = head->params;
  33237. head->params = head->params->next;
  33238. XFREE(curParam->attribute, NULL, DYNAMIC_TYPE_PKCS7);
  33239. XFREE(curParam->value, NULL, DYNAMIC_TYPE_PKCS7);
  33240. XFREE(curParam, NULL, DYNAMIC_TYPE_PKCS7);
  33241. }
  33242. curHdr = head;
  33243. head = head->next;
  33244. XFREE(curHdr->name, NULL, DYNAMIC_TYPE_PKCS7);
  33245. XFREE(curHdr->body, NULL, DYNAMIC_TYPE_PKCS7);
  33246. XFREE(curHdr, NULL, DYNAMIC_TYPE_PKCS7);
  33247. }
  33248. return 0;
  33249. }
  33250. #endif /* HAVE_SMIME */
  33251. #undef ERROR_OUT
  33252. #ifdef WOLFSSL_ASN_PRINT
  33253. /*******************************************************************************
  33254. * ASN.1 Parsing and Printing Implementation
  33255. ******************************************************************************/
  33256. /* Initialize ASN.1 print options.
  33257. *
  33258. * @param [in, out] opts ASN.1 options for printing.
  33259. * @return 0 on success.
  33260. * @return BAD_FUNC_ARG when asn1 is NULL.
  33261. */
  33262. int wc_Asn1PrintOptions_Init(Asn1PrintOptions* opts)
  33263. {
  33264. int ret = 0;
  33265. if (opts == NULL) {
  33266. ret = BAD_FUNC_ARG;
  33267. }
  33268. else {
  33269. XMEMSET(opts, 0, sizeof(*opts));
  33270. }
  33271. return ret;
  33272. }
  33273. /* Set a print option into Asn1PrintOptions object.
  33274. *
  33275. * @param [in, out] opts ASN.1 options for printing.
  33276. * @param [in] opt Option to set value of.
  33277. * @param [in] val Value to set for option.
  33278. * @return 0 on success.
  33279. * @return BAD_FUNC_ARG when asn1 is NULL.
  33280. * @return BAD_FUNC_ARG when val is out of range for option.
  33281. */
  33282. int wc_Asn1PrintOptions_Set(Asn1PrintOptions* opts, enum Asn1PrintOpt opt,
  33283. word32 val)
  33284. {
  33285. int ret = 0;
  33286. /* Validate parameters. */
  33287. if (opts == NULL) {
  33288. ret = BAD_FUNC_ARG;
  33289. }
  33290. if (ret == 0) {
  33291. switch (opt) {
  33292. /* Offset into DER/BER data to start decoding from. */
  33293. case ASN1_PRINT_OPT_OFFSET:
  33294. opts->offset = val;
  33295. break;
  33296. /* Length of DER/BER encoding to parse. */
  33297. case ASN1_PRINT_OPT_LENGTH:
  33298. opts->length = val;
  33299. break;
  33300. /* Number of spaces to indent for each change in depth. */
  33301. case ASN1_PRINT_OPT_INDENT:
  33302. /* Only 4 bits allowed for value. */
  33303. if (val >= (1 << 4)) {
  33304. ret = BAD_FUNC_ARG;
  33305. }
  33306. else {
  33307. opts->indent = (word8)val;
  33308. }
  33309. break;
  33310. /* Draw branches instead of indenting. */
  33311. case ASN1_PRINT_OPT_DRAW_BRANCH:
  33312. /* Boolean value. */
  33313. opts->draw_branch = (val > 0);
  33314. break;
  33315. /* Show raw data of primitive types as octets. */
  33316. case ASN1_PRINT_OPT_SHOW_DATA:
  33317. /* Boolean value. */
  33318. opts->show_data = (val > 0);
  33319. break;
  33320. /* Show header data as octets. */
  33321. case ASN1_PRINT_OPT_SHOW_HEADER_DATA:
  33322. /* Boolean value. */
  33323. opts->show_header_data = (val > 0);
  33324. break;
  33325. /* Show the wolfSSL OID value for OBJECT_ID. */
  33326. case ASN1_PRINT_OPT_SHOW_OID:
  33327. /* Boolean value. */
  33328. opts->show_oid = (val > 0);
  33329. break;
  33330. /* Don't show text representations of primitive types. */
  33331. case ASN1_PRINT_OPT_SHOW_NO_TEXT:
  33332. /* Boolean value. */
  33333. opts->show_no_text = (val > 0);
  33334. break;
  33335. /* Don't show dump text representations of primitive types. */
  33336. case ASN1_PRINT_OPT_SHOW_NO_DUMP_TEXT:
  33337. /* Boolean value. */
  33338. opts->show_no_dump_text = (val > 0);
  33339. break;
  33340. }
  33341. }
  33342. return ret;
  33343. }
  33344. /* Initialize an ASN.1 parse object.
  33345. *
  33346. * @param [in, out] asn1 ASN.1 parse object.
  33347. * @return 0 on success.
  33348. * @return BAD_FUNC_ARG when asn1 is NULL.
  33349. */
  33350. int wc_Asn1_Init(Asn1* asn1)
  33351. {
  33352. int ret = 0;
  33353. if (asn1 == NULL) {
  33354. ret = BAD_FUNC_ARG;
  33355. }
  33356. else {
  33357. XMEMSET(asn1, 0, sizeof(*asn1));
  33358. asn1->file = XBADFILE;
  33359. }
  33360. return ret;
  33361. }
  33362. /* Set the file to use when printing.
  33363. *
  33364. * @param [in, out] asn1 ASN.1 parse object.
  33365. * @param [in] file File to print to.
  33366. * @return 0 on success.
  33367. * @return BAD_FUNC_ARG when asn1 is NULL.
  33368. * @return BAD_FUNC_ARG when file is XBADFILE.
  33369. */
  33370. int wc_Asn1_SetFile(Asn1* asn1, XFILE file)
  33371. {
  33372. int ret = 0;
  33373. if ((asn1 == NULL) || (file == XBADFILE)) {
  33374. ret = BAD_FUNC_ARG;
  33375. }
  33376. else {
  33377. asn1->file = file;
  33378. }
  33379. return ret;
  33380. }
  33381. /* Maximum OID dotted form size. */
  33382. #define ASN1_OID_DOTTED_MAX_SZ 16
  33383. /* Print OID in dotted form or as hex bytes.
  33384. *
  33385. * @param [in] file File pointer to write to.
  33386. * @param [in] oid OBJECT_ID data.
  33387. * @param [in] oid_len Length of OBJECT_ID data.
  33388. */
  33389. static void PrintObjectIdNum(XFILE file, unsigned char* oid, word32 len)
  33390. {
  33391. word16 dotted_nums[ASN1_OID_DOTTED_MAX_SZ];
  33392. word32 num = ASN1_OID_DOTTED_MAX_SZ;
  33393. word32 i;
  33394. /* Decode OBJECT_ID into dotted form array. */
  33395. if (DecodeObjectId(oid, len, dotted_nums, &num) == 0) {
  33396. /* Print out each number of dotted form. */
  33397. for (i = 0; i < num; i++) {
  33398. XFPRINTF(file, "%d", dotted_nums[i]);
  33399. /* Add separator. */
  33400. if (i < num - 1) {
  33401. XFPRINTF(file, ".");
  33402. }
  33403. }
  33404. }
  33405. else {
  33406. /* Print out bytes as we couldn't decode. */
  33407. for (i = 0; i < len; i++) {
  33408. XFPRINTF(file, "%02x", oid[i]);
  33409. /* Add separator. */
  33410. if (i < len - 1) {
  33411. XFPRINTF(file, ":");
  33412. }
  33413. }
  33414. }
  33415. }
  33416. /* OID value to name mapping. */
  33417. typedef struct OidName {
  33418. /* wolfSSL OID value. */
  33419. word32 oid;
  33420. /* Long name to print when OID seen. */
  33421. const char* name;
  33422. } OidName;
  33423. /* Extra OID to name mappings. */
  33424. static const OidName extraOids[] = {
  33425. { 0x005c, "commonName" },
  33426. { 0x005d, "surname" },
  33427. { 0x005e, "serialNumber" },
  33428. { 0x005f, "countryName" },
  33429. { 0x0060, "localityName" },
  33430. { 0x0061, "stateOrProvinceName" },
  33431. { 0x0062, "streetAddress" },
  33432. { 0x0063, "organizationName" },
  33433. { 0x0064, "organizationUnitName" },
  33434. { 0x0065, "title" },
  33435. { 0x0086, "certificateExtension" },
  33436. { 0x028d, "emailAddress" },
  33437. { 0x0293, "challengePassword" },
  33438. { 0x029a, "extensionReq" },
  33439. };
  33440. /* Length of table of extra OID to name mappings. */
  33441. #define EXTRA_OIDS_LEN ((int)(sizeof(extraOids) / sizeof(*extraOids)))
  33442. /* Convert OID value to long name.
  33443. *
  33444. * @param [in] oid OID value.
  33445. * @param [out] name Long name for OID when known.
  33446. * @return 1 when OID known.
  33447. * @return 0 when OID not known.
  33448. */
  33449. static int Oid2LongName(word32 oid, const char** name)
  33450. {
  33451. int ret = 0;
  33452. int i;
  33453. /* Step through each entry in table. */
  33454. for (i = 0; i < EXTRA_OIDS_LEN; i++) {
  33455. if (extraOids[i].oid == oid) {
  33456. /* Return the name associated with the OID value. */
  33457. *name = extraOids[i].name;
  33458. ret = 1;
  33459. break;
  33460. }
  33461. }
  33462. return ret;
  33463. }
  33464. /* Print the text version of the OBJECT_ID.
  33465. *
  33466. * @param [in] asn1 ASN.1 parse object.
  33467. * @param [in] opts ASN.1 options for printing.
  33468. */
  33469. static void PrintObjectIdText(Asn1* asn1, Asn1PrintOptions* opts)
  33470. {
  33471. word32 oid = (word32)-1;
  33472. #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
  33473. int nid;
  33474. #endif
  33475. const char* ln = NULL;
  33476. word32 i = 0;
  33477. int known = 1;
  33478. /* Get the OID value for the OBJECT_ID. */
  33479. if (GetObjectId(asn1->data + asn1->offset, &i, &oid, oidIgnoreType,
  33480. asn1->item.len + 2) == ASN_PARSE_E) {
  33481. known = 0;
  33482. }
  33483. else
  33484. #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
  33485. /* Lookup NID for OID value. */
  33486. if ((nid = oid2nid(oid, oidIgnoreType)) != -1) {
  33487. /* Lookup long name for NID. */
  33488. ln = wolfSSL_OBJ_nid2ln(nid);
  33489. }
  33490. else
  33491. #endif
  33492. /* Lookup long name for extra known OID values. */
  33493. if (!Oid2LongName(oid, &ln)) {
  33494. /* Unknown OID value. */
  33495. ln = NULL;
  33496. known = 0;
  33497. }
  33498. XFPRINTF(asn1->file, ":");
  33499. /* Show OID value if not known or asked to. */
  33500. if ((!known) || opts->show_oid) {
  33501. XFPRINTF(asn1->file, "(0x%x) ", oid);
  33502. }
  33503. if (ln != NULL) {
  33504. /* Print long name. */
  33505. XFPRINTF(asn1->file, "%s", ln);
  33506. }
  33507. else {
  33508. /* Print out as numbers - either dotted or hex values. */
  33509. PrintObjectIdNum(asn1->file, asn1->data + asn1->item.data_idx,
  33510. asn1->item.len);
  33511. }
  33512. }
  33513. /* Print ASN.1 data as a character string.
  33514. *
  33515. * @param [in] asn1 ASN.1 parse object.
  33516. */
  33517. static void PrintText(Asn1* asn1)
  33518. {
  33519. word32 i;
  33520. XFPRINTF(asn1->file, ":");
  33521. /* Print all data bytes as characters. */
  33522. for (i = 0; i < asn1->item.len; i++) {
  33523. XFPRINTF(asn1->file, "%c", asn1->data[asn1->item.data_idx + i]);
  33524. }
  33525. }
  33526. /* Print data as a hex bytes.
  33527. *
  33528. * @param [in] file File pointer to write to.
  33529. * @param [in] data Data to print.
  33530. * @param [in] len Number of bytes to print.
  33531. */
  33532. static void PrintHex(XFILE file, unsigned char* data, word32 len)
  33533. {
  33534. word32 i;
  33535. /* Print data bytes as hex numbers. */
  33536. for (i = 0; i < len; i++) {
  33537. XFPRINTF(file, "%02x", data[i]);
  33538. }
  33539. }
  33540. /* Print ASN.1 data as a hex bytes.
  33541. *
  33542. * @param [in] asn1 ASN.1 parse object.
  33543. */
  33544. static void PrintHexText(Asn1* asn1)
  33545. {
  33546. XFPRINTF(asn1->file, ":");
  33547. PrintHex(asn1->file, asn1->data + asn1->item.data_idx, asn1->item.len);
  33548. }
  33549. /* Print ASN.1 BIT_STRING data as hex bytes noting special first byte.
  33550. *
  33551. * @param [in] asn1 ASN.1 parse object.
  33552. */
  33553. static void PrintBitStringText(Asn1* asn1)
  33554. {
  33555. if (asn1->item.len > 0) {
  33556. XFPRINTF(asn1->file, ":[%02x]", asn1->data[asn1->item.data_idx]);
  33557. PrintHex(asn1->file, asn1->data + asn1->item.data_idx + 1,
  33558. asn1->item.len - 1);
  33559. }
  33560. }
  33561. /* Print ASN.1 BOOLEAN data as text with value.
  33562. *
  33563. * @param [in] asn1 ASN.1 parse object.
  33564. */
  33565. static void PrintBooleanText(Asn1* asn1)
  33566. {
  33567. /* Booleans should be 1 byte of data. */
  33568. if (asn1->item.len == 1) {
  33569. XFPRINTF(asn1->file, ":%s (%d)",
  33570. (asn1->data[asn1->item.data_idx] == 0) ? "FALSE" : "TRUE",
  33571. asn1->data[asn1->item.data_idx]);
  33572. }
  33573. }
  33574. /* Print ASN.1 data as single byte +/- number.
  33575. *
  33576. * @param [in] asn1 ASN.1 parse object.
  33577. */
  33578. static void PrintNumberText(Asn1* asn1)
  33579. {
  33580. /* Only supporting 1 byte of data for now. */
  33581. if (asn1->item.len == 1) {
  33582. int num = asn1->data[asn1->item.data_idx];
  33583. XFPRINTF(asn1->file, ":%d", num >= 0x80 ? num - 0x100 : num);
  33584. }
  33585. }
  33586. /* Print ASN.1 data as a text based on the tag.
  33587. *
  33588. * TODO: handle more tags.
  33589. *
  33590. * @param [in] asn1 ASN.1 parse object.
  33591. * @param [in] opts ASN.1 options for printing.
  33592. */
  33593. static void PrintAsn1Text(Asn1* asn1, Asn1PrintOptions* opts)
  33594. {
  33595. /* Get the long name for OBJECT_ID where possible. */
  33596. if (asn1->item.tag == ASN_OBJECT_ID) {
  33597. PrintObjectIdText(asn1, opts);
  33598. }
  33599. /* Data is an array of printable characters. */
  33600. else if ((asn1->item.tag == ASN_UTF8STRING) ||
  33601. (asn1->item.tag == ASN_IA5_STRING) ||
  33602. (asn1->item.tag == ASN_PRINTABLE_STRING) ||
  33603. (asn1->item.tag == ASN_T61STRING) ||
  33604. (asn1->item.tag == ASN_BMPSTRING) ||
  33605. (asn1->item.tag == ASN_UTC_TIME) ||
  33606. (asn1->item.tag == ASN_GENERALIZED_TIME) ||
  33607. (asn1->item.tag == ASN_UNIVERSALSTRING) ||
  33608. (asn1->item.tag == ASN_OBJECT_DESC) ||
  33609. (asn1->item.tag == ASN_CHARACTER_STRING)) {
  33610. PrintText(asn1);
  33611. }
  33612. /* Show TRUE and FALSE with number. */
  33613. else if (asn1->item.tag == ASN_BOOLEAN) {
  33614. PrintBooleanText(asn1);
  33615. }
  33616. /* Show number. */
  33617. else if (asn1->item.tag == ASN_ENUMERATED) {
  33618. PrintNumberText(asn1);
  33619. }
  33620. /* Dumping potentially long string of hex digites. */
  33621. else if (!opts->show_no_dump_text) {
  33622. /* Dump all bytes. */
  33623. if ((asn1->item.tag == ASN_INTEGER) ||
  33624. (asn1->item.tag == ASN_OCTET_STRING) ||
  33625. ((asn1->item.tag > ASN_APPLICATION) && (asn1->item.cons))) {
  33626. PrintHexText(asn1);
  33627. }
  33628. /* First byte is number of unused bits in last byte.
  33629. * Print first specially and dump rest of the bytes. */
  33630. else if (asn1->item.tag == ASN_BIT_STRING) {
  33631. PrintBitStringText(asn1);
  33632. }
  33633. }
  33634. }
  33635. #define HexToChar(n) ((((n) >= 32) && ((n) < 127)) ? (n) : '.')
  33636. /* Dump data as hex bytes.
  33637. *
  33638. * @param [in] file File pointer to write to.
  33639. * @param [in] data Data to print.
  33640. * @param [in] len Number of bytes to print.
  33641. */
  33642. static void DumpData(XFILE file, unsigned char* data, word32 len)
  33643. {
  33644. word32 i;
  33645. word32 j;
  33646. for (i = 0; i < len; i += j) {
  33647. /* Print offset. */
  33648. XFPRINTF(file, " %04x:", i);
  33649. for (j = 0; (j < 16) && (i + j < len); j++) {
  33650. /* Print byte as hex number. */
  33651. XFPRINTF(file, "%s%02x", (j == 8) ? " " : " ", data[i + j]);
  33652. }
  33653. /* Print spaces between hex and characters. */
  33654. XFPRINTF(file, " %*s", (16 - j) * 3 + ((j < 8) ? 1 : 0), "");
  33655. for (j = 0; (j < 16) && (i + j < len); j++) {
  33656. /* Print byte as hex number. */
  33657. XFPRINTF(file, "%c", HexToChar(data[i + j]));
  33658. }
  33659. XFPRINTF(file, "\n");
  33660. }
  33661. }
  33662. /* Update current depth based on the current position.
  33663. *
  33664. * @param [in, out] asn1 ASN.1 parse object.
  33665. */
  33666. static void UpdateDepth(Asn1* asn1)
  33667. {
  33668. /* If current index is greater than or equal end index then it is done. */
  33669. while ((asn1->depth > 0) &&
  33670. (asn1->end_idx[asn1->depth-1] <= asn1->curr)) {
  33671. /* Move up a depth. */
  33672. asn1->depth--;
  33673. }
  33674. }
  33675. /* Check validity of end index of constructed ASN.1 items.
  33676. *
  33677. * @param [in, out] asn1 ASN.1 parse object.
  33678. * @return 0 on success.
  33679. * @return ASN_DEPTH_E when end offset invalid.
  33680. */
  33681. static int CheckDepth(Asn1* asn1)
  33682. {
  33683. int ret = 0;
  33684. int i;
  33685. word32 curr_end = asn1->curr + asn1->item.len;
  33686. for (i = 0; (ret == 0) && (i < asn1->depth); i++) {
  33687. /* Each end index must be at least as large as the current one. */
  33688. if (asn1->end_idx[i] < asn1->end_idx[asn1->depth]) {
  33689. ret = ASN_DEPTH_E;
  33690. }
  33691. /* Each end index must be at least as large as current index. */
  33692. if (asn1->end_idx[i] < curr_end) {
  33693. ret = ASN_DEPTH_E;
  33694. }
  33695. }
  33696. return ret;
  33697. }
  33698. /* Draw branching based on depth for an ASN.1 item.
  33699. *
  33700. * @param [in] asn1 ASN.1 parse object.
  33701. */
  33702. static void DrawBranch(Asn1* asn1)
  33703. {
  33704. int i;
  33705. word32 end = asn1->curr + asn1->item.len;
  33706. /* Write out the character for all depths but current. */
  33707. for (i = 0; i < asn1->depth; i++) {
  33708. if (asn1->item.cons || (end < asn1->end_idx[i])) {
  33709. if (i < asn1->depth - 1) {
  33710. /* Constructed or not end index and not current depth: | */
  33711. XFPRINTF(asn1->file, "\xe2\x94\x82");
  33712. }
  33713. else {
  33714. /* Constructed or not end index and current depth: |- */
  33715. XFPRINTF(asn1->file, "\xe2\x94\x9c");
  33716. }
  33717. }
  33718. else if ((i > 1) && (end >= asn1->end_idx[i-1])) {
  33719. /* End index for previous: _|_ (in top half) */
  33720. XFPRINTF(asn1->file, "\xe2\x94\xb4");
  33721. }
  33722. else {
  33723. /* End index but not for previous: L (in top half) */
  33724. XFPRINTF(asn1->file, "\xe2\x94\x94");
  33725. }
  33726. }
  33727. /* Prefix to tag name. */
  33728. if (asn1->item.cons) {
  33729. if (asn1->depth > 0) {
  33730. /* Have other line to connect to: T (in bottom half) */
  33731. XFPRINTF(asn1->file, "\xe2\x94\xac");
  33732. }
  33733. else {
  33734. /* Have no other line to connect to: r */
  33735. XFPRINTF(asn1->file, "\xe2\x94\x8c");
  33736. }
  33737. }
  33738. else {
  33739. /* In a sequence: - */
  33740. XFPRINTF(asn1->file, "\xe2\x94\x80");
  33741. }
  33742. }
  33743. /* Print data as hex bytes separated by space.
  33744. *
  33745. * @param [in] file File pointer to write to.
  33746. * @param [in] data Data to print.
  33747. * @param [in] len Number of bytes to print.
  33748. */
  33749. static void PrintHexBytes(XFILE file, unsigned char* data, word32 len)
  33750. {
  33751. word32 i;
  33752. for (i = 0; i < len; i++) {
  33753. XFPRINTF(file, " %02x", data[i]);
  33754. }
  33755. }
  33756. /* Dump header data.
  33757. *
  33758. * @param [in] asn1 ASN.1 parse object.
  33759. * @param [in] opts ASN.1 options for printing.
  33760. */
  33761. static void DumpHeader(Asn1* asn1, Asn1PrintOptions* opts)
  33762. {
  33763. /* Put on same line when not showing data too and not showing text data. */
  33764. if ((!opts->show_data) && opts->show_no_text) {
  33765. XFPRINTF(asn1->file, "%10s", "");
  33766. }
  33767. else {
  33768. /* Align with start of data. */
  33769. XFPRINTF(asn1->file, "\n%12s", "");
  33770. }
  33771. XFPRINTF(asn1->file, " %02x", asn1->item.tag);
  33772. if (asn1->curr >= asn1->offset + 1) {
  33773. /* Print the header bytes as hex bytes separated by a space. */
  33774. PrintHexBytes(asn1->file, asn1->data + asn1->offset + 1,
  33775. asn1->curr - (asn1->offset + 1));
  33776. }
  33777. }
  33778. /* Print ASN.1 item info based on header and indices.
  33779. *
  33780. * @param [in] asn1 ASN.1 parse object.
  33781. * @param [in] opts ASN.1 options for printing.
  33782. */
  33783. static void PrintInfo(Asn1* asn1, Asn1PrintOptions* opts)
  33784. {
  33785. /* Print offset of this ASN.1 item. */
  33786. XFPRINTF(asn1->file, "%4d: ", asn1->offset);
  33787. /* Print length of header. */
  33788. XFPRINTF(asn1->file, "%1d ", asn1->curr - asn1->offset);
  33789. /* Print data length. */
  33790. XFPRINTF(asn1->file, "%c%4d%c", asn1->item.cons ? '[' : '+', asn1->item.len,
  33791. asn1->item.cons ? ']' : ' ');
  33792. /* Print depth. */
  33793. XFPRINTF(asn1->file, " %s(%d)", (asn1->depth < 10) ? " " : "", asn1->depth);
  33794. if (!opts->draw_branch) {
  33795. /* Indent to depth as required. */
  33796. XFPRINTF(asn1->file, "%*s ", asn1->depth * opts->indent, "");
  33797. if (!opts->indent) {
  33798. /* Indicate constructed if no indent. */
  33799. XFPRINTF(asn1->file, "%c", asn1->item.cons ? '+' : ' ');
  33800. }
  33801. }
  33802. else {
  33803. /* Draw branch structure for ASN.1 item. */
  33804. XFPRINTF(asn1->file, " ");
  33805. DrawBranch(asn1);
  33806. }
  33807. /* Print tag name. */
  33808. XFPRINTF(asn1->file, "%-16s", TagString(asn1->item.tag));
  33809. }
  33810. /* Expecting tag part of ASN.1 item. */
  33811. #define ASN_PART_TAG 0
  33812. /* Expecting length part of ASN.1 item. */
  33813. #define ASN_PART_LENGTH 1
  33814. /* Expecting data part of ASN.1 item. */
  33815. #define ASN_PART_DATA 2
  33816. /* Print next ASN.1 item.
  33817. *
  33818. * @param [in, out] asn1 ASN.1 parse object.
  33819. * @param [in] opts ASN.1 print options.
  33820. * @return 0 on success.
  33821. * @return BAD_FUNC_ARG when asn1 or opts is NULL.
  33822. * @return ASN_LEN_E when ASN.1 item's length too long.
  33823. * @return ASN_DEPTH_E when end offset invalid.
  33824. */
  33825. static int wc_Asn1_Print(Asn1* asn1, Asn1PrintOptions* opts)
  33826. {
  33827. int ret = 0;
  33828. /* Process tag. */
  33829. if (asn1->part == ASN_PART_TAG) {
  33830. /* Recalculate which depth we are at. */
  33831. UpdateDepth(asn1);
  33832. /* Get tag. */
  33833. asn1->item.tag = asn1->data[asn1->curr] & (byte)~ASN_CONSTRUCTED;
  33834. /* Store whether tag indicates constructed. */
  33835. asn1->item.cons = (asn1->data[asn1->curr] & ASN_CONSTRUCTED) ==
  33836. ASN_CONSTRUCTED;
  33837. /* Start of ASN.1 item is current index. */
  33838. asn1->offset = asn1->curr;
  33839. /* Step over tag. */
  33840. asn1->curr++;
  33841. /* Next part is length. */
  33842. asn1->part = ASN_PART_LENGTH;
  33843. }
  33844. /* Process length. */
  33845. if (asn1->part == ASN_PART_LENGTH) {
  33846. int len;
  33847. /* Decode length and step over it. */
  33848. if (GetLength(asn1->data, &asn1->curr, &len, asn1->max) < 0) {
  33849. ret = ASN_LEN_E;
  33850. }
  33851. else {
  33852. /* Store ASN.1 item data offset. */
  33853. asn1->item.data_idx = asn1->curr;
  33854. /* Store ASN.1 item data length. */
  33855. asn1->item.len = (word32)len;
  33856. /* Print info about ASN.1 item. */
  33857. PrintInfo(asn1, opts);
  33858. if (!asn1->item.cons) {
  33859. /* Move on to print data. */
  33860. asn1->part = ASN_PART_DATA;
  33861. }
  33862. else {
  33863. /* Print header now if not printing data. */
  33864. if (opts->show_header_data) {
  33865. DumpHeader(asn1, opts);
  33866. }
  33867. XFPRINTF(asn1->file, "\n");
  33868. /* Record end offset for this depth. */
  33869. asn1->end_idx[asn1->depth++] = asn1->curr + asn1->item.len;
  33870. /* Done with this ASN.1 item. */
  33871. asn1->part = ASN_PART_TAG;
  33872. }
  33873. /* Check end indices are valid. */
  33874. ret = CheckDepth(asn1);
  33875. }
  33876. }
  33877. /* Process data. */
  33878. if ((ret == 0) && (asn1->part == ASN_PART_DATA)) {
  33879. if (!opts->show_no_text) {
  33880. /* Print text representation of data. */
  33881. PrintAsn1Text(asn1, opts);
  33882. }
  33883. if (opts->show_header_data) {
  33884. /* Dump header bytes. */
  33885. DumpHeader(asn1, opts);
  33886. }
  33887. XFPRINTF(asn1->file, "\n");
  33888. if (opts->show_data) {
  33889. /* Dump data bytes. */
  33890. DumpData(asn1->file, asn1->data + asn1->item.data_idx,
  33891. asn1->item.len);
  33892. }
  33893. /* Step past data to next ASN.1 item. */
  33894. asn1->curr += asn1->item.len;
  33895. /* Update the depth based on end indices. */
  33896. UpdateDepth(asn1);
  33897. /* Done with this ASN.1 item. */
  33898. asn1->part = ASN_PART_TAG;
  33899. }
  33900. /* Make ASN.1 item printing go out. */
  33901. fflush(asn1->file);
  33902. return ret;
  33903. }
  33904. /* Print all ASN.1 items.
  33905. *
  33906. * @param [in, out] asn1 ASN.1 parse object.
  33907. * @param [in] opts ASN.1 print options.
  33908. * @param [in] data BER/DER data to print.
  33909. * @param [in] len Length of data to print in bytes.
  33910. * @return 0 on success.
  33911. * @return BAD_FUNC_ARG when asn1, opts or data is NULL.
  33912. * @return ASN_LEN_E when ASN.1 item's length too long.
  33913. * @return ASN_DEPTH_E when end offset invalid.
  33914. * @return ASN_PARSE_E when not all of an ASN.1 item parsed.
  33915. */
  33916. int wc_Asn1_PrintAll(Asn1* asn1, Asn1PrintOptions* opts, unsigned char* data,
  33917. word32 len)
  33918. {
  33919. int ret = 0;
  33920. if ((asn1 == NULL) || (opts == NULL) || (data == NULL)) {
  33921. ret = BAD_FUNC_ARG;
  33922. }
  33923. if (ret == 0) {
  33924. /* Initialize start position. */
  33925. asn1->curr = 0;
  33926. /* Start parsing at tag. */
  33927. asn1->part = ASN_PART_TAG;
  33928. /* Start depth at 0. */
  33929. asn1->depth = 0;
  33930. /* Store the starting point of the data to parse. */
  33931. asn1->data = data + opts->offset;
  33932. if (opts->length > 0) {
  33933. /* Use user specified maximum length. */
  33934. asn1->max = opts->length;
  33935. }
  33936. else {
  33937. /* Maximum length is up to end from offset. */
  33938. asn1->max = len - opts->offset;
  33939. }
  33940. /* Keep going while no error and have data to parse. */
  33941. while ((ret == 0) && (asn1->curr < asn1->max)) {
  33942. /* Print an ASN.1 item. */
  33943. ret = wc_Asn1_Print(asn1, opts);
  33944. }
  33945. }
  33946. if ((ret == 0) && (asn1->part != ASN_PART_TAG)) {
  33947. /* Stopped before finishing ASN.1 item. */
  33948. ret = ASN_PARSE_E;
  33949. }
  33950. if ((ret == 0) && (asn1->depth != 0)) {
  33951. /* Stopped without seeing all items in a constructed item. */
  33952. ret = ASN_DEPTH_E;
  33953. }
  33954. return ret;
  33955. }
  33956. #endif /* WOLFSSL_ASN_PRINT */
  33957. #endif /* !NO_ASN */
  33958. /* Functions that parse, but are not using ASN.1 */
  33959. #if !defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
  33960. (!defined(NO_BIG_INT) || defined(WOLFSSL_SP_MATH))
  33961. /* import RSA public key elements (n, e) into RsaKey structure (key) */
  33962. /* this function does not use any ASN.1 parsing */
  33963. int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e,
  33964. word32 eSz, RsaKey* key)
  33965. {
  33966. if (n == NULL || e == NULL || key == NULL)
  33967. return BAD_FUNC_ARG;
  33968. key->type = RSA_PUBLIC;
  33969. if (mp_init(&key->n) != MP_OKAY)
  33970. return MP_INIT_E;
  33971. if (mp_read_unsigned_bin(&key->n, n, nSz) != 0) {
  33972. mp_clear(&key->n);
  33973. return ASN_GETINT_E;
  33974. }
  33975. #ifdef HAVE_WOLF_BIGINT
  33976. if ((int)nSz > 0 && wc_bigint_from_unsigned_bin(&key->n.raw, n, nSz) != 0) {
  33977. mp_clear(&key->n);
  33978. return ASN_GETINT_E;
  33979. }
  33980. #endif /* HAVE_WOLF_BIGINT */
  33981. if (mp_init(&key->e) != MP_OKAY) {
  33982. mp_clear(&key->n);
  33983. return MP_INIT_E;
  33984. }
  33985. if (mp_read_unsigned_bin(&key->e, e, eSz) != 0) {
  33986. mp_clear(&key->n);
  33987. mp_clear(&key->e);
  33988. return ASN_GETINT_E;
  33989. }
  33990. #ifdef HAVE_WOLF_BIGINT
  33991. if ((int)eSz > 0 && wc_bigint_from_unsigned_bin(&key->e.raw, e, eSz) != 0) {
  33992. mp_clear(&key->n);
  33993. mp_clear(&key->e);
  33994. return ASN_GETINT_E;
  33995. }
  33996. #endif /* HAVE_WOLF_BIGINT */
  33997. #ifdef WOLFSSL_XILINX_CRYPT
  33998. if (wc_InitRsaHw(key) != 0) {
  33999. return BAD_STATE_E;
  34000. }
  34001. #endif
  34002. return 0;
  34003. }
  34004. #endif /* !NO_RSA && !HAVE_USER_RSA && (!NO_BIG_INT || WOLFSSL_SP_MATH) */
  34005. #ifdef WOLFSSL_SEP
  34006. #endif /* WOLFSSL_SEP */