asn.c 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951
  1. /* asn.c
  2. *
  3. * Copyright (C) 2006-2022 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: Disables time parts of the ASN code for systems without an RTC
  43. or wishing to save space.
  44. * IGNORE_NAME_CONSTRAINTS: Skip ASN name checks.
  45. * ASN_DUMP_OID: Allows dump of OID information for debugging.
  46. * RSA_DECODE_EXTRA: Decodes extra information in RSA public key.
  47. * WOLFSSL_CERT_GEN: Cert generation. Saves extra certificate info in GetName.
  48. * WOLFSSL_NO_ASN_STRICT: Disable strict RFC compliance checks to
  49. restore 3.13.0 behavior.
  50. * WOLFSSL_NO_OCSP_OPTIONAL_CERTS: Skip optional OCSP certs (responder issuer
  51. must still be trusted)
  52. * WOLFSSL_NO_TRUSTED_CERTS_VERIFY: Workaround for situation where entire cert
  53. chain is not loaded. This only matches on subject and public key and
  54. does not perform a PKI validation, so it is not a secure solution.
  55. Only enabled for OCSP.
  56. * WOLFSSL_NO_OCSP_ISSUER_CHECK: Can be defined for backwards compatibility to
  57. disable checking of OCSP subject hash with issuer hash.
  58. * WOLFSSL_SMALL_CERT_VERIFY: Verify the certificate signature without using
  59. DecodedCert. Doubles up on some code but allows smaller dynamic memory
  60. usage.
  61. * WOLFSSL_NO_OCSP_DATE_CHECK: Disable date checks for OCSP responses. This
  62. may be required when the system's real-time clock is not very accurate.
  63. It is recommended to enforce the nonce check instead if possible.
  64. * WOLFSSL_FORCE_OCSP_NONCE_CHECK: Require nonces to be available in OCSP
  65. responses. The nonces are optional and may not be supported by all
  66. responders. If it can be ensured that the used responder sends nonces this
  67. option may improve security.
  68. * WOLFSSL_ASN_TEMPLATE: Encoding and decoding using a template.
  69. * WOLFSSL_DEBUG_ASN_TEMPLATE: Enables debugging output when using ASN.1
  70. templates.
  71. * WOLFSSL_ASN_TEMPLATE_TYPE_CHECK: Use ASN functions to better test compiler
  72. type issues for testing
  73. * CRLDP_VALIDATE_DATA: For ASN template only, validates the reason data
  74. * WOLFSSL_AKID_NAME: Enable support for full AuthorityKeyIdentifier extension.
  75. Only supports copying full AKID from an existing certificate.
  76. * WOLFSSL_CUSTOM_OID: Enable custom OID support for subject and request
  77. extensions
  78. * WOLFSSL_HAVE_ISSUER_NAMES: Store pointers to issuer name components and their
  79. lengths and encodings.
  80. * WOLFSSL_SUBJ_DIR_ATTR: Enable support for SubjectDirectoryAttributes
  81. extension.
  82. * WOLFSSL_SUBJ_INFO_ACC: Enable support for SubjectInfoAccess extension.
  83. * WOLFSSL_FPKI: Enable support for FPKI (Federal PKI) extensions.
  84. * WOLFSSL_CERT_NAME_ALL: Adds more certificate name capability at the
  85. cost of taking up more memory. Adds initials, givenname, dnQualifer for
  86. example.
  87. * WC_ASN_HASH_SHA256: Force use of SHA2-256 for the internal hash ID calcs.
  88. */
  89. #ifndef NO_ASN
  90. #include <wolfssl/wolfcrypt/asn.h>
  91. #include <wolfssl/wolfcrypt/coding.h>
  92. #include <wolfssl/wolfcrypt/md2.h>
  93. #include <wolfssl/wolfcrypt/hmac.h>
  94. #include <wolfssl/wolfcrypt/error-crypt.h>
  95. #include <wolfssl/wolfcrypt/pwdbased.h>
  96. #include <wolfssl/wolfcrypt/des3.h>
  97. #include <wolfssl/wolfcrypt/aes.h>
  98. #include <wolfssl/wolfcrypt/rc2.h>
  99. #include <wolfssl/wolfcrypt/wc_encrypt.h>
  100. #include <wolfssl/wolfcrypt/logging.h>
  101. #include <wolfssl/wolfcrypt/random.h>
  102. #include <wolfssl/wolfcrypt/hash.h>
  103. #ifdef NO_INLINE
  104. #include <wolfssl/wolfcrypt/misc.h>
  105. #else
  106. #define WOLFSSL_MISC_INCLUDED
  107. #include <wolfcrypt/src/misc.c>
  108. #endif
  109. #ifndef NO_RC4
  110. #include <wolfssl/wolfcrypt/arc4.h>
  111. #endif
  112. #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
  113. #include <wolfssl/wolfcrypt/sha512.h>
  114. #endif
  115. #ifndef NO_SHA256
  116. #include <wolfssl/wolfcrypt/sha256.h>
  117. #endif
  118. #ifdef HAVE_ECC
  119. #include <wolfssl/wolfcrypt/ecc.h>
  120. #endif
  121. #ifdef HAVE_ED25519
  122. #include <wolfssl/wolfcrypt/ed25519.h>
  123. #endif
  124. #ifdef HAVE_CURVE25519
  125. #include <wolfssl/wolfcrypt/curve25519.h>
  126. #endif
  127. #ifdef HAVE_ED448
  128. #include <wolfssl/wolfcrypt/ed448.h>
  129. #endif
  130. #ifdef HAVE_CURVE448
  131. #include <wolfssl/wolfcrypt/curve448.h>
  132. #endif
  133. #ifdef HAVE_PQC
  134. #if defined(HAVE_FALCON)
  135. #include <wolfssl/wolfcrypt/falcon.h>
  136. #endif
  137. #if defined(HAVE_DILITHIUM)
  138. #include <wolfssl/wolfcrypt/dilithium.h>
  139. #endif
  140. #if defined(HAVE_SPHINCS)
  141. #include <wolfssl/wolfcrypt/sphincs.h>
  142. #endif
  143. #endif
  144. #ifdef WOLFSSL_QNX_CAAM
  145. #include <wolfssl/wolfcrypt/port/caam/wolfcaam.h>
  146. #endif
  147. #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  148. #include <wolfssl/wolfcrypt/port/Renesas/renesas_cmn.h>
  149. #endif
  150. #ifndef NO_RSA
  151. #include <wolfssl/wolfcrypt/rsa.h>
  152. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  153. extern int wc_InitRsaHw(RsaKey* key);
  154. #endif
  155. #endif
  156. #ifndef NO_DSA
  157. #include <wolfssl/wolfcrypt/dsa.h>
  158. #else
  159. typedef void* DsaKey;
  160. #endif
  161. #ifdef WOLF_CRYPTO_CB
  162. #include <wolfssl/wolfcrypt/cryptocb.h>
  163. #endif
  164. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  165. #include <wolfssl/internal.h>
  166. #include <wolfssl/openssl/objects.h>
  167. #endif
  168. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  169. !defined(WOLFCRYPT_ONLY)
  170. #define WOLFSSL_X509_NAME_AVAILABLE
  171. #endif
  172. #ifdef _MSC_VER
  173. /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
  174. #pragma warning(disable: 4996)
  175. #endif
  176. #define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
  177. #if !defined(NO_SKID) && (!defined(HAVE_FIPS) || !defined(HAVE_FIPS_VERSION))
  178. #if !defined(HAVE_SELFTEST) || (defined(HAVE_SELFTEST) && \
  179. (!defined(HAVE_SELFTEST_VERSION) || \
  180. HAVE_SELFTEST_VERSION < 2))
  181. #ifndef WOLFSSL_AES_KEY_SIZE_ENUM
  182. #define WOLFSSL_AES_KEY_SIZE_ENUM
  183. enum Asn_Misc {
  184. AES_IV_SIZE = 16,
  185. AES_128_KEY_SIZE = 16,
  186. AES_192_KEY_SIZE = 24,
  187. AES_256_KEY_SIZE = 32
  188. };
  189. #endif
  190. #endif /* HAVE_SELFTEST */
  191. #endif
  192. /* Calculates the minimum number of bytes required to encode the value.
  193. *
  194. * Only support up to 2^24-1.
  195. *
  196. * @param [in] value Value to be encoded.
  197. * @return Number of bytes to encode value.
  198. */
  199. static word32 BytePrecision(word32 value)
  200. {
  201. word32 i;
  202. for (i = (word32)sizeof(value) - 1; i; --i)
  203. if (value >> ((i - 1) * WOLFSSL_BIT_SIZE))
  204. break;
  205. return i;
  206. }
  207. /* DER encodes the length value in output buffer.
  208. *
  209. * 0 -> 2^7-1: <len byte>.
  210. * 2^7 -> : <0x80 + #bytes> <len big-endian bytes>
  211. *
  212. * @param [in] length Value to encode.
  213. * @param [in, out] output Buffer to encode into.
  214. * @return Number of bytes used in encoding.
  215. */
  216. WOLFSSL_LOCAL word32 SetASNLength(word32 length, byte* output)
  217. {
  218. word32 i = 0, j;
  219. if (length < ASN_LONG_LENGTH)
  220. output[i++] = (byte)length;
  221. else {
  222. output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);
  223. for (j = BytePrecision(length); j; --j) {
  224. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  225. i++;
  226. }
  227. }
  228. return i;
  229. }
  230. #ifdef WOLFSSL_ASN_TEMPLATE
  231. /* Calculate the size of a DER encoded length value.
  232. *
  233. * 0 -> 2^7-1: <length byte>.
  234. * 2^7 -> : <0x80 + #bytes> <big-endian length bytes>
  235. *
  236. * @param [in] length Value to encode.
  237. * @return Number of bytes required to encode.
  238. */
  239. static word32 SizeASNLength(word32 length)
  240. {
  241. return 1 + ((length >= ASN_LONG_LENGTH) ? BytePrecision(length) : 0);
  242. }
  243. /* Calculate the size of a DER encoded header.
  244. *
  245. * Header = Tag | Encoded length
  246. *
  247. * @param [in] length Length value to encode.
  248. * @return Number of bytes required to encode a DER header.
  249. */
  250. #define SizeASNHeader(length) \
  251. (1 + SizeASNLength(length))
  252. #endif
  253. #ifdef WOLFSSL_ASN_TEMPLATE
  254. #ifdef WOLFSSL_SMALL_STACK
  255. /* Declare the variable that is the dynamic data for decoding BER data.
  256. *
  257. * @param [in] name Variable name to declare.
  258. * @param [in] cnt Number of elements required.
  259. */
  260. #define DECL_ASNGETDATA(name, cnt) \
  261. ASNGetData* name = NULL
  262. /* Allocates the dynamic BER decoding data.
  263. *
  264. * @param [in] name Variable name to declare.
  265. * @param [in] cnt Number of elements required.
  266. * @param [in, out] err Error variable.
  267. * @param [in] heap Dynamic memory allocation hint.
  268. */
  269. #define ALLOC_ASNGETDATA(name, cnt, err, heap) \
  270. do { \
  271. if ((err) == 0) { \
  272. (name) = (ASNGetData*)XMALLOC(sizeof(ASNGetData) * (cnt), (heap), \
  273. DYNAMIC_TYPE_TMP_BUFFER); \
  274. if ((name) == NULL) { \
  275. (err) = MEMORY_E; \
  276. } \
  277. } \
  278. } \
  279. while (0)
  280. /* Allocates the dynamic BER decoding data and clears the memory.
  281. *
  282. * @param [in] name Variable name to declare.
  283. * @param [in] cnt Number of elements required.
  284. * @param [in, out] err Error variable.
  285. * @param [in] heap Dynamic memory allocation hint.
  286. */
  287. #define CALLOC_ASNGETDATA(name, cnt, err, heap) \
  288. do { \
  289. ALLOC_ASNGETDATA(name, cnt, err, heap); \
  290. if ((err) == 0) { \
  291. XMEMSET((name), 0, sizeof(ASNGetData) * (cnt)); \
  292. } \
  293. } \
  294. while (0)
  295. /* Disposes of the dynamic BER decoding data.
  296. *
  297. * @param [in] name Variable name to declare.
  298. * @param [in] heap Dynamic memory allocation hint.
  299. */
  300. #define FREE_ASNGETDATA(name, heap) \
  301. do { \
  302. if ((name) != NULL) { \
  303. XFREE((name), (heap), DYNAMIC_TYPE_TMP_BUFFER); \
  304. } \
  305. } \
  306. while (0)
  307. /* Declare the variable that is the dynamic data for encoding DER data.
  308. *
  309. * @param [in] name Variable name to declare.
  310. * @param [in] cnt Number of elements required.
  311. */
  312. #define DECL_ASNSETDATA(name, cnt) \
  313. ASNSetData* name = NULL
  314. /* Allocates the dynamic DER encoding data.
  315. *
  316. * @param [in] name Variable name to declare.
  317. * @param [in] cnt Number of elements required.
  318. * @param [in, out] err Error variable.
  319. * @param [in] heap Dynamic memory allocation hint.
  320. */
  321. #define ALLOC_ASNSETDATA(name, cnt, err, heap) \
  322. do { \
  323. if ((err) == 0) { \
  324. (name) = (ASNSetData*)XMALLOC(sizeof(ASNGetData) * (cnt), (heap), \
  325. DYNAMIC_TYPE_TMP_BUFFER); \
  326. if ((name) == NULL) { \
  327. (err) = MEMORY_E; \
  328. } \
  329. } \
  330. } \
  331. while (0)
  332. /* Allocates the dynamic DER encoding data and clears the memory.
  333. *
  334. * @param [in] name Variable name to declare.
  335. * @param [in] cnt Number of elements required.
  336. * @param [in, out] err Error variable.
  337. * @param [in] heap Dynamic memory allocation hint.
  338. */
  339. #define CALLOC_ASNSETDATA(name, cnt, err, heap) \
  340. do { \
  341. ALLOC_ASNSETDATA(name, cnt, err, heap); \
  342. if ((err) == 0) { \
  343. XMEMSET(name, 0, sizeof(ASNSetData) * (cnt)); \
  344. } \
  345. } \
  346. while (0)
  347. /* Disposes of the dynamic DER encoding data.
  348. *
  349. * @param [in] name Variable name to declare.
  350. * @param [in] heap Dynamic memory allocation hint.
  351. */
  352. #define FREE_ASNSETDATA(name, heap) \
  353. do { \
  354. if ((name) != NULL) { \
  355. XFREE(name, heap, DYNAMIC_TYPE_TMP_BUFFER); \
  356. } \
  357. } \
  358. while (0)
  359. #else
  360. /* Declare the variable that is the dynamic data for decoding BER data.
  361. *
  362. * @param [in] name Variable name to declare.
  363. * @param [in] cnt Number of elements required.
  364. */
  365. #define DECL_ASNGETDATA(name, cnt) \
  366. ASNGetData name[cnt]
  367. /* No implementation as declaration is static.
  368. *
  369. * @param [in] name Variable name to declare.
  370. * @param [in] cnt Number of elements required.
  371. * @param [in, out] err Error variable.
  372. * @param [in] heap Dynamic memory allocation hint.
  373. */
  374. #define ALLOC_ASNGETDATA(name, cnt, err, heap)
  375. /* Clears the memory of the dynamic BER encoding data.
  376. *
  377. * @param [in] name Variable name to declare.
  378. * @param [in] cnt Number of elements required.
  379. * @param [in, out] err Error variable.
  380. * @param [in] heap Dynamic memory allocation hint.
  381. */
  382. #define CALLOC_ASNGETDATA(name, cnt, err, heap) \
  383. XMEMSET(name, 0, sizeof(name))
  384. /* No implementation as declaration is static.
  385. *
  386. * @param [in] name Variable name to declare.
  387. * @param [in] heap Dynamic memory allocation hint.
  388. */
  389. #define FREE_ASNGETDATA(name, heap)
  390. /* Declare the variable that is the dynamic data for encoding DER data.
  391. *
  392. * @param [in] name Variable name to declare.
  393. * @param [in] cnt Number of elements required.
  394. */
  395. #define DECL_ASNSETDATA(name, cnt) \
  396. ASNSetData name[cnt]
  397. /* No implementation as declaration is static.
  398. *
  399. * @param [in] name Variable name to declare.
  400. * @param [in] cnt Number of elements required.
  401. * @param [in, out] err Error variable.
  402. * @param [in] heap Dynamic memory allocation hint.
  403. */
  404. #define ALLOC_ASNSETDATA(name, cnt, err, heap)
  405. /* Clears the memory of the dynamic BER encoding data.
  406. *
  407. * @param [in] name Variable name to declare.
  408. * @param [in] cnt Number of elements required.
  409. * @param [in, out] err Error variable.
  410. * @param [in] heap Dynamic memory allocation hint.
  411. */
  412. #define CALLOC_ASNSETDATA(name, cnt, err, heap) \
  413. XMEMSET(name, 0, sizeof(name))
  414. /* No implementation as declaration is static.
  415. *
  416. * @param [in] name Variable name to declare.
  417. * @param [in] heap Dynamic memory allocation hint.
  418. */
  419. #define FREE_ASNSETDATA(name, heap)
  420. #endif
  421. #ifdef DEBUG_WOLFSSL
  422. /* Enable this when debugging the parsing or creation of ASN.1 data. */
  423. #if 0
  424. #define WOLFSSL_DEBUG_ASN_TEMPLATE
  425. #endif
  426. #endif
  427. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  428. /* String representations of tags. */
  429. static const char* tagString[4][32] = {
  430. /* Universal */
  431. {
  432. "EOC",
  433. "BOOLEAN",
  434. "INTEGER",
  435. "BIT STRING",
  436. "OCTET STRING",
  437. "NULL",
  438. "OBJECT ID",
  439. "ObjectDescriptor",
  440. "INSTANCE OF",
  441. "REAL",
  442. "ENUMERATED",
  443. "EMBEDDED PDV",
  444. "UT8String",
  445. "RELATIVE-OID",
  446. "(0x0e) 14",
  447. "(0x0f) 15",
  448. "SEQUENCE",
  449. "SET",
  450. "NumericString",
  451. "PrintableString",
  452. "T61String",
  453. "VideotexString",
  454. "IA5String",
  455. "UTCTime",
  456. "GeneralizedTime",
  457. "GraphicString",
  458. "ISO646String",
  459. "GeneralString",
  460. "UniversalString",
  461. "CHARACTER STRING",
  462. "BMPString",
  463. "(0x1f) 31",
  464. },
  465. /* Application */
  466. {
  467. "[A 0]", "[A 1]", "[A 2]", "[A 3]",
  468. "[A 4]", "[A 5]", "[A 6]", "[A 7]",
  469. "[A 8]", "[A 9]", "[A 10]", "[A 11]",
  470. "[A 12]", "[A 13]", "[A 14]", "[A 15]",
  471. "[A 16]", "[A 17]", "[A 18]", "[A 19]",
  472. "[A 20]", "[A 21]", "[A 22]", "[A 23]",
  473. "[A 24]", "[A 25]", "[A 26]", "[A 27]",
  474. "[A 28]", "[A 20]", "[A 30]", "[A 31]"
  475. },
  476. /* Context-Specific */
  477. {
  478. "[0]", "[1]", "[2]", "[3]", "[4]", "[5]", "[6]", "[7]",
  479. "[8]", "[9]", "[10]", "[11]", "[12]", "[13]", "[14]", "[15]",
  480. "[16]", "[17]", "[18]", "[19]", "[20]", "[21]", "[22]", "[23]",
  481. "[24]", "[25]", "[26]", "[27]", "[28]", "[20]", "[30]", "[31]"
  482. },
  483. /* Private */
  484. {
  485. "[P 0]", "[P 1]", "[P 2]", "[P 3]",
  486. "[P 4]", "[P 5]", "[P 6]", "[P 7]",
  487. "[P 8]", "[P 9]", "[P 10]", "[P 11]",
  488. "[P 12]", "[P 13]", "[P 14]", "[P 15]",
  489. "[P 16]", "[P 17]", "[P 18]", "[P 19]",
  490. "[P 20]", "[P 21]", "[P 22]", "[P 23]",
  491. "[P 24]", "[P 25]", "[P 26]", "[P 27]",
  492. "[P 28]", "[P 20]", "[P 30]", "[P 31]"
  493. }
  494. };
  495. /* Converts a tag byte to string.
  496. *
  497. * @param [in] tag BER tag value to interpret.
  498. * @return String corresponding to tag.
  499. */
  500. static const char* TagString(byte tag)
  501. {
  502. return tagString[tag >> 6][tag & ASN_TYPE_MASK];
  503. }
  504. #include <stdarg.h>
  505. /* Log a message that has the printf format string.
  506. *
  507. * @param [in] <va_args> printf style arguments.
  508. */
  509. #define WOLFSSL_MSG_VSNPRINTF(...) \
  510. do { \
  511. char line[81]; \
  512. snprintf(line, sizeof(line) - 1, __VA_ARGS__); \
  513. line[sizeof(line) - 1] = '\0'; \
  514. WOLFSSL_MSG(line); \
  515. } \
  516. while (0)
  517. #endif
  518. /* Returns whether ASN.1 item is an integer and the Most-Significant Bit is set.
  519. *
  520. * @param [in] asn ASN.1 items to encode.
  521. * @param [in] data_a Data to place in each item. Lengths set were not known.
  522. * @param [in] i Index of item to check.
  523. * @return 1 when ASN.1 item is an integer and MSB is 1.
  524. * @erturn 0 otherwise.
  525. */
  526. #define ASNIntMSBSet(asn, data_a, i) \
  527. (((asn)[i].tag == ASN_INTEGER) && \
  528. ((data_a)[i].data.buffer.data != NULL && \
  529. ((data_a)[i].data.buffer.data[0] & 0x80) == 0x80))
  530. /* Calculate the size of a DER encoded number.
  531. *
  532. * @param [in] n Number to be encoded.
  533. * @param [in] bits Maximum number of bits to encode.
  534. * @param [in] tag BER tag e.g. INTEGER, BIT_STRING, etc.
  535. * @return Number of bytes to the ASN.1 item.
  536. */
  537. static word32 SizeASN_Num(word32 n, int bits, byte tag)
  538. {
  539. int j;
  540. word32 len;
  541. len = 1 + 1 + bits / 8;
  542. /* Discover actual size by checking for high zeros. */
  543. for (j = bits - 8; j > 0; j -= 8) {
  544. if (n >> j)
  545. break;
  546. len--;
  547. }
  548. if (tag == ASN_BIT_STRING)
  549. len++;
  550. else if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80))
  551. len++;
  552. return len;
  553. }
  554. /* Calculate the size of the data in the constructed item based on the
  555. * length of the ASN.1 items below.
  556. *
  557. * @param [in] asn ASN.1 items to encode.
  558. * @param [in, out] data Data to place in each item. Lengths set were not
  559. * known.
  560. * @param [in] idx Index of item working on.
  561. */
  562. static void SizeASN_CalcDataLength(const ASNItem* asn, ASNSetData *data,
  563. int idx, int max)
  564. {
  565. int j;
  566. data[idx].data.buffer.length = 0;
  567. /* Sum the item length of all items underneath. */
  568. for (j = idx + 1; j < max; j++) {
  569. /* Stop looking if the next ASN.1 is same level or higher. */
  570. if (asn[j].depth <= asn[idx].depth)
  571. break;
  572. /* Only add in length if it is one level below. */
  573. if (asn[j].depth - 1 == asn[idx].depth) {
  574. data[idx].data.buffer.length += data[j].length;
  575. /* The length of a header only item doesn't include the data unless
  576. * a replacement buffer is supplied.
  577. */
  578. if (asn[j].headerOnly && data[j].data.buffer.data == NULL &&
  579. data[j].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
  580. data[idx].data.buffer.length += data[j].data.buffer.length;
  581. }
  582. }
  583. }
  584. }
  585. /* Calculate the size of the DER encoding.
  586. *
  587. * Call SetASN_Items() to write encoding to a buffer.
  588. *
  589. * @param [in] asn ASN.1 items to encode.
  590. * @param [in, out] data Data to place in each item. Lengths set where not
  591. * known.
  592. * @param [in] count Count of items to encode.
  593. * @param [out] encSz Length of the DER encoding.
  594. * @return 0 on success.
  595. * @return BAD_STATE_E when the data type is not supported.
  596. */
  597. int SizeASN_Items(const ASNItem* asn, ASNSetData *data, int count, int* encSz)
  598. {
  599. int i;
  600. word32 sz = 0;
  601. word32 len;
  602. word32 dataLen;
  603. int length;
  604. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  605. WOLFSSL_ENTER("SizeASN_Items");
  606. #endif
  607. for (i = count - 1; i >= 0; i--) {
  608. /* Skip this ASN.1 item when encoding. */
  609. if (data[i].noOut) {
  610. /* Set the offset to the current size - used in writing DER. */
  611. data[i].offset = sz;
  612. continue;
  613. }
  614. len = 0;
  615. switch (data[i].dataType) {
  616. /* Calculate the size of the number of different sizes. */
  617. case ASN_DATA_TYPE_WORD8:
  618. len = SizeASN_Num(data[i].data.u8, 8, asn[i].tag);
  619. break;
  620. case ASN_DATA_TYPE_WORD16:
  621. len = SizeASN_Num(data[i].data.u16, 16, asn[i].tag);
  622. break;
  623. #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
  624. /* Not used yet! */
  625. case ASN_DATA_TYPE_WORD32:
  626. len = SizeASN_Num(data[i].data.u32, 32, asn[i].tag);
  627. break;
  628. #endif
  629. case ASN_DATA_TYPE_MP:
  630. /* Calculate the size of the MP integer data. */
  631. length = mp_unsigned_bin_size(data[i].data.mp);
  632. length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
  633. len = SizeASNHeader(length) + length;
  634. break;
  635. case ASN_DATA_TYPE_REPLACE_BUFFER:
  636. /* Buffer is put in directly - use the length. */
  637. len = data[i].data.buffer.length;
  638. break;
  639. case ASN_DATA_TYPE_NONE:
  640. /* Calculate the size based on the data to be included.
  641. * Mostly used for constructed items.
  642. */
  643. if (asn[i].headerOnly) {
  644. if (data[i].data.buffer.data != NULL) {
  645. /* Force all child nodes to be ignored. Buffer
  646. * overwrites children. */
  647. {
  648. int ii;
  649. for (ii = i + 1; ii < count; ii++) {
  650. if (asn[ii].depth <= asn[i].depth)
  651. break;
  652. sz -= data[ii].length;
  653. data[ii].noOut = 1;
  654. }
  655. }
  656. }
  657. else {
  658. /* Calculate data length from items below if no buffer
  659. * supplied. */
  660. SizeASN_CalcDataLength(asn, data, i, count);
  661. }
  662. }
  663. if (asn[i].tag == ASN_BOOLEAN) {
  664. dataLen = 1;
  665. }
  666. else {
  667. dataLen = data[i].data.buffer.length;
  668. }
  669. /* BIT_STRING and INTEGER have one byte prepended. */
  670. if ((asn[i].tag == ASN_BIT_STRING) ||
  671. ASNIntMSBSet(asn, data, i)) {
  672. dataLen++;
  673. /* ASN.1 items are below and cannot include extra byte. */
  674. if (asn[i].headerOnly) {
  675. len++;
  676. }
  677. }
  678. /* Add in the size of tag and length. */
  679. len += SizeASNHeader(dataLen);
  680. /* Include data in length if not header only or if
  681. * buffer supplied. */
  682. if (!asn[i].headerOnly || data[i].data.buffer.data != NULL) {
  683. len += dataLen;
  684. }
  685. break;
  686. #ifdef DEBUG_WOLFSSL
  687. default:
  688. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  689. WOLFSSL_MSG_VSNPRINTF("%2d: %d", i, data[i].dataType);
  690. WOLFSSL_MSG("Bad data type");
  691. #endif
  692. return BAD_STATE_E;
  693. #endif
  694. }
  695. /* Set the total length of the item. */
  696. data[i].length = len;
  697. /* Add length to total size. */
  698. sz += len;
  699. /* Set the offset to the current size - used in writing DER. */
  700. data[i].offset = sz;
  701. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  702. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  703. data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
  704. asn[i].depth, "", TagString(asn[i].tag));
  705. #endif
  706. }
  707. *encSz = sz;
  708. return 0;
  709. }
  710. /* Create the DER encoding of a number.
  711. *
  712. * Assumes that the out buffer is large enough for encoding.
  713. *
  714. * @param [in] n Number to be encoded.
  715. * @param [in] bits Maximum number of bits to encode.
  716. * @param [in] tag DER tag e.g. INTEGER, BIT_STRING, etc.
  717. */
  718. static void SetASN_Num(word32 n, int bits, byte* out, byte tag)
  719. {
  720. int j;
  721. word32 idx;
  722. byte len;
  723. /* Encoding: Tag (1 byte) | Length (1 byte) | Data (number) */
  724. /* Data will start at index 2 unless BIT_STRING or INTEGER */
  725. idx = 2;
  726. /* Set the length of the number based on maximum bit length. */
  727. len = bits / 8;
  728. /* Discover actual size by checking for leading zero bytes. */
  729. for (j = bits - 8; j > 0; j -= 8) {
  730. if ((n >> j) != 0) {
  731. break;
  732. }
  733. len--;
  734. }
  735. /* Keep j, index of first non-zero byte, for writing out. */
  736. /* A BIT_STRING has the number of unused bits in last byte prepended to
  737. * data.
  738. */
  739. if (tag == ASN_BIT_STRING) {
  740. byte unusedBits = 0;
  741. byte lastByte = n >> j;
  742. /* Quick check last bit. */
  743. if ((lastByte & 0x01) == 0x00) {
  744. unusedBits++;
  745. /* Check each bit for first least significant bit set. */
  746. while (((lastByte >> unusedBits) & 0x01) == 0x00)
  747. unusedBits++;
  748. }
  749. /* Add unused bits byte. */
  750. len++;
  751. out[idx++] = unusedBits;
  752. }
  753. /* An INTEGER has a prepended byte if MSB of number is 1 - makes encoded
  754. * value positive. */
  755. if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80)) {
  756. len++;
  757. out[idx++] = 0;
  758. }
  759. /* Go back and put in length. */
  760. out[1] = len;
  761. /* Place in the required bytes of the number. */
  762. for (; j >= 0; j -= 8)
  763. out[idx++] = n >> j;
  764. }
  765. /* Creates the DER encoding of the ASN.1 items.
  766. *
  767. * Assumes the output buffer is large enough to hold encoding.
  768. * Must call SizeASN_Items() to determine size of encoding and offsets.
  769. *
  770. * @param [in] asn ASN.1 items to encode.
  771. * @param [in] data Data to place in each item.
  772. * @param [in] count Count of items to encode.
  773. * @param [in, out] output Buffer to write encoding into.
  774. * @return Size of the DER encoding in bytes.
  775. */
  776. int SetASN_Items(const ASNItem* asn, ASNSetData *data, int count, byte* output)
  777. {
  778. int i;
  779. int length;
  780. int err;
  781. word32 sz;
  782. word32 idx;
  783. byte* out;
  784. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  785. WOLFSSL_ENTER("SetASN_Items");
  786. #endif
  787. /* Offset of first item is the total length.
  788. * SizeASN_Items() calculated this. */
  789. sz = data[0].offset;
  790. /* Write out each item. */
  791. for (i = 0; i < count; i++) {
  792. /* Skip items not writing out. */
  793. if (data[i].noOut)
  794. continue;
  795. /* Start position to write item based on reverse offsets. */
  796. out = output + sz - data[i].offset;
  797. /* Index from start of item out. */
  798. idx = 0;
  799. if (data[i].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
  800. /* Put in the tag - not dumping in DER from buffer. */
  801. out[idx++] = asn[i].tag |
  802. (asn[i].constructed ? ASN_CONSTRUCTED : 0);
  803. }
  804. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  805. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  806. sz - data[i].offset,
  807. data[i].length, asn[i].constructed ? '+' : ' ', asn[i].depth,
  808. "", TagString(asn[i].tag));
  809. #endif
  810. switch (data[i].dataType) {
  811. /* Write out the length and data of a number. */
  812. case ASN_DATA_TYPE_WORD8:
  813. SetASN_Num(data[i].data.u8, 8, out, asn[i].tag);
  814. break;
  815. case ASN_DATA_TYPE_WORD16:
  816. SetASN_Num(data[i].data.u16, 16, out, asn[i].tag);
  817. break;
  818. #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
  819. /* Not used yet! */
  820. case ASN_DATA_TYPE_WORD32:
  821. SetASN_Num(data[i].data.u32, 32, out, asn[i].tag);
  822. break;
  823. #endif
  824. /* Write out the length and data of a multi-precision number. */
  825. case ASN_DATA_TYPE_MP:
  826. /* Get length in bytes. */
  827. length = mp_unsigned_bin_size(data[i].data.mp);
  828. /* Add one for leading zero to make encoding a positive num. */
  829. length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
  830. /* Write out length. */
  831. idx += SetASNLength(length, out + idx);
  832. /* Write out leading zero to make positive. */
  833. if (mp_leading_bit(data[i].data.mp)) {
  834. out[idx++] = 0;
  835. }
  836. /* Encode number in big-endian byte array. */
  837. err = mp_to_unsigned_bin(data[i].data.mp, out + idx);
  838. if (err != MP_OKAY) {
  839. WOLFSSL_MSG("SetASN_Items: Failed to write mp_int");
  840. return MP_TO_E;
  841. }
  842. break;
  843. case ASN_DATA_TYPE_REPLACE_BUFFER:
  844. if (data[i].data.buffer.data == NULL) {
  845. /* Return pointer for caller to use. */
  846. data[i].data.buffer.data = out + idx;
  847. }
  848. else {
  849. /* Dump in the DER encoded data. */
  850. XMEMCPY(out + idx, data[i].data.buffer.data,
  851. data[i].data.buffer.length);
  852. }
  853. break;
  854. case ASN_DATA_TYPE_NONE:
  855. if (asn[i].tag == ASN_BOOLEAN) {
  856. /* Always one byte of data. */
  857. out[idx++] = 1;
  858. /* TRUE = 0xff, FALSE = 0x00 */
  859. out[idx] = data[i].data.u8 ? -1 : 0;
  860. }
  861. else if (asn[i].tag == ASN_TAG_NULL) {
  862. /* NULL tag is always a zero length item. */
  863. out[idx] = 0;
  864. }
  865. else {
  866. word32 dataLen = data[i].data.buffer.length;
  867. /* Add one to data length for BIT_STRING unused bits and
  868. * INTEGER leading zero to make positive.
  869. */
  870. if ((asn[i].tag == ASN_BIT_STRING) ||
  871. ASNIntMSBSet(asn, data, i)) {
  872. dataLen++;
  873. }
  874. /* Write out length. */
  875. idx += SetASNLength(dataLen, out + idx);
  876. if ((asn[i].tag == ASN_BIT_STRING) ||
  877. ASNIntMSBSet(asn, data, i)) {
  878. /* Write out leading byte. BIT_STRING has no unused bits
  879. * - use number data types if needed. */
  880. out[idx++] = 0x00;
  881. }
  882. /* Record pointer for caller if data not supplied. */
  883. if (data[i].data.buffer.data == NULL) {
  884. data[i].data.buffer.data = out + idx;
  885. }
  886. /* Copy supplied data if not putting out header only or
  887. * if buffer supplied. */
  888. else if (!asn[i].headerOnly ||
  889. data[i].data.buffer.data != NULL) {
  890. /* Allow data to come from output buffer. */
  891. XMEMMOVE(out + idx, data[i].data.buffer.data,
  892. data[i].data.buffer.length);
  893. }
  894. }
  895. break;
  896. #ifdef DEBUG_WOLFSSL
  897. default:
  898. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  899. WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data[i].dataType);
  900. #endif
  901. return BAD_STATE_E;
  902. #endif
  903. }
  904. }
  905. return sz;
  906. }
  907. static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
  908. word32 oidType, int length);
  909. /* Maximum supported depth in ASN.1 description. */
  910. #define GET_ASN_MAX_DEPTH 7
  911. /* Maximum number of checked numbered choices. Only one of the items with the
  912. * number is allowed.
  913. */
  914. #define GET_ASN_MAX_CHOICES 2
  915. /* Use existing function to decode BER length encoding. */
  916. #define GetASN_Length GetLength_ex
  917. /* Check an INTEGER's first byte - must be a positive number.
  918. *
  919. * @param [in] input BER encoded data.
  920. * @param [in] idx Index of BIT_STRING data.
  921. * @param [in] length Length of input data.
  922. * @param [in] positive Indicates number must be positive.
  923. * @return 0 on success.
  924. * @return ASN_PARSE_E when 0 is not required but seen.
  925. * @return ASN_EXPECT_0_E when 0 is required and not seen.
  926. */
  927. static int GetASN_Integer(const byte* input, word32 idx, int length,
  928. int positive)
  929. {
  930. if (input[idx] == 0) {
  931. /* Check leading zero byte required. */
  932. if ((length > 1) && ((input[idx + 1] & 0x80) == 0)) {
  933. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  934. WOLFSSL_MSG("Zero not required on INTEGER");
  935. #endif
  936. return ASN_PARSE_E;
  937. }
  938. }
  939. /* Check whether a leading zero byte was required. */
  940. else if (positive && (input[idx] & 0x80)) {
  941. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  942. WOLFSSL_MSG("INTEGER is negative");
  943. #endif
  944. return ASN_EXPECT_0_E;
  945. }
  946. return 0;
  947. }
  948. /* Check a BIT_STRING's first byte - unused bits.
  949. *
  950. * @param [in] input BER encoded data.
  951. * @param [in] idx Index of BIT_STRING data.
  952. * @param [in] length Length of input data.
  953. * @return 0 on success.
  954. * @return ASN_PARSE_E when unused bits is invalid.
  955. */
  956. static int GetASN_BitString(const byte* input, word32 idx, int length)
  957. {
  958. /* Ensure unused bits value is valid range. */
  959. if (input[idx] > 7) {
  960. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  961. WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits too big: %d > 7",
  962. input[idx]);
  963. #endif
  964. return ASN_PARSE_E;
  965. }
  966. /* Ensure unused bits are zero. */
  967. if ((byte)(input[idx + length - 1] << (8 - input[idx])) != 0) {
  968. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  969. WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits used: %d %02x",
  970. input[idx], input[idx + length - 1]);
  971. #endif
  972. return ASN_PARSE_E;
  973. }
  974. return 0;
  975. }
  976. /* Get the ASN.1 items from the BER encoding.
  977. *
  978. * @param [in] asn ASN.1 item expected.
  979. * @param [in] data Data array to place found item into.
  980. * @param [in] input BER encoded data.
  981. * @param [in] idx Starting index of item data.
  982. * @param [in] len Length of input buffer upto end of this item's data.
  983. * @param [in] zeroPadded INTEGER was zero padded to make positive.
  984. * @return 0 on success.
  985. * @return ASN_PARSE_E when BER encoded data is invalid.
  986. * @return ASN_EXPECT_0_E when NULL tagged item has a non-zero length.
  987. * @return MP_INIT_E when the unable to initialize an mp_int.
  988. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  989. * @return BAD_STATE_E when the data type is not supported.
  990. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  991. */
  992. static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data,
  993. const byte* input, word32 idx, int len,
  994. int zeroPadded)
  995. {
  996. int i;
  997. int err;
  998. /* Parse data based on data type to extract. */
  999. switch (data->dataType) {
  1000. /* Parse a data into a number of specified bits. */
  1001. case ASN_DATA_TYPE_WORD8:
  1002. /* Check data is small enough to fit. */
  1003. if (len != 1) {
  1004. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1005. WOLFSSL_MSG_VSNPRINTF("Expecting one byte: %d", len);
  1006. #endif
  1007. return ASN_PARSE_E;
  1008. }
  1009. /* Fill number with all of data. */
  1010. *data->data.u8 = input[idx];
  1011. break;
  1012. case ASN_DATA_TYPE_WORD16:
  1013. /* Check data is small enough to fit. */
  1014. if (len == 0 || len > 2) {
  1015. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1016. WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", len);
  1017. #endif
  1018. return ASN_PARSE_E;
  1019. }
  1020. /* Fill number with all of data. */
  1021. *data->data.u16 = 0;
  1022. for (i = 0; i < len; i++) {
  1023. *data->data.u16 <<= 8;
  1024. *data->data.u16 |= input[idx + i] ;
  1025. }
  1026. break;
  1027. case ASN_DATA_TYPE_WORD32:
  1028. /* Check data is small enough to fit. */
  1029. if (len == 0 || len > 4) {
  1030. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1031. WOLFSSL_MSG_VSNPRINTF("Expecting 1 to 4 bytes: %d", len);
  1032. #endif
  1033. return ASN_PARSE_E;
  1034. }
  1035. /* Fill number with all of data. */
  1036. *data->data.u32 = 0;
  1037. for (i = 0; i < len; i++) {
  1038. *data->data.u32 <<= 8;
  1039. *data->data.u32 |= input[idx + i] ;
  1040. }
  1041. break;
  1042. case ASN_DATA_TYPE_BUFFER:
  1043. /* Check buffer is big enough to hold data. */
  1044. if (len > (int)*data->data.buffer.length) {
  1045. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1046. WOLFSSL_MSG_VSNPRINTF("Buffer too small for data: %d %d", len,
  1047. *data->data.buffer.length);
  1048. #endif
  1049. return ASN_PARSE_E;
  1050. }
  1051. /* Copy in data and record actual length seen. */
  1052. XMEMCPY(data->data.buffer.data, input + idx, len);
  1053. *data->data.buffer.length = len;
  1054. break;
  1055. case ASN_DATA_TYPE_EXP_BUFFER:
  1056. /* Check data is same size expected. */
  1057. if (len != (int)data->data.ref.length) {
  1058. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1059. WOLFSSL_MSG_VSNPRINTF("Data not expected length: %d %d", len,
  1060. data->data.ref.length);
  1061. #endif
  1062. return ASN_PARSE_E;
  1063. }
  1064. /* Check data is same as expected. */
  1065. if (XMEMCMP(data->data.ref.data, input + idx, len) != 0) {
  1066. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1067. WOLFSSL_MSG("Data not as expected");
  1068. #endif
  1069. return ASN_PARSE_E;
  1070. }
  1071. break;
  1072. case ASN_DATA_TYPE_MP:
  1073. case ASN_DATA_TYPE_MP_POS_NEG:
  1074. /* Initialize mp_int and read in big-endian byte array. */
  1075. if (mp_init(data->data.mp) != MP_OKAY) {
  1076. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1077. WOLFSSL_MSG_VSNPRINTF("Failed to init mp: %p", data->data.mp);
  1078. #endif
  1079. return MP_INIT_E;
  1080. }
  1081. err = mp_read_unsigned_bin(data->data.mp, (byte*)input + idx, len);
  1082. if (err != 0) {
  1083. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1084. WOLFSSL_MSG_VSNPRINTF("Failed to read mp: %d", err);
  1085. #endif
  1086. mp_clear(data->data.mp);
  1087. return ASN_GETINT_E;
  1088. }
  1089. #ifdef HAVE_WOLF_BIGINT
  1090. err = wc_bigint_from_unsigned_bin(&data->data.mp->raw, input + idx,
  1091. len);
  1092. if (err != 0) {
  1093. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1094. WOLFSSL_MSG_VSNPRINTF("Failed to create bigint: %d", err);
  1095. #endif
  1096. mp_clear(data->data.mp);
  1097. return ASN_GETINT_E;
  1098. }
  1099. #endif /* HAVE_WOLF_BIGINT */
  1100. #ifdef WOLFSSL_SP_INT_NEGATIVE
  1101. /* Don't always read as positive. */
  1102. if ((data->dataType == ASN_DATA_TYPE_MP_POS_NEG) && (!zeroPadded) &&
  1103. (input[idx] & 0x80)) {
  1104. #ifdef MP_NEG
  1105. data->data.mp->sign = MP_NEG;
  1106. #else
  1107. #ifdef OPENSSL_EXTRA
  1108. /* public API wolfSSL_ASN1_INTEGER_get() depends
  1109. * indirectly on negative bignum handling here.
  1110. */
  1111. #error OPENSSL_EXTRA requires negative bignum support.
  1112. #endif
  1113. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1114. WOLFSSL_MSG_VSNPRINTF("ASN negative integer without bignum support.");
  1115. #endif
  1116. mp_clear(data->data.mp);
  1117. return ASN_GETINT_E;
  1118. #endif
  1119. }
  1120. #else
  1121. (void)zeroPadded;
  1122. #endif
  1123. break;
  1124. case ASN_DATA_TYPE_CHOICE:
  1125. /* Check if tag matched any of the choices specified. */
  1126. for (i = 0; data->data.choice[i] != 0; i++)
  1127. if (data->data.choice[i] == data->tag)
  1128. break;
  1129. if (data->data.choice[i] == 0) {
  1130. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1131. WOLFSSL_MSG("Tag didn't match a choice");
  1132. #endif
  1133. return ASN_PARSE_E;
  1134. }
  1135. /* Store data pointer and length for caller. */
  1136. data->data.ref.data = input + idx;
  1137. data->data.ref.length = len;
  1138. break;
  1139. case ASN_DATA_TYPE_NONE:
  1140. /* Default behaviour based on tag. */
  1141. if (asn->tag == ASN_BOOLEAN) {
  1142. /* BOOLEAN has only one byte of data in BER. */
  1143. if (len != 1) {
  1144. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1145. WOLFSSL_MSG_VSNPRINTF("BOOLEAN length too long: %d", len);
  1146. #endif
  1147. return ASN_PARSE_E;
  1148. }
  1149. if (data->data.u8 == NULL)
  1150. return BAD_STATE_E;
  1151. /* Store C boolean value. */
  1152. *data->data.u8 = (input[idx] != 0);
  1153. break;
  1154. }
  1155. if (asn->tag == ASN_TAG_NULL) {
  1156. /* NULL has no data in BER. */
  1157. if (len != 0) {
  1158. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1159. WOLFSSL_MSG_VSNPRINTF("NULL length too long: %d", len);
  1160. #endif
  1161. return ASN_EXPECT_0_E;
  1162. }
  1163. data->data.ref.data = input + idx;
  1164. break;
  1165. }
  1166. if (asn->tag == ASN_OBJECT_ID) {
  1167. word32 oidIdx = 0;
  1168. /* Store OID data pointer and length */
  1169. data->data.oid.data = input + idx;
  1170. data->data.oid.length = len;
  1171. /* Get the OID sum. */
  1172. err = GetOID(input + idx, &oidIdx, &data->data.oid.sum,
  1173. data->data.oid.type, len);
  1174. if (err < 0) {
  1175. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1176. WOLFSSL_MSG_VSNPRINTF("OID check failed: %d", err);
  1177. #endif
  1178. return err;
  1179. }
  1180. break;
  1181. }
  1182. /* Otherwise store data pointer and length. */
  1183. data->data.ref.data = input + idx;
  1184. data->data.ref.length = len;
  1185. break;
  1186. #ifdef DEBUG_WOLFSSL
  1187. default:
  1188. /* Bad ASN data type. */
  1189. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1190. WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data->dataType);
  1191. #endif
  1192. return BAD_STATE_E;
  1193. #endif
  1194. }
  1195. return 0;
  1196. }
  1197. /* Get the ASN.1 items from the BER encoding.
  1198. *
  1199. * @param [in] asn ASN.1 items expected.
  1200. * @param [in] data Data array to place found items into.
  1201. * @param [in] count Count of items to parse.
  1202. * @param [in] complete Whether the whole buffer is to be used up.
  1203. * @param [in] input BER encoded data.
  1204. * @param [in, out] inOutIdx On in, starting index of data.
  1205. * On out, end of parsed data.
  1206. * @param [in] length Length of input buffer.
  1207. * @return 0 on success.
  1208. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1209. * is invalid.
  1210. * @return BUFFER_E when data in buffer is too small.
  1211. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1212. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1213. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1214. * non-zero length.
  1215. * @return MP_INIT_E when the unable to initialize an mp_int.
  1216. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1217. * @return BAD_STATE_E when the data type is not supported.
  1218. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  1219. */
  1220. int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, int complete,
  1221. const byte* input, word32* inOutIdx, word32 length)
  1222. {
  1223. int i;
  1224. int j;
  1225. int err;
  1226. int len;
  1227. /* Current index into buffer. */
  1228. word32 idx = *inOutIdx;
  1229. /* Initialize the end index at each depth to be the length. */
  1230. word32 endIdx[GET_ASN_MAX_DEPTH] = { length, length, length, length, length,
  1231. length, length };
  1232. /* Set choices to -1 to indicate they haven't been seen or found. */
  1233. signed char choiceMet[GET_ASN_MAX_CHOICES] = { -1, -1 };
  1234. /* Not matching a choice right now. */
  1235. int choice = 0;
  1236. /* Current depth of ASN.1 item. */
  1237. int depth;
  1238. /* Minimum depth value seen. */
  1239. int minDepth;
  1240. /* Integer had a zero prepended. */
  1241. int zeroPadded;
  1242. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1243. WOLFSSL_ENTER("GetASN_Items");
  1244. #endif
  1245. /* Start depth at first items depth. */
  1246. minDepth = depth = asn[0].depth;
  1247. /* Check every ASN.1 item. */
  1248. for (i = 0; i < count; i++) {
  1249. /* Store offset of ASN.1 item. */
  1250. data[i].offset = idx;
  1251. /* Length of data in ASN.1 item starts empty. */
  1252. data[i].length = 0;
  1253. /* Get current item depth. */
  1254. depth = asn[i].depth;
  1255. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1256. if (depth > GET_ASN_MAX_DEPTH) {
  1257. WOLFSSL_MSG("Depth in template too large");
  1258. return ASN_PARSE_E;
  1259. }
  1260. #endif
  1261. /* Keep track of minimum depth. */
  1262. if (depth < minDepth) {
  1263. minDepth = depth;
  1264. }
  1265. /* Reset choice if different from previous. */
  1266. if (choice > 0 && asn[i].optional != choice) {
  1267. choice = 0;
  1268. }
  1269. /* Check if first of numbered choice. */
  1270. if (choice == 0 && asn[i].optional > 1) {
  1271. choice = asn[i].optional;
  1272. if (choiceMet[choice - 2] == -1) {
  1273. /* Choice seen but not found a match yet. */
  1274. choiceMet[choice - 2] = 0;
  1275. }
  1276. }
  1277. /* Check for end of data or not a choice and tag not matching. */
  1278. if (idx == endIdx[depth] || (data[i].dataType != ASN_DATA_TYPE_CHOICE &&
  1279. (input[idx] & ~ASN_CONSTRUCTED) != asn[i].tag)) {
  1280. if (asn[i].optional) {
  1281. /* Skip over ASN.1 items underneath this optional item. */
  1282. for (j = i + 1; j < count; j++) {
  1283. if (asn[i].depth >= asn[j].depth)
  1284. break;
  1285. data[j].offset = idx;
  1286. data[j].length = 0;
  1287. }
  1288. i = j - 1;
  1289. continue;
  1290. }
  1291. /* Check for end of data. */
  1292. if (idx == length) {
  1293. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1294. WOLFSSL_MSG_VSNPRINTF(
  1295. "%2d: %4d %4d %c %*s %-16s%*s (index past end)",
  1296. i, data[i].offset, data[i].length,
  1297. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1298. TagString(asn[i].tag), 6 - asn[i].depth, "");
  1299. WOLFSSL_MSG_VSNPRINTF("Index past end of data: %d %d", idx,
  1300. length);
  1301. #endif
  1302. return BUFFER_E;
  1303. }
  1304. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1305. /* Show expected versus found. */
  1306. WOLFSSL_MSG_VSNPRINTF(
  1307. "%2d: %4d %4d %c %*s %-16s%*s Tag=0x%02x (%s)",
  1308. i, data[i].offset, data[i].length,
  1309. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1310. TagString(asn[i].tag), 6 - asn[i].depth, "",
  1311. input[idx], TagString(input[idx]));
  1312. #endif
  1313. /* Check for end of data at this depth. */
  1314. if (idx == endIdx[depth]) {
  1315. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1316. WOLFSSL_MSG_VSNPRINTF("Index past outer item: %d %d", idx,
  1317. endIdx[depth]);
  1318. #endif
  1319. return ASN_PARSE_E;
  1320. }
  1321. /* Expecting an OBJECT_ID */
  1322. if (asn[i].tag == ASN_OBJECT_ID) {
  1323. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1324. WOLFSSL_MSG("Expecting OBJECT ID");
  1325. #endif
  1326. return ASN_OBJECT_ID_E;
  1327. }
  1328. /* Expecting a BIT_STRING */
  1329. if (asn[i].tag == ASN_BIT_STRING) {
  1330. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1331. WOLFSSL_MSG("Expecting BIT STRING");
  1332. #endif
  1333. return ASN_BITSTR_E;
  1334. }
  1335. /* Not the expected tag. */
  1336. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1337. WOLFSSL_MSG("Bad tag");
  1338. #endif
  1339. return ASN_PARSE_E;
  1340. }
  1341. /* Store found tag in data. */
  1342. data[i].tag = input[idx];
  1343. if (data[i].dataType != ASN_DATA_TYPE_CHOICE) {
  1344. int constructed = (input[idx] & ASN_CONSTRUCTED) == ASN_CONSTRUCTED;
  1345. /* Check constructed match expected for non-choice ASN.1 item. */
  1346. if (asn[i].constructed != constructed) {
  1347. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1348. WOLFSSL_MSG_VSNPRINTF(
  1349. "%2d: %4d %4d %c %*s %-16s%*s Tag=0x%02x (%s)",
  1350. i, data[i].offset, data[i].length,
  1351. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1352. TagString(asn[i].tag), 6 - asn[i].depth, "",
  1353. input[idx], TagString(input[idx]));
  1354. if (!constructed) {
  1355. WOLFSSL_MSG("Not constructed");
  1356. }
  1357. else {
  1358. WOLFSSL_MSG("Not expected to be constructed");
  1359. }
  1360. #endif
  1361. return ASN_PARSE_E;
  1362. }
  1363. }
  1364. /* Move index to start of length. */
  1365. idx++;
  1366. /* Get the encoded length. */
  1367. if (GetASN_Length(input, &idx, &len, endIdx[depth], 1) < 0) {
  1368. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1369. WOLFSSL_MSG_VSNPRINTF("%2d: idx=%d len=%d end=%d", i, idx, len,
  1370. endIdx[depth]);
  1371. #endif
  1372. return ASN_PARSE_E;
  1373. }
  1374. /* Store length of data. */
  1375. data[i].length = len;
  1376. /* Note the max length of items under this one. */
  1377. endIdx[depth + 1] = idx + len;
  1378. if (choice > 1) {
  1379. /* Note we found a number choice. */
  1380. choiceMet[choice - 2] = 1;
  1381. }
  1382. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1383. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  1384. data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
  1385. asn[i].depth, "", TagString(data[i].tag));
  1386. #endif
  1387. /* Assume no zero padding on INTEGER. */
  1388. zeroPadded = 0;
  1389. /* Check data types that prepended a byte. */
  1390. if (asn[i].tag == ASN_INTEGER) {
  1391. /* Check validity of first byte. */
  1392. err = GetASN_Integer(input, idx, len,
  1393. data[i].dataType == ASN_DATA_TYPE_MP);
  1394. if (err != 0)
  1395. return err;
  1396. if (len > 1 && input[idx] == 0) {
  1397. zeroPadded = 1;
  1398. /* Move over prepended byte. */
  1399. idx++;
  1400. len--;
  1401. }
  1402. }
  1403. else if (asn[i].tag == ASN_BIT_STRING) {
  1404. /* Check prepended byte is correct. */
  1405. err = GetASN_BitString(input, idx, len);
  1406. if (err != 0)
  1407. return err;
  1408. /* Move over prepended byte. */
  1409. idx++;
  1410. len--;
  1411. }
  1412. else if ((asn[i].tag == ASN_OBJECT_ID) && (len < 3)) {
  1413. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1414. WOLFSSL_MSG_VSNPRINTF("OID length must be 3 or more: %d", len);
  1415. #endif
  1416. return ASN_PARSE_E;
  1417. }
  1418. /* Don't parse data if only header required. */
  1419. if (asn[i].headerOnly) {
  1420. /* Store reference to data and length. */
  1421. data[i].data.ref.data = input + idx;
  1422. data[i].data.ref.length = len;
  1423. continue;
  1424. }
  1425. /* Store the data at idx in the ASN data item. */
  1426. err = GetASN_StoreData(&asn[i], &data[i], input, idx, len, zeroPadded);
  1427. if (err != 0) {
  1428. return err;
  1429. }
  1430. /* Move index to next item. */
  1431. idx += len;
  1432. /* When matched numbered choice ... */
  1433. if (asn[i].optional > 1) {
  1434. /* Skip over other ASN.1 items of the same number. */
  1435. for (j = i + 1; j < count; j++) {
  1436. if (asn[j].depth <= asn[i].depth &&
  1437. asn[j].optional != asn[i].optional) {
  1438. break;
  1439. }
  1440. }
  1441. i = j - 1;
  1442. }
  1443. }
  1444. if (complete) {
  1445. /* When expecting ASN.1 items to completely use data, check we did. */
  1446. for (j = depth; j > minDepth; j--) {
  1447. if (idx < endIdx[j]) {
  1448. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1449. WOLFSSL_MSG_VSNPRINTF(
  1450. "More data in constructed item at depth: %d", j - 1);
  1451. #endif
  1452. return ASN_PARSE_E;
  1453. }
  1454. }
  1455. }
  1456. /* Check all choices where met - found an item for them. */
  1457. for (j = 0; j < GET_ASN_MAX_CHOICES; j++) {
  1458. if (choiceMet[j] == 0) {
  1459. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1460. WOLFSSL_MSG_VSNPRINTF("No choice seen: %d", j + 2);
  1461. #endif
  1462. return ASN_PARSE_E;
  1463. }
  1464. }
  1465. /* Return index after ASN.1 data has been parsed. */
  1466. *inOutIdx = idx;
  1467. return 0;
  1468. }
  1469. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1470. /* Calculate the size of the DER encoding.
  1471. *
  1472. * Call SetASN_Items() to write encoding to a buffer.
  1473. *
  1474. * @param [in] asn ASN.1 items to encode.
  1475. * @param [in, out] data Data to place in each item. Lengths set were not
  1476. * known.
  1477. * @param [in] count Count of items to encode.
  1478. * @param [out] len Length of the DER encoding.
  1479. * @return Size of the DER encoding in bytes.
  1480. */
  1481. static int SizeASN_ItemsDebug(const char* name, const ASNItem* asn,
  1482. ASNSetData *data, int count, int* encSz)
  1483. {
  1484. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1485. return SizeASN_Items(asn, data, count, encSz);
  1486. }
  1487. /* Creates the DER encoding of the ASN.1 items.
  1488. *
  1489. * Assumes the output buffer is large enough to hold encoding.
  1490. * Must call SizeASN_Items() to determine size of encoding and offsets.
  1491. *
  1492. * Displays the template name first.
  1493. *
  1494. * @param [in] name Name of ASN.1 template.
  1495. * @param [in] asn ASN.1 items to encode.
  1496. * @param [in] data Data to place in each item.
  1497. * @param [in] count Count of items to encode.
  1498. * @param [in, out] output Buffer to write encoding into.
  1499. * @return Size of the DER encoding in bytes.
  1500. */
  1501. static int SetASN_ItemsDebug(const char* name, const ASNItem* asn,
  1502. ASNSetData *data, int count, byte* output)
  1503. {
  1504. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1505. return SetASN_Items(asn, data, count, output);
  1506. }
  1507. /* Get the ASN.1 items from the BER encoding.
  1508. *
  1509. * Displays the template name first.
  1510. *
  1511. * @param [in] name Name of ASN.1 template.
  1512. * @param [in] asn ASN.1 items expected.
  1513. * @param [in] data Data array to place found items into.
  1514. * @param [in] count Count of items to parse.
  1515. * @param [in] complete Whether the whole buffer is to be used up.
  1516. * @param [in] input BER encoded data.
  1517. * @param [in, out] inOutIdx On in, starting index of data.
  1518. * On out, end of parsed data.
  1519. * @param [in] maxIdx Maximum index of input data.
  1520. * @return 0 on success.
  1521. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1522. * is invalid.
  1523. * @return BUFFER_E when data in buffer is too small.
  1524. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1525. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1526. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1527. * non-zero length.
  1528. * @return MP_INIT_E when the unable to initialize an mp_int.
  1529. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1530. * @return BAD_STATE_E when the data type is not supported.
  1531. */
  1532. static int GetASN_ItemsDebug(const char* name, const ASNItem* asn,
  1533. ASNGetData *data, int count, int complete, const byte* input,
  1534. word32* inOutIdx, word32 maxIdx)
  1535. {
  1536. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1537. return GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx);
  1538. }
  1539. /* Calculate the size of the DER encoding.
  1540. *
  1541. * Call SetASN_Items() to write encoding to a buffer.
  1542. *
  1543. * @param [in] asn ASN.1 items to encode.
  1544. * @param [in, out] data Data to place in each item. Lengths set were not
  1545. * known.
  1546. * @param [in] count Count of items to encode.
  1547. * @param [out] len Length of the DER encoding.
  1548. * @return Size of the DER encoding in bytes.
  1549. */
  1550. #define SizeASN_Items(asn, data, count, encSz) \
  1551. SizeASN_ItemsDebug(#asn, asn, data, count, encSz)
  1552. /* Creates the DER encoding of the ASN.1 items.
  1553. *
  1554. * Assumes the output buffer is large enough to hold encoding.
  1555. * Must call SizeASN_Items() to determine size of encoding and offsets.
  1556. *
  1557. * Displays the template name first.
  1558. *
  1559. * @param [in] name Name of ASN.1 template.
  1560. * @param [in] asn ASN.1 items to encode.
  1561. * @param [in] data Data to place in each item.
  1562. * @param [in] count Count of items to encode.
  1563. * @param [in, out] output Buffer to write encoding into.
  1564. * @return Size of the DER encoding in bytes.
  1565. */
  1566. #define SetASN_Items(asn, data, count, output) \
  1567. SetASN_ItemsDebug(#asn, asn, data, count, output)
  1568. /* Get the ASN.1 items from the BER encoding.
  1569. *
  1570. * Displays the template name first.
  1571. *
  1572. * @param [in] name Name of ASN.1 template.
  1573. * @param [in] asn ASN.1 items expected.
  1574. * @param [in] data Data array to place found items into.
  1575. * @param [in] count Count of items to parse.
  1576. * @param [in] complete Whether the whole buffer is to be used up.
  1577. * @param [in] input BER encoded data.
  1578. * @param [in, out] inOutIdx On in, starting index of data.
  1579. * On out, end of parsed data.
  1580. * @param [in] maxIdx Maximum index of input data.
  1581. * @return 0 on success.
  1582. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1583. * is invalid.
  1584. * @return BUFFER_E when data in buffer is too small.
  1585. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1586. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1587. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1588. * non-zero length.
  1589. * @return MP_INIT_E when the unable to initialize an mp_int.
  1590. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1591. * @return BAD_STATE_E when the data type is not supported.
  1592. */
  1593. #define GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx) \
  1594. GetASN_ItemsDebug(#asn, asn, data, count, complete, input, inOutIdx, maxIdx)
  1595. #endif /* WOLFSSL_DEBUG_ASN_TEMPLATE */
  1596. /* Decode a BER encoded constructed sequence.
  1597. *
  1598. * @param [in] input Buffer of BER encoded data.
  1599. * @param [in, out] inOutIdx On in, index to start decoding from.
  1600. * On out, index of next encoded byte.
  1601. * @param [out] len Length of data under SEQUENCE.
  1602. * @param [in] maxIdx Maximim index of data. Index of byte after SEQ.
  1603. * @param [in] complete All data used with SEQUENCE and data under.
  1604. * @return 0 on success.
  1605. * @return BUFFER_E when not enough data to complete decode.
  1606. * @return ASN_PARSE when decoding failed.
  1607. */
  1608. static int GetASN_Sequence(const byte* input, word32* inOutIdx, int* len,
  1609. word32 maxIdx, int complete)
  1610. {
  1611. int ret = 0;
  1612. word32 idx = *inOutIdx;
  1613. /* Check buffer big enough for tag. */
  1614. if (idx + 1 > maxIdx) {
  1615. ret = BUFFER_E;
  1616. }
  1617. /* Check it is a constructed SEQUENCE. */
  1618. if ((ret == 0) && (input[idx++] != (ASN_SEQUENCE | ASN_CONSTRUCTED))) {
  1619. ret = ASN_PARSE_E;
  1620. }
  1621. /* Get the length. */
  1622. if ((ret == 0) && (GetASN_Length(input, &idx, len, maxIdx, 1) < 0)) {
  1623. ret = ASN_PARSE_E;
  1624. }
  1625. /* Check all data used if complete set. */
  1626. if ((ret == 0) && complete && (idx + *len != maxIdx)) {
  1627. ret = ASN_PARSE_E;
  1628. }
  1629. if (ret == 0) {
  1630. /* Return index of next byte of encoded data. */
  1631. *inOutIdx = idx;
  1632. }
  1633. return ret;
  1634. }
  1635. #ifdef WOLFSSL_ASN_TEMPLATE_TYPE_CHECK
  1636. /* Setup ASN data item to get an 8-bit number.
  1637. *
  1638. * @param [in] dataASN Dynamic ASN data item.
  1639. * @param [in] num Pointer to an 8-bit variable.
  1640. */
  1641. void GetASN_Int8Bit(ASNGetData *dataASN, byte* num)
  1642. {
  1643. dataASN->dataType = ASN_DATA_TYPE_WORD8;
  1644. dataASN->data.u8 = num;
  1645. }
  1646. /* Setup ASN data item to get a 16-bit number.
  1647. *
  1648. * @param [in] dataASN Dynamic ASN data item.
  1649. * @param [in] num Pointer to a 16-bit variable.
  1650. */
  1651. void GetASN_Int16Bit(ASNGetData *dataASN, word16* num)
  1652. {
  1653. dataASN->dataType = ASN_DATA_TYPE_WORD16;
  1654. dataASN->data.u16 = num;
  1655. }
  1656. /* Setup ASN data item to get a 32-bit number.
  1657. *
  1658. * @param [in] dataASN Dynamic ASN data item.
  1659. * @param [in] num Pointer to a 32-bit variable.
  1660. */
  1661. void GetASN_Int32Bit(ASNGetData *dataASN, word32* num)
  1662. {
  1663. dataASN->dataType = ASN_DATA_TYPE_WORD32;
  1664. dataASN->data.u32 = num;
  1665. }
  1666. /* Setup ASN data item to get data into a buffer of a specific length.
  1667. *
  1668. * @param [in] dataASN Dynamic ASN data item.
  1669. * @param [in] data Buffer to hold data.
  1670. * @param [in] length Length of buffer in bytes.
  1671. */
  1672. void GetASN_Buffer(ASNGetData *dataASN, byte* data, word32* length)
  1673. {
  1674. dataASN->dataType = ASN_DATA_TYPE_BUFFER;
  1675. dataASN->data.buffer.data = data;
  1676. dataASN->data.buffer.length = length;
  1677. }
  1678. /* Setup ASN data item to check parsed data against expected buffer.
  1679. *
  1680. * @param [in] dataASN Dynamic ASN data item.
  1681. * @param [in] data Buffer containing expected data.
  1682. * @param [in] length Length of buffer in bytes.
  1683. */
  1684. void GetASN_ExpBuffer(ASNGetData *dataASN, const byte* data, word32 length)
  1685. {
  1686. dataASN->dataType = ASN_DATA_TYPE_EXP_BUFFER;
  1687. dataASN->data.ref.data = data;
  1688. dataASN->data.ref.length = length;
  1689. }
  1690. /* Setup ASN data item to get a number into an mp_int.
  1691. *
  1692. * @param [in] dataASN Dynamic ASN data item.
  1693. * @param [in] num Multi-precision number object.
  1694. */
  1695. void GetASN_MP(ASNGetData *dataASN, mp_int* num)
  1696. {
  1697. dataASN->dataType = ASN_DATA_TYPE_MP;
  1698. dataASN->data.mp = num;
  1699. }
  1700. /* Setup ASN data item to get a positive or negative number into an mp_int.
  1701. *
  1702. * @param [in] dataASN Dynamic ASN data item.
  1703. * @param [in] num Multi-precision number object.
  1704. */
  1705. void GetASN_MP_PosNeg(ASNGetData *dataASN, mp_int* num)
  1706. {
  1707. dataASN->dataType = ASN_DATA_TYPE_MP_POS_NEG;
  1708. dataASN->data.mp = num;
  1709. }
  1710. /* Setup ASN data item to be a choice of tags.
  1711. *
  1712. * @param [in] dataASN Dynamic ASN data item.
  1713. * @param [in] options 0 terminated list of tags that are valid.
  1714. */
  1715. void GetASN_Choice(ASNGetData *dataASN, const byte* options)
  1716. {
  1717. dataASN->dataType = ASN_DATA_TYPE_CHOICE;
  1718. dataASN->data.choice = options;
  1719. }
  1720. /* Setup ASN data item to get a boolean value.
  1721. *
  1722. * @param [in] dataASN Dynamic ASN data item.
  1723. * @param [in] num Pointer to an 8-bit variable.
  1724. */
  1725. void GetASN_Boolean(ASNGetData *dataASN, byte* num)
  1726. {
  1727. dataASN->dataType = ASN_DATA_TYPE_NONE;
  1728. dataASN->data.choice = num;
  1729. }
  1730. /* Setup ASN data item to be a an OID of a specific type.
  1731. *
  1732. * @param [in] dataASN Dynamic ASN data item.
  1733. * @param [in] oidType Type of OID to expect.
  1734. */
  1735. void GetASN_OID(ASNGetData *dataASN, int oidType)
  1736. {
  1737. dataASN->data.oid.type = oidType;
  1738. }
  1739. /* Get the data and length from an ASN data item.
  1740. *
  1741. * @param [in] dataASN Dynamic ASN data item.
  1742. * @param [out] data Pointer to data of item.
  1743. * @param [out] length Length of buffer in bytes.
  1744. */
  1745. void GetASN_GetConstRef(ASNGetData * dataASN, const byte** data, word32* length)
  1746. {
  1747. *data = dataASN->data.ref.data;
  1748. *length = dataASN->data.ref.length;
  1749. }
  1750. /* Get the data and length from an ASN data item.
  1751. *
  1752. * @param [in] dataASN Dynamic ASN data item.
  1753. * @param [out] data Pointer to data of item.
  1754. * @param [out] length Length of buffer in bytes.
  1755. */
  1756. void GetASN_GetRef(ASNGetData * dataASN, byte** data, word32* length)
  1757. {
  1758. *data = (byte*)dataASN->data.ref.data;
  1759. *length = dataASN->data.ref.length;
  1760. }
  1761. /* Get the data and length from an ASN data item that is an OID.
  1762. *
  1763. * @param [in] dataASN Dynamic ASN data item.
  1764. * @param [out] data Pointer to .
  1765. * @param [out] length Length of buffer in bytes.
  1766. */
  1767. void GetASN_OIDData(ASNGetData * dataASN, byte** data, word32* length)
  1768. {
  1769. *data = (byte*)dataASN->data.oid.data;
  1770. *length = dataASN->data.oid.length;
  1771. }
  1772. /* Setup an ASN data item to set a boolean.
  1773. *
  1774. * @param [in] dataASN Dynamic ASN data item.
  1775. * @param [in] val Boolean value.
  1776. */
  1777. void SetASN_Boolean(ASNSetData *dataASN, byte val)
  1778. {
  1779. dataASN->dataType = ASN_DATA_TYPE_NONE;
  1780. dataASN->data.u8 = val;
  1781. }
  1782. /* Setup an ASN data item to set an 8-bit number.
  1783. *
  1784. * @param [in] dataASN Dynamic ASN data item.
  1785. * @param [in] num 8-bit number to set.
  1786. */
  1787. void SetASN_Int8Bit(ASNSetData *dataASN, byte num)
  1788. {
  1789. dataASN->dataType = ASN_DATA_TYPE_WORD8;
  1790. dataASN->data.u8 = num;
  1791. }
  1792. /* Setup an ASN data item to set a 16-bit number.
  1793. *
  1794. * @param [in] dataASN Dynamic ASN data item.
  1795. * @param [in] num 16-bit number to set.
  1796. */
  1797. void SetASN_Int16Bit(ASNSetData *dataASN, word16 num)
  1798. {
  1799. dataASN->dataType = ASN_DATA_TYPE_WORD16;
  1800. dataASN->data.u16 = num;
  1801. }
  1802. /* Setup an ASN data item to set the data in a buffer.
  1803. *
  1804. * @param [in] dataASN Dynamic ASN data item.
  1805. * @param [in] data Buffer containing data to set.
  1806. * @param [in] length Length of data in buffer in bytes.
  1807. */
  1808. void SetASN_Buffer(ASNSetData *dataASN, const byte* data, word32 length)
  1809. {
  1810. dataASN->data.buffer.data = data;
  1811. dataASN->data.buffer.length = length;
  1812. }
  1813. /* Setup an ASN data item to set the DER encode data in a buffer.
  1814. *
  1815. * @param [in] dataASN Dynamic ASN data item.
  1816. * @param [in] data Buffer containing BER encoded data to set.
  1817. * @param [in] length Length of data in buffer in bytes.
  1818. */
  1819. void SetASN_ReplaceBuffer(ASNSetData *dataASN, const byte* data, word32 length)
  1820. {
  1821. dataASN->dataType = ASN_DATA_TYPE_REPLACE_BUFFER;
  1822. dataASN->data.buffer.data = data;
  1823. dataASN->data.buffer.length = length;
  1824. }
  1825. /* Setup an ASN data item to set an multi-precision number.
  1826. *
  1827. * @param [in] dataASN Dynamic ASN data item.
  1828. * @param [in] num Multi-precision number.
  1829. */
  1830. void SetASN_MP(ASNSetData *dataASN, mp_int* num)
  1831. {
  1832. dataASN->dataType = ASN_DATA_TYPE_MP;
  1833. dataASN->data.mp = num;
  1834. }
  1835. /* Setup an ASN data item to set an OID based on id and type.
  1836. *
  1837. * oid and oidType pair are unique.
  1838. *
  1839. * @param [in] dataASN Dynamic ASN data item.
  1840. * @param [in] oid OID identifier.
  1841. * @param [in] oidType Type of OID.
  1842. */
  1843. void SetASN_OID(ASNSetData *dataASN, int oid, int oidType)
  1844. {
  1845. dataASN->data.buffer.data = OidFromId(oid, oidType,
  1846. &dataASN->data.buffer.length);
  1847. }
  1848. #endif /* WOLFSSL_ASN_TEMPLATE_TYPE_CHECK */
  1849. #ifdef CRLDP_VALIDATE_DATA
  1850. /* Get the data of the BIT_STRING as a 16-bit number.
  1851. *
  1852. * @param [in] dataASN Dynamic ASN data item.
  1853. * @param [out] val ASN.1 item's data as a 16-bit number.
  1854. * @return 0 on success.
  1855. * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
  1856. * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
  1857. */
  1858. static int GetASN_BitString_Int16Bit(ASNGetData* dataASN, word16* val)
  1859. {
  1860. int ret;
  1861. int i;
  1862. const byte* input = dataASN->data.ref.data;
  1863. int length = dataASN->data.ref.length;
  1864. /* Validate the BIT_STRING data. */
  1865. ret = GetASN_BitString(input, 0, length);
  1866. if (ret == 0) {
  1867. /* Skip unused bits byte. */
  1868. input++;
  1869. length--;
  1870. /* Check the data is usable. */
  1871. if (length == 0 || length > 2) {
  1872. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1873. WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", length);
  1874. #endif
  1875. ret = ASN_PARSE_E;
  1876. }
  1877. }
  1878. if (ret == 0) {
  1879. /* Fill 16-bit var with all the data. */
  1880. *val = 0;
  1881. for (i = 0; i < length; i++) {
  1882. *val <<= 8;
  1883. *val |= input[i];
  1884. }
  1885. }
  1886. return ret;
  1887. }
  1888. #endif /* CRLDP_VALIDATE_DATA */
  1889. #endif /* WOLFSSL_ASN_TEMPLATE */
  1890. /* Decode the BER/DER length field.
  1891. *
  1892. * @param [in] input BER encoded data.
  1893. * @param [in, out] inOutIdx On in, starting index of length.
  1894. * On out, end of parsed length.
  1895. * @param [out] len Length value decoded.
  1896. * @param [in] maxIdx Maximum index of input data.
  1897. * @return Length on success.
  1898. * @return ASN_PARSE_E if the encoding is invalid.
  1899. * @return BUFFER_E when not enough data to complete decode.
  1900. */
  1901. int GetLength(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  1902. {
  1903. return GetLength_ex(input, inOutIdx, len, maxIdx, 1);
  1904. }
  1905. /* Decode the BER/DER length field and check the length is valid on request.
  1906. *
  1907. * BER/DER has Type-Length-Value triplets.
  1908. * When requested will check that the Length decoded, indicating the number
  1909. * of bytes in the Value, is available in the buffer after the Length bytes.
  1910. *
  1911. * Only supporting a length upto INT_MAX.
  1912. *
  1913. * @param [in] input BER encoded data.
  1914. * @param [in, out] inOutIdx On in, starting index of length.
  1915. * On out, end of parsed length.
  1916. * @param [out] len Length value decoded.
  1917. * @param [in] maxIdx Maximum index of input data.
  1918. * @param [in] check Whether to check the buffer has at least the
  1919. * decoded length of bytes remaining.
  1920. * @return Length on success.
  1921. * @return ASN_PARSE_E if the encoding is invalid.
  1922. * @return BUFFER_E when not enough data to complete decode.
  1923. */
  1924. int GetLength_ex(const byte* input, word32* inOutIdx, int* len, word32 maxIdx,
  1925. int check)
  1926. {
  1927. int length = 0;
  1928. word32 idx = *inOutIdx;
  1929. byte b;
  1930. /* Ensure zero return length on error. */
  1931. *len = 0;
  1932. /* Check there is at least on byte available containing length information.
  1933. */
  1934. if ((idx + 1) > maxIdx) {
  1935. WOLFSSL_MSG("GetLength - bad index on input");
  1936. return BUFFER_E;
  1937. }
  1938. /* Get the first length byte. */
  1939. b = input[idx++];
  1940. /* Check if the first byte indicates the count of bytes. */
  1941. if (b >= ASN_LONG_LENGTH) {
  1942. /* Bottom 7 bits are the number of bytes to calculate length with.
  1943. * Note: 0 indicates indefinite length encoding *not* 0 bytes of length.
  1944. */
  1945. word32 bytes = b & 0x7F;
  1946. int minLen;
  1947. /* Calculate minimum length to be encoded with bytes. */
  1948. if (b == 0x80) {
  1949. /* Indefinite length encoding - no length bytes. */
  1950. minLen = 0;
  1951. }
  1952. else if (bytes == 1) {
  1953. minLen = 0x80;
  1954. }
  1955. /* Only support up to the number of bytes that fit into return var. */
  1956. else if (bytes > sizeof(length)) {
  1957. WOLFSSL_MSG("GetLength - overlong data length spec");
  1958. return ASN_PARSE_E;
  1959. } else {
  1960. minLen = 1 << ((bytes - 1) * 8);
  1961. }
  1962. /* Check the number of bytes required are available. */
  1963. if ((idx + bytes) > maxIdx) {
  1964. WOLFSSL_MSG("GetLength - bad long length");
  1965. return BUFFER_E;
  1966. }
  1967. /* Big-endian encoding of number. */
  1968. while (bytes--) {
  1969. b = input[idx++];
  1970. length = (length << 8) | b;
  1971. }
  1972. /* Negative value indicates we overflowed the signed int. */
  1973. if (length < 0) {
  1974. return ASN_PARSE_E;
  1975. }
  1976. /* Don't allow lengths that are longer than strictly required. */
  1977. if (length < minLen) {
  1978. return ASN_PARSE_E;
  1979. }
  1980. }
  1981. else {
  1982. /* Length in first byte. */
  1983. length = b;
  1984. }
  1985. /* When request, check the buffer has at least length bytes left. */
  1986. if (check && ((idx + length) > maxIdx)) {
  1987. WOLFSSL_MSG("GetLength - value exceeds buffer length");
  1988. return BUFFER_E;
  1989. }
  1990. /* Return index after length encoding. */
  1991. *inOutIdx = idx;
  1992. /* Return length if valid. */
  1993. if (length > 0) {
  1994. *len = length;
  1995. }
  1996. /* Return length calculated or error code. */
  1997. return length;
  1998. }
  1999. /* Gets the tag of next BER/DER encoded item.
  2000. *
  2001. * Checks there is enough data in the buffer for the tag byte.
  2002. *
  2003. * @param [in] input BER encoded data.
  2004. * @param [in, out] inOutIdx On in, starting index of tag.
  2005. * On out, end of parsed tag.
  2006. * @param [out] tag Tag value found.
  2007. * @param [in] maxIdx Maximum index of input data.
  2008. *
  2009. * return 0 on success
  2010. * return BAD_FUNC_ARG when tag, inOutIdx or input is NULL.
  2011. * return BUFFER_E when not enough space in buffer for tag.
  2012. */
  2013. int GetASNTag(const byte* input, word32* inOutIdx, byte* tag, word32 maxIdx)
  2014. {
  2015. int ret = 0;
  2016. word32 idx = 0;
  2017. /* Check validity of parameters. */
  2018. if ((tag == NULL) || (inOutIdx == NULL) || (input == NULL)) {
  2019. ret = BAD_FUNC_ARG;
  2020. }
  2021. if (ret == 0) {
  2022. /* Get index and ensure space for tag. */
  2023. idx = *inOutIdx;
  2024. if (idx + ASN_TAG_SZ > maxIdx) {
  2025. WOLFSSL_MSG("Buffer too small for ASN tag");
  2026. ret = BUFFER_E;
  2027. }
  2028. }
  2029. if (ret == 0) {
  2030. /* Return the tag and the index after tag. */
  2031. *tag = input[idx];
  2032. *inOutIdx = idx + ASN_TAG_SZ;
  2033. }
  2034. /* Return error code. */
  2035. return ret;
  2036. }
  2037. /* Decode the DER/BER header (Type-Length) and check the length when requested.
  2038. *
  2039. * BER/DER has Type-Length-Value triplets.
  2040. * Check that the tag/type is the required value.
  2041. * When requested will check that the Length decoded, indicating the number
  2042. * of bytes in the Value, is available in the buffer after the Length bytes.
  2043. *
  2044. * Only supporting a length upto INT_MAX.
  2045. *
  2046. * @param [in] input Buffer holding DER/BER encoded data.
  2047. * @param [in] tag ASN.1 tag value expected in header.
  2048. * @param [in, out] inOutIdx On in, starting index of header.
  2049. * On out, end of parsed header.
  2050. * @param [out] len Number of bytes in the ASN.1 data.
  2051. * @param [in] maxIdx Length of data in buffer.
  2052. * @param [in] check Whether to check the buffer has at least the
  2053. * decoded length of bytes remaining.
  2054. * @return Number of bytes in the ASN.1 data on success.
  2055. * @return BUFFER_E when there is not enough data to parse.
  2056. * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
  2057. */
  2058. static int GetASNHeader_ex(const byte* input, byte tag, word32* inOutIdx,
  2059. int* len, word32 maxIdx, int check)
  2060. {
  2061. int ret = 0;
  2062. word32 idx = *inOutIdx;
  2063. byte tagFound;
  2064. int length = 0;
  2065. /* Get tag/type. */
  2066. if (GetASNTag(input, &idx, &tagFound, maxIdx) != 0) {
  2067. ret = ASN_PARSE_E;
  2068. }
  2069. /* Ensure tag is the expected value. */
  2070. if ((ret == 0) && (tagFound != tag)) {
  2071. ret = ASN_PARSE_E;
  2072. }
  2073. /* Get the encoded length. */
  2074. if ((ret == 0) && (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)) {
  2075. ret = ASN_PARSE_E;
  2076. }
  2077. if (ret == 0) {
  2078. /* Return the length of data and index after header. */
  2079. *len = length;
  2080. *inOutIdx = idx;
  2081. ret = length;
  2082. }
  2083. /* Return number of data bytes or error code. */
  2084. return ret;
  2085. }
  2086. /* Decode the DER/BER header (Type-Length) and check the length.
  2087. *
  2088. * BER/DER has Type-Length-Value triplets.
  2089. * Check that the tag/type is the required value.
  2090. * Checks that the Length decoded, indicating the number of bytes in the Value,
  2091. * is available in the buffer after the Length bytes.
  2092. *
  2093. * @param [in] input Buffer holding DER/BER encoded data.
  2094. * @param [in] tag ASN.1 tag value expected in header.
  2095. * @param [in, out] inOutIdx On in, starting index of header.
  2096. * On out, end of parsed header.
  2097. * @param [out] len Number of bytes in the ASN.1 data.
  2098. * @param [in] maxIdx Length of data in buffer.
  2099. * @return Number of bytes in the ASN.1 data on success.
  2100. * @return BUFFER_E when there is not enough data to parse.
  2101. * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
  2102. */
  2103. static int GetASNHeader(const byte* input, byte tag, word32* inOutIdx, int* len,
  2104. word32 maxIdx)
  2105. {
  2106. return GetASNHeader_ex(input, tag, inOutIdx, len, maxIdx, 1);
  2107. }
  2108. #ifndef WOLFSSL_ASN_TEMPLATE
  2109. static int GetHeader(const byte* input, byte* tag, word32* inOutIdx, int* len,
  2110. word32 maxIdx, int check)
  2111. {
  2112. word32 idx = *inOutIdx;
  2113. int length;
  2114. if ((idx + 1) > maxIdx)
  2115. return BUFFER_E;
  2116. *tag = input[idx++];
  2117. if (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)
  2118. return ASN_PARSE_E;
  2119. *len = length;
  2120. *inOutIdx = idx;
  2121. return length;
  2122. }
  2123. #endif
  2124. /* Decode the header of a BER/DER encoded SEQUENCE.
  2125. *
  2126. * @param [in] input Buffer holding DER/BER encoded data.
  2127. * @param [in, out] inOutIdx On in, starting index of header.
  2128. * On out, end of parsed header.
  2129. * @param [out] len Number of bytes in the ASN.1 data.
  2130. * @param [in] maxIdx Length of data in buffer.
  2131. * @return Number of bytes in the ASN.1 data on success.
  2132. * @return BUFFER_E when there is not enough data to parse.
  2133. * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
  2134. */
  2135. int GetSequence(const byte* input, word32* inOutIdx, int* len,
  2136. word32 maxIdx)
  2137. {
  2138. return GetASNHeader(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  2139. maxIdx);
  2140. }
  2141. /* Decode the header of a BER/DER encoded SEQUENCE.
  2142. *
  2143. * @param [in] input Buffer holding DER/BER encoded data.
  2144. * @param [in, out] inOutIdx On in, starting index of header.
  2145. * On out, end of parsed header.
  2146. * @param [out] len Number of bytes in the ASN.1 data.
  2147. * @param [in] maxIdx Length of data in buffer.
  2148. * @param [in] check Whether to check the buffer has at least the
  2149. * decoded length of bytes remaining.
  2150. * @return Number of bytes in the ASN.1 data on success.
  2151. * @return BUFFER_E when there is not enough data to parse.
  2152. * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
  2153. */
  2154. int GetSequence_ex(const byte* input, word32* inOutIdx, int* len,
  2155. word32 maxIdx, int check)
  2156. {
  2157. return GetASNHeader_ex(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  2158. maxIdx, check);
  2159. }
  2160. /* Decode the header of a BER/DER encoded SET.
  2161. *
  2162. * @param [in] input Buffer holding DER/BER encoded data.
  2163. * @param [in, out] inOutIdx On in, starting index of header.
  2164. * On out, end of parsed header.
  2165. * @param [out] len Number of bytes in the ASN.1 data.
  2166. * @param [in] maxIdx Length of data in buffer.
  2167. * @return Number of bytes in the ASN.1 data on success.
  2168. * @return BUFFER_E when there is not enough data to parse.
  2169. * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
  2170. */
  2171. int GetSet(const byte* input, word32* inOutIdx, int* len,
  2172. word32 maxIdx)
  2173. {
  2174. return GetASNHeader(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  2175. maxIdx);
  2176. }
  2177. /* Decode the header of a BER/DER encoded SET.
  2178. *
  2179. * @param [in] input Buffer holding DER/BER encoded data.
  2180. * @param [in, out] inOutIdx On in, starting index of header.
  2181. * On out, end of parsed header.
  2182. * @param [out] len Number of bytes in the ASN.1 data.
  2183. * @param [in] maxIdx Length of data in buffer.
  2184. * @param [in] check Whether to check the buffer has at least the
  2185. * decoded length of bytes remaining.
  2186. * @return Number of bytes in the ASN.1 data on success.
  2187. * @return BUFFER_E when there is not enough data to parse.
  2188. * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
  2189. */
  2190. int GetSet_ex(const byte* input, word32* inOutIdx, int* len,
  2191. word32 maxIdx, int check)
  2192. {
  2193. return GetASNHeader_ex(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  2194. maxIdx, check);
  2195. }
  2196. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_OCSP)
  2197. /* Decode the BER/DER encoded NULL.
  2198. *
  2199. * No data in a NULL ASN.1 item.
  2200. * Ensure that the all fields are as expected and move index past the element.
  2201. *
  2202. * @param [in] input Buffer holding DER/BER encoded data.
  2203. * @param [in, out] inOutIdx On in, starting index of NULL item.
  2204. * On out, end of parsed NULL item.
  2205. * @param [in] maxIdx Length of data in buffer.
  2206. * @return 0 on success.
  2207. * @return BUFFER_E when there is not enough data to parse.
  2208. * @return ASN_TAG_NULL_E when the NULL tag is not found.
  2209. * @return ASN_EXPECT_0_E when the length is not zero.
  2210. */
  2211. static int GetASNNull(const byte* input, word32* inOutIdx, word32 maxIdx)
  2212. {
  2213. int ret = 0;
  2214. word32 idx = *inOutIdx;
  2215. /* Check buffer has enough data for a NULL item. */
  2216. if ((idx + 2) > maxIdx) {
  2217. ret = BUFFER_E;
  2218. }
  2219. /* Check the tag is NULL. */
  2220. if ((ret == 0) && (input[idx++] != ASN_TAG_NULL)) {
  2221. ret = ASN_TAG_NULL_E;
  2222. }
  2223. /* Check the length is zero. */
  2224. if ((ret == 0) && (input[idx++] != 0)) {
  2225. ret = ASN_EXPECT_0_E;
  2226. }
  2227. if (ret == 0) {
  2228. /* Return the index after NULL tag. */
  2229. *inOutIdx = idx;
  2230. }
  2231. /* Return error code. */
  2232. return ret;
  2233. }
  2234. #endif
  2235. #ifndef WOLFSSL_ASN_TEMPLATE
  2236. /* Set the DER/BER encoding of the ASN.1 NULL element.
  2237. *
  2238. * output Buffer to write into.
  2239. * returns the number of bytes added to the buffer.
  2240. */
  2241. static int SetASNNull(byte* output)
  2242. {
  2243. output[0] = ASN_TAG_NULL;
  2244. output[1] = 0;
  2245. return 2;
  2246. }
  2247. #endif
  2248. #ifndef NO_CERTS
  2249. #ifndef WOLFSSL_ASN_TEMPLATE
  2250. /* Get the DER/BER encoding of an ASN.1 BOOLEAN.
  2251. *
  2252. * input Buffer holding DER/BER encoded data.
  2253. * inOutIdx Current index into buffer to parse.
  2254. * maxIdx Length of data in buffer.
  2255. * returns BUFFER_E when there is not enough data to parse.
  2256. * ASN_PARSE_E when the BOOLEAN tag is not found or length is not 1.
  2257. * Otherwise, 0 to indicate the value was false and 1 to indicate true.
  2258. */
  2259. static int GetBoolean(const byte* input, word32* inOutIdx, word32 maxIdx)
  2260. {
  2261. word32 idx = *inOutIdx;
  2262. byte b;
  2263. if ((idx + 3) > maxIdx)
  2264. return BUFFER_E;
  2265. b = input[idx++];
  2266. if (b != ASN_BOOLEAN)
  2267. return ASN_PARSE_E;
  2268. if (input[idx++] != 1)
  2269. return ASN_PARSE_E;
  2270. b = input[idx++] != 0;
  2271. *inOutIdx = idx;
  2272. return b;
  2273. }
  2274. #endif
  2275. #endif /* !NO_CERTS*/
  2276. /* Decode the header of a BER/DER encoded OCTET STRING.
  2277. *
  2278. * @param [in] input Buffer holding DER/BER encoded data.
  2279. * @param [in, out] inOutIdx On in, starting index of header.
  2280. * On out, end of parsed header.
  2281. * @param [out] len Number of bytes in the ASN.1 data.
  2282. * @param [in] maxIdx Length of data in buffer.
  2283. * @return Number of bytes in the ASN.1 data on success.
  2284. * @return BUFFER_E when there is not enough data to parse.
  2285. * @return ASN_PARSE_E when the tag is not a OCTET STRING or length is invalid.
  2286. */
  2287. int GetOctetString(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  2288. {
  2289. return GetASNHeader(input, ASN_OCTET_STRING, inOutIdx, len, maxIdx);
  2290. }
  2291. #ifndef WOLFSSL_ASN_TEMPLATE
  2292. /* Get the DER/BER encoding of an ASN.1 INTEGER header.
  2293. *
  2294. * Removes the leading zero byte when found.
  2295. *
  2296. * input Buffer holding DER/BER encoded data.
  2297. * inOutIdx Current index into buffer to parse.
  2298. * len The number of bytes in the ASN.1 data (excluding any leading zero).
  2299. * maxIdx Length of data in buffer.
  2300. * returns BUFFER_E when there is not enough data to parse.
  2301. * ASN_PARSE_E when the INTEGER tag is not found, length is invalid,
  2302. * or invalid use of or missing leading zero.
  2303. * Otherwise, 0 to indicate success.
  2304. */
  2305. static int GetASNInt(const byte* input, word32* inOutIdx, int* len,
  2306. word32 maxIdx)
  2307. {
  2308. int ret;
  2309. ret = GetASNHeader(input, ASN_INTEGER, inOutIdx, len, maxIdx);
  2310. if (ret < 0)
  2311. return ret;
  2312. if (*len > 0) {
  2313. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2314. /* check for invalid padding on negative integer.
  2315. * c.f. X.690 (ISO/IEC 8825-2:2003 (E)) 10.4.6; RFC 5280 4.1
  2316. */
  2317. if (*len > 1) {
  2318. if ((input[*inOutIdx] == 0xff) && (input[*inOutIdx + 1] & 0x80))
  2319. return ASN_PARSE_E;
  2320. }
  2321. #endif
  2322. /* remove leading zero, unless there is only one 0x00 byte */
  2323. if ((input[*inOutIdx] == 0x00) && (*len > 1)) {
  2324. (*inOutIdx)++;
  2325. (*len)--;
  2326. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2327. if (*len > 0 && (input[*inOutIdx] & 0x80) == 0)
  2328. return ASN_PARSE_E;
  2329. #endif
  2330. }
  2331. }
  2332. return 0;
  2333. }
  2334. #ifndef NO_CERTS
  2335. /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
  2336. * 7 bits.
  2337. *
  2338. * input Buffer holding DER/BER encoded data.
  2339. * inOutIdx Current index into buffer to parse.
  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 or length is invalid.
  2343. * Otherwise, the 7-bit value.
  2344. */
  2345. static int GetInteger7Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
  2346. {
  2347. word32 idx = *inOutIdx;
  2348. byte b;
  2349. if ((idx + 3) > maxIdx)
  2350. return BUFFER_E;
  2351. if (GetASNTag(input, &idx, &b, maxIdx) != 0)
  2352. return ASN_PARSE_E;
  2353. if (b != ASN_INTEGER)
  2354. return ASN_PARSE_E;
  2355. if (input[idx++] != 1)
  2356. return ASN_PARSE_E;
  2357. b = input[idx++];
  2358. *inOutIdx = idx;
  2359. return b;
  2360. }
  2361. #if defined(WC_RSA_PSS) && !defined(NO_RSA)
  2362. /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
  2363. * 16 bits.
  2364. *
  2365. * input Buffer holding DER/BER encoded data.
  2366. * inOutIdx Current index into buffer to parse.
  2367. * maxIdx Length of data in buffer.
  2368. * returns BUFFER_E when there is not enough data to parse.
  2369. * ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
  2370. * Otherwise, the 16-bit value.
  2371. */
  2372. static int GetInteger16Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
  2373. {
  2374. word32 idx = *inOutIdx;
  2375. byte tag;
  2376. word16 n;
  2377. if ((idx + 2) > maxIdx)
  2378. return BUFFER_E;
  2379. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2380. return ASN_PARSE_E;
  2381. if (tag != ASN_INTEGER)
  2382. return ASN_PARSE_E;
  2383. if (input[idx] == 1) {
  2384. idx++;
  2385. if ((idx + 1) > maxIdx) {
  2386. return ASN_PARSE_E;
  2387. }
  2388. n = input[idx++];
  2389. }
  2390. else if (input[idx] == 2) {
  2391. idx++;
  2392. if ((idx + 2) > maxIdx) {
  2393. return ASN_PARSE_E;
  2394. }
  2395. n = input[idx++];
  2396. n = (n << 8) | input[idx++];
  2397. }
  2398. else
  2399. return ASN_PARSE_E;
  2400. *inOutIdx = idx;
  2401. return n;
  2402. }
  2403. #endif /* WC_RSA_PSS && !NO_RSA */
  2404. #endif /* !NO_CERTS */
  2405. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2406. #if !defined(NO_DSA) && !defined(NO_SHA)
  2407. static const char sigSha1wDsaName[] = "SHAwDSA";
  2408. static const char sigSha256wDsaName[] = "SHA256wDSA";
  2409. #endif /* NO_DSA */
  2410. #ifndef NO_RSA
  2411. #ifdef WOLFSSL_MD2
  2412. static const char sigMd2wRsaName[] = "md2WithRSAEncryption";
  2413. #endif
  2414. #ifndef NO_MD5
  2415. static const char sigMd5wRsaName[] = "md5WithRSAEncryption";
  2416. #endif
  2417. #ifndef NO_SHA
  2418. static const char sigSha1wRsaName[] = "sha1WithRSAEncryption";
  2419. #endif
  2420. #ifdef WOLFSSL_SHA224
  2421. static const char sigSha224wRsaName[] = "sha224WithRSAEncryption";
  2422. #endif
  2423. #ifndef NO_SHA256
  2424. static const char sigSha256wRsaName[] = "sha256WithRSAEncryption";
  2425. #endif
  2426. #ifdef WOLFSSL_SHA384
  2427. static const char sigSha384wRsaName[] = "sha384WithRSAEncryption";
  2428. #endif
  2429. #ifdef WOLFSSL_SHA512
  2430. static const char sigSha512wRsaName[] = "sha512WithRSAEncryption";
  2431. #endif
  2432. #ifdef WOLFSSL_SHA3
  2433. #ifndef WOLFSSL_NOSHA3_224
  2434. static const char sigSha3_224wRsaName[] = "sha3_224WithRSAEncryption";
  2435. #endif
  2436. #ifndef WOLFSSL_NOSHA3_256
  2437. static const char sigSha3_256wRsaName[] = "sha3_256WithRSAEncryption";
  2438. #endif
  2439. #ifndef WOLFSSL_NOSHA3_384
  2440. static const char sigSha3_384wRsaName[] = "sha3_384WithRSAEncryption";
  2441. #endif
  2442. #ifndef WOLFSSL_NOSHA3_512
  2443. static const char sigSha3_512wRsaName[] = "sha3_512WithRSAEncryption";
  2444. #endif
  2445. #endif
  2446. #ifdef WC_RSA_PSS
  2447. static const char sigRsaSsaPssName[] = "rsassaPss";
  2448. #endif
  2449. #endif /* NO_RSA */
  2450. #ifdef HAVE_ECC
  2451. #ifndef NO_SHA
  2452. static const char sigSha1wEcdsaName[] = "SHAwECDSA";
  2453. #endif
  2454. #ifdef WOLFSSL_SHA224
  2455. static const char sigSha224wEcdsaName[] = "SHA224wECDSA";
  2456. #endif
  2457. #ifndef NO_SHA256
  2458. static const char sigSha256wEcdsaName[] = "SHA256wECDSA";
  2459. #endif
  2460. #ifdef WOLFSSL_SHA384
  2461. static const char sigSha384wEcdsaName[] = "SHA384wECDSA";
  2462. #endif
  2463. #ifdef WOLFSSL_SHA512
  2464. static const char sigSha512wEcdsaName[] = "SHA512wECDSA";
  2465. #endif
  2466. #ifdef WOLFSSL_SHA3
  2467. #ifndef WOLFSSL_NOSHA3_224
  2468. static const char sigSha3_224wEcdsaName[] = "SHA3_224wECDSA";
  2469. #endif
  2470. #ifndef WOLFSSL_NOSHA3_256
  2471. static const char sigSha3_256wEcdsaName[] = "SHA3_256wECDSA";
  2472. #endif
  2473. #ifndef WOLFSSL_NOSHA3_384
  2474. static const char sigSha3_384wEcdsaName[] = "SHA3_384wECDSA";
  2475. #endif
  2476. #ifndef WOLFSSL_NOSHA3_512
  2477. static const char sigSha3_512wEcdsaName[] = "SHA3_512wECDSA";
  2478. #endif
  2479. #endif
  2480. #endif /* HAVE_ECC */
  2481. static const char sigUnknownName[] = "Unknown";
  2482. /* Get the human readable string for a signature type
  2483. *
  2484. * oid Oid value for signature
  2485. */
  2486. const char* GetSigName(int oid) {
  2487. switch (oid) {
  2488. #if !defined(NO_DSA) && !defined(NO_SHA)
  2489. case CTC_SHAwDSA:
  2490. return sigSha1wDsaName;
  2491. case CTC_SHA256wDSA:
  2492. return sigSha256wDsaName;
  2493. #endif /* NO_DSA && NO_SHA */
  2494. #ifndef NO_RSA
  2495. #ifdef WOLFSSL_MD2
  2496. case CTC_MD2wRSA:
  2497. return sigMd2wRsaName;
  2498. #endif
  2499. #ifndef NO_MD5
  2500. case CTC_MD5wRSA:
  2501. return sigMd5wRsaName;
  2502. #endif
  2503. #ifndef NO_SHA
  2504. case CTC_SHAwRSA:
  2505. return sigSha1wRsaName;
  2506. #endif
  2507. #ifdef WOLFSSL_SHA224
  2508. case CTC_SHA224wRSA:
  2509. return sigSha224wRsaName;
  2510. #endif
  2511. #ifndef NO_SHA256
  2512. case CTC_SHA256wRSA:
  2513. return sigSha256wRsaName;
  2514. #endif
  2515. #ifdef WOLFSSL_SHA384
  2516. case CTC_SHA384wRSA:
  2517. return sigSha384wRsaName;
  2518. #endif
  2519. #ifdef WOLFSSL_SHA512
  2520. case CTC_SHA512wRSA:
  2521. return sigSha512wRsaName;
  2522. #endif
  2523. #ifdef WOLFSSL_SHA3
  2524. #ifndef WOLFSSL_NOSHA3_224
  2525. case CTC_SHA3_224wRSA:
  2526. return sigSha3_224wRsaName;
  2527. #endif
  2528. #ifndef WOLFSSL_NOSHA3_256
  2529. case CTC_SHA3_256wRSA:
  2530. return sigSha3_256wRsaName;
  2531. #endif
  2532. #ifndef WOLFSSL_NOSHA3_384
  2533. case CTC_SHA3_384wRSA:
  2534. return sigSha3_384wRsaName;
  2535. #endif
  2536. #ifndef WOLFSSL_NOSHA3_512
  2537. case CTC_SHA3_512wRSA:
  2538. return sigSha3_512wRsaName;
  2539. #endif
  2540. #endif
  2541. #ifdef WC_RSA_PSS
  2542. case CTC_RSASSAPSS:
  2543. return sigRsaSsaPssName;
  2544. #endif
  2545. #endif /* NO_RSA */
  2546. #ifdef HAVE_ECC
  2547. #ifndef NO_SHA
  2548. case CTC_SHAwECDSA:
  2549. return sigSha1wEcdsaName;
  2550. #endif
  2551. #ifdef WOLFSSL_SHA224
  2552. case CTC_SHA224wECDSA:
  2553. return sigSha224wEcdsaName;
  2554. #endif
  2555. #ifndef NO_SHA256
  2556. case CTC_SHA256wECDSA:
  2557. return sigSha256wEcdsaName;
  2558. #endif
  2559. #ifdef WOLFSSL_SHA384
  2560. case CTC_SHA384wECDSA:
  2561. return sigSha384wEcdsaName;
  2562. #endif
  2563. #ifdef WOLFSSL_SHA512
  2564. case CTC_SHA512wECDSA:
  2565. return sigSha512wEcdsaName;
  2566. #endif
  2567. #ifdef WOLFSSL_SHA3
  2568. #ifndef WOLFSSL_NOSHA3_224
  2569. case CTC_SHA3_224wECDSA:
  2570. return sigSha3_224wEcdsaName;
  2571. #endif
  2572. #ifndef WOLFSSL_NOSHA3_256
  2573. case CTC_SHA3_256wECDSA:
  2574. return sigSha3_256wEcdsaName;
  2575. #endif
  2576. #ifndef WOLFSSL_NOSHA3_384
  2577. case CTC_SHA3_384wECDSA:
  2578. return sigSha3_384wEcdsaName;
  2579. #endif
  2580. #ifndef WOLFSSL_NOSHA3_512
  2581. case CTC_SHA3_512wECDSA:
  2582. return sigSha3_512wEcdsaName;
  2583. #endif
  2584. #endif
  2585. #endif /* HAVE_ECC */
  2586. default:
  2587. return sigUnknownName;
  2588. }
  2589. }
  2590. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7) || \
  2591. defined(OPENSSL_EXTRA)
  2592. #if !defined(NO_DSA) || defined(HAVE_ECC) || !defined(NO_CERTS) || \
  2593. (!defined(NO_RSA) && \
  2594. (defined(WOLFSSL_CERT_GEN) || \
  2595. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA))))
  2596. /* Set the DER/BER encoding of the ASN.1 INTEGER header.
  2597. *
  2598. * When output is NULL, calculate the header length only.
  2599. *
  2600. * @param [in] len Length of INTEGER data in bytes.
  2601. * @param [in] firstByte First byte of data, most significant byte of integer,
  2602. * to encode.
  2603. * @param [out] output Buffer to write into.
  2604. * @return Number of bytes added to the buffer.
  2605. */
  2606. int SetASNInt(int len, byte firstByte, byte* output)
  2607. {
  2608. word32 idx = 0;
  2609. if (output) {
  2610. /* Write out tag. */
  2611. output[idx] = ASN_INTEGER;
  2612. }
  2613. /* Step over tag. */
  2614. idx += ASN_TAG_SZ;
  2615. /* Check if first byte has top bit set in which case a 0 is needed to
  2616. * maintain positive value. */
  2617. if (firstByte & 0x80) {
  2618. /* Add pre-prepended byte to length of data in INTEGER. */
  2619. len++;
  2620. }
  2621. /* Encode length - passing NULL for output will not encode. */
  2622. idx += SetLength(len, output ? output + idx : NULL);
  2623. /* Put out pre-pended 0 as well. */
  2624. if (firstByte & 0x80) {
  2625. if (output) {
  2626. /* Write out 0 byte. */
  2627. output[idx] = 0x00;
  2628. }
  2629. /* Update index. */
  2630. idx++;
  2631. }
  2632. /* Return index after header. */
  2633. return idx;
  2634. }
  2635. #endif
  2636. #endif
  2637. #ifndef WOLFSSL_ASN_TEMPLATE
  2638. #if !defined(NO_DSA) || defined(HAVE_ECC) || (defined(WOLFSSL_CERT_GEN) && \
  2639. !defined(NO_RSA)) || ((defined(WOLFSSL_KEY_GEN) || \
  2640. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)) || \
  2641. defined(OPENSSL_EXTRA)) && !defined(NO_RSA) && !defined(HAVE_USER_RSA))
  2642. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int.
  2643. * The number is assumed to be positive.
  2644. *
  2645. * n Multi-precision integer to encode.
  2646. * maxSz Maximum size of the encoded integer.
  2647. * A negative value indicates no check of length requested.
  2648. * output Buffer to write into.
  2649. * returns BUFFER_E when the data is too long for the buffer.
  2650. * MP_TO_E when encoding the integer fails.
  2651. * Otherwise, the number of bytes added to the buffer.
  2652. */
  2653. static int SetASNIntMP(mp_int* n, int maxSz, byte* output)
  2654. {
  2655. int idx = 0;
  2656. int leadingBit;
  2657. int length;
  2658. int err;
  2659. leadingBit = mp_leading_bit(n);
  2660. length = mp_unsigned_bin_size(n);
  2661. if (maxSz >= 0 && (1 + length + (leadingBit ? 1 : 0)) > maxSz)
  2662. return BUFFER_E;
  2663. idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output);
  2664. if (maxSz >= 0 && (idx + length) > maxSz)
  2665. return BUFFER_E;
  2666. if (output) {
  2667. err = mp_to_unsigned_bin(n, output + idx);
  2668. if (err != MP_OKAY)
  2669. return MP_TO_E;
  2670. }
  2671. idx += length;
  2672. return idx;
  2673. }
  2674. #endif
  2675. #if !defined(NO_RSA) && defined(HAVE_USER_RSA) && \
  2676. (defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA))
  2677. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int from
  2678. * an RSA key.
  2679. * The number is assumed to be positive.
  2680. *
  2681. * n Multi-precision integer to encode.
  2682. * output Buffer to write into.
  2683. * returns BUFFER_E when the data is too long for the buffer.
  2684. * MP_TO_E when encoding the integer fails.
  2685. * Otherwise, the number of bytes added to the buffer.
  2686. */
  2687. static int SetASNIntRSA(void* n, byte* output)
  2688. {
  2689. int idx = 0;
  2690. int leadingBit;
  2691. int length;
  2692. int err;
  2693. leadingBit = wc_Rsa_leading_bit(n);
  2694. length = wc_Rsa_unsigned_bin_size(n);
  2695. idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output);
  2696. if ((idx + length) > MAX_RSA_INT_SZ)
  2697. return BUFFER_E;
  2698. if (output) {
  2699. err = wc_Rsa_to_unsigned_bin(n, output + idx, length);
  2700. if (err != MP_OKAY)
  2701. return MP_TO_E;
  2702. }
  2703. idx += length;
  2704. return idx;
  2705. }
  2706. #endif /* !NO_RSA && HAVE_USER_RSA && WOLFSSL_CERT_GEN */
  2707. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2708. #ifdef WOLFSSL_ASN_TEMPLATE
  2709. /* ASN.1 template for an INTEGER. */
  2710. static const ASNItem intASN[] = {
  2711. /* INT */ { 0, ASN_INTEGER, 0, 0, 0 }
  2712. };
  2713. enum {
  2714. INTASN_IDX_INT = 0
  2715. };
  2716. /* Number of items in ASN.1 template for an INTEGER. */
  2717. #define intASN_Length (sizeof(intASN) / sizeof(ASNItem))
  2718. #endif /* WOLFSSL_ASN_TEMPLATE */
  2719. /* Windows header clash for WinCE using GetVersion */
  2720. /* Decode Version - one byte INTEGER.
  2721. *
  2722. * @param [in] input Buffer of BER data.
  2723. * @param [in, out] inOutIdx On in, start of encoded Version.
  2724. * On out, start of next encode ASN.1 item.
  2725. * @param [out] version Number encoded in INTEGER.
  2726. * @param [in] maxIdx Maximum index of data in buffer.
  2727. * @return 0 on success.
  2728. * @return ASN_PARSE_E when encoding is invalid.
  2729. * @return BUFFER_E when data in buffer is too small.
  2730. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2731. */
  2732. int GetMyVersion(const byte* input, word32* inOutIdx,
  2733. int* version, word32 maxIdx)
  2734. {
  2735. #ifndef WOLFSSL_ASN_TEMPLATE
  2736. word32 idx = *inOutIdx;
  2737. byte tag;
  2738. if ((idx + MIN_VERSION_SZ) > maxIdx)
  2739. return ASN_PARSE_E;
  2740. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2741. return ASN_PARSE_E;
  2742. if (tag != ASN_INTEGER)
  2743. return ASN_PARSE_E;
  2744. if (input[idx++] != 0x01)
  2745. return ASN_VERSION_E;
  2746. *version = input[idx++];
  2747. *inOutIdx = idx;
  2748. return *version;
  2749. #else
  2750. ASNGetData dataASN[intASN_Length];
  2751. int ret;
  2752. byte num;
  2753. /* Clear dynamic data and set the version number variable. */
  2754. XMEMSET(dataASN, 0, sizeof(dataASN));
  2755. GetASN_Int8Bit(&dataASN[INTASN_IDX_INT], &num);
  2756. /* Decode the version (INTEGER). */
  2757. ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2758. maxIdx);
  2759. if (ret == 0) {
  2760. /* Return version through variable and return value. */
  2761. *version = num;
  2762. ret = num;
  2763. }
  2764. return ret;
  2765. #endif /* WOLFSSL_ASN_TEMPLATE */
  2766. }
  2767. #ifndef NO_PWDBASED
  2768. /* Decode small integer, 32 bits or less.
  2769. *
  2770. * @param [in] input Buffer of BER data.
  2771. * @param [in, out] inOutIdx On in, start of encoded INTEGER.
  2772. * On out, start of next encode ASN.1 item.
  2773. * @param [out] number Number encoded in INTEGER.
  2774. * @param [in] maxIdx Maximum index of data in buffer.
  2775. * @return 0 on success.
  2776. * @return ASN_PARSE_E when encoding is invalid.
  2777. * @return BUFFER_E when data in buffer is too small.
  2778. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2779. */
  2780. int GetShortInt(const byte* input, word32* inOutIdx, int* number, word32 maxIdx)
  2781. {
  2782. #ifndef WOLFSSL_ASN_TEMPLATE
  2783. word32 idx = *inOutIdx;
  2784. word32 len;
  2785. byte tag;
  2786. *number = 0;
  2787. /* check for type and length bytes */
  2788. if ((idx + 2) > maxIdx)
  2789. return BUFFER_E;
  2790. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2791. return ASN_PARSE_E;
  2792. if (tag != ASN_INTEGER)
  2793. return ASN_PARSE_E;
  2794. len = input[idx++];
  2795. if (len > 4)
  2796. return ASN_PARSE_E;
  2797. if (len + idx > maxIdx)
  2798. return ASN_PARSE_E;
  2799. while (len--) {
  2800. *number = *number << 8 | input[idx++];
  2801. }
  2802. *inOutIdx = idx;
  2803. return *number;
  2804. #else
  2805. ASNGetData dataASN[intASN_Length];
  2806. int ret;
  2807. word32 num;
  2808. /* Clear dynamic data and set the 32-bit number variable. */
  2809. XMEMSET(dataASN, 0, sizeof(dataASN));
  2810. GetASN_Int32Bit(&dataASN[INTASN_IDX_INT], &num);
  2811. /* Decode the short int (INTEGER). */
  2812. ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2813. maxIdx);
  2814. if (ret == 0) {
  2815. /* Return number through variable and return value. */
  2816. *number = num;
  2817. ret = num;
  2818. }
  2819. return ret;
  2820. #endif
  2821. }
  2822. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS12)
  2823. /* Set small integer, 32 bits or less. DER encoding with no leading 0s
  2824. * returns total amount written including ASN tag and length byte on success */
  2825. int SetShortInt(byte* input, word32* inOutIdx, word32 number, word32 maxIdx)
  2826. {
  2827. word32 idx = *inOutIdx;
  2828. word32 len = 0;
  2829. int i;
  2830. byte ar[MAX_LENGTH_SZ];
  2831. /* check for room for type and length bytes */
  2832. if ((idx + 2) > maxIdx)
  2833. return BUFFER_E;
  2834. input[idx++] = ASN_INTEGER;
  2835. idx++; /* place holder for length byte */
  2836. if (MAX_LENGTH_SZ + idx > maxIdx)
  2837. return ASN_PARSE_E;
  2838. /* find first non zero byte */
  2839. XMEMSET(ar, 0, MAX_LENGTH_SZ);
  2840. c32toa(number, ar);
  2841. for (i = 0; i < MAX_LENGTH_SZ; i++) {
  2842. if (ar[i] != 0) {
  2843. break;
  2844. }
  2845. }
  2846. /* handle case of 0 */
  2847. if (i == MAX_LENGTH_SZ) {
  2848. input[idx++] = 0; len++;
  2849. }
  2850. for (; i < MAX_LENGTH_SZ && idx < maxIdx; i++) {
  2851. input[idx++] = ar[i]; len++;
  2852. }
  2853. /* jump back to beginning of input buffer using unaltered inOutIdx value
  2854. * and set number of bytes for integer, then update the index value */
  2855. input[*inOutIdx + 1] = (byte)len;
  2856. *inOutIdx = idx;
  2857. return len + 2; /* size of integer bytes plus ASN TAG and length byte */
  2858. }
  2859. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2860. #endif /* !NO_PWDBASED */
  2861. #ifndef WOLFSSL_ASN_TEMPLATE
  2862. /* May not have one, not an error */
  2863. static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version,
  2864. word32 maxIdx)
  2865. {
  2866. word32 idx = *inOutIdx;
  2867. byte tag;
  2868. WOLFSSL_ENTER("GetExplicitVersion");
  2869. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2870. return ASN_PARSE_E;
  2871. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  2872. int ret;
  2873. *inOutIdx = ++idx; /* skip header */
  2874. ret = GetMyVersion(input, inOutIdx, version, maxIdx);
  2875. if (ret >= 0) {
  2876. /* check if version is expected value rfc 5280 4.1 {0, 1, 2} */
  2877. if (*version > MAX_X509_VERSION || *version < MIN_X509_VERSION) {
  2878. WOLFSSL_MSG("Unexpected certificate version");
  2879. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  2880. ret = ASN_VERSION_E;
  2881. }
  2882. }
  2883. return ret;
  2884. }
  2885. /* go back as is */
  2886. *version = 0;
  2887. return 0;
  2888. }
  2889. #endif
  2890. /* Decode small integer, 32 bits or less.
  2891. *
  2892. * mp_int is initialized.
  2893. *
  2894. * @param [out] mpi mp_int to hold number.
  2895. * @param [in] input Buffer of BER data.
  2896. * @param [in, out] inOutIdx On in, start of encoded INTEGER.
  2897. * On out, start of next encode ASN.1 item.
  2898. * @param [in] maxIdx Maximum index of data in buffer.
  2899. * @return 0 on success.
  2900. * @return ASN_PARSE_E when encoding is invalid.
  2901. * @return BUFFER_E when data in buffer is too small.
  2902. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2903. * @return MP_INIT_E when the unable to initialize an mp_int.
  2904. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  2905. */
  2906. int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, word32 maxIdx)
  2907. {
  2908. #ifndef WOLFSSL_ASN_TEMPLATE
  2909. word32 idx = *inOutIdx;
  2910. int ret;
  2911. int length;
  2912. ret = GetASNInt(input, &idx, &length, maxIdx);
  2913. if (ret != 0)
  2914. return ret;
  2915. if (mp_init(mpi) != MP_OKAY)
  2916. return MP_INIT_E;
  2917. if (mp_read_unsigned_bin(mpi, input + idx, length) != 0) {
  2918. mp_clear(mpi);
  2919. return ASN_GETINT_E;
  2920. }
  2921. #ifdef HAVE_WOLF_BIGINT
  2922. if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
  2923. mp_clear(mpi);
  2924. return ASN_GETINT_E;
  2925. }
  2926. #endif /* HAVE_WOLF_BIGINT */
  2927. *inOutIdx = idx + length;
  2928. return 0;
  2929. #else
  2930. ASNGetData dataASN[intASN_Length];
  2931. /* Clear dynamic data and set the mp_int to fill with value. */
  2932. XMEMSET(dataASN, 0, sizeof(dataASN));
  2933. GetASN_MP_PosNeg(&dataASN[INTASN_IDX_INT], mpi);
  2934. /* Decode the big number (INTEGER). */
  2935. return GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2936. maxIdx);
  2937. #endif
  2938. }
  2939. #if (defined(HAVE_ECC) || !defined(NO_DSA)) && !defined(WOLFSSL_ASN_TEMPLATE)
  2940. static int GetIntPositive(mp_int* mpi, const byte* input, word32* inOutIdx,
  2941. word32 maxIdx)
  2942. {
  2943. word32 idx = *inOutIdx;
  2944. int ret;
  2945. int length;
  2946. ret = GetASNInt(input, &idx, &length, maxIdx);
  2947. if (ret != 0)
  2948. return ret;
  2949. if (((input[idx] & 0x80) == 0x80) && (input[idx - 1] != 0x00))
  2950. return MP_INIT_E;
  2951. if (mp_init(mpi) != MP_OKAY)
  2952. return MP_INIT_E;
  2953. if (mp_read_unsigned_bin(mpi, input + idx, length) != 0) {
  2954. mp_clear(mpi);
  2955. return ASN_GETINT_E;
  2956. }
  2957. #ifdef HAVE_WOLF_BIGINT
  2958. if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
  2959. mp_clear(mpi);
  2960. return ASN_GETINT_E;
  2961. }
  2962. #endif /* HAVE_WOLF_BIGINT */
  2963. *inOutIdx = idx + length;
  2964. return 0;
  2965. }
  2966. #endif /* (ECC || !NO_DSA) && !WOLFSSL_ASN_TEMPLATE */
  2967. #ifndef WOLFSSL_ASN_TEMPLATE
  2968. #if (!defined(WOLFSSL_KEY_GEN) && !defined(OPENSSL_EXTRA) && defined(RSA_LOW_MEM)) \
  2969. || defined(WOLFSSL_RSA_PUBLIC_ONLY) || (!defined(NO_DSA))
  2970. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA)) || !defined(NO_DSA)
  2971. static int SkipInt(const byte* input, word32* inOutIdx, word32 maxIdx)
  2972. {
  2973. word32 idx = *inOutIdx;
  2974. int ret;
  2975. int length;
  2976. ret = GetASNInt(input, &idx, &length, maxIdx);
  2977. if (ret != 0)
  2978. return ret;
  2979. *inOutIdx = idx + length;
  2980. return 0;
  2981. }
  2982. #endif
  2983. #endif
  2984. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2985. #ifdef WOLFSSL_ASN_TEMPLATE
  2986. /* ASN.1 template for a BIT_STRING. */
  2987. static const ASNItem bitStringASN[] = {
  2988. /* BIT_STR */ { 0, ASN_BIT_STRING, 0, 1, 0 }
  2989. };
  2990. enum {
  2991. BITSTRINGASN_IDX_BIT_STR = 0
  2992. };
  2993. /* Number of items in ASN.1 template for a BIT_STRING. */
  2994. #define bitStringASN_Length (sizeof(bitStringASN) / sizeof(ASNItem))
  2995. #endif
  2996. /* Decode and check the BIT_STRING is valid. Return length and unused bits.
  2997. *
  2998. * @param [in] input Buffer holding BER encoding.
  2999. * @param [in, out] inOutIdx On in, start of BIT_STRING.
  3000. * On out, start of ASN.1 item after BIT_STRING.
  3001. * @param [out] len Length of BIT_STRING data.
  3002. * @param [in] maxIdx Maximum index of data in buffer.
  3003. * @param [in] zeroBits Indicates whether zero unused bits is expected.
  3004. * @param [in] unusedBits Number of unused bits in last byte.
  3005. * @return 0 on success.
  3006. * @return ASN_PARSE_E when encoding is invalid.
  3007. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  3008. * @return BUFFER_E when data in buffer is too small.
  3009. * @return ASN_EXPECT_0_E when unused bits is not zero when expected.
  3010. */
  3011. int CheckBitString(const byte* input, word32* inOutIdx, int* len,
  3012. word32 maxIdx, int zeroBits, byte* unusedBits)
  3013. {
  3014. #ifndef WOLFSSL_ASN_TEMPLATE
  3015. word32 idx = *inOutIdx;
  3016. int length;
  3017. byte b;
  3018. if (GetASNTag(input, &idx, &b, maxIdx) != 0) {
  3019. return ASN_BITSTR_E;
  3020. }
  3021. if (b != ASN_BIT_STRING) {
  3022. return ASN_BITSTR_E;
  3023. }
  3024. if (GetLength(input, &idx, &length, maxIdx) < 0)
  3025. return ASN_PARSE_E;
  3026. /* extra sanity check that length is greater than 0 */
  3027. if (length <= 0) {
  3028. WOLFSSL_MSG("Error length was 0 in CheckBitString");
  3029. return BUFFER_E;
  3030. }
  3031. if (idx + 1 > maxIdx) {
  3032. WOLFSSL_MSG("Attempted buffer read larger than input buffer");
  3033. return BUFFER_E;
  3034. }
  3035. b = input[idx];
  3036. if (zeroBits && b != 0x00)
  3037. return ASN_EXPECT_0_E;
  3038. if (b >= 0x08)
  3039. return ASN_PARSE_E;
  3040. if (b != 0) {
  3041. if ((byte)(input[idx + length - 1] << (8 - b)) != 0)
  3042. return ASN_PARSE_E;
  3043. }
  3044. idx++;
  3045. length--; /* length has been checked for greater than 0 */
  3046. *inOutIdx = idx;
  3047. if (len != NULL)
  3048. *len = length;
  3049. if (unusedBits != NULL)
  3050. *unusedBits = b;
  3051. return 0;
  3052. #else
  3053. ASNGetData dataASN[bitStringASN_Length];
  3054. int ret;
  3055. int bits;
  3056. /* Parse BIT_STRING and check validity of unused bits. */
  3057. XMEMSET(dataASN, 0, sizeof(dataASN));
  3058. /* Decode BIT_STRING. */
  3059. ret = GetASN_Items(bitStringASN, dataASN, bitStringASN_Length, 0, input,
  3060. inOutIdx, maxIdx);
  3061. if (ret == 0) {
  3062. /* Get unused bits from dynamic ASN.1 data. */
  3063. bits = GetASNItem_UnusedBits(dataASN[BITSTRINGASN_IDX_BIT_STR]);
  3064. /* Check unused bits is 0 when expected. */
  3065. if (zeroBits && (bits != 0)) {
  3066. ret = ASN_EXPECT_0_E;
  3067. }
  3068. }
  3069. if (ret == 0) {
  3070. /* Return length of data and unused bits if required. */
  3071. if (len != NULL) {
  3072. *len = dataASN[BITSTRINGASN_IDX_BIT_STR].data.ref.length;
  3073. }
  3074. if (unusedBits != NULL) {
  3075. *unusedBits = bits;
  3076. }
  3077. }
  3078. return ret;
  3079. #endif
  3080. }
  3081. /* RSA (with CertGen or KeyGen) OR ECC OR ED25519 OR ED448 (with CertGen or
  3082. * KeyGen) */
  3083. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
  3084. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
  3085. defined(OPENSSL_EXTRA))) || \
  3086. (defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)) || \
  3087. ((defined(HAVE_ED25519) || defined(HAVE_ED448)) && \
  3088. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
  3089. defined(OPENSSL_EXTRA))) || \
  3090. (defined(WC_ENABLE_ASYM_KEY_EXPORT) && !defined(NO_CERT)) || \
  3091. (!defined(NO_DSA) && !defined(HAVE_SELFTEST) && defined(WOLFSSL_KEY_GEN)) || \
  3092. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA))
  3093. /* Set the DER/BER encoding of the ASN.1 BIT STRING header.
  3094. *
  3095. * When output is NULL, calculate the header length only.
  3096. *
  3097. * @param [in] len Length of BIT STRING data.
  3098. * That is, the number of least significant zero bits
  3099. * before a one.
  3100. * The last byte is the most-significant non-zero byte
  3101. * of a number.
  3102. * @param [out] output Buffer to write into.
  3103. * @return Number of bytes added to the buffer.
  3104. */
  3105. word32 SetBitString(word32 len, byte unusedBits, byte* output)
  3106. {
  3107. word32 idx = 0;
  3108. if (output) {
  3109. /* Write out tag. */
  3110. output[idx] = ASN_BIT_STRING;
  3111. }
  3112. /* Step over tag. */
  3113. idx += ASN_TAG_SZ;
  3114. /* Encode length - passing NULL for output will not encode.
  3115. * Add one to length for unused bits. */
  3116. idx += SetLength(len + 1, output ? output + idx : NULL);
  3117. if (output) {
  3118. /* Write out unused bits. */
  3119. output[idx] = unusedBits;
  3120. }
  3121. /* Skip over unused bits. */
  3122. idx++;
  3123. /* Return index after header. */
  3124. return idx;
  3125. }
  3126. #endif /* !NO_RSA || HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  3127. #ifdef ASN_BER_TO_DER
  3128. /* Convert BER to DER */
  3129. /* Pull informtation from the ASN.1 BER encoded item header */
  3130. static int GetBerHeader(const byte* data, word32* idx, word32 maxIdx,
  3131. byte* pTag, word32* pLen, int* indef)
  3132. {
  3133. int len = 0;
  3134. byte tag;
  3135. word32 i = *idx;
  3136. *indef = 0;
  3137. /* Check there is enough data for a minimal header */
  3138. if (i + 2 > maxIdx) {
  3139. return ASN_PARSE_E;
  3140. }
  3141. /* Retrieve tag */
  3142. tag = data[i++];
  3143. /* Indefinite length handled specially */
  3144. if (data[i] == ASN_INDEF_LENGTH) {
  3145. /* Check valid tag for indefinite */
  3146. if (((tag & 0xc0) == 0) && ((tag & ASN_CONSTRUCTED) == 0x00)) {
  3147. return ASN_PARSE_E;
  3148. }
  3149. i++;
  3150. *indef = 1;
  3151. }
  3152. else if (GetLength(data, &i, &len, maxIdx) < 0) {
  3153. return ASN_PARSE_E;
  3154. }
  3155. /* Return tag, length and index after BER item header */
  3156. *pTag = tag;
  3157. *pLen = len;
  3158. *idx = i;
  3159. return 0;
  3160. }
  3161. #ifndef INDEF_ITEMS_MAX
  3162. #define INDEF_ITEMS_MAX 20
  3163. #endif
  3164. /* Indef length item data */
  3165. typedef struct Indef {
  3166. word32 start;
  3167. int depth;
  3168. int headerLen;
  3169. word32 len;
  3170. } Indef;
  3171. /* Indef length items */
  3172. typedef struct IndefItems
  3173. {
  3174. Indef len[INDEF_ITEMS_MAX];
  3175. int cnt;
  3176. int idx;
  3177. int depth;
  3178. } IndefItems;
  3179. /* Get header length of current item */
  3180. static int IndefItems_HeaderLen(IndefItems* items)
  3181. {
  3182. return items->len[items->idx].headerLen;
  3183. }
  3184. /* Get data length of current item */
  3185. static word32 IndefItems_Len(IndefItems* items)
  3186. {
  3187. return items->len[items->idx].len;
  3188. }
  3189. /* Add a indefinite length item */
  3190. static int IndefItems_AddItem(IndefItems* items, word32 start)
  3191. {
  3192. int ret = 0;
  3193. int i;
  3194. if (items->cnt == INDEF_ITEMS_MAX) {
  3195. ret = MEMORY_E;
  3196. }
  3197. else {
  3198. i = items->cnt++;
  3199. items->len[i].start = start;
  3200. items->len[i].depth = items->depth++;
  3201. items->len[i].headerLen = 1;
  3202. items->len[i].len = 0;
  3203. items->idx = i;
  3204. }
  3205. return ret;
  3206. }
  3207. /* Increase data length of current item */
  3208. static void IndefItems_AddData(IndefItems* items, word32 length)
  3209. {
  3210. items->len[items->idx].len += length;
  3211. }
  3212. /* Update header length of current item to reflect data length */
  3213. static void IndefItems_UpdateHeaderLen(IndefItems* items)
  3214. {
  3215. items->len[items->idx].headerLen +=
  3216. SetLength(items->len[items->idx].len, NULL);
  3217. }
  3218. /* Go to indefinite parent of current item */
  3219. static void IndefItems_Up(IndefItems* items)
  3220. {
  3221. int i;
  3222. int depth = items->len[items->idx].depth - 1;
  3223. for (i = items->cnt - 1; i >= 0; i--) {
  3224. if (items->len[i].depth == depth) {
  3225. break;
  3226. }
  3227. }
  3228. items->idx = i;
  3229. items->depth = depth + 1;
  3230. }
  3231. /* Calculate final length by adding length of indefinite child items */
  3232. static void IndefItems_CalcLength(IndefItems* items)
  3233. {
  3234. int i;
  3235. int idx = items->idx;
  3236. for (i = idx + 1; i < items->cnt; i++) {
  3237. if (items->len[i].depth == items->depth) {
  3238. items->len[idx].len += items->len[i].headerLen;
  3239. items->len[idx].len += items->len[i].len;
  3240. }
  3241. }
  3242. items->len[idx].headerLen += SetLength(items->len[idx].len, NULL);
  3243. }
  3244. /* Add more data to indefinite length item */
  3245. static void IndefItems_MoreData(IndefItems* items, word32 length)
  3246. {
  3247. if (items->cnt > 0 && items->idx >= 0) {
  3248. items->len[items->idx].len += length;
  3249. }
  3250. }
  3251. /* Convert a BER encoding with indefinite length items to DER.
  3252. *
  3253. * ber BER encoded data.
  3254. * berSz Length of BER encoded data.
  3255. * der Buffer to hold DER encoded version of data.
  3256. * NULL indicates only the length is required.
  3257. * derSz The size of the buffer to hold the DER encoded data.
  3258. * Will be set if der is NULL, otherwise the value is checked as der is
  3259. * filled.
  3260. * returns ASN_PARSE_E if the BER data is invalid and BAD_FUNC_ARG if ber or
  3261. * derSz are NULL.
  3262. */
  3263. int wc_BerToDer(const byte* ber, word32 berSz, byte* der, word32* derSz)
  3264. {
  3265. int ret = 0;
  3266. word32 i, j;
  3267. #ifdef WOLFSSL_SMALL_STACK
  3268. IndefItems* indefItems = NULL;
  3269. #else
  3270. IndefItems indefItems[1];
  3271. #endif
  3272. byte tag, basic;
  3273. word32 length;
  3274. int indef;
  3275. if (ber == NULL || derSz == NULL)
  3276. return BAD_FUNC_ARG;
  3277. #ifdef WOLFSSL_SMALL_STACK
  3278. indefItems = (IndefItems *)XMALLOC(sizeof(IndefItems), NULL,
  3279. DYNAMIC_TYPE_TMP_BUFFER);
  3280. if (indefItems == NULL) {
  3281. ret = MEMORY_E;
  3282. goto end;
  3283. }
  3284. #endif
  3285. XMEMSET(indefItems, 0, sizeof(*indefItems));
  3286. /* Calculate indefinite item lengths */
  3287. for (i = 0; i < berSz; ) {
  3288. word32 start = i;
  3289. /* Get next BER item */
  3290. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3291. if (ret != 0) {
  3292. goto end;
  3293. }
  3294. if (indef) {
  3295. /* Indefinite item - add to list */
  3296. ret = IndefItems_AddItem(indefItems, i);
  3297. if (ret != 0) {
  3298. goto end;
  3299. }
  3300. if ((tag & 0xC0) == 0 &&
  3301. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3302. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3303. /* Constructed basic type - get repeating tag */
  3304. basic = tag & (~ASN_CONSTRUCTED);
  3305. /* Add up lengths of each item below */
  3306. for (; i < berSz; ) {
  3307. /* Get next BER_item */
  3308. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3309. if (ret != 0) {
  3310. goto end;
  3311. }
  3312. /* End of content closes item */
  3313. if (tag == ASN_EOC) {
  3314. /* Must be zero length */
  3315. if (length != 0) {
  3316. ret = ASN_PARSE_E;
  3317. goto end;
  3318. }
  3319. break;
  3320. }
  3321. /* Must not be indefinite and tag must match parent */
  3322. if (indef || tag != basic) {
  3323. ret = ASN_PARSE_E;
  3324. goto end;
  3325. }
  3326. /* Add to length */
  3327. IndefItems_AddData(indefItems, length);
  3328. /* Skip data */
  3329. i += length;
  3330. }
  3331. /* Ensure we got an EOC and not end of data */
  3332. if (tag != ASN_EOC) {
  3333. ret = ASN_PARSE_E;
  3334. goto end;
  3335. }
  3336. /* Set the header length to include the length field */
  3337. IndefItems_UpdateHeaderLen(indefItems);
  3338. /* Go to indefinite parent item */
  3339. IndefItems_Up(indefItems);
  3340. }
  3341. }
  3342. else if (tag == ASN_EOC) {
  3343. /* End-of-content must be 0 length */
  3344. if (length != 0) {
  3345. ret = ASN_PARSE_E;
  3346. goto end;
  3347. }
  3348. /* Check there is an item to close - missing EOC */
  3349. if (indefItems->depth == 0) {
  3350. ret = ASN_PARSE_E;
  3351. goto end;
  3352. }
  3353. /* Finish calculation of data length for indefinite item */
  3354. IndefItems_CalcLength(indefItems);
  3355. /* Go to indefinite parent item */
  3356. IndefItems_Up(indefItems);
  3357. }
  3358. else {
  3359. /* Known length item to add in - make sure enough data for it */
  3360. if (i + length > berSz) {
  3361. ret = ASN_PARSE_E;
  3362. goto end;
  3363. }
  3364. /* Include all data - can't have indefinite inside definite */
  3365. i += length;
  3366. /* Add entire item to current indefinite item */
  3367. IndefItems_MoreData(indefItems, i - start);
  3368. }
  3369. }
  3370. /* Check we had a EOC for each indefinite item */
  3371. if (indefItems->depth != 0) {
  3372. ret = ASN_PARSE_E;
  3373. goto end;
  3374. }
  3375. /* Write out DER */
  3376. j = 0;
  3377. /* Reset index */
  3378. indefItems->idx = 0;
  3379. for (i = 0; i < berSz; ) {
  3380. word32 start = i;
  3381. /* Get item - checked above */
  3382. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3383. if (indef) {
  3384. if (der != NULL) {
  3385. /* Check enough space for header */
  3386. if (j + IndefItems_HeaderLen(indefItems) > *derSz) {
  3387. ret = BUFFER_E;
  3388. goto end;
  3389. }
  3390. if ((tag & 0xC0) == 0 &&
  3391. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3392. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3393. /* Remove constructed tag for basic types */
  3394. tag &= ~ASN_CONSTRUCTED;
  3395. }
  3396. /* Add tag and length */
  3397. der[j] = tag;
  3398. (void)SetLength(IndefItems_Len(indefItems), der + j + 1);
  3399. }
  3400. /* Add header length of indefinite item */
  3401. j += IndefItems_HeaderLen(indefItems);
  3402. if ((tag & 0xC0) == 0 &&
  3403. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3404. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3405. /* For basic type - get each child item and add data */
  3406. for (; i < berSz; ) {
  3407. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3408. if (tag == ASN_EOC) {
  3409. break;
  3410. }
  3411. if (der != NULL) {
  3412. if (j + length > *derSz) {
  3413. ret = BUFFER_E;
  3414. goto end;
  3415. }
  3416. XMEMCPY(der + j, ber + i, length);
  3417. }
  3418. j += length;
  3419. i += length;
  3420. }
  3421. }
  3422. /* Move to next indef item in list */
  3423. indefItems->idx++;
  3424. }
  3425. else if (tag == ASN_EOC) {
  3426. /* End-Of-Content is not written out in DER */
  3427. }
  3428. else {
  3429. /* Write out definite length item as is. */
  3430. i += length;
  3431. if (der != NULL) {
  3432. /* Ensure space for item */
  3433. if (j + i - start > *derSz) {
  3434. ret = BUFFER_E;
  3435. goto end;
  3436. }
  3437. /* Copy item as is */
  3438. XMEMCPY(der + j, ber + start, i - start);
  3439. }
  3440. j += i - start;
  3441. }
  3442. }
  3443. /* Return the length of the DER encoded ASN.1 */
  3444. *derSz = j;
  3445. if (der == NULL) {
  3446. ret = LENGTH_ONLY_E;
  3447. }
  3448. end:
  3449. #ifdef WOLFSSL_SMALL_STACK
  3450. if (indefItems != NULL) {
  3451. XFREE(indefItems, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3452. }
  3453. #endif
  3454. return ret;
  3455. }
  3456. #endif
  3457. #ifndef WOLFSSL_ASN_TEMPLATE
  3458. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)
  3459. /* Set the DER/BER encoding of the ASN.1 BIT_STRING with a 16-bit value.
  3460. *
  3461. * val 16-bit value to encode.
  3462. * output Buffer to write into.
  3463. * returns the number of bytes added to the buffer.
  3464. */
  3465. static word32 SetBitString16Bit(word16 val, byte* output)
  3466. {
  3467. word32 idx;
  3468. int len;
  3469. byte lastByte;
  3470. byte unusedBits = 0;
  3471. if ((val >> 8) != 0) {
  3472. len = 2;
  3473. lastByte = (byte)(val >> 8);
  3474. }
  3475. else {
  3476. len = 1;
  3477. lastByte = (byte)val;
  3478. }
  3479. while (((lastByte >> unusedBits) & 0x01) == 0x00)
  3480. unusedBits++;
  3481. idx = SetBitString(len, unusedBits, output);
  3482. output[idx++] = (byte)val;
  3483. if (len > 1)
  3484. output[idx++] = (byte)(val >> 8);
  3485. return idx;
  3486. }
  3487. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_CERT_GEN */
  3488. #endif /* !WOLFSSL_ASN_TEMPLATE */
  3489. /* hashType */
  3490. #ifdef WOLFSSL_MD2
  3491. static const byte hashMd2hOid[] = {42, 134, 72, 134, 247, 13, 2, 2};
  3492. #endif
  3493. #ifndef NO_MD5
  3494. static const byte hashMd5hOid[] = {42, 134, 72, 134, 247, 13, 2, 5};
  3495. #endif
  3496. #ifndef NO_SHA
  3497. static const byte hashSha1hOid[] = {43, 14, 3, 2, 26};
  3498. #endif
  3499. #ifdef WOLFSSL_SHA224
  3500. static const byte hashSha224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 4};
  3501. #endif
  3502. #ifndef NO_SHA256
  3503. static const byte hashSha256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 1};
  3504. #endif
  3505. #ifdef WOLFSSL_SHA384
  3506. static const byte hashSha384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 2};
  3507. #endif
  3508. #ifdef WOLFSSL_SHA512
  3509. static const byte hashSha512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 3};
  3510. #ifndef WOLFSSL_NOSHA512_224
  3511. static const byte hashSha512_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 5};
  3512. #endif
  3513. #ifndef WOLFSSL_NOSHA512_256
  3514. static const byte hashSha512_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 6};
  3515. #endif
  3516. #endif
  3517. #ifdef WOLFSSL_SHA3
  3518. #ifndef WOLFSSL_NOSHA3_224
  3519. static const byte hashSha3_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 7};
  3520. #endif /* WOLFSSL_NOSHA3_224 */
  3521. #ifndef WOLFSSL_NOSHA3_256
  3522. static const byte hashSha3_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 8};
  3523. #endif /* WOLFSSL_NOSHA3_256 */
  3524. #ifndef WOLFSSL_NOSHA3_384
  3525. static const byte hashSha3_384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 9};
  3526. #endif /* WOLFSSL_NOSHA3_384 */
  3527. #ifndef WOLFSSL_NOSHA3_512
  3528. static const byte hashSha3_512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 10};
  3529. #endif /* WOLFSSL_NOSHA3_512 */
  3530. #endif /* WOLFSSL_SHA3 */
  3531. /* hmacType */
  3532. #ifndef NO_HMAC
  3533. #ifdef WOLFSSL_SHA224
  3534. static const byte hmacSha224Oid[] = {42, 134, 72, 134, 247, 13, 2, 8};
  3535. #endif
  3536. #ifndef NO_SHA256
  3537. static const byte hmacSha256Oid[] = {42, 134, 72, 134, 247, 13, 2, 9};
  3538. #endif
  3539. #ifdef WOLFSSL_SHA384
  3540. static const byte hmacSha384Oid[] = {42, 134, 72, 134, 247, 13, 2, 10};
  3541. #endif
  3542. #ifdef WOLFSSL_SHA512
  3543. static const byte hmacSha512Oid[] = {42, 134, 72, 134, 247, 13, 2, 11};
  3544. #endif
  3545. #endif
  3546. /* sigType */
  3547. #if !defined(NO_DSA) && !defined(NO_SHA)
  3548. static const byte sigSha1wDsaOid[] = {42, 134, 72, 206, 56, 4, 3};
  3549. static const byte sigSha256wDsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 2};
  3550. #endif /* NO_DSA */
  3551. #ifndef NO_RSA
  3552. #ifdef WOLFSSL_MD2
  3553. static const byte sigMd2wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 2};
  3554. #endif
  3555. #ifndef NO_MD5
  3556. static const byte sigMd5wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 4};
  3557. #endif
  3558. #ifndef NO_SHA
  3559. static const byte sigSha1wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 5};
  3560. #endif
  3561. #ifdef WOLFSSL_SHA224
  3562. static const byte sigSha224wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,14};
  3563. #endif
  3564. #ifndef NO_SHA256
  3565. static const byte sigSha256wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,11};
  3566. #endif
  3567. #ifdef WOLFSSL_SHA384
  3568. static const byte sigSha384wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,12};
  3569. #endif
  3570. #ifdef WOLFSSL_SHA512
  3571. static const byte sigSha512wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,13};
  3572. #endif
  3573. #ifdef WOLFSSL_SHA3
  3574. #ifndef WOLFSSL_NOSHA3_224
  3575. static const byte sigSha3_224wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 13};
  3576. #endif
  3577. #ifndef WOLFSSL_NOSHA3_256
  3578. static const byte sigSha3_256wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 14};
  3579. #endif
  3580. #ifndef WOLFSSL_NOSHA3_384
  3581. static const byte sigSha3_384wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 15};
  3582. #endif
  3583. #ifndef WOLFSSL_NOSHA3_512
  3584. static const byte sigSha3_512wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 16};
  3585. #endif
  3586. #endif
  3587. #ifdef WC_RSA_PSS
  3588. static const byte sigRsaSsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
  3589. #endif
  3590. #endif /* NO_RSA */
  3591. #ifdef HAVE_ECC
  3592. #ifndef NO_SHA
  3593. static const byte sigSha1wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 1};
  3594. #endif
  3595. #ifdef WOLFSSL_SHA224
  3596. static const byte sigSha224wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 1};
  3597. #endif
  3598. #ifndef NO_SHA256
  3599. static const byte sigSha256wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 2};
  3600. #endif
  3601. #ifdef WOLFSSL_SHA384
  3602. static const byte sigSha384wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 3};
  3603. #endif
  3604. #ifdef WOLFSSL_SHA512
  3605. static const byte sigSha512wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 4};
  3606. #endif
  3607. #ifdef WOLFSSL_SHA3
  3608. #ifndef WOLFSSL_NOSHA3_224
  3609. static const byte sigSha3_224wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 9};
  3610. #endif
  3611. #ifndef WOLFSSL_NOSHA3_256
  3612. static const byte sigSha3_256wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 10};
  3613. #endif
  3614. #ifndef WOLFSSL_NOSHA3_384
  3615. static const byte sigSha3_384wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 11};
  3616. #endif
  3617. #ifndef WOLFSSL_NOSHA3_512
  3618. static const byte sigSha3_512wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 12};
  3619. #endif
  3620. #endif
  3621. #endif /* HAVE_ECC */
  3622. #ifdef HAVE_ED25519
  3623. static const byte sigEd25519Oid[] = {43, 101, 112};
  3624. #endif /* HAVE_ED25519 */
  3625. #ifdef HAVE_ED448
  3626. static const byte sigEd448Oid[] = {43, 101, 113};
  3627. #endif /* HAVE_ED448 */
  3628. #ifdef HAVE_PQC
  3629. #ifdef HAVE_FALCON
  3630. /* Falcon Level 1: 1 3 9999 3 1 */
  3631. static const byte sigFalcon_Level1Oid[] = {43, 206, 15, 3, 1};
  3632. /* Falcon Level 5: 1 3 9999 3 4 */
  3633. static const byte sigFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
  3634. #endif /* HAVE_FACON */
  3635. #ifdef HAVE_DILITHIUM
  3636. /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
  3637. static const byte sigDilithium_Level2Oid[] =
  3638. {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};
  3639. /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
  3640. static const byte sigDilithium_Level3Oid[] =
  3641. {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};
  3642. /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
  3643. static const byte sigDilithium_Level5Oid[] =
  3644. {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
  3645. /* Dilithium AES Level 2: 1.3.6.1.4.1.2.267.11.4.4 */
  3646. static const byte sigDilithiumAes_Level2Oid[] =
  3647. {43, 6, 1, 4, 1, 2, 130, 11, 11, 4, 4};
  3648. /* Dilithium AES Level 3: 1.3.6.1.4.1.2.267.11.6.5 */
  3649. static const byte sigDilithiumAes_Level3Oid[] =
  3650. {43, 6, 1, 4, 1, 2, 130, 11, 11, 6, 5};
  3651. /* Dilithium AES Level 5: 1.3.6.1.4.1.2.267.11.8.7 */
  3652. static const byte sigDilithiumAes_Level5Oid[] =
  3653. {43, 6, 1, 4, 1, 2, 130, 11, 11, 8, 7};
  3654. #endif /* HAVE_DILITHIUM */
  3655. #ifdef HAVE_SPHINCS
  3656. /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
  3657. static const byte sigSphincsFast_Level1Oid[] =
  3658. {43, 206, 15, 6, 7, 4};
  3659. /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
  3660. static const byte sigSphincsFast_Level3Oid[] =
  3661. {43, 206, 15, 6, 8, 3};
  3662. /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
  3663. static const byte sigSphincsFast_Level5Oid[] =
  3664. {43, 206, 15, 6, 9, 3};
  3665. /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
  3666. static const byte sigSphincsSmall_Level1Oid[] =
  3667. {43, 206, 15, 6, 7, 10};
  3668. /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
  3669. static const byte sigSphincsSmall_Level3Oid[] =
  3670. {43, 206, 15, 6, 8, 7};
  3671. /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
  3672. static const byte sigSphincsSmall_Level5Oid[] =
  3673. {43, 206, 15, 6, 9, 7};
  3674. #endif /* HAVE_SPHINCS */
  3675. #endif /* HAVE_PQC */
  3676. /* keyType */
  3677. #ifndef NO_DSA
  3678. static const byte keyDsaOid[] = {42, 134, 72, 206, 56, 4, 1};
  3679. #endif /* NO_DSA */
  3680. #ifndef NO_RSA
  3681. static const byte keyRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 1};
  3682. #ifdef WC_RSA_PSS
  3683. static const byte keyRsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
  3684. #endif
  3685. #endif /* NO_RSA */
  3686. #ifdef HAVE_ECC
  3687. static const byte keyEcdsaOid[] = {42, 134, 72, 206, 61, 2, 1};
  3688. #endif /* HAVE_ECC */
  3689. #ifdef HAVE_ED25519
  3690. static const byte keyEd25519Oid[] = {43, 101, 112};
  3691. #endif /* HAVE_ED25519 */
  3692. #ifdef HAVE_CURVE25519
  3693. static const byte keyCurve25519Oid[] = {43, 101, 110};
  3694. #endif
  3695. #ifdef HAVE_ED448
  3696. static const byte keyEd448Oid[] = {43, 101, 113};
  3697. #endif /* HAVE_ED448 */
  3698. #ifdef HAVE_CURVE448
  3699. static const byte keyCurve448Oid[] = {43, 101, 111};
  3700. #endif /* HAVE_CURVE448 */
  3701. #ifndef NO_DH
  3702. static const byte keyDhOid[] = {42, 134, 72, 134, 247, 13, 1, 3, 1};
  3703. #endif /* !NO_DH */
  3704. #ifdef HAVE_PQC
  3705. #ifdef HAVE_FALCON
  3706. /* Falcon Level 1: 1 3 9999 3 1 */
  3707. static const byte keyFalcon_Level1Oid[] = {43, 206, 15, 3, 1};
  3708. /* Falcon Level 5: 1 3 9999 3 4 */
  3709. static const byte keyFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
  3710. #endif /* HAVE_FALCON */
  3711. #ifdef HAVE_DILITHIUM
  3712. /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
  3713. static const byte keyDilithium_Level2Oid[] =
  3714. {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};
  3715. /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
  3716. static const byte keyDilithium_Level3Oid[] =
  3717. {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};
  3718. /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
  3719. static const byte keyDilithium_Level5Oid[] =
  3720. {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
  3721. /* Dilithium AES Level 2: 1.3.6.1.4.1.2.267.11.4.4 */
  3722. static const byte keyDilithiumAes_Level2Oid[] =
  3723. {43, 6, 1, 4, 1, 2, 130, 11, 11, 4, 4};
  3724. /* Dilithium AES Level 3: 1.3.6.1.4.1.2.267.11.6.5 */
  3725. static const byte keyDilithiumAes_Level3Oid[] =
  3726. {43, 6, 1, 4, 1, 2, 130, 11, 11, 6, 5};
  3727. /* Dilithium AES Level 5: 1.3.6.1.4.1.2.267.11.8.7 */
  3728. static const byte keyDilithiumAes_Level5Oid[] =
  3729. {43, 6, 1, 4, 1, 2, 130, 11, 11, 8, 7};
  3730. #endif /* HAVE_DILITHIUM */
  3731. #ifdef HAVE_SPHINCS
  3732. /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
  3733. static const byte keySphincsFast_Level1Oid[] =
  3734. {43, 206, 15, 6, 7, 4};
  3735. /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
  3736. static const byte keySphincsFast_Level3Oid[] =
  3737. {43, 206, 15, 6, 8, 3};
  3738. /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
  3739. static const byte keySphincsFast_Level5Oid[] =
  3740. {43, 206, 15, 6, 9, 3};
  3741. /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
  3742. static const byte keySphincsSmall_Level1Oid[] =
  3743. {43, 206, 15, 6, 7, 10};
  3744. /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
  3745. static const byte keySphincsSmall_Level3Oid[] =
  3746. {43, 206, 15, 6, 8, 7};
  3747. /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
  3748. static const byte keySphincsSmall_Level5Oid[] =
  3749. {43, 206, 15, 6, 9, 7};
  3750. #endif /* HAVE_SPHINCS */
  3751. #endif /* HAVE_PQC */
  3752. /* curveType */
  3753. #ifdef HAVE_ECC
  3754. /* See "ecc_sets" table in ecc.c */
  3755. #endif /* HAVE_ECC */
  3756. #ifdef HAVE_AES_CBC
  3757. /* blkType */
  3758. #ifdef WOLFSSL_AES_128
  3759. static const byte blkAes128CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 2};
  3760. #endif
  3761. #ifdef WOLFSSL_AES_192
  3762. static const byte blkAes192CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 22};
  3763. #endif
  3764. #ifdef WOLFSSL_AES_256
  3765. static const byte blkAes256CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 42};
  3766. #endif
  3767. #endif /* HAVE_AES_CBC */
  3768. #ifdef HAVE_AESGCM
  3769. #ifdef WOLFSSL_AES_128
  3770. static const byte blkAes128GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 6};
  3771. #endif
  3772. #ifdef WOLFSSL_AES_192
  3773. static const byte blkAes192GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 26};
  3774. #endif
  3775. #ifdef WOLFSSL_AES_256
  3776. static const byte blkAes256GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 46};
  3777. #endif
  3778. #endif /* HAVE_AESGCM */
  3779. #ifdef HAVE_AESCCM
  3780. #ifdef WOLFSSL_AES_128
  3781. static const byte blkAes128CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 7};
  3782. #endif
  3783. #ifdef WOLFSSL_AES_192
  3784. static const byte blkAes192CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 27};
  3785. #endif
  3786. #ifdef WOLFSSL_AES_256
  3787. static const byte blkAes256CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 47};
  3788. #endif
  3789. #endif /* HAVE_AESCCM */
  3790. #ifndef NO_DES3
  3791. static const byte blkDesCbcOid[] = {43, 14, 3, 2, 7};
  3792. static const byte blkDes3CbcOid[] = {42, 134, 72, 134, 247, 13, 3, 7};
  3793. #endif
  3794. /* keyWrapType */
  3795. #ifdef WOLFSSL_AES_128
  3796. static const byte wrapAes128Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 5};
  3797. #endif
  3798. #ifdef WOLFSSL_AES_192
  3799. static const byte wrapAes192Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 25};
  3800. #endif
  3801. #ifdef WOLFSSL_AES_256
  3802. static const byte wrapAes256Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 45};
  3803. #endif
  3804. #ifdef HAVE_PKCS7
  3805. /* From RFC 3211 */
  3806. static const byte wrapPwriKekOid[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3,9};
  3807. #endif
  3808. /* cmsKeyAgreeType */
  3809. #ifndef NO_SHA
  3810. static const byte dhSinglePass_stdDH_sha1kdf_Oid[] =
  3811. {43, 129, 5, 16, 134, 72, 63, 0, 2};
  3812. #endif
  3813. #ifdef WOLFSSL_SHA224
  3814. static const byte dhSinglePass_stdDH_sha224kdf_Oid[] = {43, 129, 4, 1, 11, 0};
  3815. #endif
  3816. #ifndef NO_SHA256
  3817. static const byte dhSinglePass_stdDH_sha256kdf_Oid[] = {43, 129, 4, 1, 11, 1};
  3818. #endif
  3819. #ifdef WOLFSSL_SHA384
  3820. static const byte dhSinglePass_stdDH_sha384kdf_Oid[] = {43, 129, 4, 1, 11, 2};
  3821. #endif
  3822. #ifdef WOLFSSL_SHA512
  3823. static const byte dhSinglePass_stdDH_sha512kdf_Oid[] = {43, 129, 4, 1, 11, 3};
  3824. #endif
  3825. /* ocspType */
  3826. #ifdef HAVE_OCSP
  3827. static const byte ocspBasicOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 1};
  3828. static const byte ocspNonceOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 2};
  3829. static const byte ocspNoCheckOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 5};
  3830. #endif /* HAVE_OCSP */
  3831. /* certExtType */
  3832. static const byte extBasicCaOid[] = {85, 29, 19};
  3833. static const byte extAltNamesOid[] = {85, 29, 17};
  3834. static const byte extCrlDistOid[] = {85, 29, 31};
  3835. static const byte extAuthInfoOid[] = {43, 6, 1, 5, 5, 7, 1, 1};
  3836. static const byte extAuthKeyOid[] = {85, 29, 35};
  3837. static const byte extSubjKeyOid[] = {85, 29, 14};
  3838. static const byte extCertPolicyOid[] = {85, 29, 32};
  3839. static const byte extKeyUsageOid[] = {85, 29, 15};
  3840. static const byte extInhibitAnyOid[] = {85, 29, 54};
  3841. static const byte extExtKeyUsageOid[] = {85, 29, 37};
  3842. #ifndef IGNORE_NAME_CONSTRAINTS
  3843. static const byte extNameConsOid[] = {85, 29, 30};
  3844. #endif
  3845. #ifdef HAVE_CRL
  3846. static const byte extCrlNumberOid[] = {85, 29, 20};
  3847. #endif
  3848. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  3849. static const byte extSubjDirAttrOid[] = {85, 29, 9};
  3850. #endif
  3851. #ifdef WOLFSSL_SUBJ_INFO_ACC
  3852. static const byte extSubjInfoAccessOid[] = {43, 6, 1, 5, 5, 7, 1, 11};
  3853. #endif
  3854. /* certAuthInfoType */
  3855. static const byte extAuthInfoOcspOid[] = {43, 6, 1, 5, 5, 7, 48, 1};
  3856. static const byte extAuthInfoCaIssuerOid[] = {43, 6, 1, 5, 5, 7, 48, 2};
  3857. #ifdef WOLFSSL_SUBJ_INFO_ACC
  3858. static const byte extAuthInfoCaRespOid[] = {43, 6, 1, 5, 5, 7, 48, 5};
  3859. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  3860. /* certPolicyType */
  3861. static const byte extCertPolicyAnyOid[] = {85, 29, 32, 0};
  3862. #ifdef WOLFSSL_FPKI
  3863. #define CERT_POLICY_TYPE_OID_BASE(num) {96, 134, 72, 1, 101, 3, 2, 1, 3, num}
  3864. static const byte extCertPolicyFpkiCommonAuthOid[] =
  3865. CERT_POLICY_TYPE_OID_BASE(13);
  3866. static const byte extCertPolicyFpkiPivAuthOid[] =
  3867. CERT_POLICY_TYPE_OID_BASE(40);
  3868. static const byte extCertPolicyFpkiPivAuthHwOid[] =
  3869. CERT_POLICY_TYPE_OID_BASE(41);
  3870. static const byte extCertPolicyFpkiPiviAuthOid[] =
  3871. CERT_POLICY_TYPE_OID_BASE(45);
  3872. #endif /* WOLFSSL_FPKI */
  3873. /* certAltNameType */
  3874. static const byte extAltNamesHwNameOid[] = {43, 6, 1, 5, 5, 7, 8, 4};
  3875. /* certKeyUseType */
  3876. static const byte extExtKeyUsageAnyOid[] = {85, 29, 37, 0};
  3877. static const byte extExtKeyUsageServerAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 1};
  3878. static const byte extExtKeyUsageClientAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 2};
  3879. static const byte extExtKeyUsageCodeSigningOid[] = {43, 6, 1, 5, 5, 7, 3, 3};
  3880. static const byte extExtKeyUsageEmailProtectOid[] = {43, 6, 1, 5, 5, 7, 3, 4};
  3881. static const byte extExtKeyUsageTimestampOid[] = {43, 6, 1, 5, 5, 7, 3, 8};
  3882. static const byte extExtKeyUsageOcspSignOid[] = {43, 6, 1, 5, 5, 7, 3, 9};
  3883. #ifdef WOLFSSL_WOLFSSH
  3884. #define EXT_KEY_USAGE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 3, num}
  3885. static const byte extExtKeyUsageSshClientAuthOid[] =
  3886. EXT_KEY_USAGE_OID_BASE(21);
  3887. static const byte extExtKeyUsageSshMSCLOid[] =
  3888. {43, 6, 1, 4, 1, 130, 55, 20, 2, 2};
  3889. static const byte extExtKeyUsageSshKpClientAuthOid[] =
  3890. {43, 6, 1, 5, 2, 3, 4};
  3891. #endif /* WOLFSSL_WOLFSSH */
  3892. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  3893. #define SUBJ_DIR_ATTR_TYPE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 9, num}
  3894. static const byte extSubjDirAttrDobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(1);
  3895. static const byte extSubjDirAttrPobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(2);
  3896. static const byte extSubjDirAttrGenderOid[] =
  3897. SUBJ_DIR_ATTR_TYPE_OID_BASE(3);
  3898. static const byte extSubjDirAttrCocOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(4);
  3899. static const byte extSubjDirAttrCorOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(5);
  3900. #endif
  3901. #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3902. defined(WOLFSSL_ASN_TEMPLATE) || defined(OPENSSL_EXTRA) || \
  3903. defined(OPENSSL_EXTRA_X509_SMALL)
  3904. /* csrAttrType */
  3905. #define CSR_ATTR_TYPE_OID_BASE(num) {42, 134, 72, 134, 247, 13, 1, 9, num}
  3906. #if !defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3907. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  3908. defined(WOLFSSL_ASN_TEMPLATE)
  3909. static const byte attrEmailOid[] = CSR_ATTR_TYPE_OID_BASE(1);
  3910. #endif
  3911. #ifdef WOLFSSL_CERT_REQ
  3912. static const byte attrUnstructuredNameOid[] = CSR_ATTR_TYPE_OID_BASE(2);
  3913. static const byte attrPkcs9ContentTypeOid[] = CSR_ATTR_TYPE_OID_BASE(3);
  3914. static const byte attrChallengePasswordOid[] = CSR_ATTR_TYPE_OID_BASE(7);
  3915. static const byte attrExtensionRequestOid[] = CSR_ATTR_TYPE_OID_BASE(14);
  3916. static const byte attrSerialNumberOid[] = {85, 4, 5};
  3917. static const byte attrDnQualifier[] = {85, 4, 46};
  3918. static const byte attrInitals[] = {85, 4, 43};
  3919. static const byte attrSurname[] = {85, 4, 4};
  3920. static const byte attrGivenName[] = {85, 4, 42};
  3921. #endif
  3922. #endif
  3923. /* kdfType */
  3924. static const byte pbkdf2Oid[] = {42, 134, 72, 134, 247, 13, 1, 5, 12};
  3925. /* PKCS5 */
  3926. #if !defined(NO_DES3) && !defined(NO_MD5)
  3927. static const byte pbeMd5Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 3};
  3928. #endif
  3929. #if !defined(NO_DES3) && !defined(NO_SHA)
  3930. static const byte pbeSha1Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 10};
  3931. #endif
  3932. static const byte pbes2[] = {42, 134, 72, 134, 247, 13, 1, 5, 13};
  3933. /* PKCS12 */
  3934. #if !defined(NO_RC4) && !defined(NO_SHA)
  3935. static const byte pbeSha1RC4128[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 1};
  3936. #endif
  3937. #if !defined(NO_DES3) && !defined(NO_SHA)
  3938. static const byte pbeSha1Des3[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 3};
  3939. #endif
  3940. #ifdef HAVE_LIBZ
  3941. /* zlib compression */
  3942. static const byte zlibCompress[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3, 8};
  3943. #endif
  3944. #ifdef WOLFSSL_APACHE_HTTPD
  3945. /* tlsExtType */
  3946. static const byte tlsFeatureOid[] = {43, 6, 1, 5, 5, 7, 1, 24};
  3947. /* certNameType */
  3948. static const byte dnsSRVOid[] = {43, 6, 1, 5, 5, 7, 8, 7};
  3949. #endif
  3950. #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3951. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  3952. defined(WOLFSSL_ASN_TEMPLATE)
  3953. /* Pilot attribute types (0.9.2342.19200300.100.1.*) */
  3954. static const byte uidOid[] = {9, 146, 38, 137, 147, 242, 44, 100, 1, 1}; /* user id */
  3955. #endif
  3956. #if defined(WOLFSSL_CERT_GEN) || \
  3957. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  3958. defined(WOLFSSL_ASN_TEMPLATE)
  3959. static const byte dcOid[] = {9, 146, 38, 137, 147, 242, 44, 100, 1, 25}; /* domain component */
  3960. #endif
  3961. /* Looks up the ID/type of an OID.
  3962. *
  3963. * When known returns the OID as a byte array and its length.
  3964. * ID-type are unique.
  3965. *
  3966. * Use oidIgnoreType to autofail.
  3967. *
  3968. * @param [in] id OID id.
  3969. * @param [in] type Type of OID (enum Oid_Types).
  3970. * @param [out] oidSz Length of OID byte array returned.
  3971. * @return Array of bytes for the OID.
  3972. * @return NULL when ID/type not recognized.
  3973. */
  3974. const byte* OidFromId(word32 id, word32 type, word32* oidSz)
  3975. {
  3976. const byte* oid = NULL;
  3977. *oidSz = 0;
  3978. switch (type) {
  3979. case oidHashType:
  3980. switch (id) {
  3981. #ifdef WOLFSSL_MD2
  3982. case MD2h:
  3983. oid = hashMd2hOid;
  3984. *oidSz = sizeof(hashMd2hOid);
  3985. break;
  3986. #endif
  3987. #ifndef NO_MD5
  3988. case MD5h:
  3989. oid = hashMd5hOid;
  3990. *oidSz = sizeof(hashMd5hOid);
  3991. break;
  3992. #endif
  3993. #ifndef NO_SHA
  3994. case SHAh:
  3995. oid = hashSha1hOid;
  3996. *oidSz = sizeof(hashSha1hOid);
  3997. break;
  3998. #endif
  3999. #ifdef WOLFSSL_SHA224
  4000. case SHA224h:
  4001. oid = hashSha224hOid;
  4002. *oidSz = sizeof(hashSha224hOid);
  4003. break;
  4004. #endif
  4005. #ifndef NO_SHA256
  4006. case SHA256h:
  4007. oid = hashSha256hOid;
  4008. *oidSz = sizeof(hashSha256hOid);
  4009. break;
  4010. #endif
  4011. #ifdef WOLFSSL_SHA384
  4012. case SHA384h:
  4013. oid = hashSha384hOid;
  4014. *oidSz = sizeof(hashSha384hOid);
  4015. break;
  4016. #endif
  4017. #ifdef WOLFSSL_SHA512
  4018. #ifndef WOLFSSL_NOSHA512_224
  4019. case SHA512_224h:
  4020. oid = hashSha512_224hOid;
  4021. *oidSz = sizeof(hashSha512_224hOid);
  4022. break;
  4023. #endif
  4024. #ifndef WOLFSSL_NOSHA512_256
  4025. case SHA512_256h:
  4026. oid = hashSha512_256hOid;
  4027. *oidSz = sizeof(hashSha512_256hOid);
  4028. break;
  4029. #endif
  4030. case SHA512h:
  4031. oid = hashSha512hOid;
  4032. *oidSz = sizeof(hashSha512hOid);
  4033. break;
  4034. #endif
  4035. #ifdef WOLFSSL_SHA3
  4036. #ifndef WOLFSSL_NOSHA3_224
  4037. case SHA3_224h:
  4038. oid = hashSha3_224hOid;
  4039. *oidSz = sizeof(hashSha3_224hOid);
  4040. break;
  4041. #endif /* WOLFSSL_NOSHA3_224 */
  4042. #ifndef WOLFSSL_NOSHA3_256
  4043. case SHA3_256h:
  4044. oid = hashSha3_256hOid;
  4045. *oidSz = sizeof(hashSha3_256hOid);
  4046. break;
  4047. #endif /* WOLFSSL_NOSHA3_256 */
  4048. #ifndef WOLFSSL_NOSHA3_384
  4049. case SHA3_384h:
  4050. oid = hashSha3_384hOid;
  4051. *oidSz = sizeof(hashSha3_384hOid);
  4052. break;
  4053. #endif /* WOLFSSL_NOSHA3_384 */
  4054. #ifndef WOLFSSL_NOSHA3_512
  4055. case SHA3_512h:
  4056. oid = hashSha3_512hOid;
  4057. *oidSz = sizeof(hashSha3_512hOid);
  4058. break;
  4059. #endif /* WOLFSSL_NOSHA3_512 */
  4060. #endif /* WOLFSSL_SHA3 */
  4061. default:
  4062. break;
  4063. }
  4064. break;
  4065. case oidSigType:
  4066. switch (id) {
  4067. #if !defined(NO_DSA) && !defined(NO_SHA)
  4068. case CTC_SHAwDSA:
  4069. oid = sigSha1wDsaOid;
  4070. *oidSz = sizeof(sigSha1wDsaOid);
  4071. break;
  4072. case CTC_SHA256wDSA:
  4073. oid = sigSha256wDsaOid;
  4074. *oidSz = sizeof(sigSha256wDsaOid);
  4075. break;
  4076. #endif /* NO_DSA */
  4077. #ifndef NO_RSA
  4078. #ifdef WOLFSSL_MD2
  4079. case CTC_MD2wRSA:
  4080. oid = sigMd2wRsaOid;
  4081. *oidSz = sizeof(sigMd2wRsaOid);
  4082. break;
  4083. #endif
  4084. #ifndef NO_MD5
  4085. case CTC_MD5wRSA:
  4086. oid = sigMd5wRsaOid;
  4087. *oidSz = sizeof(sigMd5wRsaOid);
  4088. break;
  4089. #endif
  4090. #ifndef NO_SHA
  4091. case CTC_SHAwRSA:
  4092. oid = sigSha1wRsaOid;
  4093. *oidSz = sizeof(sigSha1wRsaOid);
  4094. break;
  4095. #endif
  4096. #ifdef WOLFSSL_SHA224
  4097. case CTC_SHA224wRSA:
  4098. oid = sigSha224wRsaOid;
  4099. *oidSz = sizeof(sigSha224wRsaOid);
  4100. break;
  4101. #endif
  4102. #ifndef NO_SHA256
  4103. case CTC_SHA256wRSA:
  4104. oid = sigSha256wRsaOid;
  4105. *oidSz = sizeof(sigSha256wRsaOid);
  4106. break;
  4107. #endif
  4108. #ifdef WOLFSSL_SHA384
  4109. case CTC_SHA384wRSA:
  4110. oid = sigSha384wRsaOid;
  4111. *oidSz = sizeof(sigSha384wRsaOid);
  4112. break;
  4113. #endif
  4114. #ifdef WOLFSSL_SHA512
  4115. case CTC_SHA512wRSA:
  4116. oid = sigSha512wRsaOid;
  4117. *oidSz = sizeof(sigSha512wRsaOid);
  4118. break;
  4119. #endif /* WOLFSSL_SHA512 */
  4120. #ifdef WOLFSSL_SHA3
  4121. #ifndef WOLFSSL_NOSHA3_224
  4122. case CTC_SHA3_224wRSA:
  4123. oid = sigSha3_224wRsaOid;
  4124. *oidSz = sizeof(sigSha3_224wRsaOid);
  4125. break;
  4126. #endif
  4127. #ifndef WOLFSSL_NOSHA3_256
  4128. case CTC_SHA3_256wRSA:
  4129. oid = sigSha3_256wRsaOid;
  4130. *oidSz = sizeof(sigSha3_256wRsaOid);
  4131. break;
  4132. #endif
  4133. #ifndef WOLFSSL_NOSHA3_384
  4134. case CTC_SHA3_384wRSA:
  4135. oid = sigSha3_384wRsaOid;
  4136. *oidSz = sizeof(sigSha3_384wRsaOid);
  4137. break;
  4138. #endif
  4139. #ifndef WOLFSSL_NOSHA3_512
  4140. case CTC_SHA3_512wRSA:
  4141. oid = sigSha3_512wRsaOid;
  4142. *oidSz = sizeof(sigSha3_512wRsaOid);
  4143. break;
  4144. #endif
  4145. #endif
  4146. #ifdef WC_RSA_PSS
  4147. case CTC_RSASSAPSS:
  4148. oid = sigRsaSsaPssOid;
  4149. *oidSz = sizeof(sigRsaSsaPssOid);
  4150. break;
  4151. #endif
  4152. #endif /* NO_RSA */
  4153. #ifdef HAVE_ECC
  4154. #ifndef NO_SHA
  4155. case CTC_SHAwECDSA:
  4156. oid = sigSha1wEcdsaOid;
  4157. *oidSz = sizeof(sigSha1wEcdsaOid);
  4158. break;
  4159. #endif
  4160. #ifdef WOLFSSL_SHA224
  4161. case CTC_SHA224wECDSA:
  4162. oid = sigSha224wEcdsaOid;
  4163. *oidSz = sizeof(sigSha224wEcdsaOid);
  4164. break;
  4165. #endif
  4166. #ifndef NO_SHA256
  4167. case CTC_SHA256wECDSA:
  4168. oid = sigSha256wEcdsaOid;
  4169. *oidSz = sizeof(sigSha256wEcdsaOid);
  4170. break;
  4171. #endif
  4172. #ifdef WOLFSSL_SHA384
  4173. case CTC_SHA384wECDSA:
  4174. oid = sigSha384wEcdsaOid;
  4175. *oidSz = sizeof(sigSha384wEcdsaOid);
  4176. break;
  4177. #endif
  4178. #ifdef WOLFSSL_SHA512
  4179. case CTC_SHA512wECDSA:
  4180. oid = sigSha512wEcdsaOid;
  4181. *oidSz = sizeof(sigSha512wEcdsaOid);
  4182. break;
  4183. #endif
  4184. #ifdef WOLFSSL_SHA3
  4185. #ifndef WOLFSSL_NOSHA3_224
  4186. case CTC_SHA3_224wECDSA:
  4187. oid = sigSha3_224wEcdsaOid;
  4188. *oidSz = sizeof(sigSha3_224wEcdsaOid);
  4189. break;
  4190. #endif
  4191. #ifndef WOLFSSL_NOSHA3_256
  4192. case CTC_SHA3_256wECDSA:
  4193. oid = sigSha3_256wEcdsaOid;
  4194. *oidSz = sizeof(sigSha3_256wEcdsaOid);
  4195. break;
  4196. #endif
  4197. #ifndef WOLFSSL_NOSHA3_384
  4198. case CTC_SHA3_384wECDSA:
  4199. oid = sigSha3_384wEcdsaOid;
  4200. *oidSz = sizeof(sigSha3_384wEcdsaOid);
  4201. break;
  4202. #endif
  4203. #ifndef WOLFSSL_NOSHA3_512
  4204. case CTC_SHA3_512wECDSA:
  4205. oid = sigSha3_512wEcdsaOid;
  4206. *oidSz = sizeof(sigSha3_512wEcdsaOid);
  4207. break;
  4208. #endif
  4209. #endif
  4210. #endif /* HAVE_ECC */
  4211. #ifdef HAVE_ED25519
  4212. case CTC_ED25519:
  4213. oid = sigEd25519Oid;
  4214. *oidSz = sizeof(sigEd25519Oid);
  4215. break;
  4216. #endif
  4217. #ifdef HAVE_ED448
  4218. case CTC_ED448:
  4219. oid = sigEd448Oid;
  4220. *oidSz = sizeof(sigEd448Oid);
  4221. break;
  4222. #endif
  4223. #ifdef HAVE_PQC
  4224. #ifdef HAVE_FALCON
  4225. case CTC_FALCON_LEVEL1:
  4226. oid = sigFalcon_Level1Oid;
  4227. *oidSz = sizeof(sigFalcon_Level1Oid);
  4228. break;
  4229. case CTC_FALCON_LEVEL5:
  4230. oid = sigFalcon_Level5Oid;
  4231. *oidSz = sizeof(sigFalcon_Level5Oid);
  4232. break;
  4233. #endif /* HAVE_FALCON */
  4234. #ifdef HAVE_DILITHIUM
  4235. case CTC_DILITHIUM_LEVEL2:
  4236. oid = sigDilithium_Level2Oid;
  4237. *oidSz = sizeof(sigDilithium_Level2Oid);
  4238. break;
  4239. case CTC_DILITHIUM_LEVEL3:
  4240. oid = sigDilithium_Level3Oid;
  4241. *oidSz = sizeof(sigDilithium_Level3Oid);
  4242. break;
  4243. case CTC_DILITHIUM_LEVEL5:
  4244. oid = sigDilithium_Level5Oid;
  4245. *oidSz = sizeof(sigDilithium_Level5Oid);
  4246. break;
  4247. case CTC_DILITHIUM_AES_LEVEL2:
  4248. oid = sigDilithiumAes_Level2Oid;
  4249. *oidSz = sizeof(sigDilithiumAes_Level2Oid);
  4250. break;
  4251. case CTC_DILITHIUM_AES_LEVEL3:
  4252. oid = sigDilithiumAes_Level3Oid;
  4253. *oidSz = sizeof(sigDilithiumAes_Level3Oid);
  4254. break;
  4255. case CTC_DILITHIUM_AES_LEVEL5:
  4256. oid = sigDilithiumAes_Level5Oid;
  4257. *oidSz = sizeof(sigDilithiumAes_Level5Oid);
  4258. break;
  4259. #endif /* HAVE_DILITHIUM */
  4260. #ifdef HAVE_SPHINCS
  4261. case CTC_SPHINCS_FAST_LEVEL1:
  4262. oid = sigSphincsFast_Level1Oid;
  4263. *oidSz = sizeof(sigSphincsFast_Level1Oid);
  4264. break;
  4265. case CTC_SPHINCS_FAST_LEVEL3:
  4266. oid = sigSphincsFast_Level3Oid;
  4267. *oidSz = sizeof(sigSphincsFast_Level3Oid);
  4268. break;
  4269. case CTC_SPHINCS_FAST_LEVEL5:
  4270. oid = sigSphincsFast_Level5Oid;
  4271. *oidSz = sizeof(sigSphincsFast_Level5Oid);
  4272. break;
  4273. case CTC_SPHINCS_SMALL_LEVEL1:
  4274. oid = sigSphincsSmall_Level1Oid;
  4275. *oidSz = sizeof(sigSphincsSmall_Level1Oid);
  4276. break;
  4277. case CTC_SPHINCS_SMALL_LEVEL3:
  4278. oid = sigSphincsSmall_Level3Oid;
  4279. *oidSz = sizeof(sigSphincsSmall_Level3Oid);
  4280. break;
  4281. case CTC_SPHINCS_SMALL_LEVEL5:
  4282. oid = sigSphincsSmall_Level5Oid;
  4283. *oidSz = sizeof(sigSphincsSmall_Level5Oid);
  4284. break;
  4285. #endif /* HAVE_SPHINCS */
  4286. #endif /* HAVE_PQC */
  4287. default:
  4288. break;
  4289. }
  4290. break;
  4291. case oidKeyType:
  4292. switch (id) {
  4293. #ifndef NO_DSA
  4294. case DSAk:
  4295. oid = keyDsaOid;
  4296. *oidSz = sizeof(keyDsaOid);
  4297. break;
  4298. #endif /* NO_DSA */
  4299. #ifndef NO_RSA
  4300. case RSAk:
  4301. oid = keyRsaOid;
  4302. *oidSz = sizeof(keyRsaOid);
  4303. break;
  4304. #ifdef WC_RSA_PSS
  4305. case RSAPSSk:
  4306. oid = keyRsaPssOid;
  4307. *oidSz = sizeof(keyRsaPssOid);
  4308. break;
  4309. #endif
  4310. #endif /* NO_RSA */
  4311. #ifdef HAVE_ECC
  4312. case ECDSAk:
  4313. oid = keyEcdsaOid;
  4314. *oidSz = sizeof(keyEcdsaOid);
  4315. break;
  4316. #endif /* HAVE_ECC */
  4317. #ifdef HAVE_ED25519
  4318. case ED25519k:
  4319. oid = keyEd25519Oid;
  4320. *oidSz = sizeof(keyEd25519Oid);
  4321. break;
  4322. #endif /* HAVE_ED25519 */
  4323. #ifdef HAVE_CURVE25519
  4324. case X25519k:
  4325. oid = keyCurve25519Oid;
  4326. *oidSz = sizeof(keyCurve25519Oid);
  4327. break;
  4328. #endif /* HAVE_CURVE25519 */
  4329. #ifdef HAVE_ED448
  4330. case ED448k:
  4331. oid = keyEd448Oid;
  4332. *oidSz = sizeof(keyEd448Oid);
  4333. break;
  4334. #endif /* HAVE_ED448 */
  4335. #ifdef HAVE_CURVE448
  4336. case X448k:
  4337. oid = keyCurve448Oid;
  4338. *oidSz = sizeof(keyCurve448Oid);
  4339. break;
  4340. #endif /* HAVE_CURVE448 */
  4341. #ifndef NO_DH
  4342. case DHk:
  4343. oid = keyDhOid;
  4344. *oidSz = sizeof(keyDhOid);
  4345. break;
  4346. #endif /* !NO_DH */
  4347. #ifdef HAVE_PQC
  4348. #ifdef HAVE_FALCON
  4349. case FALCON_LEVEL1k:
  4350. oid = keyFalcon_Level1Oid;
  4351. *oidSz = sizeof(keyFalcon_Level1Oid);
  4352. break;
  4353. case FALCON_LEVEL5k:
  4354. oid = keyFalcon_Level5Oid;
  4355. *oidSz = sizeof(keyFalcon_Level5Oid);
  4356. break;
  4357. #endif /* HAVE_FALCON */
  4358. #ifdef HAVE_DILITHIUM
  4359. case DILITHIUM_LEVEL2k:
  4360. oid = keyDilithium_Level2Oid;
  4361. *oidSz = sizeof(keyDilithium_Level2Oid);
  4362. break;
  4363. case DILITHIUM_LEVEL3k:
  4364. oid = keyDilithium_Level3Oid;
  4365. *oidSz = sizeof(keyDilithium_Level3Oid);
  4366. break;
  4367. case DILITHIUM_LEVEL5k:
  4368. oid = keyDilithium_Level5Oid;
  4369. *oidSz = sizeof(keyDilithium_Level5Oid);
  4370. break;
  4371. case DILITHIUM_AES_LEVEL2k:
  4372. oid = keyDilithiumAes_Level2Oid;
  4373. *oidSz = sizeof(keyDilithiumAes_Level2Oid);
  4374. break;
  4375. case DILITHIUM_AES_LEVEL3k:
  4376. oid = keyDilithiumAes_Level3Oid;
  4377. *oidSz = sizeof(keyDilithiumAes_Level3Oid);
  4378. break;
  4379. case DILITHIUM_AES_LEVEL5k:
  4380. oid = keyDilithiumAes_Level5Oid;
  4381. *oidSz = sizeof(keyDilithiumAes_Level5Oid);
  4382. break;
  4383. #endif /* HAVE_DILITHIUM */
  4384. #ifdef HAVE_SPHINCS
  4385. case SPHINCS_FAST_LEVEL1k:
  4386. oid = keySphincsFast_Level1Oid;
  4387. *oidSz = sizeof(keySphincsFast_Level1Oid);
  4388. break;
  4389. case SPHINCS_FAST_LEVEL3k:
  4390. oid = keySphincsFast_Level3Oid;
  4391. *oidSz = sizeof(keySphincsFast_Level3Oid);
  4392. break;
  4393. case SPHINCS_FAST_LEVEL5k:
  4394. oid = keySphincsFast_Level5Oid;
  4395. *oidSz = sizeof(keySphincsFast_Level5Oid);
  4396. break;
  4397. case SPHINCS_SMALL_LEVEL1k:
  4398. oid = keySphincsSmall_Level1Oid;
  4399. *oidSz = sizeof(keySphincsSmall_Level1Oid);
  4400. break;
  4401. case SPHINCS_SMALL_LEVEL3k:
  4402. oid = keySphincsSmall_Level3Oid;
  4403. *oidSz = sizeof(keySphincsSmall_Level3Oid);
  4404. break;
  4405. case SPHINCS_SMALL_LEVEL5k:
  4406. oid = keySphincsSmall_Level5Oid;
  4407. *oidSz = sizeof(keySphincsSmall_Level5Oid);
  4408. break;
  4409. #endif /* HAVE_SPHINCS */
  4410. #endif /* HAVE_PQC */
  4411. default:
  4412. break;
  4413. }
  4414. break;
  4415. #ifdef HAVE_ECC
  4416. case oidCurveType:
  4417. if (wc_ecc_get_oid(id, &oid, oidSz) < 0) {
  4418. WOLFSSL_MSG("ECC OID not found");
  4419. }
  4420. break;
  4421. #endif /* HAVE_ECC */
  4422. case oidBlkType:
  4423. switch (id) {
  4424. #ifdef HAVE_AES_CBC
  4425. #ifdef WOLFSSL_AES_128
  4426. case AES128CBCb:
  4427. oid = blkAes128CbcOid;
  4428. *oidSz = sizeof(blkAes128CbcOid);
  4429. break;
  4430. #endif
  4431. #ifdef WOLFSSL_AES_192
  4432. case AES192CBCb:
  4433. oid = blkAes192CbcOid;
  4434. *oidSz = sizeof(blkAes192CbcOid);
  4435. break;
  4436. #endif
  4437. #ifdef WOLFSSL_AES_256
  4438. case AES256CBCb:
  4439. oid = blkAes256CbcOid;
  4440. *oidSz = sizeof(blkAes256CbcOid);
  4441. break;
  4442. #endif
  4443. #endif /* HAVE_AES_CBC */
  4444. #ifdef HAVE_AESGCM
  4445. #ifdef WOLFSSL_AES_128
  4446. case AES128GCMb:
  4447. oid = blkAes128GcmOid;
  4448. *oidSz = sizeof(blkAes128GcmOid);
  4449. break;
  4450. #endif
  4451. #ifdef WOLFSSL_AES_192
  4452. case AES192GCMb:
  4453. oid = blkAes192GcmOid;
  4454. *oidSz = sizeof(blkAes192GcmOid);
  4455. break;
  4456. #endif
  4457. #ifdef WOLFSSL_AES_256
  4458. case AES256GCMb:
  4459. oid = blkAes256GcmOid;
  4460. *oidSz = sizeof(blkAes256GcmOid);
  4461. break;
  4462. #endif
  4463. #endif /* HAVE_AESGCM */
  4464. #ifdef HAVE_AESCCM
  4465. #ifdef WOLFSSL_AES_128
  4466. case AES128CCMb:
  4467. oid = blkAes128CcmOid;
  4468. *oidSz = sizeof(blkAes128CcmOid);
  4469. break;
  4470. #endif
  4471. #ifdef WOLFSSL_AES_192
  4472. case AES192CCMb:
  4473. oid = blkAes192CcmOid;
  4474. *oidSz = sizeof(blkAes192CcmOid);
  4475. break;
  4476. #endif
  4477. #ifdef WOLFSSL_AES_256
  4478. case AES256CCMb:
  4479. oid = blkAes256CcmOid;
  4480. *oidSz = sizeof(blkAes256CcmOid);
  4481. break;
  4482. #endif
  4483. #endif /* HAVE_AESCCM */
  4484. #ifndef NO_DES3
  4485. case DESb:
  4486. oid = blkDesCbcOid;
  4487. *oidSz = sizeof(blkDesCbcOid);
  4488. break;
  4489. case DES3b:
  4490. oid = blkDes3CbcOid;
  4491. *oidSz = sizeof(blkDes3CbcOid);
  4492. break;
  4493. #endif /* !NO_DES3 */
  4494. default:
  4495. break;
  4496. }
  4497. break;
  4498. #ifdef HAVE_OCSP
  4499. case oidOcspType:
  4500. switch (id) {
  4501. case OCSP_BASIC_OID:
  4502. oid = ocspBasicOid;
  4503. *oidSz = sizeof(ocspBasicOid);
  4504. break;
  4505. case OCSP_NONCE_OID:
  4506. oid = ocspNonceOid;
  4507. *oidSz = sizeof(ocspNonceOid);
  4508. break;
  4509. default:
  4510. break;
  4511. }
  4512. break;
  4513. #endif /* HAVE_OCSP */
  4514. case oidCertExtType:
  4515. switch (id) {
  4516. case BASIC_CA_OID:
  4517. oid = extBasicCaOid;
  4518. *oidSz = sizeof(extBasicCaOid);
  4519. break;
  4520. case ALT_NAMES_OID:
  4521. oid = extAltNamesOid;
  4522. *oidSz = sizeof(extAltNamesOid);
  4523. break;
  4524. case CRL_DIST_OID:
  4525. oid = extCrlDistOid;
  4526. *oidSz = sizeof(extCrlDistOid);
  4527. break;
  4528. case AUTH_INFO_OID:
  4529. oid = extAuthInfoOid;
  4530. *oidSz = sizeof(extAuthInfoOid);
  4531. break;
  4532. case AUTH_KEY_OID:
  4533. oid = extAuthKeyOid;
  4534. *oidSz = sizeof(extAuthKeyOid);
  4535. break;
  4536. case SUBJ_KEY_OID:
  4537. oid = extSubjKeyOid;
  4538. *oidSz = sizeof(extSubjKeyOid);
  4539. break;
  4540. case CERT_POLICY_OID:
  4541. oid = extCertPolicyOid;
  4542. *oidSz = sizeof(extCertPolicyOid);
  4543. break;
  4544. case KEY_USAGE_OID:
  4545. oid = extKeyUsageOid;
  4546. *oidSz = sizeof(extKeyUsageOid);
  4547. break;
  4548. case INHIBIT_ANY_OID:
  4549. oid = extInhibitAnyOid;
  4550. *oidSz = sizeof(extInhibitAnyOid);
  4551. break;
  4552. case EXT_KEY_USAGE_OID:
  4553. oid = extExtKeyUsageOid;
  4554. *oidSz = sizeof(extExtKeyUsageOid);
  4555. break;
  4556. #ifndef IGNORE_NAME_CONSTRAINTS
  4557. case NAME_CONS_OID:
  4558. oid = extNameConsOid;
  4559. *oidSz = sizeof(extNameConsOid);
  4560. break;
  4561. #endif
  4562. #ifdef HAVE_OCSP
  4563. case OCSP_NOCHECK_OID:
  4564. oid = ocspNoCheckOid;
  4565. *oidSz = sizeof(ocspNoCheckOid);
  4566. break;
  4567. #endif
  4568. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  4569. case SUBJ_DIR_ATTR_OID:
  4570. oid = extSubjDirAttrOid;
  4571. *oidSz = sizeof(extSubjDirAttrOid);
  4572. break;
  4573. #endif
  4574. #ifdef WOLFSSL_SUBJ_INFO_ACC
  4575. case SUBJ_INFO_ACC_OID:
  4576. oid = extSubjInfoAccessOid;
  4577. *oidSz = sizeof(extSubjInfoAccessOid);
  4578. break;
  4579. #endif
  4580. default:
  4581. break;
  4582. }
  4583. break;
  4584. case oidCrlExtType:
  4585. #ifdef HAVE_CRL
  4586. switch (id) {
  4587. case AUTH_KEY_OID:
  4588. oid = extAuthKeyOid;
  4589. *oidSz = sizeof(extAuthKeyOid);
  4590. break;
  4591. case CRL_NUMBER_OID:
  4592. oid = extCrlNumberOid;
  4593. *oidSz = sizeof(extCrlNumberOid);
  4594. break;
  4595. default:
  4596. break;
  4597. }
  4598. #endif
  4599. break;
  4600. case oidCertAuthInfoType:
  4601. switch (id) {
  4602. case AIA_OCSP_OID:
  4603. oid = extAuthInfoOcspOid;
  4604. *oidSz = sizeof(extAuthInfoOcspOid);
  4605. break;
  4606. case AIA_CA_ISSUER_OID:
  4607. oid = extAuthInfoCaIssuerOid;
  4608. *oidSz = sizeof(extAuthInfoCaIssuerOid);
  4609. break;
  4610. #ifdef WOLFSSL_SUBJ_INFO_ACC
  4611. case AIA_CA_REPO_OID:
  4612. oid = extAuthInfoCaRespOid;
  4613. *oidSz = sizeof(extAuthInfoCaRespOid);
  4614. break;
  4615. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  4616. default:
  4617. break;
  4618. }
  4619. break;
  4620. case oidCertPolicyType:
  4621. switch (id) {
  4622. case CP_ANY_OID:
  4623. oid = extCertPolicyAnyOid;
  4624. *oidSz = sizeof(extCertPolicyAnyOid);
  4625. break;
  4626. #if defined(WOLFSSL_FPKI)
  4627. case CP_FPKI_COMMON_AUTH_OID:
  4628. oid = extCertPolicyFpkiCommonAuthOid;
  4629. *oidSz = sizeof(extCertPolicyFpkiCommonAuthOid);
  4630. break;
  4631. case CP_FPKI_PIV_AUTH_OID:
  4632. oid = extCertPolicyFpkiPivAuthOid;
  4633. *oidSz = sizeof(extCertPolicyFpkiPivAuthOid);
  4634. break;
  4635. case CP_FPKI_PIV_AUTH_HW_OID: /* collision with AES256CBCb */
  4636. oid = extCertPolicyFpkiPivAuthHwOid;
  4637. *oidSz = sizeof(extCertPolicyFpkiPivAuthHwOid);
  4638. break;
  4639. case CP_FPKI_PIVI_AUTH_OID:
  4640. oid = extCertPolicyFpkiPiviAuthOid;
  4641. *oidSz = sizeof(extCertPolicyFpkiPiviAuthOid);
  4642. break;
  4643. #endif /* WOLFSSL_FPKI */
  4644. default:
  4645. break;
  4646. }
  4647. break;
  4648. case oidCertAltNameType:
  4649. switch (id) {
  4650. case HW_NAME_OID:
  4651. oid = extAltNamesHwNameOid;
  4652. *oidSz = sizeof(extAltNamesHwNameOid);
  4653. break;
  4654. default:
  4655. break;
  4656. }
  4657. break;
  4658. case oidCertKeyUseType:
  4659. switch (id) {
  4660. case EKU_ANY_OID:
  4661. oid = extExtKeyUsageAnyOid;
  4662. *oidSz = sizeof(extExtKeyUsageAnyOid);
  4663. break;
  4664. case EKU_SERVER_AUTH_OID:
  4665. oid = extExtKeyUsageServerAuthOid;
  4666. *oidSz = sizeof(extExtKeyUsageServerAuthOid);
  4667. break;
  4668. case EKU_CLIENT_AUTH_OID:
  4669. oid = extExtKeyUsageClientAuthOid;
  4670. *oidSz = sizeof(extExtKeyUsageClientAuthOid);
  4671. break;
  4672. case EKU_CODESIGNING_OID:
  4673. oid = extExtKeyUsageCodeSigningOid;
  4674. *oidSz = sizeof(extExtKeyUsageCodeSigningOid);
  4675. break;
  4676. case EKU_EMAILPROTECT_OID:
  4677. oid = extExtKeyUsageEmailProtectOid;
  4678. *oidSz = sizeof(extExtKeyUsageEmailProtectOid);
  4679. break;
  4680. case EKU_TIMESTAMP_OID:
  4681. oid = extExtKeyUsageTimestampOid;
  4682. *oidSz = sizeof(extExtKeyUsageTimestampOid);
  4683. break;
  4684. case EKU_OCSP_SIGN_OID:
  4685. oid = extExtKeyUsageOcspSignOid;
  4686. *oidSz = sizeof(extExtKeyUsageOcspSignOid);
  4687. break;
  4688. #ifdef WOLFSSL_WOLFSSH
  4689. case EKU_SSH_CLIENT_AUTH_OID:
  4690. oid = extExtKeyUsageSshClientAuthOid;
  4691. *oidSz = sizeof(extExtKeyUsageSshClientAuthOid);
  4692. break;
  4693. case EKU_SSH_MSCL_OID:
  4694. oid = extExtKeyUsageSshMSCLOid;
  4695. *oidSz = sizeof(extExtKeyUsageSshMSCLOid);
  4696. break;
  4697. case EKU_SSH_KP_CLIENT_AUTH_OID:
  4698. oid = extExtKeyUsageSshKpClientAuthOid;
  4699. *oidSz = sizeof(extExtKeyUsageSshKpClientAuthOid);
  4700. break;
  4701. #endif /* WOLFSSL_WOLFSSH */
  4702. default:
  4703. break;
  4704. }
  4705. break;
  4706. case oidKdfType:
  4707. switch (id) {
  4708. case PBKDF2_OID:
  4709. oid = pbkdf2Oid;
  4710. *oidSz = sizeof(pbkdf2Oid);
  4711. break;
  4712. default:
  4713. break;
  4714. }
  4715. break;
  4716. case oidPBEType:
  4717. switch (id) {
  4718. #if !defined(NO_SHA) && !defined(NO_RC4)
  4719. case PBE_SHA1_RC4_128_SUM:
  4720. case PBE_SHA1_RC4_128:
  4721. oid = pbeSha1RC4128;
  4722. *oidSz = sizeof(pbeSha1RC4128);
  4723. break;
  4724. #endif
  4725. #if !defined(NO_MD5) && !defined(NO_DES3)
  4726. case PBE_MD5_DES_SUM:
  4727. case PBE_MD5_DES:
  4728. oid = pbeMd5Des;
  4729. *oidSz = sizeof(pbeMd5Des);
  4730. break;
  4731. #endif
  4732. #if !defined(NO_SHA) && !defined(NO_DES3)
  4733. case PBE_SHA1_DES_SUM:
  4734. case PBE_SHA1_DES:
  4735. oid = pbeSha1Des;
  4736. *oidSz = sizeof(pbeSha1Des);
  4737. break;
  4738. #endif
  4739. #if !defined(NO_SHA) && !defined(NO_DES3)
  4740. case PBE_SHA1_DES3_SUM:
  4741. case PBE_SHA1_DES3:
  4742. oid = pbeSha1Des3;
  4743. *oidSz = sizeof(pbeSha1Des3);
  4744. break;
  4745. #endif
  4746. case PBES2_SUM:
  4747. case PBES2:
  4748. oid = pbes2;
  4749. *oidSz = sizeof(pbes2);
  4750. break;
  4751. default:
  4752. break;
  4753. }
  4754. break;
  4755. case oidKeyWrapType:
  4756. switch (id) {
  4757. #ifdef WOLFSSL_AES_128
  4758. case AES128_WRAP:
  4759. oid = wrapAes128Oid;
  4760. *oidSz = sizeof(wrapAes128Oid);
  4761. break;
  4762. #endif
  4763. #ifdef WOLFSSL_AES_192
  4764. case AES192_WRAP:
  4765. oid = wrapAes192Oid;
  4766. *oidSz = sizeof(wrapAes192Oid);
  4767. break;
  4768. #endif
  4769. #ifdef WOLFSSL_AES_256
  4770. case AES256_WRAP:
  4771. oid = wrapAes256Oid;
  4772. *oidSz = sizeof(wrapAes256Oid);
  4773. break;
  4774. #endif
  4775. #ifdef HAVE_PKCS7
  4776. case PWRI_KEK_WRAP:
  4777. oid = wrapPwriKekOid;
  4778. *oidSz = sizeof(wrapPwriKekOid);
  4779. break;
  4780. #endif
  4781. default:
  4782. break;
  4783. }
  4784. break;
  4785. case oidCmsKeyAgreeType:
  4786. switch (id) {
  4787. #ifndef NO_SHA
  4788. case dhSinglePass_stdDH_sha1kdf_scheme:
  4789. oid = dhSinglePass_stdDH_sha1kdf_Oid;
  4790. *oidSz = sizeof(dhSinglePass_stdDH_sha1kdf_Oid);
  4791. break;
  4792. #endif
  4793. #ifdef WOLFSSL_SHA224
  4794. case dhSinglePass_stdDH_sha224kdf_scheme:
  4795. oid = dhSinglePass_stdDH_sha224kdf_Oid;
  4796. *oidSz = sizeof(dhSinglePass_stdDH_sha224kdf_Oid);
  4797. break;
  4798. #endif
  4799. #ifndef NO_SHA256
  4800. case dhSinglePass_stdDH_sha256kdf_scheme:
  4801. oid = dhSinglePass_stdDH_sha256kdf_Oid;
  4802. *oidSz = sizeof(dhSinglePass_stdDH_sha256kdf_Oid);
  4803. break;
  4804. #endif
  4805. #ifdef WOLFSSL_SHA384
  4806. case dhSinglePass_stdDH_sha384kdf_scheme:
  4807. oid = dhSinglePass_stdDH_sha384kdf_Oid;
  4808. *oidSz = sizeof(dhSinglePass_stdDH_sha384kdf_Oid);
  4809. break;
  4810. #endif
  4811. #ifdef WOLFSSL_SHA512
  4812. case dhSinglePass_stdDH_sha512kdf_scheme:
  4813. oid = dhSinglePass_stdDH_sha512kdf_Oid;
  4814. *oidSz = sizeof(dhSinglePass_stdDH_sha512kdf_Oid);
  4815. break;
  4816. #endif
  4817. default:
  4818. break;
  4819. }
  4820. break;
  4821. #ifndef NO_HMAC
  4822. case oidHmacType:
  4823. switch (id) {
  4824. #ifdef WOLFSSL_SHA224
  4825. case HMAC_SHA224_OID:
  4826. oid = hmacSha224Oid;
  4827. *oidSz = sizeof(hmacSha224Oid);
  4828. break;
  4829. #endif
  4830. #ifndef NO_SHA256
  4831. case HMAC_SHA256_OID:
  4832. oid = hmacSha256Oid;
  4833. *oidSz = sizeof(hmacSha256Oid);
  4834. break;
  4835. #endif
  4836. #ifdef WOLFSSL_SHA384
  4837. case HMAC_SHA384_OID:
  4838. oid = hmacSha384Oid;
  4839. *oidSz = sizeof(hmacSha384Oid);
  4840. break;
  4841. #endif
  4842. #ifdef WOLFSSL_SHA512
  4843. case HMAC_SHA512_OID:
  4844. oid = hmacSha512Oid;
  4845. *oidSz = sizeof(hmacSha512Oid);
  4846. break;
  4847. #endif
  4848. default:
  4849. break;
  4850. }
  4851. break;
  4852. #endif /* !NO_HMAC */
  4853. #ifdef HAVE_LIBZ
  4854. case oidCompressType:
  4855. switch (id) {
  4856. case ZLIBc:
  4857. oid = zlibCompress;
  4858. *oidSz = sizeof(zlibCompress);
  4859. break;
  4860. default:
  4861. break;
  4862. }
  4863. break;
  4864. #endif /* HAVE_LIBZ */
  4865. #ifdef WOLFSSL_APACHE_HTTPD
  4866. case oidCertNameType:
  4867. switch (id) {
  4868. case NID_id_on_dnsSRV:
  4869. oid = dnsSRVOid;
  4870. *oidSz = sizeof(dnsSRVOid);
  4871. break;
  4872. default:
  4873. break;
  4874. }
  4875. break;
  4876. case oidTlsExtType:
  4877. switch (id) {
  4878. case TLS_FEATURE_OID:
  4879. oid = tlsFeatureOid;
  4880. *oidSz = sizeof(tlsFeatureOid);
  4881. break;
  4882. default:
  4883. break;
  4884. }
  4885. break;
  4886. #endif /* WOLFSSL_APACHE_HTTPD */
  4887. #ifdef WOLFSSL_CERT_REQ
  4888. case oidCsrAttrType:
  4889. switch (id) {
  4890. case GIVEN_NAME_OID:
  4891. oid = attrGivenName;
  4892. *oidSz = sizeof(attrGivenName);
  4893. break;
  4894. case SURNAME_OID:
  4895. oid = attrSurname;
  4896. *oidSz = sizeof(attrSurname);
  4897. break;
  4898. case INITIALS_OID:
  4899. oid = attrInitals;
  4900. *oidSz = sizeof(attrInitals);
  4901. break;
  4902. case DNQUALIFIER_OID:
  4903. oid = attrDnQualifier;
  4904. *oidSz = sizeof(attrDnQualifier);
  4905. break;
  4906. case UNSTRUCTURED_NAME_OID:
  4907. oid = attrUnstructuredNameOid;
  4908. *oidSz = sizeof(attrUnstructuredNameOid);
  4909. break;
  4910. case PKCS9_CONTENT_TYPE_OID:
  4911. oid = attrPkcs9ContentTypeOid;
  4912. *oidSz = sizeof(attrPkcs9ContentTypeOid);
  4913. break;
  4914. case CHALLENGE_PASSWORD_OID:
  4915. oid = attrChallengePasswordOid;
  4916. *oidSz = sizeof(attrChallengePasswordOid);
  4917. break;
  4918. case SERIAL_NUMBER_OID:
  4919. oid = attrSerialNumberOid;
  4920. *oidSz = sizeof(attrSerialNumberOid);
  4921. break;
  4922. case USER_ID_OID:
  4923. oid = uidOid;
  4924. *oidSz = sizeof(uidOid);
  4925. break;
  4926. case EXTENSION_REQUEST_OID:
  4927. oid = attrExtensionRequestOid;
  4928. *oidSz = sizeof(attrExtensionRequestOid);
  4929. break;
  4930. default:
  4931. break;
  4932. }
  4933. break;
  4934. #endif
  4935. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  4936. case oidSubjDirAttrType:
  4937. switch (id) {
  4938. case SDA_DOB_OID:
  4939. oid = extSubjDirAttrDobOid;
  4940. *oidSz = sizeof(extSubjDirAttrDobOid);
  4941. break;
  4942. case SDA_POB_OID:
  4943. oid = extSubjDirAttrPobOid;
  4944. *oidSz = sizeof(extSubjDirAttrPobOid);
  4945. break;
  4946. case SDA_GENDER_OID:
  4947. oid = extSubjDirAttrGenderOid;
  4948. *oidSz = sizeof(extSubjDirAttrGenderOid);
  4949. break;
  4950. case SDA_COC_OID:
  4951. oid = extSubjDirAttrCocOid;
  4952. *oidSz = sizeof(extSubjDirAttrCocOid);
  4953. break;
  4954. case SDA_COR_OID:
  4955. oid = extSubjDirAttrCorOid;
  4956. *oidSz = sizeof(extSubjDirAttrCorOid);
  4957. break;
  4958. default:
  4959. break;
  4960. }
  4961. break;
  4962. #endif /* WOLFSSL_SUBJ_DIR_ATTR */
  4963. case oidIgnoreType:
  4964. default:
  4965. break;
  4966. }
  4967. return oid;
  4968. }
  4969. #ifdef HAVE_ECC
  4970. /* Check the OID id is for a known elliptic curve.
  4971. *
  4972. * @param [in] oid OID id.
  4973. * @return ECC set id on success.
  4974. * @return ECC_CURVE_OID_E when OID id is 0 or not supported.
  4975. */
  4976. static int CheckCurve(word32 oid)
  4977. {
  4978. int ret;
  4979. word32 oidSz;
  4980. /* Lookup OID id. */
  4981. ret = wc_ecc_get_oid(oid, NULL, &oidSz);
  4982. /* Check for error or zero length OID size (can't get OID for encoding). */
  4983. if ((ret < 0) || (oidSz == 0)) {
  4984. WOLFSSL_MSG("CheckCurve not found");
  4985. WOLFSSL_ERROR_VERBOSE(ECC_CURVE_OID_E);
  4986. ret = ECC_CURVE_OID_E;
  4987. }
  4988. /* Return ECC set id or error code. */
  4989. return ret;
  4990. }
  4991. #endif
  4992. #ifdef HAVE_OID_ENCODING
  4993. /* Encode dotted form of OID into byte array version.
  4994. *
  4995. * @param [in] in Dotted form of OID.
  4996. * @param [in] inSz Count of numbers in dotted form.
  4997. * @param [in] out Buffer to hold OID.
  4998. * @param [in, out] outSz On in, size of buffer.
  4999. * On out, number of bytes in buffer.
  5000. * @return 0 on success
  5001. * @return BAD_FUNC_ARG when in or outSz is NULL.
  5002. * @return BUFFER_E when buffer too small.
  5003. */
  5004. int EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz)
  5005. {
  5006. int i, x, len;
  5007. word32 d, t;
  5008. /* check args */
  5009. if (in == NULL || outSz == NULL) {
  5010. return BAD_FUNC_ARG;
  5011. }
  5012. /* compute length of encoded OID */
  5013. d = (in[0] * 40) + in[1];
  5014. len = 0;
  5015. for (i = 1; i < (int)inSz; i++) {
  5016. x = 0;
  5017. t = d;
  5018. while (t) {
  5019. x++;
  5020. t >>= 1;
  5021. }
  5022. len += (x / 7) + ((x % 7) ? 1 : 0) + (d == 0 ? 1 : 0);
  5023. if (i < (int)inSz - 1) {
  5024. d = in[i + 1];
  5025. }
  5026. }
  5027. if (out) {
  5028. /* verify length */
  5029. if ((int)*outSz < len) {
  5030. return BUFFER_E; /* buffer provided is not large enough */
  5031. }
  5032. /* calc first byte */
  5033. d = (in[0] * 40) + in[1];
  5034. /* encode bytes */
  5035. x = 0;
  5036. for (i = 1; i < (int)inSz; i++) {
  5037. if (d) {
  5038. int y = x, z;
  5039. byte mask = 0;
  5040. while (d) {
  5041. out[x++] = (byte)((d & 0x7F) | mask);
  5042. d >>= 7;
  5043. mask |= 0x80; /* upper bit is set on all but the last byte */
  5044. }
  5045. /* now swap bytes y...x-1 */
  5046. z = x - 1;
  5047. while (y < z) {
  5048. mask = out[y];
  5049. out[y] = out[z];
  5050. out[z] = mask;
  5051. ++y;
  5052. --z;
  5053. }
  5054. }
  5055. else {
  5056. out[x++] = 0x00; /* zero value */
  5057. }
  5058. /* next word */
  5059. if (i < (int)inSz - 1) {
  5060. d = in[i + 1];
  5061. }
  5062. }
  5063. }
  5064. /* return length */
  5065. *outSz = len;
  5066. return 0;
  5067. }
  5068. #endif /* HAVE_OID_ENCODING */
  5069. #ifdef HAVE_OID_DECODING
  5070. /* Encode dotted form of OID into byte array version.
  5071. *
  5072. * @param [in] in Byte array containing OID.
  5073. * @param [in] inSz Size of OID in bytes.
  5074. * @param [in] out Array to hold dotted form of OID.
  5075. * @param [in, out] outSz On in, number of elements in array.
  5076. * On out, count of numbers in dotted form.
  5077. * @return 0 on success
  5078. * @return BAD_FUNC_ARG when in or outSz is NULL.
  5079. * @return BUFFER_E when dotted form buffer too small.
  5080. */
  5081. int DecodeObjectId(const byte* in, word32 inSz, word16* out, word32* outSz)
  5082. {
  5083. int x = 0, y = 0;
  5084. word32 t = 0;
  5085. /* check args */
  5086. if (in == NULL || outSz == NULL) {
  5087. return BAD_FUNC_ARG;
  5088. }
  5089. /* decode bytes */
  5090. while (inSz--) {
  5091. t = (t << 7) | (in[x] & 0x7F);
  5092. if (!(in[x] & 0x80)) {
  5093. if (y >= (int)*outSz) {
  5094. return BUFFER_E;
  5095. }
  5096. if (y == 0) {
  5097. out[0] = (t / 40);
  5098. out[1] = (t % 40);
  5099. y = 2;
  5100. }
  5101. else {
  5102. out[y++] = t;
  5103. }
  5104. t = 0; /* reset tmp */
  5105. }
  5106. x++;
  5107. }
  5108. /* return length */
  5109. *outSz = y;
  5110. return 0;
  5111. }
  5112. #endif /* HAVE_OID_DECODING */
  5113. /* Decode the header of a BER/DER encoded OBJECT ID.
  5114. *
  5115. * @param [in] input Buffer holding DER/BER encoded data.
  5116. * @param [in, out] inOutIdx On in, starting index of header.
  5117. * On out, end of parsed header.
  5118. * @param [out] len Number of bytes in the ASN.1 data.
  5119. * @param [in] maxIdx Length of data in buffer.
  5120. * @return 0 on success.
  5121. * @return BUFFER_E when there is not enough data to parse.
  5122. * @return ASN_PARSE_E when the tag is not a OBJECT ID or length is invalid.
  5123. */
  5124. int GetASNObjectId(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  5125. {
  5126. int ret = GetASNHeader(input, ASN_OBJECT_ID, inOutIdx, len, maxIdx);
  5127. if (ret > 0) {
  5128. /* Only return 0 on success. */
  5129. ret = 0;
  5130. }
  5131. return ret;
  5132. }
  5133. /* Set the DER/BER encoding of the ASN.1 OBJECT ID header.
  5134. *
  5135. * When output is NULL, calculate the header length only.
  5136. *
  5137. * @param [in] len Length of OBJECT ID data in bytes.
  5138. * @param [out] output Buffer to write into.
  5139. * @return Number of bytes added to the buffer.
  5140. */
  5141. int SetObjectId(int len, byte* output)
  5142. {
  5143. int idx = 0;
  5144. if (output) {
  5145. /* Write out tag. */
  5146. output[idx] = ASN_OBJECT_ID;
  5147. }
  5148. /* Skip tag. */
  5149. idx += ASN_TAG_SZ;
  5150. /* Encode length - passing NULL for output will not encode. */
  5151. idx += SetLength(len, output ? output + idx : NULL);
  5152. /* Return index after header. */
  5153. return idx;
  5154. }
  5155. #ifdef ASN_DUMP_OID
  5156. /* Dump the OID information.
  5157. *
  5158. * Decode the OID too if function available.
  5159. *
  5160. * @param [in] oidData OID data from buffer.
  5161. * @param [in] oidSz Size of OID data in buffer.
  5162. * @param [in] oid OID id.
  5163. * @param [in] oidType Type of OID.
  5164. * @return 0 on success.
  5165. * @return BUFFER_E when not enough bytes for proper decode.
  5166. * (HAVE_OID_DECODING)
  5167. */
  5168. static int DumpOID(const byte* oidData, word32 oidSz, word32 oid,
  5169. word32 oidType)
  5170. {
  5171. int ret = 0;
  5172. word32 i;
  5173. /* support for dumping OID information */
  5174. printf("OID (Type %d, Sz %d, Sum %d): ", oidType, oidSz, oid);
  5175. /* Dump bytes in decimal. */
  5176. for (i = 0; i < oidSz; i++) {
  5177. printf("%d, ", oidData[i]);
  5178. }
  5179. printf("\n");
  5180. /* Dump bytes in hexadecimal. */
  5181. for (i = 0; i < oidSz; i++) {
  5182. printf("%02x, ", oidData[i]);
  5183. }
  5184. printf("\n");
  5185. #ifdef HAVE_OID_DECODING
  5186. {
  5187. word16 decOid[MAX_OID_SZ];
  5188. word32 decOidSz = sizeof(decOid);
  5189. /* Decode the OID into dotted form. */
  5190. ret = DecodeObjectId(oidData, oidSz, decOid, &decOidSz);
  5191. if (ret == 0) {
  5192. printf(" Decoded (Sz %d): ", decOidSz);
  5193. for (i=0; i<decOidSz; i++) {
  5194. printf("%d.", decOid[i]);
  5195. }
  5196. printf("\n");
  5197. }
  5198. else {
  5199. printf("DecodeObjectId failed: %d\n", ret);
  5200. }
  5201. }
  5202. #endif /* HAVE_OID_DECODING */
  5203. return ret;
  5204. }
  5205. #endif /* ASN_DUMP_OID */
  5206. /* Get the OID data and verify it is of the type specified when compiled in.
  5207. *
  5208. * @param [in] input Buffer holding OID.
  5209. * @param [in, out] inOutIdx On in, starting index of OID.
  5210. * On out, end of parsed OID.
  5211. * @param [out] oid OID id.
  5212. * @param [in] oidType Expected type of OID. Define NO_VERIFY_OID to
  5213. * not compile in check.
  5214. * @param [in] length Length of OID data in buffer.
  5215. * @return 0 on success.
  5216. * @return ASN_UNKNOWN_OID_E when OID is not recognized.
  5217. * @return BUFFER_E when not enough bytes for proper decode. (ASN_DUMP_OID and
  5218. * HAVE_OID_DECODING)
  5219. */
  5220. static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
  5221. word32 oidType, int length)
  5222. {
  5223. int ret = 0;
  5224. word32 idx = *inOutIdx;
  5225. #ifndef NO_VERIFY_OID
  5226. word32 actualOidSz;
  5227. const byte* actualOid;
  5228. const byte* checkOid = NULL;
  5229. word32 checkOidSz;
  5230. #endif /* NO_VERIFY_OID */
  5231. #ifdef HAVE_PQC
  5232. word32 found_collision = 0;
  5233. #endif
  5234. (void)oidType;
  5235. *oid = 0;
  5236. #ifndef NO_VERIFY_OID
  5237. /* Keep references to OID data and length for check. */
  5238. actualOid = &input[idx];
  5239. actualOidSz = (word32)length;
  5240. #endif /* NO_VERIFY_OID */
  5241. #if defined(HAVE_PQC) && defined(HAVE_LIBOQS)
  5242. /* Since we are summing it up, there could be collisions...and indeed there
  5243. * are:
  5244. *
  5245. * DILITHIUM_LEVEL5
  5246. * 1.3.6.1.4.1.2.267.7.6.7
  5247. * {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7}
  5248. * -> 220
  5249. * DILITHIUM_AES_LEVEL3
  5250. * 1.3.6.1.4.1.2.267.11.4.5
  5251. * {43, 6, 1, 4, 1, 2, 130, 11, 11, 6, 5}
  5252. * -> 220
  5253. *
  5254. * As a small hack, we're going to look for the special case of
  5255. * DILITHIUM_AES_LEVEL3k and if we find it, instead of *oid being set to 220
  5256. * we will set it to 221. Note that DILITHIUM_AES_LEVEL3k is defined as 221.
  5257. *
  5258. * Same thing for SPHINCS_FAST_LEVEL1 and SPHINCS_FAST_LEVEL3. We will look
  5259. * for the special case of SPHINCS_FAST_LEVEL3 and set *oid to 283 instead
  5260. * of 281; 282 is taken.
  5261. *
  5262. * These hacks will hopefully disappear when new standardized OIDs appear.
  5263. */
  5264. if (memcmp(&input[idx], sigDilithiumAes_Level3Oid,
  5265. sizeof(sigDilithiumAes_Level3Oid)) == 0) {
  5266. found_collision = DILITHIUM_AES_LEVEL3k;
  5267. } else if (memcmp(&input[idx], sigSphincsFast_Level3Oid,
  5268. sizeof(sigSphincsFast_Level3Oid)) == 0) {
  5269. found_collision = SPHINCS_FAST_LEVEL3k;
  5270. }
  5271. #endif /* HAVE_PQC */
  5272. /* Sum it up for now. */
  5273. while (length--) {
  5274. /* odd HC08 compiler behavior here when input[idx++] */
  5275. *oid += (word32)input[idx];
  5276. idx++;
  5277. }
  5278. #ifdef HAVE_PQC
  5279. if (found_collision) {
  5280. *oid = found_collision;
  5281. }
  5282. #endif /* HAVE_PQC */
  5283. /* Return the index after the OID data. */
  5284. *inOutIdx = idx;
  5285. #ifndef NO_VERIFY_OID
  5286. /* 'Ignore' type means we don't care which OID it is. */
  5287. if (oidType != oidIgnoreType) {
  5288. /* Get the OID data for the id-type. */
  5289. checkOid = OidFromId(*oid, oidType, &checkOidSz);
  5290. #if defined(WOLFSSL_FPKI)
  5291. /* Handle OID sum collision of
  5292. AES256CBCb (454) 2.16.840.1.101.3.4.1.42
  5293. CP_FPKI_PIV_AUTH_HW_OID (454) 2.16.840.1.101.3.2.1.3.41
  5294. */
  5295. #if defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  5296. if ((actualOidSz == (word32)sizeof(blkAes256CbcOid)) &&
  5297. (XMEMCMP(actualOid, blkAes256CbcOid,
  5298. sizeof(blkAes256CbcOid)) == 0)) {
  5299. checkOid = blkAes256CbcOid;
  5300. checkOidSz = sizeof(blkAes256CbcOid);
  5301. }
  5302. #endif /* HAVE_AES_CBC */
  5303. #endif /* WOLFSSL_FPKI */
  5304. #ifdef ASN_DUMP_OID
  5305. /* Dump out the data for debug. */
  5306. ret = DumpOID(actualOid, actualOidSz, *oid, oidType);
  5307. #endif
  5308. /* TODO: Want to fail when checkOid is NULL.
  5309. * Can't as too many situations where unknown OID is to be
  5310. * supported. Extra parameter for must not be NULL?
  5311. */
  5312. /* Check that the OID data matches what we found for the OID id. */
  5313. if ((ret == 0) && (checkOid != NULL) && ((checkOidSz != actualOidSz) ||
  5314. (XMEMCMP(actualOid, checkOid, checkOidSz) != 0))) {
  5315. WOLFSSL_MSG("OID Check Failed");
  5316. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  5317. ret = ASN_UNKNOWN_OID_E;
  5318. }
  5319. }
  5320. #endif /* NO_VERIFY_OID */
  5321. return ret;
  5322. }
  5323. #ifdef WOLFSSL_ASN_TEMPLATE
  5324. /* ASN.1 template for an OBJECT_ID. */
  5325. static const ASNItem objectIdASN[] = {
  5326. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 }
  5327. };
  5328. enum {
  5329. OBJECTIDASN_IDX_OID = 0
  5330. };
  5331. /* Number of items in ASN.1 template for an OBJECT_ID. */
  5332. #define objectIdASN_Length (sizeof(objectIdASN) / sizeof(ASNItem))
  5333. #endif
  5334. /* Get the OID id/sum from the BER encoded OBJECT_ID.
  5335. *
  5336. * @param [in] input Buffer holding BER encoded data.
  5337. * @param [in, out] inOutIdx On in, start of OBJECT_ID.
  5338. * On out, start of ASN.1 item after OBJECT_ID.
  5339. * @param [out] oid Id of OID in OBJECT_ID data.
  5340. * @param [in] oidType Type of OID to expect.
  5341. * @param [in] maxIdx Maximum index of data in buffer.
  5342. * @return 0 on success.
  5343. * @return ASN_PARSE_E when encoding is invalid.
  5344. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  5345. */
  5346. int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
  5347. word32 oidType, word32 maxIdx)
  5348. {
  5349. #ifndef WOLFSSL_ASN_TEMPLATE
  5350. int ret, length;
  5351. WOLFSSL_ENTER("GetObjectId()");
  5352. ret = GetASNObjectId(input, inOutIdx, &length, maxIdx);
  5353. if (ret != 0)
  5354. return ret;
  5355. return GetOID(input, inOutIdx, oid, oidType, length);
  5356. #else
  5357. ASNGetData dataASN[objectIdASN_Length];
  5358. int ret;
  5359. WOLFSSL_ENTER("GetObjectId()");
  5360. /* Clear dynamic data and set OID type expected. */
  5361. XMEMSET(dataASN, 0, sizeof(dataASN));
  5362. GetASN_OID(&dataASN[OBJECTIDASN_IDX_OID], oidType);
  5363. /* Decode OBJECT_ID. */
  5364. ret = GetASN_Items(objectIdASN, dataASN, objectIdASN_Length, 0, input,
  5365. inOutIdx, maxIdx);
  5366. if (ret == 0) {
  5367. /* Return the id/sum. */
  5368. *oid = dataASN[OBJECTIDASN_IDX_OID].data.oid.sum;
  5369. }
  5370. return ret;
  5371. #endif /* WOLFSSL_ASN_TEMPLATE */
  5372. }
  5373. #ifndef WOLFSSL_ASN_TEMPLATE
  5374. static int SkipObjectId(const byte* input, word32* inOutIdx, word32 maxIdx)
  5375. {
  5376. word32 idx = *inOutIdx;
  5377. int length;
  5378. int ret;
  5379. ret = GetASNObjectId(input, &idx, &length, maxIdx);
  5380. if (ret != 0)
  5381. return ret;
  5382. idx += length;
  5383. *inOutIdx = idx;
  5384. return 0;
  5385. }
  5386. #endif
  5387. #ifdef WOLFSSL_ASN_TEMPLATE
  5388. /* ASN.1 template for an algorithm identifier. */
  5389. static const ASNItem algoIdASN[] = {
  5390. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5391. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  5392. /* NULL */ { 1, ASN_TAG_NULL, 0, 0, 1 },
  5393. };
  5394. enum {
  5395. ALGOIDASN_IDX_SEQ = 0,
  5396. ALGOIDASN_IDX_OID,
  5397. ALGOIDASN_IDX_NULL
  5398. };
  5399. /* Number of items in ASN.1 template for an algorithm identifier. */
  5400. #define algoIdASN_Length (sizeof(algoIdASN) / sizeof(ASNItem))
  5401. #endif
  5402. /* Get the OID id/sum from the BER encoding of an algorithm identifier.
  5403. *
  5404. * NULL tag is skipped if present.
  5405. *
  5406. * @param [in] input Buffer holding BER encoded data.
  5407. * @param [in, out] inOutIdx On in, start of algorithm identifier.
  5408. * On out, start of ASN.1 item after algorithm id.
  5409. * @param [out] oid Id of OID in algorithm identifier data.
  5410. * @param [in] oidType Type of OID to expect.
  5411. * @param [in] maxIdx Maximum index of data in buffer.
  5412. * @return 0 on success.
  5413. * @return ASN_PARSE_E when encoding is invalid.
  5414. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  5415. */
  5416. int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
  5417. word32 oidType, word32 maxIdx)
  5418. {
  5419. #ifndef WOLFSSL_ASN_TEMPLATE
  5420. int length;
  5421. word32 idx = *inOutIdx;
  5422. int ret;
  5423. *oid = 0;
  5424. WOLFSSL_ENTER("GetAlgoId");
  5425. if (GetSequence(input, &idx, &length, maxIdx) < 0)
  5426. return ASN_PARSE_E;
  5427. if (GetObjectId(input, &idx, oid, oidType, maxIdx) < 0)
  5428. return ASN_OBJECT_ID_E;
  5429. /* could have NULL tag and 0 terminator, but may not */
  5430. if (idx < maxIdx) {
  5431. word32 localIdx = idx; /*use localIdx to not advance when checking tag*/
  5432. byte tag;
  5433. if (GetASNTag(input, &localIdx, &tag, maxIdx) == 0) {
  5434. if (tag == ASN_TAG_NULL) {
  5435. ret = GetASNNull(input, &idx, maxIdx);
  5436. if (ret != 0)
  5437. return ret;
  5438. }
  5439. }
  5440. }
  5441. *inOutIdx = idx;
  5442. return 0;
  5443. #else
  5444. DECL_ASNGETDATA(dataASN, algoIdASN_Length);
  5445. int ret = 0;
  5446. WOLFSSL_ENTER("GetAlgoId");
  5447. CALLOC_ASNGETDATA(dataASN, algoIdASN_Length, ret, NULL);
  5448. if (ret == 0) {
  5449. /* Set OID type expected. */
  5450. GetASN_OID(&dataASN[ALGOIDASN_IDX_OID], oidType);
  5451. /* Decode the algorithm identifier. */
  5452. ret = GetASN_Items(algoIdASN, dataASN, algoIdASN_Length, 0, input,
  5453. inOutIdx, maxIdx);
  5454. }
  5455. if (ret == 0) {
  5456. /* Return the OID id/sum. */
  5457. *oid = dataASN[ALGOIDASN_IDX_OID].data.oid.sum;
  5458. }
  5459. FREE_ASNGETDATA(dataASN, NULL);
  5460. return ret;
  5461. #endif /* WOLFSSL_ASN_TEMPLATE */
  5462. }
  5463. #ifndef NO_RSA
  5464. #ifdef WC_RSA_PSS
  5465. /* RFC 8017 - PKCS #1 has RSA PSS parameter ASN definition. */
  5466. /* Convert a hash OID to a hash type.
  5467. *
  5468. * @param [in] oid Hash OID.
  5469. * @param [out] type Hash type.
  5470. * @return 0 on success.
  5471. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5472. */
  5473. static int RsaPssHashOidToType(word32 oid, enum wc_HashType* type)
  5474. {
  5475. int ret = 0;
  5476. switch (oid) {
  5477. /* SHA-1 is missing as it is the default is not allowed to appear. */
  5478. #ifdef WOLFSSL_SHA224
  5479. case SHA224h:
  5480. *type = WC_HASH_TYPE_SHA224;
  5481. break;
  5482. #endif
  5483. #ifndef NO_SHA256
  5484. case SHA256h:
  5485. *type = WC_HASH_TYPE_SHA256;
  5486. break;
  5487. #endif
  5488. #ifdef WOLFSSL_SHA384
  5489. case SHA384h:
  5490. *type = WC_HASH_TYPE_SHA384;
  5491. break;
  5492. #endif
  5493. #ifdef WOLFSSL_SHA512
  5494. case SHA512h:
  5495. *type = WC_HASH_TYPE_SHA512;
  5496. break;
  5497. /* TODO: SHA512_224h */
  5498. /* TODO: SHA512_256h */
  5499. #endif
  5500. default:
  5501. ret = ASN_PARSE_E;
  5502. break;
  5503. }
  5504. return ret;
  5505. }
  5506. /* Convert a hash OID to a MGF1 type.
  5507. *
  5508. * @param [in] oid Hash OID.
  5509. * @param [out] mgf MGF type.
  5510. * @return 0 on success.
  5511. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5512. */
  5513. static int RsaPssHashOidToMgf1(word32 oid, int* mgf)
  5514. {
  5515. int ret = 0;
  5516. switch (oid) {
  5517. /* SHA-1 is missing as it is the default is not allowed to appear. */
  5518. #ifdef WOLFSSL_SHA224
  5519. case SHA224h:
  5520. *mgf = WC_MGF1SHA224;
  5521. break;
  5522. #endif
  5523. #ifndef NO_SHA256
  5524. case SHA256h:
  5525. *mgf = WC_MGF1SHA256;
  5526. break;
  5527. #endif
  5528. #ifdef WOLFSSL_SHA384
  5529. case SHA384h:
  5530. *mgf = WC_MGF1SHA384;
  5531. break;
  5532. #endif
  5533. #ifdef WOLFSSL_SHA512
  5534. case SHA512h:
  5535. *mgf = WC_MGF1SHA512;
  5536. break;
  5537. /* TODO: SHA512_224h */
  5538. /* TODO: SHA512_256h */
  5539. #endif
  5540. default:
  5541. ret = ASN_PARSE_E;
  5542. break;
  5543. }
  5544. return ret;
  5545. }
  5546. /* Convert a hash OID to a fake signature OID.
  5547. *
  5548. * @param [in] oid Hash OID.
  5549. * @param [out] sigOid Signature OID to pass wto HashForSignature().
  5550. * @return 0 on success.
  5551. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5552. */
  5553. static int RsaPssHashOidToSigOid(word32 oid, word32* sigOid)
  5554. {
  5555. int ret = 0;
  5556. switch (oid) {
  5557. #ifndef NO_SHA
  5558. case WC_HASH_TYPE_SHA:
  5559. *sigOid = CTC_SHAwRSA;
  5560. break;
  5561. #endif
  5562. #ifdef WOLFSSL_SHA224
  5563. case WC_HASH_TYPE_SHA224:
  5564. *sigOid = CTC_SHA224wRSA;
  5565. break;
  5566. #endif
  5567. #ifndef NO_SHA256
  5568. case WC_HASH_TYPE_SHA256:
  5569. *sigOid = CTC_SHA256wRSA;
  5570. break;
  5571. #endif
  5572. #ifdef WOLFSSL_SHA384
  5573. case WC_HASH_TYPE_SHA384:
  5574. *sigOid = CTC_SHA384wRSA;
  5575. break;
  5576. #endif
  5577. #ifdef WOLFSSL_SHA512
  5578. case WC_HASH_TYPE_SHA512:
  5579. *sigOid = CTC_SHA512wRSA;
  5580. break;
  5581. #endif
  5582. /* TODO: SHA512_224h */
  5583. /* TODO: SHA512_256h */
  5584. /* Not supported by HashForSignature() */
  5585. default:
  5586. ret = ASN_PARSE_E;
  5587. break;
  5588. }
  5589. return ret;
  5590. }
  5591. #ifdef WOLFSSL_ASN_TEMPLATE
  5592. /* ASN tag for hashAlgorigthm. */
  5593. #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | 0)
  5594. /* ASN tag for maskGenAlgorithm. */
  5595. #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | 1)
  5596. /* ASN tag for saltLength. */
  5597. #define ASN_TAG_RSA_PSS_SALTLEN (ASN_CONTEXT_SPECIFIC | 2)
  5598. /* ASN tag for trailerField. */
  5599. #define ASN_TAG_RSA_PSS_TRAILER (ASN_CONTEXT_SPECIFIC | 3)
  5600. /* ASN.1 template for RSA PSS parameters. */
  5601. static const ASNItem rsaPssParamsASN[] = {
  5602. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5603. /* HASH */ { 1, ASN_TAG_RSA_PSS_HASH, 1, 1, 1 },
  5604. /* HASHSEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  5605. /* HASHOID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  5606. /* HASHNULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  5607. /* MGF */ { 1, ASN_TAG_RSA_PSS_MGF, 1, 1, 1 },
  5608. /* MGFSEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  5609. /* MGFOID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  5610. /* MGFPARAM */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  5611. /* MGFHOID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  5612. /* MGFHNULL */ { 4, ASN_TAG_NULL, 0, 0, 1 },
  5613. /* SALTLEN */ { 1, ASN_TAG_RSA_PSS_SALTLEN, 1, 1, 1 },
  5614. /* SALTLENINT */ { 2, ASN_INTEGER, 0, 0, 0 },
  5615. /* TRAILER */ { 1, ASN_TAG_RSA_PSS_TRAILER, 1, 1, 1 },
  5616. /* TRAILERINT */ { 2, ASN_INTEGER, 0, 0, 0 },
  5617. };
  5618. enum {
  5619. RSAPSSPARAMSASN_IDX_SEQ = 0,
  5620. RSAPSSPARAMSASN_IDX_HASH,
  5621. RSAPSSPARAMSASN_IDX_HASHSEQ,
  5622. RSAPSSPARAMSASN_IDX_HASHOID,
  5623. RSAPSSPARAMSASN_IDX_HASHNULL,
  5624. RSAPSSPARAMSASN_IDX_MGF,
  5625. RSAPSSPARAMSASN_IDX_MGFSEQ,
  5626. RSAPSSPARAMSASN_IDX_MGFOID,
  5627. RSAPSSPARAMSASN_IDX_MGFPARAM,
  5628. RSAPSSPARAMSASN_IDX_MGFHOID,
  5629. RSAPSSPARAMSASN_IDX_MGFHNULL,
  5630. RSAPSSPARAMSASN_IDX_SALTLEN,
  5631. RSAPSSPARAMSASN_IDX_SALTLENINT,
  5632. RSAPSSPARAMSASN_IDX_TRAILER,
  5633. RSAPSSPARAMSASN_IDX_TRAILERINT,
  5634. };
  5635. /* Number of items in ASN.1 template for an algorithm identifier. */
  5636. #define rsaPssParamsASN_Length (sizeof(rsaPssParamsASN) / sizeof(ASNItem))
  5637. #else
  5638. /* ASN tag for hashAlgorigthm. */
  5639. #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0)
  5640. /* ASN tag for maskGenAlgorithm. */
  5641. #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)
  5642. /* ASN tag for saltLength. */
  5643. #define ASN_TAG_RSA_PSS_SALTLEN (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)
  5644. /* ASN tag for trailerField. */
  5645. #define ASN_TAG_RSA_PSS_TRAILER (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)
  5646. #endif
  5647. /* Decode the RSA PSS parameters.
  5648. *
  5649. * @param [in] params Buffer holding BER encoded RSA PSS parameters.
  5650. * @param [in] sz Size of data in buffer in bytes.
  5651. * @param [out] hash Hash algorithm to use on message.
  5652. * @param [out] mgf MGF algorithm to use with PSS padding.
  5653. * @param [out] saltLen Length of salt in PSS padding.
  5654. * @return ASN_PARSE_E when the decoding fails.
  5655. * @return 0 on success.
  5656. */
  5657. static int DecodeRsaPssParams(const byte* params, word32 sz,
  5658. enum wc_HashType* hash, int* mgf, int* saltLen)
  5659. {
  5660. #ifndef WOLFSSL_ASN_TEMPLATE
  5661. int ret = 0;
  5662. word32 idx = 0;
  5663. int len = 0;
  5664. word32 oid = 0;
  5665. byte tag;
  5666. int length;
  5667. if (GetSequence_ex(params, &idx, &len, sz, 1) < 0) {
  5668. ret = ASN_PARSE_E;
  5669. }
  5670. if (ret == 0) {
  5671. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_HASH)) {
  5672. /* Hash algorithm to use on message. */
  5673. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5674. ret = ASN_PARSE_E;
  5675. }
  5676. if (ret == 0) {
  5677. if (GetAlgoId(params, &idx, &oid, oidHashType, sz) < 0) {
  5678. ret = ASN_PARSE_E;
  5679. }
  5680. }
  5681. if (ret == 0) {
  5682. ret = RsaPssHashOidToType(oid, hash);
  5683. }
  5684. }
  5685. else {
  5686. /* Default hash algorithm. */
  5687. *hash = WC_HASH_TYPE_SHA;
  5688. }
  5689. }
  5690. if (ret == 0) {
  5691. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_MGF)) {
  5692. /* MGF and hash algorithm to use with padding. */
  5693. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5694. ret = ASN_PARSE_E;
  5695. }
  5696. if (ret == 0) {
  5697. if (GetAlgoId(params, &idx, &oid, oidIgnoreType, sz) < 0) {
  5698. ret = ASN_PARSE_E;
  5699. }
  5700. }
  5701. if ((ret == 0) && (oid != MGF1_OID)) {
  5702. ret = ASN_PARSE_E;
  5703. }
  5704. if (ret == 0) {
  5705. ret = GetAlgoId(params, &idx, &oid, oidHashType, sz);
  5706. if (ret == 0) {
  5707. ret = RsaPssHashOidToMgf1(oid, mgf);
  5708. }
  5709. }
  5710. }
  5711. else {
  5712. /* Default MGF/Hash algorithm. */
  5713. *mgf = WC_MGF1SHA1;
  5714. }
  5715. }
  5716. if (ret == 0) {
  5717. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_SALTLEN)) {
  5718. /* Salt length to use with padding. */
  5719. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5720. ret = ASN_PARSE_E;
  5721. }
  5722. if (ret == 0) {
  5723. ret = GetInteger16Bit(params, &idx, sz);
  5724. if (ret >= 0) {
  5725. *saltLen = ret;
  5726. ret = 0;
  5727. }
  5728. }
  5729. }
  5730. else {
  5731. /* Default salt length. */
  5732. *saltLen = 20;
  5733. }
  5734. }
  5735. if (ret == 0) {
  5736. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_TRAILER)) {
  5737. /* Unused - trialerField. */
  5738. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5739. ret = ASN_PARSE_E;
  5740. }
  5741. if (ret == 0) {
  5742. ret = GetInteger16Bit(params, &idx, sz);
  5743. if (ret > 0) {
  5744. ret = 0;
  5745. }
  5746. }
  5747. }
  5748. }
  5749. if ((ret == 0) && (idx != sz)) {
  5750. ret = ASN_PARSE_E;
  5751. }
  5752. return ret;
  5753. #else
  5754. DECL_ASNGETDATA(dataASN, rsaPssParamsASN_Length);
  5755. int ret = 0;
  5756. word16 sLen = 20;
  5757. CALLOC_ASNGETDATA(dataASN, rsaPssParamsASN_Length, ret, NULL);
  5758. if (ret == 0) {
  5759. word32 inOutIdx = 0;
  5760. /* Default values. */
  5761. *hash = WC_HASH_TYPE_SHA;
  5762. *mgf = WC_MGF1SHA1;
  5763. /* Set OID type expected. */
  5764. GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_HASHOID], oidHashType);
  5765. GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_MGFHOID], oidHashType);
  5766. /* Place the salt length into 16-bit var sLen. */
  5767. GetASN_Int16Bit(&dataASN[RSAPSSPARAMSASN_IDX_SALTLENINT], &sLen);
  5768. /* Decode the algorithm identifier. */
  5769. ret = GetASN_Items(rsaPssParamsASN, dataASN, rsaPssParamsASN_Length, 1,
  5770. params, &inOutIdx, sz);
  5771. }
  5772. if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_HASHOID].tag != 0)) {
  5773. word32 oid = dataASN[RSAPSSPARAMSASN_IDX_HASHOID].data.oid.sum;
  5774. ret = RsaPssHashOidToType(oid, hash);
  5775. }
  5776. if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].tag != 0)) {
  5777. word32 oid = dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].data.oid.sum;
  5778. ret = RsaPssHashOidToMgf1(oid, mgf);
  5779. }
  5780. if (ret == 0) {
  5781. *saltLen = sLen;
  5782. }
  5783. FREE_ASNGETDATA(dataASN, NULL);
  5784. return ret;
  5785. #endif /* WOLFSSL_ASN_TEMPLATE */
  5786. }
  5787. #endif /* WC_RSA_PSS */
  5788. #ifndef HAVE_USER_RSA
  5789. #if defined(WOLFSSL_ASN_TEMPLATE) || (!defined(NO_CERTS) && \
  5790. (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  5791. defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)))
  5792. /* Byte offset of numbers in RSA key. */
  5793. size_t rsaIntOffset[] = {
  5794. OFFSETOF(RsaKey, n),
  5795. OFFSETOF(RsaKey, e),
  5796. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  5797. OFFSETOF(RsaKey, d),
  5798. OFFSETOF(RsaKey, p),
  5799. OFFSETOF(RsaKey, q),
  5800. #if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
  5801. OFFSETOF(RsaKey, dP),
  5802. OFFSETOF(RsaKey, dQ),
  5803. OFFSETOF(RsaKey, u)
  5804. #endif
  5805. #endif
  5806. };
  5807. /* Get a number from the RSA key based on an index.
  5808. *
  5809. * Order: { n, e, d, p, q, dP, dQ, u }
  5810. *
  5811. * Caller must ensure index is not invalid!
  5812. *
  5813. * @param [in] key RSA key object.
  5814. * @param [in] idx Index of number.
  5815. * @return A pointer to an mp_int when valid index.
  5816. * @return NULL when invalid index.
  5817. */
  5818. static mp_int* GetRsaInt(RsaKey* key, byte idx)
  5819. {
  5820. /* Cast key to byte array to and use offset to get to mp_int field. */
  5821. return (mp_int*)(((byte*)key) + rsaIntOffset[idx]);
  5822. }
  5823. #endif
  5824. #ifdef WOLFSSL_ASN_TEMPLATE
  5825. /* ASN.1 template for an RSA private key.
  5826. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  5827. */
  5828. static const ASNItem rsaKeyASN[] = {
  5829. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5830. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  5831. /* Integers need to be in this specific order
  5832. * as asn code depends on this. */
  5833. /* N */ { 1, ASN_INTEGER, 0, 0, 0 },
  5834. /* E */ { 1, ASN_INTEGER, 0, 0, 0 },
  5835. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  5836. /* D */ { 1, ASN_INTEGER, 0, 0, 0 },
  5837. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  5838. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  5839. /* DP */ { 1, ASN_INTEGER, 0, 0, 0 },
  5840. /* DQ */ { 1, ASN_INTEGER, 0, 0, 0 },
  5841. /* U */ { 1, ASN_INTEGER, 0, 0, 0 },
  5842. /* otherPrimeInfos OtherPrimeInfos OPTIONAL
  5843. * v2 - multiprime */
  5844. #endif
  5845. };
  5846. enum {
  5847. RSAKEYASN_IDX_SEQ = 0,
  5848. RSAKEYASN_IDX_VER,
  5849. /* Integers need to be in this specific order
  5850. * as asn code depends on this. */
  5851. RSAKEYASN_IDX_N,
  5852. RSAKEYASN_IDX_E,
  5853. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  5854. RSAKEYASN_IDX_D,
  5855. RSAKEYASN_IDX_P,
  5856. RSAKEYASN_IDX_Q,
  5857. RSAKEYASN_IDX_DP,
  5858. RSAKEYASN_IDX_DQ,
  5859. RSAKEYASN_IDX_U,
  5860. #endif
  5861. };
  5862. /* Number of items in ASN.1 template for an RSA private key. */
  5863. #define rsaKeyASN_Length (sizeof(rsaKeyASN) / sizeof(ASNItem))
  5864. #endif
  5865. /* Decode RSA private key.
  5866. *
  5867. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  5868. *
  5869. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  5870. * being extracted.
  5871. *
  5872. * @param [in] input Buffer holding BER encoded data.
  5873. * @param [in, out] inOutIdx On in, start of RSA private key.
  5874. * On out, start of ASN.1 item after RSA private key.
  5875. * @param [in, out] key RSA key object.
  5876. * @param [in] inSz Number of bytes in buffer.
  5877. * @return 0 on success.
  5878. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  5879. * is invalid.
  5880. * @return BUFFER_E when data in buffer is too small.
  5881. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  5882. * non-zero length.
  5883. * @return MP_INIT_E when the unable to initialize an mp_int.
  5884. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  5885. */
  5886. int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  5887. word32 inSz)
  5888. {
  5889. #ifndef WOLFSSL_ASN_TEMPLATE
  5890. int version, length;
  5891. word32 algId = 0;
  5892. if (inOutIdx == NULL || input == NULL || key == NULL) {
  5893. return BAD_FUNC_ARG;
  5894. }
  5895. /* if has pkcs8 header skip it */
  5896. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  5897. /* ignore error, did not have pkcs8 header */
  5898. }
  5899. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  5900. return ASN_PARSE_E;
  5901. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  5902. return ASN_PARSE_E;
  5903. key->type = RSA_PRIVATE;
  5904. #ifdef WOLFSSL_CHECK_MEM_ZERO
  5905. mp_memzero_add("Decode RSA key d", &key->d);
  5906. mp_memzero_add("Decode RSA key p", &key->p);
  5907. mp_memzero_add("Decode RSA key q", &key->q);
  5908. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  5909. !defined(RSA_LOW_MEM)) && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5910. mp_memzero_add("Decode RSA key dP", &key->dP);
  5911. mp_memzero_add("Decode RSA key dQ", &key->dQ);
  5912. mp_memzero_add("Decode RSA key u", &key->u);
  5913. #endif
  5914. #endif
  5915. if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
  5916. GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
  5917. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  5918. GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
  5919. GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  5920. GetInt(&key->q, input, inOutIdx, inSz) < 0
  5921. #else
  5922. SkipInt(input, inOutIdx, inSz) < 0 ||
  5923. SkipInt(input, inOutIdx, inSz) < 0 ||
  5924. SkipInt(input, inOutIdx, inSz) < 0
  5925. #endif
  5926. ) {
  5927. return ASN_RSA_KEY_E;
  5928. }
  5929. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)) \
  5930. && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5931. if (GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
  5932. GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
  5933. GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  5934. #else
  5935. if (SkipInt(input, inOutIdx, inSz) < 0 ||
  5936. SkipInt(input, inOutIdx, inSz) < 0 ||
  5937. SkipInt(input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  5938. #endif
  5939. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  5940. if (wc_InitRsaHw(key) != 0) {
  5941. return BAD_STATE_E;
  5942. }
  5943. #endif
  5944. return 0;
  5945. #else
  5946. DECL_ASNGETDATA(dataASN, rsaKeyASN_Length);
  5947. int ret = 0;
  5948. int i;
  5949. byte version = (byte)-1;
  5950. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  5951. word32 algId = 0;
  5952. #endif
  5953. /* Check validity of parameters. */
  5954. if (inOutIdx == NULL || input == NULL || key == NULL) {
  5955. ret = BAD_FUNC_ARG;
  5956. }
  5957. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  5958. if (ret == 0) {
  5959. /* if has pkcs8 header skip it */
  5960. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  5961. /* ignore error, did not have pkcs8 header */
  5962. }
  5963. }
  5964. #endif
  5965. CALLOC_ASNGETDATA(dataASN, rsaKeyASN_Length, ret, key->heap);
  5966. if (ret == 0) {
  5967. /* Register variable to hold version field. */
  5968. GetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], &version);
  5969. /* Setup data to store INTEGER data in mp_int's in RSA object. */
  5970. #if defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5971. /* Extract all public fields. */
  5972. for (i = 0; i < RSA_PUB_INTS; i++) {
  5973. GetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i], GetRsaInt(key, i));
  5974. }
  5975. /* Not extracting all data from BER encoding. */
  5976. #define RSA_ASN_COMPLETE 0
  5977. #else
  5978. /* Extract all private fields. */
  5979. for (i = 0; i < RSA_INTS; i++) {
  5980. GetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i], GetRsaInt(key, i));
  5981. }
  5982. /* Extracting all data from BER encoding. */
  5983. #define RSA_ASN_COMPLETE 1
  5984. #endif
  5985. /* Parse BER encoding for RSA private key. */
  5986. ret = GetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length,
  5987. RSA_ASN_COMPLETE, input, inOutIdx, inSz);
  5988. }
  5989. /* Check version: 0 - two prime, 1 - multi-prime
  5990. * Multi-prime has optional sequence after coefficient for extra primes.
  5991. * If extra primes, parsing will fail as not all the buffer was used.
  5992. */
  5993. if ((ret == 0) && (version > PKCS1v1)) {
  5994. ret = ASN_PARSE_E;
  5995. }
  5996. if (ret == 0) {
  5997. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5998. /* RSA key object has all private key values. */
  5999. key->type = RSA_PRIVATE;
  6000. #else
  6001. /* RSA key object has all public key values. */
  6002. key->type = RSA_PUBLIC;
  6003. #endif
  6004. #ifdef WOLFSSL_XILINX_CRYPT
  6005. if (wc_InitRsaHw(key) != 0)
  6006. ret = BAD_STATE_E;
  6007. #endif
  6008. }
  6009. FREE_ASNGETDATA(dataASN, key->heap);
  6010. return ret;
  6011. #endif /* WOLFSSL_ASN_TEMPLATE */
  6012. }
  6013. #endif /* HAVE_USER_RSA */
  6014. #endif /* NO_RSA */
  6015. #ifdef WOLFSSL_ASN_TEMPLATE
  6016. /* ASN.1 template for a PKCS #8 key.
  6017. * Ignoring optional attributes and public key.
  6018. * PKCS #8: RFC 5958, 2 - PrivateKeyInfo
  6019. */
  6020. static const ASNItem pkcs8KeyASN[] = {
  6021. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  6022. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  6023. /* PKEY_ALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  6024. /* PKEY_ALGO_OID_KEY */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  6025. /* PKEY_ALGO_OID_CURVE */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  6026. /* PKEY_ALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  6027. #ifdef WC_RSA_PSS
  6028. /* PKEY_ALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  6029. #endif
  6030. /* PKEY_DATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  6031. /* attributes [0] Attributes OPTIONAL */
  6032. /* [[2: publicKey [1] PublicKey OPTIONAL ]] */
  6033. };
  6034. enum {
  6035. PKCS8KEYASN_IDX_SEQ = 0,
  6036. PKCS8KEYASN_IDX_VER,
  6037. PKCS8KEYASN_IDX_PKEY_ALGO_SEQ,
  6038. PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY,
  6039. PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE,
  6040. PKCS8KEYASN_IDX_PKEY_ALGO_NULL,
  6041. #ifdef WC_RSA_PSS
  6042. PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ,
  6043. #endif
  6044. PKCS8KEYASN_IDX_PKEY_DATA,
  6045. };
  6046. /* Number of items in ASN.1 template for a PKCS #8 key. */
  6047. #define pkcs8KeyASN_Length (sizeof(pkcs8KeyASN) / sizeof(ASNItem))
  6048. #endif
  6049. /* Remove PKCS #8 header around an RSA, ECDSA, Ed25519, or Ed448.
  6050. *
  6051. * @param [in] input Buffer holding BER data.
  6052. * @param [in, out] inOutIdx On in, start of PKCS #8 encoding.
  6053. * On out, start of encoded key.
  6054. * @param [in] sz Size of data in buffer.
  6055. * @param [out] algId Key's algorithm id from PKCS #8 header.
  6056. * @return Length of key data on success.
  6057. * @return BAD_FUNC_ARG when input or inOutIdx is NULL.
  6058. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6059. * is invalid.
  6060. * @return BUFFER_E when data in buffer is too small.
  6061. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  6062. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6063. * non-zero length.
  6064. */
  6065. int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz,
  6066. word32* algId)
  6067. {
  6068. #ifndef WOLFSSL_ASN_TEMPLATE
  6069. word32 idx;
  6070. int version, length;
  6071. int ret;
  6072. byte tag;
  6073. if (input == NULL || inOutIdx == NULL)
  6074. return BAD_FUNC_ARG;
  6075. idx = *inOutIdx;
  6076. if (GetSequence(input, &idx, &length, sz) < 0)
  6077. return ASN_PARSE_E;
  6078. if (GetMyVersion(input, &idx, &version, sz) < 0)
  6079. return ASN_PARSE_E;
  6080. if (GetAlgoId(input, &idx, algId, oidKeyType, sz) < 0)
  6081. return ASN_PARSE_E;
  6082. if (GetASNTag(input, &idx, &tag, sz) < 0)
  6083. return ASN_PARSE_E;
  6084. idx = idx - 1; /* reset idx after finding tag */
  6085. #if defined(WC_RSA_PSS) && !defined(NO_RSA)
  6086. if (*algId == RSAPSSk && tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  6087. word32 seqIdx = idx;
  6088. int seqLen;
  6089. /* Not set when -1. */
  6090. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  6091. int mgf = -1;
  6092. int saltLen = 0;
  6093. if (GetSequence(input, &idx, &seqLen, sz) < 0) {
  6094. return ASN_PARSE_E;
  6095. }
  6096. /* Get the private key parameters. */
  6097. ret = DecodeRsaPssParams(input + seqIdx,
  6098. seqLen + idx - seqIdx, &hash, &mgf, &saltLen);
  6099. if (ret != 0) {
  6100. return ASN_PARSE_E;
  6101. }
  6102. /* TODO: store parameters so that usage can be checked. */
  6103. idx += seqLen;
  6104. }
  6105. #endif /* WC_RSA_PSS && !NO_RSA */
  6106. if (tag == ASN_OBJECT_ID) {
  6107. if (SkipObjectId(input, &idx, sz) < 0)
  6108. return ASN_PARSE_E;
  6109. }
  6110. ret = GetOctetString(input, &idx, &length, sz);
  6111. if (ret < 0) {
  6112. if (ret == BUFFER_E)
  6113. return ASN_PARSE_E;
  6114. /* Some private keys don't expect an octet string */
  6115. WOLFSSL_MSG("Couldn't find Octet string");
  6116. }
  6117. *inOutIdx = idx;
  6118. return length;
  6119. #else
  6120. DECL_ASNGETDATA(dataASN, pkcs8KeyASN_Length);
  6121. int ret = 0;
  6122. word32 oid = 9;
  6123. byte version;
  6124. word32 idx;
  6125. /* Check validity of parameters. */
  6126. if (input == NULL || inOutIdx == NULL) {
  6127. return BAD_FUNC_ARG;
  6128. }
  6129. idx = *inOutIdx;
  6130. CALLOC_ASNGETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  6131. if (ret == 0) {
  6132. /* Get version, check key type and curve type. */
  6133. GetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], &version);
  6134. GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], oidKeyType);
  6135. GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE], oidCurveType);
  6136. /* Parse data. */
  6137. ret = GetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, 1, input,
  6138. &idx, sz);
  6139. }
  6140. if (ret == 0) {
  6141. /* Key type OID. */
  6142. oid = dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY].data.oid.sum;
  6143. /* Version 1 includes an optional public key.
  6144. * If public key is included then the parsing will fail as it did not
  6145. * use all the data.
  6146. */
  6147. if (version > PKCS8v1) {
  6148. ret = ASN_PARSE_E;
  6149. }
  6150. }
  6151. if (ret == 0) {
  6152. switch (oid) {
  6153. #ifndef NO_RSA
  6154. case RSAk:
  6155. /* Must have NULL item but not OBJECT_ID item. */
  6156. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag == 0) ||
  6157. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6158. ret = ASN_PARSE_E;
  6159. }
  6160. break;
  6161. #ifdef WC_RSA_PSS
  6162. case RSAPSSk:
  6163. /* Must not have NULL item. */
  6164. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
  6165. ret = ASN_PARSE_E;
  6166. }
  6167. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].tag != 0) {
  6168. enum wc_HashType hash;
  6169. int mgf;
  6170. int saltLen;
  6171. const byte* params = GetASNItem_Addr(
  6172. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
  6173. word32 paramsSz = GetASNItem_Length(
  6174. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
  6175. /* Validate the private key parameters. */
  6176. ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf,
  6177. &saltLen);
  6178. if (ret != 0) {
  6179. return ASN_PARSE_E;
  6180. }
  6181. /* TODO: store parameters so that usage can be checked. */
  6182. }
  6183. break;
  6184. #endif
  6185. #endif
  6186. #ifdef HAVE_ECC
  6187. case ECDSAk:
  6188. /* Must not have NULL item. */
  6189. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
  6190. ret = ASN_PARSE_E;
  6191. }
  6192. break;
  6193. #endif
  6194. #ifdef HAVE_ED25519
  6195. case ED25519k:
  6196. /* Neither NULL item nor OBJECT_ID item allowed. */
  6197. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6198. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6199. ret = ASN_PARSE_E;
  6200. }
  6201. break;
  6202. #endif
  6203. #ifdef HAVE_CURVE25519
  6204. case X25519k:
  6205. /* Neither NULL item nor OBJECT_ID item allowed. */
  6206. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6207. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6208. ret = ASN_PARSE_E;
  6209. }
  6210. break;
  6211. #endif
  6212. #ifdef HAVE_ED448
  6213. case ED448k:
  6214. /* Neither NULL item nor OBJECT_ID item allowed. */
  6215. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6216. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6217. ret = ASN_PARSE_E;
  6218. }
  6219. break;
  6220. #endif
  6221. #ifdef HAVE_CURVE448
  6222. case X448k:
  6223. /* Neither NULL item nor OBJECT_ID item allowed. */
  6224. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6225. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6226. ret = ASN_PARSE_E;
  6227. }
  6228. break;
  6229. #endif
  6230. /* DSAk not supported. */
  6231. /* Falcon, Dilithium and Sphincs not supported. */
  6232. /* Ignore OID lookup failures. */
  6233. default:
  6234. break;
  6235. }
  6236. }
  6237. if (ret == 0) {
  6238. /* Return algorithm id of internal key. */
  6239. *algId = oid;
  6240. /* Return index to start of internal key. */
  6241. *inOutIdx = GetASNItem_DataIdx(dataASN[PKCS8KEYASN_IDX_PKEY_DATA], input);
  6242. /* Return value is length of internal key. */
  6243. ret = dataASN[PKCS8KEYASN_IDX_PKEY_DATA].data.ref.length;
  6244. }
  6245. FREE_ASNGETDATA(dataASN, NULL);
  6246. return ret;
  6247. #endif
  6248. }
  6249. /* TODO: test case */
  6250. int ToTraditionalInline(const byte* input, word32* inOutIdx, word32 sz)
  6251. {
  6252. word32 oid;
  6253. return ToTraditionalInline_ex(input, inOutIdx, sz, &oid);
  6254. }
  6255. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6256. /* Remove PKCS8 header, move beginning of traditional to beginning of input */
  6257. int ToTraditional_ex(byte* input, word32 sz, word32* algId)
  6258. {
  6259. word32 inOutIdx = 0;
  6260. int length;
  6261. if (input == NULL)
  6262. return BAD_FUNC_ARG;
  6263. length = ToTraditionalInline_ex(input, &inOutIdx, sz, algId);
  6264. if (length < 0)
  6265. return length;
  6266. if (length + inOutIdx > sz)
  6267. return BUFFER_E;
  6268. XMEMMOVE(input, input + inOutIdx, length);
  6269. return length;
  6270. }
  6271. int ToTraditional(byte* input, word32 sz)
  6272. {
  6273. word32 oid;
  6274. return ToTraditional_ex(input, sz, &oid);
  6275. }
  6276. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  6277. #if defined(HAVE_PKCS8) && !defined(NO_CERTS)
  6278. int wc_GetPkcs8TraditionalOffset(byte* input, word32* inOutIdx, word32 sz)
  6279. {
  6280. int length;
  6281. word32 algId;
  6282. if (input == NULL || inOutIdx == NULL || (*inOutIdx > sz))
  6283. return BAD_FUNC_ARG;
  6284. length = ToTraditionalInline_ex(input, inOutIdx, sz, &algId);
  6285. return length;
  6286. }
  6287. int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz,
  6288. int algoID, const byte* curveOID, word32 oidSz)
  6289. {
  6290. #ifndef WOLFSSL_ASN_TEMPLATE
  6291. word32 keyIdx = 0;
  6292. word32 tmpSz = 0;
  6293. word32 sz;
  6294. word32 tmpAlgId = 0;
  6295. /* If out is NULL then return the max size needed
  6296. * + 2 for ASN_OBJECT_ID and ASN_OCTET_STRING tags */
  6297. if (out == NULL && outSz != NULL) {
  6298. *outSz = keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6299. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2;
  6300. if (curveOID != NULL)
  6301. *outSz += oidSz + MAX_LENGTH_SZ + 1;
  6302. WOLFSSL_MSG("Checking size of PKCS8");
  6303. return LENGTH_ONLY_E;
  6304. }
  6305. WOLFSSL_ENTER("wc_CreatePKCS8Key()");
  6306. if (key == NULL || out == NULL || outSz == NULL) {
  6307. return BAD_FUNC_ARG;
  6308. }
  6309. /* check the buffer has enough room for largest possible size */
  6310. if (curveOID != NULL) {
  6311. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6312. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 3 + oidSz + MAX_LENGTH_SZ))
  6313. return BUFFER_E;
  6314. }
  6315. else {
  6316. oidSz = 0; /* with no curveOID oid size must be 0 */
  6317. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6318. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2))
  6319. return BUFFER_E;
  6320. }
  6321. /* sanity check: make sure the key doesn't already have a PKCS 8 header */
  6322. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  6323. (void)tmpAlgId;
  6324. return ASN_PARSE_E;
  6325. }
  6326. /* PrivateKeyInfo ::= SEQUENCE */
  6327. keyIdx = MAX_SEQ_SZ; /* save room for sequence */
  6328. /* version Version
  6329. * no header information just INTEGER */
  6330. sz = SetMyVersion(PKCS8v0, out + keyIdx, 0);
  6331. tmpSz += sz; keyIdx += sz;
  6332. /* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier */
  6333. sz = 0; /* set sz to 0 and get privateKey oid buffer size needed */
  6334. if (curveOID != NULL && oidSz > 0) {
  6335. byte buf[MAX_LENGTH_SZ];
  6336. sz = SetLength(oidSz, buf);
  6337. sz += 1; /* plus one for ASN object id */
  6338. }
  6339. sz = SetAlgoID(algoID, out + keyIdx, oidKeyType, oidSz + sz);
  6340. tmpSz += sz; keyIdx += sz;
  6341. /* privateKey PrivateKey *
  6342. * pkcs8 ecc uses slightly different format. Places curve oid in
  6343. * buffer */
  6344. if (curveOID != NULL && oidSz > 0) {
  6345. sz = SetObjectId(oidSz, out + keyIdx);
  6346. keyIdx += sz; tmpSz += sz;
  6347. XMEMCPY(out + keyIdx, curveOID, oidSz);
  6348. keyIdx += oidSz; tmpSz += oidSz;
  6349. }
  6350. sz = SetOctetString(keySz, out + keyIdx);
  6351. keyIdx += sz; tmpSz += sz;
  6352. XMEMCPY(out + keyIdx, key, keySz);
  6353. tmpSz += keySz;
  6354. /* attributes optional
  6355. * No attributes currently added */
  6356. /* rewind and add sequence */
  6357. sz = SetSequence(tmpSz, out);
  6358. XMEMMOVE(out + sz, out + MAX_SEQ_SZ, tmpSz);
  6359. *outSz = tmpSz + sz;
  6360. return tmpSz + sz;
  6361. #else
  6362. DECL_ASNSETDATA(dataASN, pkcs8KeyASN_Length);
  6363. int sz;
  6364. int ret = 0;
  6365. word32 keyIdx = 0;
  6366. word32 tmpAlgId = 0;
  6367. WOLFSSL_ENTER("wc_CreatePKCS8Key()");
  6368. /* Check validity of parameters. */
  6369. if (out == NULL && outSz != NULL) {
  6370. }
  6371. else if (key == NULL || out == NULL || outSz == NULL) {
  6372. ret = BAD_FUNC_ARG;
  6373. }
  6374. /* Sanity check: make sure key doesn't have PKCS #8 header. */
  6375. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  6376. (void)tmpAlgId;
  6377. ret = ASN_PARSE_E;
  6378. }
  6379. CALLOC_ASNSETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  6380. if (ret == 0) {
  6381. /* Only support default PKCS #8 format - v0. */
  6382. SetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], PKCS8v0);
  6383. /* Set key OID that corresponds to key data. */
  6384. SetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], algoID, oidKeyType);
  6385. if (curveOID != NULL && oidSz > 0) {
  6386. /* ECC key and curveOID set to write. */
  6387. SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE], curveOID, oidSz);
  6388. }
  6389. else {
  6390. /* EC curve OID to encode. */
  6391. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].noOut = 1;
  6392. }
  6393. /* Only RSA keys have NULL tagged item after OID. */
  6394. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].noOut = (algoID != RSAk);
  6395. #ifdef WC_RSA_PSS
  6396. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].noOut = 1;
  6397. #endif
  6398. /* Set key data to encode. */
  6399. SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_DATA], key, keySz);
  6400. /* Get the size of the DER encoding. */
  6401. ret = SizeASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, &sz);
  6402. }
  6403. if (ret == 0) {
  6404. /* Always return the calculated size. */
  6405. *outSz = sz;
  6406. }
  6407. /* Check for buffer to encoded into. */
  6408. if ((ret == 0) && (out == NULL)) {
  6409. WOLFSSL_MSG("Checking size of PKCS8");
  6410. ret = LENGTH_ONLY_E;
  6411. }
  6412. if (ret == 0) {
  6413. /* Encode PKCS #8 key into buffer. */
  6414. SetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, out);
  6415. ret = sz;
  6416. }
  6417. FREE_ASNSETDATA(dataASN, NULL);
  6418. return ret;
  6419. #endif /* WOLFSSL_ASN_TEMPLATE */
  6420. }
  6421. #endif /* HAVE_PKCS8 && !NO_CERTS */
  6422. #if defined(HAVE_PKCS12) || !defined(NO_CHECK_PRIVATE_KEY)
  6423. /* check that the private key is a pair for the public key
  6424. * return 1 (true) on match
  6425. * return 0 or negative value on failure/error
  6426. *
  6427. * privKey : buffer holding DER format private key
  6428. * privKeySz : size of private key buffer
  6429. * pubKey : buffer holding DER format public key
  6430. * pubKeySz : size of public key buffer
  6431. * ks : type of key */
  6432. int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz,
  6433. const byte* pubKey, word32 pubKeySz, enum Key_Sum ks)
  6434. {
  6435. int ret;
  6436. (void)privKeySz;
  6437. (void)pubKeySz;
  6438. (void)ks;
  6439. if (privKey == NULL || pubKey == NULL) {
  6440. return BAD_FUNC_ARG;
  6441. }
  6442. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  6443. /* test if RSA key */
  6444. if (ks == RSAk
  6445. #ifdef WC_RSA_PSS
  6446. || ks == RSAPSSk
  6447. #endif
  6448. ) {
  6449. #ifdef WOLFSSL_SMALL_STACK
  6450. RsaKey* a;
  6451. RsaKey* b = NULL;
  6452. #else
  6453. RsaKey a[1], b[1];
  6454. #endif
  6455. word32 keyIdx = 0;
  6456. #ifdef WOLFSSL_SMALL_STACK
  6457. a = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  6458. if (a == NULL)
  6459. return MEMORY_E;
  6460. b = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  6461. if (b == NULL) {
  6462. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6463. return MEMORY_E;
  6464. }
  6465. #endif
  6466. if ((ret = wc_InitRsaKey(a, NULL)) < 0) {
  6467. #ifdef WOLFSSL_SMALL_STACK
  6468. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6469. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6470. #endif
  6471. return ret;
  6472. }
  6473. if ((ret = wc_InitRsaKey(b, NULL)) < 0) {
  6474. wc_FreeRsaKey(a);
  6475. #ifdef WOLFSSL_SMALL_STACK
  6476. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6477. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6478. #endif
  6479. return ret;
  6480. }
  6481. if ((ret = wc_RsaPrivateKeyDecode(privKey, &keyIdx, a, privKeySz)) == 0) {
  6482. WOLFSSL_MSG("Checking RSA key pair");
  6483. keyIdx = 0; /* reset to 0 for parsing public key */
  6484. if ((ret = wc_RsaPublicKeyDecode(pubKey, &keyIdx, b,
  6485. pubKeySz)) == 0) {
  6486. /* limit for user RSA crypto because of RsaKey
  6487. * dereference. */
  6488. #if defined(HAVE_USER_RSA)
  6489. WOLFSSL_MSG("Cannot verify RSA pair with user RSA");
  6490. ret = 1; /* return first RSA cert as match */
  6491. #else
  6492. /* both keys extracted successfully now check n and e
  6493. * values are the same. This is dereferencing RsaKey */
  6494. if (mp_cmp(&(a->n), &(b->n)) != MP_EQ ||
  6495. mp_cmp(&(a->e), &(b->e)) != MP_EQ) {
  6496. ret = MP_CMP_E;
  6497. WOLFSSL_ERROR_VERBOSE(ret);
  6498. }
  6499. else
  6500. ret = 1;
  6501. #endif
  6502. }
  6503. else {
  6504. WOLFSSL_ERROR_VERBOSE(ret);
  6505. }
  6506. }
  6507. wc_FreeRsaKey(b);
  6508. wc_FreeRsaKey(a);
  6509. #ifdef WOLFSSL_SMALL_STACK
  6510. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6511. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6512. #endif
  6513. }
  6514. else
  6515. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  6516. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  6517. if (ks == ECDSAk) {
  6518. #ifdef WOLFSSL_SMALL_STACK
  6519. ecc_key* key_pair;
  6520. byte* privDer;
  6521. #else
  6522. ecc_key key_pair[1];
  6523. byte privDer[MAX_ECC_BYTES];
  6524. #endif
  6525. word32 privSz = MAX_ECC_BYTES;
  6526. word32 keyIdx = 0;
  6527. #ifdef WOLFSSL_SMALL_STACK
  6528. key_pair = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL, DYNAMIC_TYPE_ECC);
  6529. if (key_pair == NULL)
  6530. return MEMORY_E;
  6531. privDer = (byte*)XMALLOC(MAX_ECC_BYTES, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6532. if (privDer == NULL) {
  6533. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6534. return MEMORY_E;
  6535. }
  6536. #endif
  6537. if ((ret = wc_ecc_init(key_pair)) < 0) {
  6538. #ifdef WOLFSSL_SMALL_STACK
  6539. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6540. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6541. #endif
  6542. return ret;
  6543. }
  6544. if ((ret = wc_EccPrivateKeyDecode(privKey, &keyIdx, key_pair,
  6545. privKeySz)) == 0) {
  6546. WOLFSSL_MSG("Checking ECC key pair");
  6547. if ((ret = wc_ecc_export_private_only(key_pair, privDer, &privSz))
  6548. == 0) {
  6549. #ifdef WOLFSSL_CHECK_MEM_ZERO
  6550. wc_MemZero_Add("wc_CheckPrivateKey privDer", privDer, privSz);
  6551. #endif
  6552. wc_ecc_free(key_pair);
  6553. ret = wc_ecc_init(key_pair);
  6554. if (ret == 0) {
  6555. ret = wc_ecc_import_private_key(privDer,
  6556. privSz, pubKey,
  6557. pubKeySz, key_pair);
  6558. }
  6559. /* public and private extracted successfully now check if is
  6560. * a pair and also do sanity checks on key. wc_ecc_check_key
  6561. * checks that private * base generator equals pubkey */
  6562. if (ret == 0) {
  6563. if ((ret = wc_ecc_check_key(key_pair)) == 0) {
  6564. ret = 1;
  6565. }
  6566. else {
  6567. WOLFSSL_ERROR_VERBOSE(ret);
  6568. }
  6569. }
  6570. ForceZero(privDer, privSz);
  6571. }
  6572. }
  6573. else {
  6574. WOLFSSL_ERROR_VERBOSE(ret);
  6575. }
  6576. wc_ecc_free(key_pair);
  6577. #ifdef WOLFSSL_SMALL_STACK
  6578. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6579. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6580. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  6581. wc_MemZero_Check(privDer, MAX_ECC_BYTES);
  6582. #endif
  6583. }
  6584. else
  6585. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  6586. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  6587. if (ks == ED25519k) {
  6588. #ifdef WOLFSSL_SMALL_STACK
  6589. ed25519_key* key_pair;
  6590. #else
  6591. ed25519_key key_pair[1];
  6592. #endif
  6593. word32 keyIdx = 0;
  6594. #ifdef WOLFSSL_SMALL_STACK
  6595. key_pair = (ed25519_key*)XMALLOC(sizeof(ed25519_key), NULL,
  6596. DYNAMIC_TYPE_ED25519);
  6597. if (key_pair == NULL)
  6598. return MEMORY_E;
  6599. #endif
  6600. if ((ret = wc_ed25519_init(key_pair)) < 0) {
  6601. #ifdef WOLFSSL_SMALL_STACK
  6602. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  6603. #endif
  6604. return ret;
  6605. }
  6606. if ((ret = wc_Ed25519PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6607. privKeySz)) == 0) {
  6608. WOLFSSL_MSG("Checking ED25519 key pair");
  6609. keyIdx = 0;
  6610. if ((ret = wc_ed25519_import_public(pubKey, pubKeySz,
  6611. key_pair)) == 0) {
  6612. /* public and private extracted successfully no check if is
  6613. * a pair and also do sanity checks on key. wc_ecc_check_key
  6614. * checks that private * base generator equals pubkey */
  6615. if ((ret = wc_ed25519_check_key(key_pair)) == 0) {
  6616. ret = 1;
  6617. }
  6618. else {
  6619. WOLFSSL_ERROR_VERBOSE(ret);
  6620. }
  6621. }
  6622. }
  6623. else {
  6624. WOLFSSL_ERROR_VERBOSE(ret);
  6625. }
  6626. wc_ed25519_free(key_pair);
  6627. #ifdef WOLFSSL_SMALL_STACK
  6628. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  6629. #endif
  6630. }
  6631. else
  6632. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  6633. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  6634. if (ks == ED448k) {
  6635. #ifdef WOLFSSL_SMALL_STACK
  6636. ed448_key* key_pair = NULL;
  6637. #else
  6638. ed448_key key_pair[1];
  6639. #endif
  6640. word32 keyIdx = 0;
  6641. #ifdef WOLFSSL_SMALL_STACK
  6642. key_pair = (ed448_key*)XMALLOC(sizeof(ed448_key), NULL,
  6643. DYNAMIC_TYPE_ED448);
  6644. if (key_pair == NULL)
  6645. return MEMORY_E;
  6646. #endif
  6647. if ((ret = wc_ed448_init(key_pair)) < 0) {
  6648. #ifdef WOLFSSL_SMALL_STACK
  6649. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  6650. #endif
  6651. return ret;
  6652. }
  6653. if ((ret = wc_Ed448PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6654. privKeySz)) == 0) {
  6655. WOLFSSL_MSG("Checking ED448 key pair");
  6656. keyIdx = 0;
  6657. if ((ret = wc_ed448_import_public(pubKey, pubKeySz,
  6658. key_pair)) == 0) {
  6659. /* public and private extracted successfully no check if is
  6660. * a pair and also do sanity checks on key. wc_ecc_check_key
  6661. * checks that private * base generator equals pubkey */
  6662. if ((ret = wc_ed448_check_key(key_pair)) == 0) {
  6663. ret = 1;
  6664. }
  6665. else {
  6666. WOLFSSL_ERROR_VERBOSE(ret);
  6667. }
  6668. }
  6669. }
  6670. else {
  6671. WOLFSSL_ERROR_VERBOSE(ret);
  6672. }
  6673. wc_ed448_free(key_pair);
  6674. #ifdef WOLFSSL_SMALL_STACK
  6675. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  6676. #endif
  6677. }
  6678. else
  6679. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  6680. #if defined(HAVE_PQC)
  6681. #if defined(HAVE_FALCON)
  6682. if ((ks == FALCON_LEVEL1k) || (ks == FALCON_LEVEL5k)) {
  6683. #ifdef WOLFSSL_SMALL_STACK
  6684. falcon_key* key_pair = NULL;
  6685. #else
  6686. falcon_key key_pair[1];
  6687. #endif
  6688. word32 keyIdx = 0;
  6689. #ifdef WOLFSSL_SMALL_STACK
  6690. key_pair = (falcon_key*)XMALLOC(sizeof(falcon_key), NULL,
  6691. DYNAMIC_TYPE_FALCON);
  6692. if (key_pair == NULL)
  6693. return MEMORY_E;
  6694. #endif
  6695. ret = wc_falcon_init(key_pair);
  6696. if (ret < 0) {
  6697. #ifdef WOLFSSL_SMALL_STACK
  6698. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6699. #endif
  6700. return ret;
  6701. }
  6702. if (ks == FALCON_LEVEL1k) {
  6703. ret = wc_falcon_set_level(key_pair, 1);
  6704. }
  6705. else if (ks == FALCON_LEVEL5k) {
  6706. ret = wc_falcon_set_level(key_pair, 5);
  6707. }
  6708. if (ret < 0) {
  6709. #ifdef WOLFSSL_SMALL_STACK
  6710. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6711. #endif
  6712. return ret;
  6713. }
  6714. if ((ret = wc_Falcon_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6715. privKeySz)) == 0) {
  6716. WOLFSSL_MSG("Checking Falcon key pair");
  6717. keyIdx = 0;
  6718. if ((ret = wc_falcon_import_public(pubKey, pubKeySz,
  6719. key_pair)) == 0) {
  6720. /* Public and private extracted successfully. Sanity check. */
  6721. if ((ret = wc_falcon_check_key(key_pair)) == 0) {
  6722. ret = 1;
  6723. }
  6724. else {
  6725. WOLFSSL_ERROR_VERBOSE(ret);
  6726. }
  6727. }
  6728. }
  6729. else {
  6730. WOLFSSL_ERROR_VERBOSE(ret);
  6731. }
  6732. wc_falcon_free(key_pair);
  6733. #ifdef WOLFSSL_SMALL_STACK
  6734. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6735. #endif
  6736. }
  6737. else
  6738. #endif /* HAVE_FALCON */
  6739. #if defined(HAVE_DILITHIUM)
  6740. if ((ks == DILITHIUM_LEVEL2k) ||
  6741. (ks == DILITHIUM_LEVEL3k) ||
  6742. (ks == DILITHIUM_LEVEL5k) ||
  6743. (ks == DILITHIUM_AES_LEVEL2k) ||
  6744. (ks == DILITHIUM_AES_LEVEL3k) ||
  6745. (ks == DILITHIUM_AES_LEVEL5k)) {
  6746. #ifdef WOLFSSL_SMALL_STACK
  6747. dilithium_key* key_pair = NULL;
  6748. #else
  6749. dilithium_key key_pair[1];
  6750. #endif
  6751. word32 keyIdx = 0;
  6752. #ifdef WOLFSSL_SMALL_STACK
  6753. key_pair = (dilithium_key*)XMALLOC(sizeof(dilithium_key), NULL,
  6754. DYNAMIC_TYPE_DILITHIUM);
  6755. if (key_pair == NULL)
  6756. return MEMORY_E;
  6757. #endif
  6758. ret = wc_dilithium_init(key_pair);
  6759. if (ret < 0) {
  6760. #ifdef WOLFSSL_SMALL_STACK
  6761. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6762. #endif
  6763. return ret;
  6764. }
  6765. if (ks == DILITHIUM_LEVEL2k) {
  6766. ret = wc_dilithium_set_level_and_sym(key_pair, 2, SHAKE_VARIANT);
  6767. }
  6768. else if (ks == DILITHIUM_LEVEL3k) {
  6769. ret = wc_dilithium_set_level_and_sym(key_pair, 3, SHAKE_VARIANT);
  6770. }
  6771. else if (ks == DILITHIUM_LEVEL5k) {
  6772. ret = wc_dilithium_set_level_and_sym(key_pair, 5, SHAKE_VARIANT);
  6773. }
  6774. else if (ks == DILITHIUM_AES_LEVEL2k) {
  6775. ret = wc_dilithium_set_level_and_sym(key_pair, 2, AES_VARIANT);
  6776. }
  6777. else if (ks == DILITHIUM_AES_LEVEL3k) {
  6778. ret = wc_dilithium_set_level_and_sym(key_pair, 3, AES_VARIANT);
  6779. }
  6780. else if (ks == DILITHIUM_AES_LEVEL5k) {
  6781. ret = wc_dilithium_set_level_and_sym(key_pair, 5, AES_VARIANT);
  6782. }
  6783. if (ret < 0) {
  6784. #ifdef WOLFSSL_SMALL_STACK
  6785. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6786. #endif
  6787. return ret;
  6788. }
  6789. if ((ret = wc_Dilithium_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6790. privKeySz)) == 0) {
  6791. WOLFSSL_MSG("Checking Dilithium key pair");
  6792. keyIdx = 0;
  6793. if ((ret = wc_dilithium_import_public(pubKey, pubKeySz,
  6794. key_pair)) == 0) {
  6795. /* Public and private extracted successfully. Sanity check. */
  6796. if ((ret = wc_dilithium_check_key(key_pair)) == 0)
  6797. ret = 1;
  6798. }
  6799. }
  6800. wc_dilithium_free(key_pair);
  6801. #ifdef WOLFSSL_SMALL_STACK
  6802. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6803. #endif
  6804. }
  6805. else
  6806. #endif /* HAVE_DILITHIUM */
  6807. #if defined(HAVE_SPHINCS)
  6808. if ((ks == SPHINCS_FAST_LEVEL1k) ||
  6809. (ks == SPHINCS_FAST_LEVEL3k) ||
  6810. (ks == SPHINCS_FAST_LEVEL5k) ||
  6811. (ks == SPHINCS_SMALL_LEVEL1k) ||
  6812. (ks == SPHINCS_SMALL_LEVEL3k) ||
  6813. (ks == SPHINCS_SMALL_LEVEL5k)) {
  6814. #ifdef WOLFSSL_SMALL_STACK
  6815. sphincs_key* key_pair = NULL;
  6816. #else
  6817. sphincs_key key_pair[1];
  6818. #endif
  6819. word32 keyIdx = 0;
  6820. #ifdef WOLFSSL_SMALL_STACK
  6821. key_pair = (sphincs_key*)XMALLOC(sizeof(sphincs_key), NULL,
  6822. DYNAMIC_TYPE_SPHINCS);
  6823. if (key_pair == NULL)
  6824. return MEMORY_E;
  6825. #endif
  6826. ret = wc_sphincs_init(key_pair);
  6827. if (ret < 0) {
  6828. #ifdef WOLFSSL_SMALL_STACK
  6829. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6830. #endif
  6831. return ret;
  6832. }
  6833. if (ks == SPHINCS_FAST_LEVEL1k) {
  6834. ret = wc_sphincs_set_level_and_optim(key_pair, 1, FAST_VARIANT);
  6835. }
  6836. else if (ks == SPHINCS_FAST_LEVEL3k) {
  6837. ret = wc_sphincs_set_level_and_optim(key_pair, 3, FAST_VARIANT);
  6838. }
  6839. else if (ks == SPHINCS_FAST_LEVEL5k) {
  6840. ret = wc_sphincs_set_level_and_optim(key_pair, 5, FAST_VARIANT);
  6841. }
  6842. else if (ks == SPHINCS_SMALL_LEVEL1k) {
  6843. ret = wc_sphincs_set_level_and_optim(key_pair, 1, SMALL_VARIANT);
  6844. }
  6845. else if (ks == SPHINCS_SMALL_LEVEL3k) {
  6846. ret = wc_sphincs_set_level_and_optim(key_pair, 3, SMALL_VARIANT);
  6847. }
  6848. else if (ks == SPHINCS_SMALL_LEVEL5k) {
  6849. ret = wc_sphincs_set_level_and_optim(key_pair, 5, SMALL_VARIANT);
  6850. }
  6851. if (ret < 0) {
  6852. #ifdef WOLFSSL_SMALL_STACK
  6853. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6854. #endif
  6855. return ret;
  6856. }
  6857. if ((ret = wc_Sphincs_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6858. privKeySz)) == 0) {
  6859. WOLFSSL_MSG("Checking Sphincs key pair");
  6860. keyIdx = 0;
  6861. if ((ret = wc_sphincs_import_public(pubKey, pubKeySz,
  6862. key_pair)) == 0) {
  6863. /* Public and private extracted successfully. Sanity check. */
  6864. if ((ret = wc_sphincs_check_key(key_pair)) == 0)
  6865. ret = 1;
  6866. }
  6867. }
  6868. wc_sphincs_free(key_pair);
  6869. #ifdef WOLFSSL_SMALL_STACK
  6870. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6871. #endif
  6872. }
  6873. else
  6874. #endif /* HAVE_SPHINCS */
  6875. #endif /* HAVE_PQC */
  6876. {
  6877. ret = 0;
  6878. }
  6879. (void)ks;
  6880. return ret;
  6881. }
  6882. /* check that the private key is a pair for the public key in certificate
  6883. * return 1 (true) on match
  6884. * return 0 or negative value on failure/error
  6885. *
  6886. * key : buffer holding DER format key
  6887. * keySz : size of key buffer
  6888. * der : a initialized and parsed DecodedCert holding a certificate */
  6889. int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der)
  6890. {
  6891. if (key == NULL || der == NULL) {
  6892. return BAD_FUNC_ARG;
  6893. }
  6894. return wc_CheckPrivateKey(key, keySz, der->publicKey,
  6895. der->pubKeySize, (enum Key_Sum) der->keyOID);
  6896. }
  6897. #endif /* HAVE_PKCS12 || !NO_CHECK_PRIVATE_KEY */
  6898. #ifndef NO_PWDBASED
  6899. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6900. /* Check the PBE algorithm is supported and return wolfSSL id, version and block
  6901. * size of encryption algorithm.
  6902. *
  6903. * When PBES2, version is PKCS5v2, CheckAlgoV2() must be called to get id and
  6904. * blockSz based on encryption algorithm.
  6905. *
  6906. * @param [in] first First byte of OID to use in check.
  6907. * @param [in] second Second byte of OID to use in check.
  6908. * @param [out] id wolfSSL id for PBE algorithm.
  6909. * @param [out] version Version of PBE OID:
  6910. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  6911. * @param [out] blockSz Block size of encryption algorithm.
  6912. * @return 0 on success.
  6913. * @return ALGO_ID_E when OID not supported.
  6914. * @return ASN_INPUT_E when first byte is invalid.
  6915. */
  6916. static int CheckAlgo(int first, int second, int* id, int* version, int* blockSz)
  6917. {
  6918. int ret = 0;
  6919. (void)id;
  6920. (void)blockSz;
  6921. *version = -1;
  6922. /* pkcs-12 1 = pkcs-12PbeIds */
  6923. if (first == 1) {
  6924. /* PKCS #12: Appendix C */
  6925. switch (second) {
  6926. #if !defined(NO_SHA)
  6927. #ifndef NO_RC4
  6928. case PBE_SHA1_RC4_128:
  6929. *id = PBE_SHA1_RC4_128;
  6930. *version = PKCS12v1;
  6931. if (blockSz != NULL) {
  6932. *blockSz = 1;
  6933. }
  6934. break;
  6935. #endif
  6936. #ifndef NO_DES3
  6937. case PBE_SHA1_DES3:
  6938. *id = PBE_SHA1_DES3;
  6939. *version = PKCS12v1;
  6940. if (blockSz != NULL) {
  6941. *blockSz = DES_BLOCK_SIZE;
  6942. }
  6943. break;
  6944. #endif
  6945. #ifdef WC_RC2
  6946. case PBE_SHA1_40RC2_CBC:
  6947. *id = PBE_SHA1_40RC2_CBC;
  6948. *version = PKCS12v1;
  6949. if (blockSz != NULL) {
  6950. *blockSz = RC2_BLOCK_SIZE;
  6951. }
  6952. break;
  6953. #endif
  6954. #endif /* !NO_SHA */
  6955. default:
  6956. ret = ALGO_ID_E;
  6957. break;
  6958. }
  6959. }
  6960. else if (first != PKCS5) {
  6961. /* Bad OID. */
  6962. ret = ASN_INPUT_E;
  6963. }
  6964. /* PKCS #5 PBES2: Appendix A.4
  6965. * pkcs-5 13 = id-PBES2 */
  6966. else if (second == PBES2) {
  6967. *version = PKCS5v2;
  6968. /* Id and block size come from CheckAlgoV2() */
  6969. }
  6970. else {
  6971. /* PKCS #5 PBES1: Appendix A.3 */
  6972. /* see RFC 2898 for ids */
  6973. switch (second) {
  6974. #ifndef NO_DES3
  6975. #ifndef NO_MD5
  6976. case PBES1_MD5_DES:
  6977. *id = PBE_MD5_DES;
  6978. *version = PKCS5;
  6979. if (blockSz != NULL) {
  6980. *blockSz = DES_BLOCK_SIZE;
  6981. }
  6982. break;
  6983. #endif
  6984. #ifndef NO_SHA
  6985. case PBES1_SHA1_DES:
  6986. *id = PBE_SHA1_DES;
  6987. *version = PKCS5;
  6988. if (blockSz != NULL) {
  6989. *blockSz = DES_BLOCK_SIZE;
  6990. }
  6991. break;
  6992. #endif
  6993. #endif /* !NO_DES3 */
  6994. default:
  6995. ret = ALGO_ID_E;
  6996. break;
  6997. }
  6998. }
  6999. /* Return error code. */
  7000. return ret;
  7001. }
  7002. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7003. #ifdef HAVE_PKCS8
  7004. /* Check the encryption algorithm with PBES2 is supported and return block size
  7005. * and wolfSSL id for the PBE.
  7006. *
  7007. * @param [in] oid Encryption algorithm OID id.
  7008. * @param [out] id wolfSSL id for PBE algorithm.
  7009. * @param [out] version Version of PBE OID:
  7010. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  7011. * @return 0 on success.
  7012. * @return ALGO_ID_E when encryption algorithm is not supported with PBES2.
  7013. */
  7014. static int CheckAlgoV2(int oid, int* id, int* blockSz)
  7015. {
  7016. int ret = 0;
  7017. (void)id;
  7018. (void)blockSz;
  7019. switch (oid) {
  7020. #if !defined(NO_DES3) && !defined(NO_SHA)
  7021. case DESb:
  7022. *id = PBE_SHA1_DES;
  7023. if (blockSz != NULL) {
  7024. *blockSz = DES_BLOCK_SIZE;
  7025. }
  7026. break;
  7027. case DES3b:
  7028. *id = PBE_SHA1_DES3;
  7029. if (blockSz != NULL) {
  7030. *blockSz = DES_BLOCK_SIZE;
  7031. }
  7032. break;
  7033. #endif
  7034. #ifdef WOLFSSL_AES_256
  7035. case AES256CBCb:
  7036. *id = PBE_AES256_CBC;
  7037. if (blockSz != NULL) {
  7038. *blockSz = AES_BLOCK_SIZE;
  7039. }
  7040. break;
  7041. #endif
  7042. #ifdef WOLFSSL_AES_128
  7043. case AES128CBCb:
  7044. *id = PBE_AES128_CBC;
  7045. if (blockSz != NULL) {
  7046. *blockSz = AES_BLOCK_SIZE;
  7047. }
  7048. break;
  7049. #endif
  7050. default:
  7051. WOLFSSL_MSG("No PKCS v2 algo found");
  7052. ret = ALGO_ID_E;
  7053. break;
  7054. }
  7055. /* Return error code. */
  7056. return ret;
  7057. }
  7058. #endif /* HAVE_PKCS8 */
  7059. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7060. int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz,
  7061. int* algoID, void* heap)
  7062. {
  7063. word32 tmpIdx = 0;
  7064. if (key == NULL || algoID == NULL)
  7065. return BAD_FUNC_ARG;
  7066. *algoID = 0;
  7067. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  7068. {
  7069. RsaKey *rsa = (RsaKey *)XMALLOC(sizeof *rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7070. if (rsa == NULL)
  7071. return MEMORY_E;
  7072. wc_InitRsaKey(rsa, heap);
  7073. if (wc_RsaPrivateKeyDecode(key, &tmpIdx, rsa, keySz) == 0) {
  7074. *algoID = RSAk;
  7075. }
  7076. else {
  7077. WOLFSSL_MSG("Not RSA DER key");
  7078. }
  7079. wc_FreeRsaKey(rsa);
  7080. XFREE(rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7081. }
  7082. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  7083. #if defined(HAVE_ECC) && !defined(NO_ASN_CRYPT)
  7084. if (*algoID == 0) {
  7085. ecc_key *ecc = (ecc_key *)XMALLOC(sizeof *ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7086. if (ecc == NULL)
  7087. return MEMORY_E;
  7088. tmpIdx = 0;
  7089. wc_ecc_init_ex(ecc, heap, INVALID_DEVID);
  7090. if (wc_EccPrivateKeyDecode(key, &tmpIdx, ecc, keySz) == 0) {
  7091. *algoID = ECDSAk;
  7092. /* now find oid */
  7093. if (wc_ecc_get_oid(ecc->dp->oidSum, curveOID, oidSz) < 0) {
  7094. WOLFSSL_MSG("Error getting ECC curve OID");
  7095. wc_ecc_free(ecc);
  7096. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7097. return BAD_FUNC_ARG;
  7098. }
  7099. }
  7100. else {
  7101. WOLFSSL_MSG("Not ECC DER key either");
  7102. }
  7103. wc_ecc_free(ecc);
  7104. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7105. }
  7106. #endif /* HAVE_ECC && !NO_ASN_CRYPT */
  7107. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  7108. if (*algoID == 0) {
  7109. ed25519_key *ed25519 = (ed25519_key *)XMALLOC(sizeof *ed25519, heap,
  7110. DYNAMIC_TYPE_TMP_BUFFER);
  7111. if (ed25519 == NULL)
  7112. return MEMORY_E;
  7113. tmpIdx = 0;
  7114. if (wc_ed25519_init_ex(ed25519, heap, INVALID_DEVID) == 0) {
  7115. if (wc_Ed25519PrivateKeyDecode(key, &tmpIdx, ed25519, keySz) == 0) {
  7116. *algoID = ED25519k;
  7117. }
  7118. else {
  7119. WOLFSSL_MSG("Not ED25519 DER key");
  7120. }
  7121. wc_ed25519_free(ed25519);
  7122. }
  7123. else {
  7124. WOLFSSL_MSG("GetKeyOID wc_ed25519_init failed");
  7125. }
  7126. XFREE(ed25519, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7127. }
  7128. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  7129. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  7130. if (*algoID == 0) {
  7131. ed448_key *ed448 = (ed448_key *)XMALLOC(sizeof *ed448, heap,
  7132. DYNAMIC_TYPE_TMP_BUFFER);
  7133. if (ed448 == NULL)
  7134. return MEMORY_E;
  7135. tmpIdx = 0;
  7136. if (wc_ed448_init(ed448) == 0) {
  7137. if (wc_Ed448PrivateKeyDecode(key, &tmpIdx, ed448, keySz) == 0) {
  7138. *algoID = ED448k;
  7139. }
  7140. else {
  7141. WOLFSSL_MSG("Not ED448 DER key");
  7142. }
  7143. wc_ed448_free(ed448);
  7144. }
  7145. else {
  7146. WOLFSSL_MSG("GetKeyOID wc_ed448_init failed");
  7147. }
  7148. XFREE(ed448, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7149. }
  7150. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  7151. #if defined(HAVE_PQC)
  7152. #if defined(HAVE_FALCON)
  7153. if (*algoID == 0) {
  7154. falcon_key *falcon = (falcon_key *)XMALLOC(sizeof(*falcon), heap,
  7155. DYNAMIC_TYPE_TMP_BUFFER);
  7156. if (falcon == NULL)
  7157. return MEMORY_E;
  7158. if (wc_falcon_init(falcon) != 0) {
  7159. tmpIdx = 0;
  7160. if (wc_falcon_set_level(falcon, 1) == 0) {
  7161. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  7162. == 0) {
  7163. *algoID = FALCON_LEVEL1k;
  7164. }
  7165. else {
  7166. WOLFSSL_MSG("Not Falcon Level 1 DER key");
  7167. }
  7168. }
  7169. else if (wc_falcon_set_level(falcon, 5) == 0) {
  7170. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  7171. == 0) {
  7172. *algoID = FALCON_LEVEL5k;
  7173. }
  7174. else {
  7175. WOLFSSL_MSG("Not Falcon Level 5 DER key");
  7176. }
  7177. }
  7178. else {
  7179. WOLFSSL_MSG("GetKeyOID falcon initialization failed");
  7180. }
  7181. wc_falcon_free(falcon);
  7182. }
  7183. XFREE(falcon, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7184. }
  7185. #endif /* HAVE_FALCON */
  7186. #if defined(HAVE_DILITHIUM)
  7187. if (*algoID == 0) {
  7188. dilithium_key *dilithium = (dilithium_key *)XMALLOC(sizeof(*dilithium),
  7189. heap, DYNAMIC_TYPE_TMP_BUFFER);
  7190. if (dilithium == NULL)
  7191. return MEMORY_E;
  7192. if (wc_dilithium_init(dilithium) != 0) {
  7193. tmpIdx = 0;
  7194. if (wc_dilithium_set_level_and_sym(dilithium, 2, SHAKE_VARIANT)
  7195. == 0) {
  7196. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7197. keySz) == 0) {
  7198. *algoID = DILITHIUM_LEVEL2k;
  7199. }
  7200. else {
  7201. WOLFSSL_MSG("Not Dilithium Level 2 DER key");
  7202. }
  7203. }
  7204. else if (wc_dilithium_set_level_and_sym(dilithium, 3, SHAKE_VARIANT)
  7205. == 0) {
  7206. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7207. keySz) == 0) {
  7208. *algoID = DILITHIUM_LEVEL3k;
  7209. }
  7210. else {
  7211. WOLFSSL_MSG("Not Dilithium Level 3 DER key");
  7212. }
  7213. }
  7214. else if (wc_dilithium_set_level_and_sym(dilithium, 5, SHAKE_VARIANT)
  7215. == 0) {
  7216. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7217. keySz) == 0) {
  7218. *algoID = DILITHIUM_LEVEL5k;
  7219. }
  7220. else {
  7221. WOLFSSL_MSG("Not Dilithium Level 5 DER key");
  7222. }
  7223. }
  7224. else if (wc_dilithium_set_level_and_sym(dilithium, 2, AES_VARIANT)
  7225. == 0) {
  7226. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7227. keySz) == 0) {
  7228. *algoID = DILITHIUM_AES_LEVEL2k;
  7229. }
  7230. else {
  7231. WOLFSSL_MSG("Not Dilithium AES Level 2 DER key");
  7232. }
  7233. }
  7234. else if (wc_dilithium_set_level_and_sym(dilithium, 3, AES_VARIANT)
  7235. == 0) {
  7236. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7237. keySz) == 0) {
  7238. *algoID = DILITHIUM_AES_LEVEL3k;
  7239. }
  7240. else {
  7241. WOLFSSL_MSG("Not Dilithium AES Level 3 DER key");
  7242. }
  7243. }
  7244. else if (wc_dilithium_set_level_and_sym(dilithium, 5, AES_VARIANT)
  7245. == 0) {
  7246. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7247. keySz) == 0) {
  7248. *algoID = DILITHIUM_AES_LEVEL5k;
  7249. }
  7250. else {
  7251. WOLFSSL_MSG("Not Dilithium AES Level 5 DER key");
  7252. }
  7253. }
  7254. else {
  7255. WOLFSSL_MSG("GetKeyOID dilithium initialization failed");
  7256. }
  7257. wc_dilithium_free(dilithium);
  7258. }
  7259. XFREE(dilithium, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7260. }
  7261. #endif /* HAVE_DILITHIUM */
  7262. #if defined(HAVE_SPHINCS)
  7263. if (*algoID == 0) {
  7264. sphincs_key *sphincs = (sphincs_key *)XMALLOC(sizeof(*sphincs),
  7265. heap, DYNAMIC_TYPE_TMP_BUFFER);
  7266. if (sphincs == NULL)
  7267. return MEMORY_E;
  7268. if (wc_sphincs_init(sphincs) != 0) {
  7269. tmpIdx = 0;
  7270. if (wc_sphincs_set_level_and_optim(sphincs, 1, FAST_VARIANT)
  7271. == 0) {
  7272. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7273. keySz) == 0) {
  7274. *algoID = SPHINCS_FAST_LEVEL1k;
  7275. }
  7276. else {
  7277. WOLFSSL_MSG("Not Sphincs-fast Level 1 DER key");
  7278. }
  7279. }
  7280. else if (wc_sphincs_set_level_and_optim(sphincs, 3, FAST_VARIANT)
  7281. == 0) {
  7282. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7283. keySz) == 0) {
  7284. *algoID = SPHINCS_FAST_LEVEL3k;
  7285. }
  7286. else {
  7287. WOLFSSL_MSG("Not Sphincs-fast Level 3 DER key");
  7288. }
  7289. }
  7290. else if (wc_sphincs_set_level_and_optim(sphincs, 5, FAST_VARIANT)
  7291. == 0) {
  7292. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7293. keySz) == 0) {
  7294. *algoID = SPHINCS_FAST_LEVEL5k;
  7295. }
  7296. else {
  7297. WOLFSSL_MSG("Not Sphincs-fast Level 5 DER key");
  7298. }
  7299. }
  7300. else if (wc_sphincs_set_level_and_optim(sphincs, 1, SMALL_VARIANT)
  7301. == 0) {
  7302. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7303. keySz) == 0) {
  7304. *algoID = SPHINCS_SMALL_LEVEL1k;
  7305. }
  7306. else {
  7307. WOLFSSL_MSG("Not Sphincs-small Level 1 DER key");
  7308. }
  7309. }
  7310. else if (wc_sphincs_set_level_and_optim(sphincs, 3, SMALL_VARIANT)
  7311. == 0) {
  7312. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7313. keySz) == 0) {
  7314. *algoID = SPHINCS_SMALL_LEVEL3k;
  7315. }
  7316. else {
  7317. WOLFSSL_MSG("Not Sphincs-small Level 3 DER key");
  7318. }
  7319. }
  7320. else if (wc_sphincs_set_level_and_optim(sphincs, 5, SMALL_VARIANT)
  7321. == 0) {
  7322. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7323. keySz) == 0) {
  7324. *algoID = SPHINCS_SMALL_LEVEL5k;
  7325. }
  7326. else {
  7327. WOLFSSL_MSG("Not Sphincs-small Level 5 DER key");
  7328. }
  7329. }
  7330. else {
  7331. WOLFSSL_MSG("GetKeyOID sphincs initialization failed");
  7332. }
  7333. wc_sphincs_free(sphincs);
  7334. }
  7335. XFREE(sphincs, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7336. }
  7337. #endif /* HAVE_SPHINCS */
  7338. #endif /* HAVE_PQC */
  7339. /* if flag is not set then this is not a key that we understand. */
  7340. if (*algoID == 0) {
  7341. WOLFSSL_MSG("Bad key DER or compile options");
  7342. return BAD_FUNC_ARG;
  7343. }
  7344. (void)tmpIdx;
  7345. (void)curveOID;
  7346. (void)oidSz;
  7347. (void)keySz;
  7348. (void)heap;
  7349. return 1;
  7350. }
  7351. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7352. #ifdef WOLFSSL_ASN_TEMPLATE
  7353. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7354. /* ASN.1 template for PBES2 parameters.
  7355. * PKCS #5: RFC 8018, A.4 - PBES2-params without outer SEQUENCE
  7356. * A.2 - PBKDF2-params
  7357. * B.2 - Encryption schemes
  7358. * C - AlgorithmIdentifier
  7359. */
  7360. static const ASNItem pbes2ParamsASN[] = {
  7361. /* KDF_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7362. /* PBKDF2 */
  7363. /* KDF_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  7364. /* PBKDF2_PARAMS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7365. /* Salt */
  7366. /* PBKDF2_PARAMS_SALT */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  7367. /* Iteration count */
  7368. /* PBKDF2_PARAMS_ITER */ { 2, ASN_INTEGER, 0, 0, 0 },
  7369. /* Key length */
  7370. /* PBKDF2_PARAMS_KEYLEN */ { 2, ASN_INTEGER, 0, 0, 1 },
  7371. /* PRF - default is HMAC-SHA1 */
  7372. /* PBKDF2_PARAMS_PRF */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  7373. /* PBKDF2_PARAMS_PRF_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  7374. /* PBKDF2_PARAMS_PRF_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  7375. /* ENCS_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7376. /* Encryption algorithm */
  7377. /* ENCS_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  7378. /* IV for CBC */
  7379. /* ENCS_PARAMS */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  7380. };
  7381. enum {
  7382. PBES2PARAMSASN_IDX_KDF_SEQ = 0,
  7383. PBES2PARAMSASN_IDX_KDF_OID,
  7384. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SEQ,
  7385. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT,
  7386. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER,
  7387. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_KEYLEN,
  7388. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF,
  7389. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID,
  7390. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_NULL,
  7391. PBES2PARAMSASN_IDX_ENCS_SEQ,
  7392. PBES2PARAMSASN_IDX_ENCS_OID,
  7393. PBES2PARAMSASN_IDX_ENCS_PARAMS,
  7394. };
  7395. /* Number of items in ASN.1 template for PBES2 parameters. */
  7396. #define pbes2ParamsASN_Length (sizeof(pbes2ParamsASN) / sizeof(ASNItem))
  7397. /* ASN.1 template for PBES1 parameters.
  7398. * PKCS #5: RFC 8018, A.3. - PBEParameter without outer SEQUENCE
  7399. */
  7400. static const ASNItem pbes1ParamsASN[] = {
  7401. /* Salt */
  7402. /* SALT */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  7403. /* Iteration count */
  7404. /* ITER */ { 0, ASN_INTEGER, 0, 0, 0 },
  7405. };
  7406. enum {
  7407. PBES1PARAMSASN_IDX_SALT = 0,
  7408. PBES1PARAMSASN_IDX_ITER,
  7409. };
  7410. /* Number of items in ASN.1 template for PBES1 parameters. */
  7411. #define pbes1ParamsASN_Length (sizeof(pbes1ParamsASN) / sizeof(ASNItem))
  7412. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7413. #endif /* WOLFSSL_ASN_TEMPLATE */
  7414. #ifdef HAVE_PKCS8
  7415. /*
  7416. * Equivalent to calling TraditionalEnc with the same parameters but with
  7417. * encAlgId set to 0. This function must be kept alive because it's sometimes
  7418. * part of the API (WOLFSSL_ASN_API).
  7419. */
  7420. int UnTraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  7421. const char* password, int passwordSz, int vPKCS, int vAlgo,
  7422. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  7423. {
  7424. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz,
  7425. vPKCS, vAlgo, 0, salt, saltSz, itt, rng, heap);
  7426. }
  7427. static int GetAlgoV2(int encAlgId, const byte** oid, int *len, int* id,
  7428. int *blkSz)
  7429. {
  7430. int ret = 0;
  7431. switch (encAlgId) {
  7432. #if !defined(NO_DES3) && !defined(NO_SHA)
  7433. case DESb:
  7434. *len = sizeof(blkDesCbcOid);
  7435. *oid = blkDesCbcOid;
  7436. *id = PBE_SHA1_DES;
  7437. *blkSz = 8;
  7438. break;
  7439. case DES3b:
  7440. *len = sizeof(blkDes3CbcOid);
  7441. *oid = blkDes3CbcOid;
  7442. *id = PBE_SHA1_DES3;
  7443. *blkSz = 8;
  7444. break;
  7445. #endif
  7446. #if defined(WOLFSSL_AES_256) && defined(HAVE_AES_CBC)
  7447. case AES256CBCb:
  7448. *len = sizeof(blkAes256CbcOid);
  7449. *oid = blkAes256CbcOid;
  7450. *id = PBE_AES256_CBC;
  7451. *blkSz = 16;
  7452. break;
  7453. #endif
  7454. default:
  7455. (void)len;
  7456. (void)oid;
  7457. (void)id;
  7458. (void)blkSz;
  7459. ret = ALGO_ID_E;
  7460. }
  7461. return ret;
  7462. }
  7463. int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz,
  7464. const char* password, int passwordSz, int vPKCS, int pbeOid,
  7465. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  7466. void* heap)
  7467. {
  7468. #ifdef WOLFSSL_SMALL_STACK
  7469. byte* saltTmp = NULL;
  7470. #else
  7471. byte saltTmp[MAX_SALT_SIZE];
  7472. #endif
  7473. int genSalt = 0;
  7474. int ret = 0;
  7475. int version = 0;
  7476. int pbeId = 0;
  7477. int blockSz = 0;
  7478. const byte* encOid = NULL;
  7479. int encOidSz = 0;
  7480. word32 padSz = 0;
  7481. word32 innerLen = 0;
  7482. word32 outerLen = 0;
  7483. const byte* pbeOidBuf = NULL;
  7484. word32 pbeOidBufSz = 0;
  7485. word32 pbeLen = 0;
  7486. word32 kdfLen = 0;
  7487. word32 encLen = 0;
  7488. byte cbcIv[MAX_IV_SIZE];
  7489. word32 idx = 0;
  7490. word32 encIdx = 0;
  7491. (void)heap;
  7492. WOLFSSL_ENTER("wc_EncryptPKCS8Key");
  7493. if (key == NULL || outSz == NULL || password == NULL) {
  7494. ret = BAD_FUNC_ARG;
  7495. }
  7496. if (ret == 0) {
  7497. ret = CheckAlgo(vPKCS, pbeOid, &pbeId, &version, &blockSz);
  7498. }
  7499. if (ret == 0 && (salt == NULL || saltSz == 0)) {
  7500. genSalt = 1;
  7501. saltSz = 8;
  7502. }
  7503. if (ret == 0 && version == PKCS5v2) {
  7504. ret = GetAlgoV2(encAlgId, &encOid, &encOidSz, &pbeId, &blockSz);
  7505. }
  7506. if (ret == 0) {
  7507. padSz = (blockSz - (keySz & (blockSz - 1))) & (blockSz - 1);
  7508. /* inner = OCT salt INT itt */
  7509. innerLen = 2 + saltSz + 2 + (itt < 256 ? 1 : 2);
  7510. if (version != PKCS5v2) {
  7511. pbeOidBuf = OidFromId(pbeId, oidPBEType, &pbeOidBufSz);
  7512. /* pbe = OBJ pbse1 SEQ [ inner ] */
  7513. pbeLen = 2 + pbeOidBufSz + 2 + innerLen;
  7514. }
  7515. else {
  7516. pbeOidBuf = pbes2;
  7517. pbeOidBufSz = sizeof(pbes2);
  7518. /* kdf = OBJ pbkdf2 [ SEQ innerLen ] */
  7519. kdfLen = 2 + sizeof(pbkdf2Oid) + 2 + innerLen;
  7520. /* enc = OBJ enc_alg OCT iv */
  7521. encLen = 2 + encOidSz + 2 + blockSz;
  7522. /* pbe = OBJ pbse2 SEQ [ SEQ [ kdf ] SEQ [ enc ] ] */
  7523. pbeLen = 2 + sizeof(pbes2) + 2 + 2 + kdfLen + 2 + encLen;
  7524. ret = wc_RNG_GenerateBlock(rng, cbcIv, blockSz);
  7525. }
  7526. }
  7527. if (ret == 0) {
  7528. /* outerLen = length of PBE encoding + octet string data */
  7529. /* Plus 2 for tag and length for pbe */
  7530. outerLen = 2 + pbeLen;
  7531. /* Octet string tag, length */
  7532. outerLen += 1 + SetLength(keySz + padSz, NULL);
  7533. /* Octet string bytes */
  7534. outerLen += keySz + padSz;
  7535. if (out == NULL) {
  7536. /* Sequence tag, length */
  7537. *outSz = 1 + SetLength(outerLen, NULL) + outerLen;
  7538. return LENGTH_ONLY_E;
  7539. }
  7540. SetOctetString(keySz + padSz, out);
  7541. idx += SetSequence(outerLen, out + idx);
  7542. encIdx = idx + outerLen - keySz - padSz;
  7543. /* Put Encrypted content in place. */
  7544. XMEMCPY(out + encIdx, key, keySz);
  7545. if (padSz > 0) {
  7546. XMEMSET(out + encIdx + keySz, padSz, padSz);
  7547. keySz += padSz;
  7548. }
  7549. if (genSalt == 1) {
  7550. #ifdef WOLFSSL_SMALL_STACK
  7551. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7552. if (saltTmp == NULL) {
  7553. ret = MEMORY_E;
  7554. }
  7555. else
  7556. #endif
  7557. {
  7558. salt = saltTmp;
  7559. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  7560. WOLFSSL_MSG("Error generating random salt");
  7561. }
  7562. }
  7563. }
  7564. }
  7565. if (ret == 0) {
  7566. ret = wc_CryptKey(password, passwordSz, salt, saltSz, itt, pbeId,
  7567. out + encIdx, keySz, version, cbcIv, 1, 0);
  7568. }
  7569. if (ret == 0) {
  7570. if (version != PKCS5v2) {
  7571. /* PBE algorithm */
  7572. idx += SetSequence(pbeLen, out + idx);
  7573. idx += SetObjectId(pbeOidBufSz, out + idx);
  7574. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  7575. idx += pbeOidBufSz;
  7576. }
  7577. else {
  7578. /* PBES2 algorithm identifier */
  7579. idx += SetSequence(pbeLen, out + idx);
  7580. idx += SetObjectId(pbeOidBufSz, out + idx);
  7581. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  7582. idx += pbeOidBufSz;
  7583. /* PBES2 Parameters: SEQ [ kdf ] SEQ [ enc ] */
  7584. idx += SetSequence(2 + kdfLen + 2 + encLen, out + idx);
  7585. /* KDF Algorithm Identifier */
  7586. idx += SetSequence(kdfLen, out + idx);
  7587. idx += SetObjectId(sizeof(pbkdf2Oid), out + idx);
  7588. XMEMCPY(out + idx, pbkdf2Oid, sizeof(pbkdf2Oid));
  7589. idx += sizeof(pbkdf2Oid);
  7590. }
  7591. idx += SetSequence(innerLen, out + idx);
  7592. idx += SetOctetString(saltSz, out + idx);
  7593. XMEMCPY(out + idx, salt, saltSz); idx += saltSz;
  7594. ret = SetShortInt(out, &idx, itt, *outSz);
  7595. if (ret > 0)
  7596. ret = 0;
  7597. }
  7598. if (ret == 0) {
  7599. if (version == PKCS5v2) {
  7600. /* Encryption Algorithm Identifier */
  7601. idx += SetSequence(encLen, out + idx);
  7602. idx += SetObjectId(encOidSz, out + idx);
  7603. XMEMCPY(out + idx, encOid, encOidSz);
  7604. idx += encOidSz;
  7605. /* Encryption Algorithm Parameter: CBC IV */
  7606. idx += SetOctetString(blockSz, out + idx);
  7607. XMEMCPY(out + idx, cbcIv, blockSz);
  7608. idx += blockSz;
  7609. }
  7610. idx += SetOctetString(keySz, out + idx);
  7611. /* Default PRF - no need to write out OID */
  7612. idx += keySz;
  7613. ret = idx;
  7614. }
  7615. #ifdef WOLFSSL_SMALL_STACK
  7616. if (saltTmp != NULL) {
  7617. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7618. }
  7619. #endif
  7620. WOLFSSL_LEAVE("wc_EncryptPKCS8Key", ret);
  7621. return ret;
  7622. }
  7623. int wc_DecryptPKCS8Key(byte* input, word32 sz, const char* password,
  7624. int passwordSz)
  7625. {
  7626. int ret;
  7627. int length;
  7628. word32 inOutIdx = 0;
  7629. if (input == NULL || password == NULL) {
  7630. return BAD_FUNC_ARG;
  7631. }
  7632. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  7633. ret = ASN_PARSE_E;
  7634. }
  7635. else {
  7636. ret = DecryptContent(input + inOutIdx, sz - inOutIdx, password,
  7637. passwordSz);
  7638. if (ret > 0) {
  7639. XMEMMOVE(input, input + inOutIdx, ret);
  7640. }
  7641. }
  7642. if (ret > 0) {
  7643. /* DecryptContent will decrypt the data, but it will leave any padding
  7644. * bytes intact. This code calculates the length without the padding
  7645. * and we return that to the user. */
  7646. inOutIdx = 0;
  7647. if (GetSequence(input, &inOutIdx, &length, ret) < 0) {
  7648. ret = ASN_PARSE_E;
  7649. }
  7650. else {
  7651. ret = inOutIdx + length;
  7652. }
  7653. }
  7654. return ret;
  7655. }
  7656. /* Takes an unencrypted, traditional DER-encoded key and converts it to a PKCS#8
  7657. * encrypted key. If out is not NULL, it will hold the encrypted key. If it's
  7658. * NULL, LENGTH_ONLY_E will be returned and outSz will have the required out
  7659. * buffer size. */
  7660. int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  7661. const char* password, int passwordSz, int vPKCS, int vAlgo,
  7662. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  7663. void* heap)
  7664. {
  7665. int ret = 0;
  7666. byte *pkcs8Key = NULL;
  7667. word32 pkcs8KeySz = 0;
  7668. int algId = 0;
  7669. const byte* curveOid = NULL;
  7670. word32 curveOidSz = 0;
  7671. if (ret == 0) {
  7672. /* check key type and get OID if ECC */
  7673. ret = wc_GetKeyOID(key, keySz, &curveOid, &curveOidSz, &algId, heap);
  7674. if (ret == 1)
  7675. ret = 0;
  7676. }
  7677. if (ret == 0) {
  7678. ret = wc_CreatePKCS8Key(NULL, &pkcs8KeySz, key, keySz, algId, curveOid,
  7679. curveOidSz);
  7680. if (ret == LENGTH_ONLY_E)
  7681. ret = 0;
  7682. }
  7683. if (ret == 0) {
  7684. pkcs8Key = (byte*)XMALLOC(pkcs8KeySz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7685. if (pkcs8Key == NULL)
  7686. ret = MEMORY_E;
  7687. }
  7688. if (ret == 0) {
  7689. ret = wc_CreatePKCS8Key(pkcs8Key, &pkcs8KeySz, key, keySz, algId,
  7690. curveOid, curveOidSz);
  7691. if (ret >= 0) {
  7692. pkcs8KeySz = ret;
  7693. ret = 0;
  7694. }
  7695. }
  7696. #ifdef WOLFSSL_CHECK_MEM_ZERO
  7697. if (ret == 0) {
  7698. wc_MemZero_Add("TraditionalEnc pkcs8Key", pkcs8Key, pkcs8KeySz);
  7699. }
  7700. #endif
  7701. if (ret == 0) {
  7702. ret = wc_EncryptPKCS8Key(pkcs8Key, pkcs8KeySz, out, outSz, password,
  7703. passwordSz, vPKCS, vAlgo, encAlgId, salt, saltSz, itt, rng, heap);
  7704. }
  7705. if (pkcs8Key != NULL) {
  7706. ForceZero(pkcs8Key, pkcs8KeySz);
  7707. XFREE(pkcs8Key, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7708. }
  7709. (void)rng;
  7710. return ret;
  7711. }
  7712. /* Same as TraditionalEnc, but in the public API. */
  7713. int wc_CreateEncryptedPKCS8Key(byte* key, word32 keySz, byte* out,
  7714. word32* outSz, const char* password, int passwordSz, int vPKCS,
  7715. int pbeOid, int encAlgId, byte* salt, word32 saltSz, int itt,
  7716. WC_RNG* rng, void* heap)
  7717. {
  7718. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz, vPKCS,
  7719. pbeOid, encAlgId, salt, saltSz, itt, rng, heap);
  7720. }
  7721. #ifdef WOLFSSL_ASN_TEMPLATE
  7722. /* ASN.1 template for PKCS #8/#7 encrypted key for decrypting
  7723. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  7724. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  7725. */
  7726. static const ASNItem pkcs8DecASN[] = {
  7727. /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7728. /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  7729. /* ENCALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  7730. /* PKCS #7 */
  7731. /* ENCCONTENT */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ENC_CONTENT,
  7732. 0, 0, 2 },
  7733. /* PKCS #8 */
  7734. /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
  7735. };
  7736. enum {
  7737. PKCS8DECASN_IDX_ENCALGO_SEQ = 0,
  7738. PKCS8DECASN_IDX_ENCALGO_OID,
  7739. PKCS8DECASN_IDX_ENCALGO_PARAMS,
  7740. PKCS8DECASN_IDX_ENCCONTENT,
  7741. PKCS8DECASN_IDX_ENCDATA,
  7742. };
  7743. /* Number of items in ASN.1 template for PKCS #8/#7 encrypted key. */
  7744. #define pkcs8DecASN_Length (sizeof(pkcs8DecASN) / sizeof(ASNItem))
  7745. #endif
  7746. /* Decrypt data using PBE algorithm.
  7747. *
  7748. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  7749. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  7750. *
  7751. * Note: input buffer is overwritten with decrypted data!
  7752. *
  7753. * Salt is in KDF parameters and IV is PBE parameters when needed.
  7754. *
  7755. * @param [in] input Data to decrypt and unwrap.
  7756. * @param [in] sz Size of encrypted data.
  7757. * @param [in] password Password to derive encryption key with.
  7758. * @param [in] passwordSz Size of password in bytes.
  7759. * @return Length of decrypted data on success.
  7760. * @return MEMORY_E when dynamic memory allocation fails.
  7761. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  7762. * is invalid.
  7763. * @return BUFFER_E when data in buffer is too small.
  7764. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  7765. * @return Other when decryption fails.
  7766. */
  7767. int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz)
  7768. {
  7769. #ifndef WOLFSSL_ASN_TEMPLATE
  7770. word32 inOutIdx = 0, seqEnd, oid, shaOid = 0;
  7771. int ret = 0, first, second, length = 0, version, saltSz, id = 0;
  7772. int iterations = 0, keySz = 0;
  7773. #ifdef WOLFSSL_SMALL_STACK
  7774. byte* salt = NULL;
  7775. byte* cbcIv = NULL;
  7776. #else
  7777. byte salt[MAX_SALT_SIZE];
  7778. byte cbcIv[MAX_IV_SIZE];
  7779. #endif
  7780. byte tag;
  7781. if (passwordSz < 0) {
  7782. WOLFSSL_MSG("Bad password size");
  7783. return BAD_FUNC_ARG;
  7784. }
  7785. if (GetAlgoId(input, &inOutIdx, &oid, oidIgnoreType, sz) < 0) {
  7786. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7787. }
  7788. first = input[inOutIdx - 2]; /* PKCS version always 2nd to last byte */
  7789. second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
  7790. if (CheckAlgo(first, second, &id, &version, NULL) < 0) {
  7791. ERROR_OUT(ASN_INPUT_E, exit_dc); /* Algo ID error */
  7792. }
  7793. if (version == PKCS5v2) {
  7794. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  7795. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7796. }
  7797. if (GetAlgoId(input, &inOutIdx, &oid, oidKdfType, sz) < 0) {
  7798. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7799. }
  7800. if (oid != PBKDF2_OID) {
  7801. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7802. }
  7803. }
  7804. if (GetSequence(input, &inOutIdx, &length, sz) <= 0) {
  7805. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7806. }
  7807. /* Find the end of this SEQUENCE so we can check for the OPTIONAL and
  7808. * DEFAULT items. */
  7809. seqEnd = inOutIdx + length;
  7810. ret = GetOctetString(input, &inOutIdx, &saltSz, sz);
  7811. if (ret < 0)
  7812. goto exit_dc;
  7813. if (saltSz > MAX_SALT_SIZE) {
  7814. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7815. }
  7816. #ifdef WOLFSSL_SMALL_STACK
  7817. salt = (byte*)XMALLOC(MAX_SALT_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7818. if (salt == NULL) {
  7819. ERROR_OUT(MEMORY_E, exit_dc);
  7820. }
  7821. #endif
  7822. XMEMCPY(salt, &input[inOutIdx], saltSz);
  7823. inOutIdx += saltSz;
  7824. if (GetShortInt(input, &inOutIdx, &iterations, sz) < 0) {
  7825. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7826. }
  7827. /* OPTIONAL key length */
  7828. if (seqEnd > inOutIdx) {
  7829. word32 localIdx = inOutIdx;
  7830. if (GetASNTag(input, &localIdx, &tag, sz) < 0) {
  7831. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7832. }
  7833. if (tag == ASN_INTEGER &&
  7834. GetShortInt(input, &inOutIdx, &keySz, sz) < 0) {
  7835. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7836. }
  7837. }
  7838. /* DEFAULT HMAC is SHA-1 */
  7839. if (seqEnd > inOutIdx) {
  7840. if (GetAlgoId(input, &inOutIdx, &oid, oidHmacType, sz) < 0) {
  7841. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7842. }
  7843. shaOid = oid;
  7844. }
  7845. #ifdef WOLFSSL_SMALL_STACK
  7846. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7847. if (cbcIv == NULL) {
  7848. ERROR_OUT(MEMORY_E, exit_dc);
  7849. }
  7850. #endif
  7851. if (version == PKCS5v2) {
  7852. /* get encryption algo */
  7853. if (GetAlgoId(input, &inOutIdx, &oid, oidBlkType, sz) < 0) {
  7854. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7855. }
  7856. if (CheckAlgoV2(oid, &id, NULL) < 0) {
  7857. ERROR_OUT(ASN_PARSE_E, exit_dc); /* PKCS v2 algo id error */
  7858. }
  7859. if (shaOid == 0)
  7860. shaOid = oid;
  7861. ret = GetOctetString(input, &inOutIdx, &length, sz);
  7862. if (ret < 0)
  7863. goto exit_dc;
  7864. if (length > MAX_IV_SIZE) {
  7865. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7866. }
  7867. XMEMCPY(cbcIv, &input[inOutIdx], length);
  7868. inOutIdx += length;
  7869. }
  7870. if (GetASNTag(input, &inOutIdx, &tag, sz) < 0) {
  7871. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7872. }
  7873. if (tag != (ASN_CONTEXT_SPECIFIC | 0) && tag != ASN_OCTET_STRING) {
  7874. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7875. }
  7876. if (GetLength(input, &inOutIdx, &length, sz) < 0) {
  7877. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7878. }
  7879. ret = wc_CryptKey(password, passwordSz, salt, saltSz, iterations, id,
  7880. input + inOutIdx, length, version, cbcIv, 0, shaOid);
  7881. exit_dc:
  7882. #ifdef WOLFSSL_SMALL_STACK
  7883. XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7884. XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7885. #endif
  7886. if (ret == 0) {
  7887. XMEMMOVE(input, input + inOutIdx, length);
  7888. ret = length;
  7889. }
  7890. return ret;
  7891. #else
  7892. /* pbes2ParamsASN longer than pkcs8DecASN_Length/pbes1ParamsASN_Length. */
  7893. DECL_ASNGETDATA(dataASN, pbes2ParamsASN_Length);
  7894. int ret = 0;
  7895. int id;
  7896. int version;
  7897. word32 idx = 0;
  7898. word32 pIdx = 0;
  7899. word32 iterations;
  7900. word32 keySz = 0;
  7901. word32 saltSz;
  7902. word32 shaOid = 0;
  7903. byte* salt = NULL;
  7904. byte* key = NULL;
  7905. byte cbcIv[MAX_IV_SIZE];
  7906. byte* params;
  7907. WOLFSSL_ENTER("DecryptContent");
  7908. CALLOC_ASNGETDATA(dataASN, pbes2ParamsASN_Length, ret, NULL);
  7909. if (ret == 0) {
  7910. /* Check OID is a PBE Type */
  7911. GetASN_OID(&dataASN[PKCS8DECASN_IDX_ENCALGO_OID], oidPBEType);
  7912. ret = GetASN_Items(pkcs8DecASN, dataASN, pkcs8DecASN_Length, 0, input,
  7913. &idx, sz);
  7914. }
  7915. if (ret == 0) {
  7916. /* Check the PBE algorithm and get the version and id. */
  7917. idx = dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.length;
  7918. /* Second last byte: 1 (PKCS #12 PBE Id) or 5 (PKCS #5)
  7919. * Last byte: Alg or PBES2 */
  7920. ret = CheckAlgo(dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 2],
  7921. dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 1],
  7922. &id, &version, NULL);
  7923. }
  7924. if (ret == 0) {
  7925. /* Get the parameters data. */
  7926. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCALGO_PARAMS], &params, &sz);
  7927. /* Having a numbered choice means none or both will have errored out. */
  7928. if (dataASN[PKCS8DECASN_IDX_ENCCONTENT].tag != 0)
  7929. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCCONTENT], &key, &keySz);
  7930. else if (dataASN[PKCS8DECASN_IDX_ENCDATA].tag != 0)
  7931. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCDATA], &key, &keySz);
  7932. else
  7933. ret = ASN_RSA_KEY_E;
  7934. }
  7935. if (ret == 0) {
  7936. if (version != PKCS5v2) {
  7937. /* Initialize for PBES1 parameters and put iterations in var. */
  7938. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes1ParamsASN_Length);
  7939. GetASN_Int32Bit(&dataASN[PBES1PARAMSASN_IDX_ITER], &iterations);
  7940. /* Parse the PBES1 parameters. */
  7941. ret = GetASN_Items(pbes1ParamsASN, dataASN, pbes1ParamsASN_Length,
  7942. 0, params, &pIdx, sz);
  7943. if (ret == 0) {
  7944. /* Get the salt data. */
  7945. GetASN_GetRef(&dataASN[PBES1PARAMSASN_IDX_SALT], &salt, &saltSz);
  7946. }
  7947. }
  7948. else {
  7949. word32 ivSz = MAX_IV_SIZE;
  7950. /* Initialize for PBES2 parameters. Put iterations in var; match
  7951. * KDF, HMAC and cipher, and copy CBC into buffer. */
  7952. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes2ParamsASN_Length);
  7953. GetASN_ExpBuffer(&dataASN[PBES2PARAMSASN_IDX_KDF_OID], pbkdf2Oid, sizeof(pbkdf2Oid));
  7954. GetASN_Int32Bit(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER], &iterations);
  7955. GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID], oidHmacType);
  7956. GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_ENCS_OID], oidBlkType);
  7957. GetASN_Buffer(&dataASN[PBES2PARAMSASN_IDX_ENCS_PARAMS], cbcIv, &ivSz);
  7958. /* Parse the PBES2 parameters */
  7959. ret = GetASN_Items(pbes2ParamsASN, dataASN, pbes2ParamsASN_Length,
  7960. 0, params, &pIdx, sz);
  7961. if (ret == 0) {
  7962. /* Get the salt data. */
  7963. GetASN_GetRef(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT], &salt, &saltSz);
  7964. /* Get the digest and encryption algorithm id. */
  7965. shaOid = dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID].data.oid.sum; /* Default HMAC-SHA1 */
  7966. id = dataASN[PBES2PARAMSASN_IDX_ENCS_OID].data.oid.sum;
  7967. /* Convert encryption algorithm to a PBE algorithm if needed. */
  7968. CheckAlgoV2(id, &id, NULL);
  7969. }
  7970. }
  7971. }
  7972. if (ret == 0) {
  7973. /* Decrypt the key. */
  7974. ret = wc_CryptKey(password, passwordSz, salt, saltSz, iterations, id,
  7975. key, keySz, version, cbcIv, 0, shaOid);
  7976. }
  7977. if (ret == 0) {
  7978. /* Copy the decrypted key into the input (inline). */
  7979. XMEMMOVE(input, key, keySz);
  7980. ret = keySz;
  7981. }
  7982. FREE_ASNGETDATA(dataASN, NULL);
  7983. return ret;
  7984. #endif
  7985. }
  7986. /* Decrypt data using PBE algorithm and get key from PKCS#8 wrapping.
  7987. *
  7988. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  7989. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo
  7990. *
  7991. * Note: input buffer is overwritten with decrypted key!
  7992. *
  7993. * Salt is in KDF parameters and IV is PBE parameters when needed.
  7994. *
  7995. * @param [in] input Data to decrypt and unwrap.
  7996. * @param [in] sz Size of encrypted data.
  7997. * @param [in] password Password to derive encryption key with.
  7998. * @param [in] passwordSz Size of password in bytes.
  7999. * @param [out] algId Key algorithm from PKCS#8 wrapper.
  8000. * @return Length of decrypted data on success.
  8001. * @return MEMORY_E when dynamic memory allocation fails.
  8002. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8003. * is invalid.
  8004. * @return BUFFER_E when data in buffer is too small.
  8005. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8006. * @return Other when decryption fails.
  8007. */
  8008. int ToTraditionalEnc(byte* input, word32 sz, const char* password,
  8009. int passwordSz, word32* algId)
  8010. {
  8011. int ret;
  8012. ret = wc_DecryptPKCS8Key(input, sz, password, passwordSz);
  8013. if (ret > 0) {
  8014. ret = ToTraditional_ex(input, ret, algId);
  8015. }
  8016. return ret;
  8017. }
  8018. #endif /* HAVE_PKCS8 */
  8019. #ifdef HAVE_PKCS12
  8020. #define PKCS8_MIN_BLOCK_SIZE 8
  8021. static int Pkcs8Pad(byte* buf, int sz, int blockSz)
  8022. {
  8023. int i, padSz;
  8024. /* calculate pad size */
  8025. padSz = blockSz - (sz & (blockSz - 1));
  8026. /* pad with padSz value */
  8027. if (buf) {
  8028. for (i = 0; i < padSz; i++) {
  8029. buf[sz+i] = (byte)(padSz & 0xFF);
  8030. }
  8031. }
  8032. /* return adjusted length */
  8033. return sz + padSz;
  8034. }
  8035. #ifdef WOLFSSL_ASN_TEMPLATE
  8036. /* ASN.1 template for PKCS #8 encrypted key with PBES1 parameters.
  8037. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  8038. * PKCS #5: RFC 8018, A.3 - PBEParameter
  8039. */
  8040. static const ASNItem p8EncPbes1ASN[] = {
  8041. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8042. /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8043. /* PBE algorithm */
  8044. /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8045. /* ENCALGO_PBEPARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8046. /* Salt */
  8047. /* ENCALGO_PBEPARAM_SALT */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  8048. /* Iteration Count */
  8049. /* ENCALGO_PBEPARAM_ITER */ { 3, ASN_INTEGER, 0, 0, 0 },
  8050. /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  8051. };
  8052. enum {
  8053. P8ENCPBES1ASN_IDX_SEQ = 0,
  8054. P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8055. P8ENCPBES1ASN_IDX_ENCALGO_OID,
  8056. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SEQ,
  8057. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT,
  8058. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER,
  8059. P8ENCPBES1ASN_IDX_ENCDATA,
  8060. };
  8061. #define p8EncPbes1ASN_Length (sizeof(p8EncPbes1ASN) / sizeof(ASNItem))
  8062. #endif
  8063. /* Wrap a private key in PKCS#8 and encrypt.
  8064. *
  8065. * Used for PKCS#12 and PKCS#7.
  8066. * vPKCS is the version of PKCS to use.
  8067. * vAlgo is the algorithm version to use.
  8068. *
  8069. * When salt is NULL, a random number is generated.
  8070. *
  8071. * data returned is :
  8072. * [ seq - obj [ seq -salt,itt]] , construct with encrypted data
  8073. *
  8074. * @param [in] input Data to encrypt.
  8075. * @param [in] inputSz Length of data in bytes.
  8076. * @param [out] out Buffer to write wrapped encrypted data into.
  8077. * @param [out] outSz Length of encrypted data in bytes.
  8078. * @param [in] password Password used to create encryption key.
  8079. * @param [in] passwordSz Length of password in bytes.
  8080. * @param [in] vPKCS First byte used to determine PBE algorithm.
  8081. * @param [in] vAlgo Second byte used to determine PBE algorithm.
  8082. * @param [in] salt Salt to use with KDF.
  8083. * @param [in] saltSz Length of salt in bytes.
  8084. * @param [in] itt Number of iterations to use in KDF.
  8085. * @param [in] rng Random number generator to use to generate salt.
  8086. * @param [in] heap Dynamic memory allocator hint.
  8087. * @return The size of encrypted data on success
  8088. * @return LENGTH_ONLY_E when out is NULL and able to encode.
  8089. * @return ASN_PARSE_E when the salt size is too large.
  8090. * @return ASN_VERSION_E when attempting to use a PBES2 algorithm (use
  8091. * TraditionalEnc).
  8092. * @return MEMORY_E when dynamic memory allocation fails.
  8093. * @return Other when encryption or random number generation fails.
  8094. */
  8095. int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz,
  8096. const char* password, int passwordSz, int vPKCS, int vAlgo,
  8097. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  8098. {
  8099. #ifndef WOLFSSL_ASN_TEMPLATE
  8100. word32 sz;
  8101. word32 inOutIdx = 0;
  8102. word32 tmpIdx = 0;
  8103. word32 totalSz = 0;
  8104. word32 seqSz;
  8105. word32 innerSz;
  8106. int ret;
  8107. int version, id, blockSz = 0;
  8108. #ifdef WOLFSSL_SMALL_STACK
  8109. byte* saltTmp = NULL;
  8110. byte* cbcIv = NULL;
  8111. #else
  8112. byte saltTmp[MAX_SALT_SIZE];
  8113. byte cbcIv[MAX_IV_SIZE];
  8114. #endif
  8115. byte seq[MAX_SEQ_SZ];
  8116. byte shr[MAX_SHORT_SZ];
  8117. word32 maxShr = MAX_SHORT_SZ;
  8118. word32 algoSz;
  8119. const byte* algoName;
  8120. (void)heap;
  8121. WOLFSSL_ENTER("EncryptContent()");
  8122. if (CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0)
  8123. return ASN_INPUT_E; /* Algo ID error */
  8124. if (version == PKCS5v2) {
  8125. WOLFSSL_MSG("PKCS#5 version 2 not supported yet");
  8126. return BAD_FUNC_ARG;
  8127. }
  8128. if (saltSz > MAX_SALT_SIZE)
  8129. return ASN_PARSE_E;
  8130. if (outSz == NULL) {
  8131. return BAD_FUNC_ARG;
  8132. }
  8133. /* calculate size */
  8134. /* size of constructed string at end */
  8135. sz = Pkcs8Pad(NULL, inputSz, blockSz);
  8136. totalSz = ASN_TAG_SZ;
  8137. totalSz += SetLength(sz, seq);
  8138. totalSz += sz;
  8139. /* size of sequence holding object id and sub sequence of salt and itt */
  8140. algoName = OidFromId(id, oidPBEType, &algoSz);
  8141. if (algoName == NULL) {
  8142. WOLFSSL_MSG("Unknown Algorithm");
  8143. return 0;
  8144. }
  8145. innerSz = SetObjectId(algoSz, seq);
  8146. innerSz += algoSz;
  8147. /* get subsequence of salt and itt */
  8148. if (salt == NULL || saltSz == 0) {
  8149. sz = 8;
  8150. }
  8151. else {
  8152. sz = saltSz;
  8153. }
  8154. seqSz = SetOctetString(sz, seq);
  8155. seqSz += sz;
  8156. tmpIdx = 0;
  8157. ret = SetShortInt(shr, &tmpIdx, itt, maxShr);
  8158. if (ret >= 0) {
  8159. seqSz += ret;
  8160. }
  8161. else {
  8162. return ret;
  8163. }
  8164. innerSz += seqSz + SetSequence(seqSz, seq);
  8165. totalSz += innerSz + SetSequence(innerSz, seq);
  8166. if (out == NULL) {
  8167. *outSz = totalSz;
  8168. return LENGTH_ONLY_E;
  8169. }
  8170. inOutIdx = 0;
  8171. if (totalSz > *outSz)
  8172. return BUFFER_E;
  8173. inOutIdx += SetSequence(innerSz, out + inOutIdx);
  8174. inOutIdx += SetObjectId(algoSz, out + inOutIdx);
  8175. XMEMCPY(out + inOutIdx, algoName, algoSz);
  8176. inOutIdx += algoSz;
  8177. inOutIdx += SetSequence(seqSz, out + inOutIdx);
  8178. /* create random salt if one not provided */
  8179. if (salt == NULL || saltSz == 0) {
  8180. saltSz = 8;
  8181. #ifdef WOLFSSL_SMALL_STACK
  8182. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8183. if (saltTmp == NULL)
  8184. return MEMORY_E;
  8185. #endif
  8186. salt = saltTmp;
  8187. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  8188. WOLFSSL_MSG("Error generating random salt");
  8189. #ifdef WOLFSSL_SMALL_STACK
  8190. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8191. #endif
  8192. return ret;
  8193. }
  8194. }
  8195. inOutIdx += SetOctetString(saltSz, out + inOutIdx);
  8196. if (saltSz + inOutIdx > *outSz) {
  8197. #ifdef WOLFSSL_SMALL_STACK
  8198. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8199. #endif
  8200. return BUFFER_E;
  8201. }
  8202. XMEMCPY(out + inOutIdx, salt, saltSz);
  8203. inOutIdx += saltSz;
  8204. /* place iteration setting in buffer */
  8205. ret = SetShortInt(out, &inOutIdx, itt, *outSz);
  8206. if (ret < 0) {
  8207. #ifdef WOLFSSL_SMALL_STACK
  8208. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8209. #endif
  8210. return ret;
  8211. }
  8212. if (inOutIdx + 1 > *outSz) {
  8213. #ifdef WOLFSSL_SMALL_STACK
  8214. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8215. #endif
  8216. return BUFFER_E;
  8217. }
  8218. out[inOutIdx++] = ASN_CONTEXT_SPECIFIC | 0;
  8219. /* get pad size and verify buffer room */
  8220. sz = Pkcs8Pad(NULL, inputSz, blockSz);
  8221. if (sz + inOutIdx > *outSz) {
  8222. #ifdef WOLFSSL_SMALL_STACK
  8223. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8224. #endif
  8225. return BUFFER_E;
  8226. }
  8227. inOutIdx += SetLength(sz, out + inOutIdx);
  8228. /* copy input to output buffer and pad end */
  8229. XMEMCPY(out + inOutIdx, input, inputSz);
  8230. sz = Pkcs8Pad(out + inOutIdx, inputSz, blockSz);
  8231. #ifdef WOLFSSL_SMALL_STACK
  8232. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8233. if (cbcIv == NULL) {
  8234. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8235. return MEMORY_E;
  8236. }
  8237. #endif
  8238. /* encrypt */
  8239. if ((ret = wc_CryptKey(password, passwordSz, salt, saltSz, itt, id,
  8240. out + inOutIdx, sz, version, cbcIv, 1, 0)) < 0) {
  8241. #ifdef WOLFSSL_SMALL_STACK
  8242. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8243. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8244. #endif
  8245. return ret; /* encrypt failure */
  8246. }
  8247. #ifdef WOLFSSL_SMALL_STACK
  8248. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8249. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8250. #endif
  8251. (void)rng;
  8252. return inOutIdx + sz;
  8253. #else
  8254. DECL_ASNSETDATA(dataASN, p8EncPbes1ASN_Length);
  8255. int ret = 0;
  8256. int sz = 0;
  8257. int version;
  8258. int id;
  8259. int blockSz = 0;
  8260. byte* pkcs8;
  8261. word32 pkcs8Sz;
  8262. byte cbcIv[MAX_IV_SIZE];
  8263. (void)heap;
  8264. WOLFSSL_ENTER("EncryptContent()");
  8265. /* Must have a output size to return or check. */
  8266. if (outSz == NULL) {
  8267. ret = BAD_FUNC_ARG;
  8268. }
  8269. /* Check salt size is valid. */
  8270. if ((ret == 0) && (saltSz > MAX_SALT_SIZE)) {
  8271. ret = ASN_PARSE_E;
  8272. }
  8273. /* Get algorithm parameters for algorithm identifier. */
  8274. if ((ret == 0) && CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0) {
  8275. ret = ASN_INPUT_E;
  8276. }
  8277. /* Check PKCS #5 version - only PBSE1 parameters supported. */
  8278. if ((ret == 0) && (version == PKCS5v2)) {
  8279. ret = BAD_FUNC_ARG;
  8280. }
  8281. CALLOC_ASNSETDATA(dataASN, p8EncPbes1ASN_Length, ret, heap);
  8282. if (ret == 0) {
  8283. /* Setup data to go into encoding including PBE algorithm, salt,
  8284. * iteration count, and padded key length. */
  8285. SetASN_OID(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_OID], id, oidPBEType);
  8286. if (salt == NULL || saltSz == 0) {
  8287. salt = NULL;
  8288. saltSz = PKCS5_SALT_SZ;
  8289. /* Salt generated into encoding below. */
  8290. }
  8291. SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT],
  8292. salt, saltSz);
  8293. SetASN_Int16Bit(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER], itt);
  8294. pkcs8Sz = Pkcs8Pad(NULL, inputSz, blockSz);
  8295. SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCDATA], NULL, pkcs8Sz);
  8296. /* Calculate size of encoding. */
  8297. ret = SizeASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8298. dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8299. (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
  8300. &sz);
  8301. }
  8302. /* Return size when no output buffer. */
  8303. if ((ret == 0) && (out == NULL)) {
  8304. *outSz = sz;
  8305. ret = LENGTH_ONLY_E;
  8306. }
  8307. /* Check output buffer is big enough for encoded data. */
  8308. if ((ret == 0) && (sz > (int)*outSz)) {
  8309. ret = BAD_FUNC_ARG;
  8310. }
  8311. if (ret == 0) {
  8312. /* Encode PKCS#8 key. */
  8313. SetASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8314. dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8315. (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
  8316. out);
  8317. if (salt == NULL) {
  8318. /* Generate salt into encoding. */
  8319. salt = (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT].data.buffer.data;
  8320. ret = wc_RNG_GenerateBlock(rng, salt, saltSz);
  8321. }
  8322. }
  8323. if (ret == 0) {
  8324. /* Store PKCS#8 key in output buffer. */
  8325. pkcs8 = (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCDATA].data.buffer.data;
  8326. XMEMCPY(pkcs8, input, inputSz);
  8327. Pkcs8Pad(pkcs8, inputSz, blockSz);
  8328. /* Encrypt PKCS#8 key inline. */
  8329. ret = wc_CryptKey(password, passwordSz, salt, saltSz, itt, id, pkcs8,
  8330. pkcs8Sz, version, cbcIv, 1, 0);
  8331. }
  8332. if (ret == 0) {
  8333. /* Returning size on success. */
  8334. ret = sz;
  8335. }
  8336. FREE_ASNSETDATA(dataASN, heap);
  8337. return ret;
  8338. #endif /* WOLFSSL_ASN_TEMPLATE */
  8339. }
  8340. #endif /* HAVE_PKCS12 */
  8341. #endif /* NO_PWDBASED */
  8342. #ifndef NO_RSA
  8343. #ifndef HAVE_USER_RSA
  8344. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  8345. /* This function is to retrieve key position information in a cert.*
  8346. * The information will be used to call TSIP TLS-linked API for *
  8347. * certificate verification. */
  8348. static int RsaPublicKeyDecodeRawIndex(const byte* input, word32* inOutIdx,
  8349. word32 inSz, word32* key_n,
  8350. word32* key_n_len, word32* key_e,
  8351. word32* key_e_len)
  8352. {
  8353. int ret = 0;
  8354. int length = 0;
  8355. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8356. byte b;
  8357. #endif
  8358. if (input == NULL || inOutIdx == NULL)
  8359. return BAD_FUNC_ARG;
  8360. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8361. return ASN_PARSE_E;
  8362. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8363. if ((*inOutIdx + 1) > inSz)
  8364. return BUFFER_E;
  8365. b = input[*inOutIdx];
  8366. if (b != ASN_INTEGER) {
  8367. /* not from decoded cert, will have algo id, skip past */
  8368. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8369. return ASN_PARSE_E;
  8370. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  8371. return ASN_PARSE_E;
  8372. /* Option NULL ASN.1 tag */
  8373. if (*inOutIdx >= inSz) {
  8374. return BUFFER_E;
  8375. }
  8376. if (input[*inOutIdx] == ASN_TAG_NULL) {
  8377. ret = GetASNNull(input, inOutIdx, inSz);
  8378. if (ret != 0)
  8379. return ret;
  8380. }
  8381. /* TODO: support RSA PSS */
  8382. /* should have bit tag length and seq next */
  8383. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  8384. if (ret != 0)
  8385. return ret;
  8386. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8387. return ASN_PARSE_E;
  8388. }
  8389. #endif /* OPENSSL_EXTRA */
  8390. /* Get modulus */
  8391. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8392. *key_n += *inOutIdx;
  8393. if (ret < 0) {
  8394. return ASN_RSA_KEY_E;
  8395. }
  8396. if (key_n_len)
  8397. *key_n_len = length;
  8398. *inOutIdx += length;
  8399. /* Get exponent */
  8400. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8401. *key_e += *inOutIdx;
  8402. if (ret < 0) {
  8403. return ASN_RSA_KEY_E;
  8404. }
  8405. if (key_e_len)
  8406. *key_e_len = length;
  8407. return ret;
  8408. }
  8409. #endif /* WOLFSSL_RENESAS_TSIP */
  8410. #ifdef WOLFSSL_ASN_TEMPLATE
  8411. /* ASN.1 template for an RSA public key.
  8412. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8413. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8414. */
  8415. static const ASNItem rsaPublicKeyASN[] = {
  8416. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8417. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8418. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8419. /* ALGOID_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  8420. #ifdef WC_RSA_PSS
  8421. /* ALGOID_P_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  8422. #endif
  8423. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 1, 0 },
  8424. /* RSAPublicKey */
  8425. /* PUBKEY_RSA_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8426. /* PUBKEY_RSA_N */ { 3, ASN_INTEGER, 0, 0, 0 },
  8427. /* PUBKEY_RSA_E */ { 3, ASN_INTEGER, 0, 0, 0 },
  8428. };
  8429. enum {
  8430. RSAPUBLICKEYASN_IDX_SEQ = 0,
  8431. RSAPUBLICKEYASN_IDX_ALGOID_SEQ,
  8432. RSAPUBLICKEYASN_IDX_ALGOID_OID,
  8433. RSAPUBLICKEYASN_IDX_ALGOID_NULL,
  8434. #ifdef WC_RSA_PSS
  8435. RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ,
  8436. #endif
  8437. RSAPUBLICKEYASN_IDX_PUBKEY,
  8438. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ,
  8439. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N,
  8440. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E,
  8441. };
  8442. /* Number of items in ASN.1 template for an RSA public key. */
  8443. #define rsaPublicKeyASN_Length (sizeof(rsaPublicKeyASN) / sizeof(ASNItem))
  8444. #endif
  8445. /* Decode RSA public key.
  8446. *
  8447. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8448. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8449. *
  8450. * @param [in] input Buffer holding BER encoded data.
  8451. * @param [in, out] inOutIdx On in, start of RSA public key.
  8452. * On out, start of ASN.1 item after RSA public key.
  8453. * @param [in] inSz Number of bytes in buffer.
  8454. * @param [out] n Pointer to modulus in buffer.
  8455. * @param [out] nSz Size of modulus in bytes.
  8456. * @param [out] e Pointer to exponent in buffer.
  8457. * @param [out] eSz Size of exponent in bytes.
  8458. * @return 0 on success.
  8459. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8460. * is invalid.
  8461. * @return BUFFER_E when data in buffer is too small.
  8462. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8463. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8464. * non-zero length.
  8465. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8466. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8467. */
  8468. int wc_RsaPublicKeyDecode_ex(const byte* input, word32* inOutIdx, word32 inSz,
  8469. const byte** n, word32* nSz, const byte** e, word32* eSz)
  8470. {
  8471. #ifndef WOLFSSL_ASN_TEMPLATE
  8472. int ret = 0;
  8473. int length = 0;
  8474. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8475. word32 localIdx;
  8476. byte tag;
  8477. #endif
  8478. if (input == NULL || inOutIdx == NULL)
  8479. return BAD_FUNC_ARG;
  8480. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8481. return ASN_PARSE_E;
  8482. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8483. localIdx = *inOutIdx;
  8484. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  8485. return BUFFER_E;
  8486. if (tag != ASN_INTEGER) {
  8487. /* not from decoded cert, will have algo id, skip past */
  8488. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8489. return ASN_PARSE_E;
  8490. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  8491. return ASN_PARSE_E;
  8492. /* Option NULL ASN.1 tag */
  8493. if (*inOutIdx >= inSz) {
  8494. return BUFFER_E;
  8495. }
  8496. localIdx = *inOutIdx;
  8497. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  8498. return ASN_PARSE_E;
  8499. if (tag == ASN_TAG_NULL) {
  8500. ret = GetASNNull(input, inOutIdx, inSz);
  8501. if (ret != 0)
  8502. return ret;
  8503. }
  8504. #ifdef WC_RSA_PSS
  8505. /* Skip RSA PSS parameters. */
  8506. else if (tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  8507. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8508. return ASN_PARSE_E;
  8509. *inOutIdx += length;
  8510. }
  8511. #endif
  8512. /* should have bit tag length and seq next */
  8513. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  8514. if (ret != 0)
  8515. return ret;
  8516. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8517. return ASN_PARSE_E;
  8518. }
  8519. #endif /* OPENSSL_EXTRA */
  8520. /* Get modulus */
  8521. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8522. if (ret < 0) {
  8523. return ASN_RSA_KEY_E;
  8524. }
  8525. if (nSz)
  8526. *nSz = length;
  8527. if (n)
  8528. *n = &input[*inOutIdx];
  8529. *inOutIdx += length;
  8530. /* Get exponent */
  8531. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8532. if (ret < 0) {
  8533. return ASN_RSA_KEY_E;
  8534. }
  8535. if (eSz)
  8536. *eSz = length;
  8537. if (e)
  8538. *e = &input[*inOutIdx];
  8539. *inOutIdx += length;
  8540. return ret;
  8541. #else
  8542. DECL_ASNGETDATA(dataASN, rsaPublicKeyASN_Length);
  8543. int ret = 0;
  8544. #ifdef WC_RSA_PSS
  8545. word32 oid = RSAk;
  8546. #endif
  8547. /* Check validity of parameters. */
  8548. if (input == NULL || inOutIdx == NULL) {
  8549. ret = BAD_FUNC_ARG;
  8550. }
  8551. CALLOC_ASNGETDATA(dataASN, rsaPublicKeyASN_Length, ret, NULL);
  8552. if (ret == 0) {
  8553. /* Try decoding PKCS #1 public key by ignoring rest of ASN.1. */
  8554. ret = GetASN_Items(&rsaPublicKeyASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8555. &dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8556. (int)(rsaPublicKeyASN_Length - RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ),
  8557. 0, input, inOutIdx, inSz);
  8558. if (ret != 0) {
  8559. /* Didn't work - try whole SubjectKeyInfo instead. */
  8560. #ifdef WC_RSA_PSS
  8561. /* Could be RSA or RSA PSS key. */
  8562. GetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], oidKeyType);
  8563. #else
  8564. /* Set the OID to expect. */
  8565. GetASN_ExpBuffer(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID],
  8566. keyRsaOid, sizeof(keyRsaOid));
  8567. #endif
  8568. /* Decode SubjectKeyInfo. */
  8569. ret = GetASN_Items(rsaPublicKeyASN, dataASN,
  8570. rsaPublicKeyASN_Length, 1, input, inOutIdx,
  8571. inSz);
  8572. }
  8573. }
  8574. #ifdef WC_RSA_PSS
  8575. if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].tag != 0)) {
  8576. /* Two possible OIDs supported - RSA and RSA PSS. */
  8577. oid = dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].data.oid.sum;
  8578. if ((oid != RSAk) && (oid != RSAPSSk)) {
  8579. ret = ASN_PARSE_E;
  8580. }
  8581. }
  8582. if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].tag != 0)) {
  8583. /* Can't have NULL and SEQ. */
  8584. if (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_NULL].tag != 0) {
  8585. ret = ASN_PARSE_E;
  8586. }
  8587. /* SEQ present only with RSA PSS. */
  8588. if ((ret == 0) && (oid != RSAPSSk)) {
  8589. ret = ASN_PARSE_E;
  8590. }
  8591. if (ret == 0) {
  8592. enum wc_HashType hash;
  8593. int mgf;
  8594. int saltLen;
  8595. const byte* params = GetASNItem_Addr(
  8596. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
  8597. word32 paramsSz = GetASNItem_Length(
  8598. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
  8599. /* Validate the private key parameters. */
  8600. ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf, &saltLen);
  8601. /* TODO: store parameters so that usage can be checked. */
  8602. }
  8603. }
  8604. #endif
  8605. if (ret == 0) {
  8606. /* Return the buffers and lengths asked for. */
  8607. if (n != NULL) {
  8608. *n = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.data;
  8609. }
  8610. if (nSz != NULL) {
  8611. *nSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.length;
  8612. }
  8613. if (e != NULL) {
  8614. *e = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.data;
  8615. }
  8616. if (eSz != NULL) {
  8617. *eSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.length;
  8618. }
  8619. }
  8620. FREE_ASNGETDATA(dataASN, NULL);
  8621. return ret;
  8622. #endif /* WOLFSSL_ASN_TEMPLATE */
  8623. }
  8624. /* Decode RSA public key.
  8625. *
  8626. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8627. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8628. *
  8629. * @param [in] input Buffer holding BER encoded data.
  8630. * @param [in, out] inOutIdx On in, start of RSA public key.
  8631. * On out, start of ASN.1 item after RSA public key.
  8632. * @param [in, out] key RSA key object.
  8633. * @param [in] inSz Number of bytes in buffer.
  8634. * @return 0 on success.
  8635. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8636. * is invalid.
  8637. * @return BUFFER_E when data in buffer is too small.
  8638. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8639. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8640. * non-zero length.
  8641. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8642. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8643. */
  8644. int wc_RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  8645. word32 inSz)
  8646. {
  8647. #ifndef WOLFSSL_ASN_TEMPLATE
  8648. int ret;
  8649. const byte *n = NULL, *e = NULL;
  8650. word32 nSz = 0, eSz = 0;
  8651. if (key == NULL)
  8652. return BAD_FUNC_ARG;
  8653. ret = wc_RsaPublicKeyDecode_ex(input, inOutIdx, inSz, &n, &nSz, &e, &eSz);
  8654. if (ret == 0) {
  8655. ret = wc_RsaPublicKeyDecodeRaw(n, nSz, e, eSz, key);
  8656. }
  8657. return ret;
  8658. #else
  8659. DECL_ASNGETDATA(dataASN, rsaPublicKeyASN_Length);
  8660. int ret = 0;
  8661. /* Check validity of parameters. */
  8662. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  8663. ret = BAD_FUNC_ARG;
  8664. }
  8665. CALLOC_ASNGETDATA(dataASN, rsaPublicKeyASN_Length, ret, NULL);
  8666. if (ret == 0) {
  8667. /* Set mp_ints to fill with modulus and exponent data. */
  8668. GetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], &key->n);
  8669. GetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], &key->e);
  8670. /* Try decoding PKCS #1 public key by ignoring rest of ASN.1. */
  8671. ret = GetASN_Items(&rsaPublicKeyASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8672. &dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8673. (int)(rsaPublicKeyASN_Length - RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ),
  8674. 0, input, inOutIdx, inSz);
  8675. if (ret != 0) {
  8676. mp_free(&key->n);
  8677. mp_free(&key->e);
  8678. /* Didn't work - try whole SubjectKeyInfo instead. */
  8679. /* Set the OID to expect. */
  8680. GetASN_ExpBuffer(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID],
  8681. keyRsaOid, sizeof(keyRsaOid));
  8682. /* Decode SubjectKeyInfo. */
  8683. ret = GetASN_Items(rsaPublicKeyASN, dataASN,
  8684. rsaPublicKeyASN_Length, 1, input, inOutIdx,
  8685. inSz);
  8686. }
  8687. }
  8688. FREE_ASNGETDATA(dataASN, NULL);
  8689. return ret;
  8690. #endif
  8691. }
  8692. /* import RSA public key elements (n, e) into RsaKey structure (key) */
  8693. int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e,
  8694. word32 eSz, RsaKey* key)
  8695. {
  8696. if (n == NULL || e == NULL || key == NULL)
  8697. return BAD_FUNC_ARG;
  8698. key->type = RSA_PUBLIC;
  8699. if (mp_init(&key->n) != MP_OKAY)
  8700. return MP_INIT_E;
  8701. if (mp_read_unsigned_bin(&key->n, n, nSz) != 0) {
  8702. mp_clear(&key->n);
  8703. return ASN_GETINT_E;
  8704. }
  8705. #ifdef HAVE_WOLF_BIGINT
  8706. if ((int)nSz > 0 && wc_bigint_from_unsigned_bin(&key->n.raw, n, nSz) != 0) {
  8707. mp_clear(&key->n);
  8708. return ASN_GETINT_E;
  8709. }
  8710. #endif /* HAVE_WOLF_BIGINT */
  8711. if (mp_init(&key->e) != MP_OKAY) {
  8712. mp_clear(&key->n);
  8713. return MP_INIT_E;
  8714. }
  8715. if (mp_read_unsigned_bin(&key->e, e, eSz) != 0) {
  8716. mp_clear(&key->n);
  8717. mp_clear(&key->e);
  8718. return ASN_GETINT_E;
  8719. }
  8720. #ifdef HAVE_WOLF_BIGINT
  8721. if ((int)eSz > 0 && wc_bigint_from_unsigned_bin(&key->e.raw, e, eSz) != 0) {
  8722. mp_clear(&key->n);
  8723. mp_clear(&key->e);
  8724. return ASN_GETINT_E;
  8725. }
  8726. #endif /* HAVE_WOLF_BIGINT */
  8727. #ifdef WOLFSSL_XILINX_CRYPT
  8728. if (wc_InitRsaHw(key) != 0) {
  8729. return BAD_STATE_E;
  8730. }
  8731. #endif
  8732. return 0;
  8733. }
  8734. #endif /* HAVE_USER_RSA */
  8735. #endif /* !NO_RSA */
  8736. #ifndef NO_DH
  8737. #if defined(WOLFSSL_DH_EXTRA)
  8738. /*
  8739. * Decodes DH public key to fill specified DhKey.
  8740. *
  8741. * return 0 on success, negative on failure
  8742. */
  8743. int wc_DhPublicKeyDecode(const byte* input, word32* inOutIdx,
  8744. DhKey* key, word32 inSz)
  8745. {
  8746. int ret = 0;
  8747. int length;
  8748. word32 oid = 0;
  8749. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  8750. return BAD_FUNC_ARG;
  8751. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8752. return ASN_PARSE_E;
  8753. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8754. return ASN_PARSE_E;
  8755. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  8756. if (oid != DHk || ret < 0)
  8757. return ASN_DH_KEY_E;
  8758. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8759. return ASN_PARSE_E;
  8760. if (GetInt(&key->p, input, inOutIdx, inSz) < 0)
  8761. return ASN_DH_KEY_E;
  8762. if (GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8763. mp_clear(&key->p);
  8764. return ASN_DH_KEY_E;
  8765. }
  8766. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  8767. if (ret > 0) {
  8768. /* Found Bit String WOLFSSL_DH_EXTRA is required to access DhKey.pub */
  8769. if (GetInt(&key->pub, input, inOutIdx, inSz) < 0) {
  8770. mp_clear(&key->p);
  8771. mp_clear(&key->g);
  8772. return ASN_DH_KEY_E;
  8773. }
  8774. }
  8775. else {
  8776. mp_clear(&key->p);
  8777. mp_clear(&key->g);
  8778. return ASN_DH_KEY_E;
  8779. }
  8780. return 0;
  8781. }
  8782. #endif /* WOLFSSL_DH_EXTRA */
  8783. #ifdef WOLFSSL_ASN_TEMPLATE
  8784. /* ASN.1 template for DH key.
  8785. * PKCS #3, 9 - DHParameter.
  8786. * (Also in: RFC 2786, 3)
  8787. */
  8788. static const ASNItem dhParamASN[] = {
  8789. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8790. /* prime */
  8791. /* PRIME */ { 1, ASN_INTEGER, 0, 0, 0 },
  8792. /* base */
  8793. /* BASE */ { 1, ASN_INTEGER, 0, 0, 0 },
  8794. /* privateValueLength */
  8795. /* PRIVLEN */ { 1, ASN_INTEGER, 0, 0, 1 },
  8796. };
  8797. enum {
  8798. DHPARAMASN_IDX_SEQ = 0,
  8799. DHPARAMASN_IDX_PRIME,
  8800. DHPARAMASN_IDX_BASE,
  8801. DHPARAMASN_IDX_PRIVLEN,
  8802. };
  8803. /* Number of items in ASN.1 template for DH key. */
  8804. #define dhParamASN_Length (sizeof(dhParamASN) / sizeof(ASNItem))
  8805. #ifdef WOLFSSL_DH_EXTRA
  8806. /* ASN.1 template for DH key wrapped in PKCS #8 or SubjectPublicKeyInfo.
  8807. * PKCS #8: RFC 5208, 5 - PrivateKeyInfo
  8808. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8809. * RFC 3279, 2.3.3 - DH in SubjectPublicKeyInfo
  8810. */
  8811. static const ASNItem dhKeyPkcs8ASN[] = {
  8812. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8813. /* VER */ { 1, ASN_INTEGER, 0, 0, 1 },
  8814. /* PKEYALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8815. /* PKEYALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8816. /* DHParameter */
  8817. /* PKEYALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8818. /* p */
  8819. /* PKEYALGO_PARAM_P */ { 3, ASN_INTEGER, 0, 0, 0 },
  8820. /* g */
  8821. /* PKEYALGO_PARAM_G */ { 3, ASN_INTEGER, 0, 0, 0 },
  8822. /* q - factor of p-1 */
  8823. /* PKEYALGO_PARAM_Q */ { 3, ASN_INTEGER, 0, 0, 1 },
  8824. /* j - subgroup factor */
  8825. /* PKEYALGO_PARAM_J */ { 3, ASN_INTEGER, 0, 0, 1 },
  8826. /* ValidationParms */
  8827. /* PKEYALGO_PARAM_VALID */ { 3, ASN_SEQUENCE, 0, 0, 1 },
  8828. /* PrivateKey - PKCS #8 */
  8829. /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 2 },
  8830. /* PKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
  8831. /* PublicKey - SubjectPublicKeyInfo. */
  8832. /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 2 },
  8833. /* PUBKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
  8834. };
  8835. enum {
  8836. DHKEYPKCS8ASN_IDX_SEQ = 0,
  8837. DHKEYPKCS8ASN_IDX_VER,
  8838. DHKEYPKCS8ASN_IDX_PKEYALGO_SEQ,
  8839. DHKEYPKCS8ASN_IDX_PKEYALGO_OID,
  8840. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_SEQ,
  8841. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P,
  8842. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G,
  8843. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q,
  8844. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J,
  8845. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID,
  8846. DHKEYPKCS8ASN_IDX_PKEY_STR,
  8847. DHKEYPKCS8ASN_IDX_PKEY_INT,
  8848. DHKEYPKCS8ASN_IDX_PUBKEY_STR,
  8849. DHKEYPKCS8ASN_IDX_PUBKEY_INT,
  8850. };
  8851. #define dhKeyPkcs8ASN_Length (sizeof(dhKeyPkcs8ASN) / sizeof(ASNItem))
  8852. #endif
  8853. #endif
  8854. /* Decodes either PKCS#3 DH parameters or PKCS#8 DH key file (WOLFSSL_DH_EXTRA).
  8855. *
  8856. * See also wc_DhParamsLoad(). Loads directly into buffers rather than key
  8857. * object.
  8858. *
  8859. * @param [in] input BER/DER encoded data.
  8860. * @param [in, out] inOutIdx On in, start of DH key data.
  8861. * On out, end of DH key data.
  8862. * @param [in, out] key DH key object.
  8863. * @param [in] inSz Size of data in bytes.
  8864. * @return 0 on success.
  8865. * @return BAD_FUNC_ARG when input, inOutIDx or key is NULL.
  8866. * @return MEMORY_E when dynamic memory allocation fails.
  8867. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8868. * is invalid.
  8869. * @return BUFFER_E when data in buffer is too small.
  8870. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8871. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8872. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8873. * non-zero length.
  8874. * @return MP_INIT_E when the unable to initialize an mp_int.
  8875. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  8876. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8877. */
  8878. int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
  8879. {
  8880. #ifndef WOLFSSL_ASN_TEMPLATE
  8881. int ret = 0;
  8882. int length;
  8883. #ifdef WOLFSSL_DH_EXTRA
  8884. #if !defined(HAVE_FIPS) || \
  8885. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8886. word32 oid = 0, temp = 0;
  8887. #endif
  8888. #endif
  8889. WOLFSSL_ENTER("wc_DhKeyDecode");
  8890. if (inOutIdx == NULL)
  8891. return BAD_FUNC_ARG;
  8892. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8893. return ASN_PARSE_E;
  8894. #ifdef WOLFSSL_DH_EXTRA
  8895. #if !defined(HAVE_FIPS) || \
  8896. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8897. temp = *inOutIdx;
  8898. #endif
  8899. #endif
  8900. /* Assume input started after 1.2.840.113549.1.3.1 dhKeyAgreement */
  8901. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  8902. ret = ASN_DH_KEY_E;
  8903. }
  8904. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8905. mp_clear(&key->p);
  8906. ret = ASN_DH_KEY_E;
  8907. }
  8908. #ifdef WOLFSSL_DH_EXTRA
  8909. #if !defined(HAVE_FIPS) || \
  8910. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8911. /* If ASN_DH_KEY_E: Check if input started at beginning of key */
  8912. if (ret == ASN_DH_KEY_E) {
  8913. *inOutIdx = temp;
  8914. /* the version (0) - private only (for public skip) */
  8915. if (GetASNInt(input, inOutIdx, &length, inSz) == 0) {
  8916. *inOutIdx += length;
  8917. }
  8918. /* Size of dhKeyAgreement section */
  8919. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8920. return ASN_PARSE_E;
  8921. /* Check for dhKeyAgreement */
  8922. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  8923. if (oid != DHk || ret < 0)
  8924. return ASN_DH_KEY_E;
  8925. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8926. return ASN_PARSE_E;
  8927. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  8928. return ASN_DH_KEY_E;
  8929. }
  8930. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8931. mp_clear(&key->p);
  8932. return ASN_DH_KEY_E;
  8933. }
  8934. }
  8935. temp = *inOutIdx;
  8936. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  8937. if (ret > 0) {
  8938. /* Found Bit String */
  8939. if (GetInt(&key->pub, input, inOutIdx, inSz) == 0) {
  8940. WOLFSSL_MSG("Found Public Key");
  8941. ret = 0;
  8942. }
  8943. } else {
  8944. *inOutIdx = temp;
  8945. ret = (GetOctetString(input, inOutIdx, &length, inSz) >= 0);
  8946. if (ret > 0) {
  8947. /* Found Octet String */
  8948. if (GetInt(&key->priv, input, inOutIdx, inSz) == 0) {
  8949. WOLFSSL_MSG("Found Private Key");
  8950. /* Compute public */
  8951. ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
  8952. }
  8953. } else {
  8954. /* Don't use length from failed CheckBitString/GetOctetString */
  8955. *inOutIdx = temp;
  8956. ret = 0;
  8957. }
  8958. }
  8959. #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
  8960. #endif /* WOLFSSL_DH_EXTRA */
  8961. WOLFSSL_LEAVE("wc_DhKeyDecode", ret);
  8962. return ret;
  8963. #else
  8964. #ifdef WOLFSSL_DH_EXTRA
  8965. DECL_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length);
  8966. #else
  8967. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  8968. #endif
  8969. int ret = 0;
  8970. /* Check input parameters are valid. */
  8971. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  8972. ret = BAD_FUNC_ARG;
  8973. }
  8974. #ifdef WOLFSSL_DH_EXTRA
  8975. ALLOC_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length, ret, key->heap);
  8976. #else
  8977. ALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, key->heap);
  8978. #endif
  8979. if (ret == 0) {
  8980. /* Initialize data and set mp_ints to hold p and g. */
  8981. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhParamASN_Length);
  8982. GetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
  8983. GetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
  8984. /* Try simple PKCS #3 template. */
  8985. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  8986. inOutIdx, inSz);
  8987. #ifdef WOLFSSL_DH_EXTRA
  8988. if (ret != 0) {
  8989. mp_free(&key->p);
  8990. mp_free(&key->g);
  8991. /* Initialize data and set mp_ints to hold p, g, q, priv and pub. */
  8992. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhKeyPkcs8ASN_Length);
  8993. GetASN_ExpBuffer(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID],
  8994. keyDhOid, sizeof(keyDhOid));
  8995. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
  8996. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
  8997. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q], &key->q);
  8998. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
  8999. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
  9000. /* Try PKCS #8 wrapped template. */
  9001. ret = GetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, 1,
  9002. input, inOutIdx, inSz);
  9003. if (ret == 0) {
  9004. /* VERSION only present in PKCS #8 private key structure */
  9005. if ((dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].length != 0) &&
  9006. (dataASN[DHKEYPKCS8ASN_IDX_VER].length == 0)) {
  9007. ret = ASN_PARSE_E;
  9008. }
  9009. else if ((dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].length != 0) &&
  9010. (dataASN[DHKEYPKCS8ASN_IDX_VER].length != 0)) {
  9011. ret = ASN_PARSE_E;
  9012. }
  9013. }
  9014. }
  9015. #endif
  9016. }
  9017. FREE_ASNGETDATA(dataASN, key->heap);
  9018. return ret;
  9019. #endif /* WOLFSSL_ASN_TEMPLATE */
  9020. }
  9021. #ifdef WOLFSSL_DH_EXTRA
  9022. /* Export DH Key (private or public) */
  9023. int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv)
  9024. {
  9025. #ifndef WOLFSSL_ASN_TEMPLATE
  9026. int ret, privSz = 0, pubSz = 0, keySz;
  9027. word32 idx, len, total;
  9028. if (key == NULL || outSz == NULL) {
  9029. return BAD_FUNC_ARG;
  9030. }
  9031. /* determine size */
  9032. if (exportPriv) {
  9033. /* octect string: priv */
  9034. privSz = SetASNIntMP(&key->priv, -1, NULL);
  9035. idx = 1 + SetLength(privSz, NULL) + privSz; /* +1 for ASN_OCTET_STRING */
  9036. }
  9037. else {
  9038. /* bit string: public */
  9039. pubSz = SetASNIntMP(&key->pub, -1, NULL);
  9040. idx = SetBitString(pubSz, 0, NULL) + pubSz;
  9041. }
  9042. keySz = idx;
  9043. /* DH Parameters sequence with P and G */
  9044. total = 0;
  9045. ret = wc_DhParamsToDer(key, NULL, &total);
  9046. if (ret != LENGTH_ONLY_E)
  9047. return ret;
  9048. idx += total;
  9049. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  9050. idx += SetObjectId(sizeof(keyDhOid), NULL);
  9051. idx += sizeof(keyDhOid);
  9052. len = idx - keySz;
  9053. /* sequence - all but pub/priv */
  9054. idx += SetSequence(len, NULL);
  9055. if (exportPriv) {
  9056. /* version: 0 (ASN_INTEGER, 0x01, 0x00) */
  9057. idx += 3;
  9058. }
  9059. /* sequence */
  9060. total = idx + SetSequence(idx, NULL);
  9061. /* if no output, then just getting size */
  9062. if (output == NULL) {
  9063. *outSz = total;
  9064. return LENGTH_ONLY_E;
  9065. }
  9066. /* make sure output fits in buffer */
  9067. if (total > *outSz) {
  9068. return BUFFER_E;
  9069. }
  9070. total = idx;
  9071. /* sequence */
  9072. idx = SetSequence(total, output);
  9073. if (exportPriv) {
  9074. /* version: 0 */
  9075. idx += SetMyVersion(0, output + idx, 0);
  9076. }
  9077. /* sequence - all but pub/priv */
  9078. idx += SetSequence(len, output + idx);
  9079. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  9080. idx += SetObjectId(sizeof(keyDhOid), output + idx);
  9081. XMEMCPY(output + idx, keyDhOid, sizeof(keyDhOid));
  9082. idx += sizeof(keyDhOid);
  9083. /* DH Parameters sequence with P and G */
  9084. total = *outSz - idx;
  9085. ret = wc_DhParamsToDer(key, output + idx, &total);
  9086. if (ret < 0)
  9087. return ret;
  9088. idx += total;
  9089. /* octect string: priv */
  9090. if (exportPriv) {
  9091. idx += SetOctetString(privSz, output + idx);
  9092. idx += SetASNIntMP(&key->priv, -1, output + idx);
  9093. }
  9094. else {
  9095. /* bit string: public */
  9096. idx += SetBitString(pubSz, 0, output + idx);
  9097. idx += SetASNIntMP(&key->pub, -1, output + idx);
  9098. }
  9099. *outSz = idx;
  9100. return idx;
  9101. #else
  9102. ASNSetData dataASN[dhKeyPkcs8ASN_Length];
  9103. int ret = 0;
  9104. int sz;
  9105. WOLFSSL_ENTER("wc_DhKeyToDer");
  9106. XMEMSET(dataASN, 0, sizeof(dataASN));
  9107. SetASN_Int8Bit(&dataASN[DHKEYPKCS8ASN_IDX_VER], 0);
  9108. SetASN_OID(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID], DHk, oidKeyType);
  9109. /* Set mp_int containing p and g. */
  9110. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
  9111. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
  9112. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q].noOut = 1;
  9113. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J].noOut = 1;
  9114. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID].noOut = 1;
  9115. if (exportPriv) {
  9116. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
  9117. dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_STR].noOut = 1;
  9118. dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].noOut = 1;
  9119. }
  9120. else {
  9121. dataASN[DHKEYPKCS8ASN_IDX_VER].noOut = 1;
  9122. dataASN[DHKEYPKCS8ASN_IDX_PKEY_STR].noOut = 1;
  9123. dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].noOut = 1;
  9124. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
  9125. }
  9126. /* Calculate the size of the DH parameters. */
  9127. ret = SizeASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, &sz);
  9128. if (output == NULL) {
  9129. *outSz = sz;
  9130. ret = LENGTH_ONLY_E;
  9131. }
  9132. /* Check buffer is big enough for encoding. */
  9133. if ((ret == 0) && ((int)*outSz < sz)) {
  9134. ret = BUFFER_E;
  9135. }
  9136. if (ret == 0) {
  9137. /* Encode the DH parameters into buffer. */
  9138. SetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, output);
  9139. /* Set the actual encoding size. */
  9140. *outSz = sz;
  9141. /* Return the actual encoding size. */
  9142. ret = sz;
  9143. }
  9144. return ret;
  9145. #endif
  9146. }
  9147. int wc_DhPubKeyToDer(DhKey* key, byte* out, word32* outSz)
  9148. {
  9149. return wc_DhKeyToDer(key, out, outSz, 0);
  9150. }
  9151. int wc_DhPrivKeyToDer(DhKey* key, byte* out, word32* outSz)
  9152. {
  9153. return wc_DhKeyToDer(key, out, outSz, 1);
  9154. }
  9155. /* Convert DH key parameters to DER format, write to output (outSz)
  9156. * If output is NULL then max expected size is set to outSz and LENGTH_ONLY_E is
  9157. * returned.
  9158. *
  9159. * Note : static function due to redefinition complications with DhKey and FIPS
  9160. * version 2 build.
  9161. *
  9162. * return bytes written on success */
  9163. int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz)
  9164. {
  9165. #ifndef WOLFSSL_ASN_TEMPLATE
  9166. word32 idx, total;
  9167. if (key == NULL || outSz == NULL) {
  9168. return BAD_FUNC_ARG;
  9169. }
  9170. /* determine size */
  9171. /* integer - g */
  9172. idx = SetASNIntMP(&key->g, -1, NULL);
  9173. /* integer - p */
  9174. idx += SetASNIntMP(&key->p, -1, NULL);
  9175. total = idx;
  9176. /* sequence */
  9177. idx += SetSequence(idx, NULL);
  9178. if (output == NULL) {
  9179. *outSz = idx;
  9180. return LENGTH_ONLY_E;
  9181. }
  9182. /* make sure output fits in buffer */
  9183. if (idx > *outSz) {
  9184. return BUFFER_E;
  9185. }
  9186. /* write DH parameters */
  9187. /* sequence - for P and G only */
  9188. idx = SetSequence(total, output);
  9189. /* integer - p */
  9190. idx += SetASNIntMP(&key->p, -1, output + idx);
  9191. /* integer - g */
  9192. idx += SetASNIntMP(&key->g, -1, output + idx);
  9193. *outSz = idx;
  9194. return idx;
  9195. #else
  9196. ASNSetData dataASN[dhParamASN_Length];
  9197. int ret = 0;
  9198. int sz = 0;
  9199. WOLFSSL_ENTER("wc_DhParamsToDer");
  9200. if (key == NULL || outSz == NULL) {
  9201. ret = BAD_FUNC_ARG;
  9202. }
  9203. if (ret == 0) {
  9204. XMEMSET(dataASN, 0, sizeof(dataASN));
  9205. /* Set mp_int containing p and g. */
  9206. SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
  9207. SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
  9208. /* privateValueLength not encoded. */
  9209. dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
  9210. /* Calculate the size of the DH parameters. */
  9211. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  9212. }
  9213. if ((ret == 0) && (output == NULL)) {
  9214. *outSz = sz;
  9215. ret = LENGTH_ONLY_E;
  9216. }
  9217. /* Check buffer is big enough for encoding. */
  9218. if ((ret == 0) && (*outSz < (word32)sz)) {
  9219. ret = BUFFER_E;
  9220. }
  9221. if (ret == 0) {
  9222. /* Encode the DH parameters into buffer. */
  9223. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, output);
  9224. /* Set the actual encoding size. */
  9225. *outSz = sz;
  9226. /* Return count of bytes written. */
  9227. ret = sz;
  9228. }
  9229. return ret;
  9230. #endif
  9231. }
  9232. #endif /* WOLFSSL_DH_EXTRA */
  9233. /* Decode DH parameters.
  9234. *
  9235. * PKCS #3, 9 - DHParameter.
  9236. * (Also in: RFC 2786, 3)
  9237. *
  9238. * @param [in] input Buffer holding BER encoded data.
  9239. * @param [in, out] inOutIdx On in, start of RSA public key.
  9240. * On out, start of ASN.1 item after RSA public key.
  9241. * @param [in] inSz Number of bytes in buffer.
  9242. * @param [in, out] p Buffer to hold prime.
  9243. * @param [out] pInOutSz On in, size of buffer to hold prime in bytes.
  9244. * On out, size of prime in bytes.
  9245. * @param [in, out] g Buffer to hold base.
  9246. * @param [out] gInOutSz On in, size of buffer to hold base in bytes.
  9247. * On out, size of base in bytes.
  9248. * @return 0 on success.
  9249. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9250. * is invalid.
  9251. * @return BUFFER_E when data in buffer is too small.
  9252. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  9253. */
  9254. int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
  9255. byte* g, word32* gInOutSz)
  9256. {
  9257. #ifndef WOLFSSL_ASN_TEMPLATE
  9258. word32 idx = 0;
  9259. int ret;
  9260. int length;
  9261. if (GetSequence(input, &idx, &length, inSz) <= 0)
  9262. return ASN_PARSE_E;
  9263. ret = GetASNInt(input, &idx, &length, inSz);
  9264. if (ret != 0)
  9265. return ret;
  9266. if (length <= (int)*pInOutSz) {
  9267. XMEMCPY(p, &input[idx], length);
  9268. *pInOutSz = length;
  9269. }
  9270. else {
  9271. return BUFFER_E;
  9272. }
  9273. idx += length;
  9274. ret = GetASNInt(input, &idx, &length, inSz);
  9275. if (ret != 0)
  9276. return ret;
  9277. if (length <= (int)*gInOutSz) {
  9278. XMEMCPY(g, &input[idx], length);
  9279. *gInOutSz = length;
  9280. }
  9281. else {
  9282. return BUFFER_E;
  9283. }
  9284. return 0;
  9285. #else
  9286. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  9287. word32 idx = 0;
  9288. int ret = 0;
  9289. /* Make sure pointers are valid before use. */
  9290. if ((input == NULL) || (p == NULL) || (pInOutSz == NULL) || (g == NULL) ||
  9291. (gInOutSz == NULL)) {
  9292. ret = BAD_FUNC_ARG;
  9293. }
  9294. CALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, NULL);
  9295. if (ret == 0) {
  9296. /* Set the buffers to copy p and g into. */
  9297. GetASN_Buffer(&dataASN[DHPARAMASN_IDX_PRIME], p, pInOutSz);
  9298. GetASN_Buffer(&dataASN[DHPARAMASN_IDX_BASE], g, gInOutSz);
  9299. /* Decode the DH Parameters. */
  9300. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  9301. &idx, inSz);
  9302. }
  9303. FREE_ASNGETDATA(dataASN, NULL);
  9304. return ret;
  9305. #endif /* WOLFSSL_ASN_TEMPLATE */
  9306. }
  9307. #endif /* !NO_DH */
  9308. #ifndef NO_DSA
  9309. static mp_int* GetDsaInt(DsaKey* key, int idx)
  9310. {
  9311. if (idx == 0)
  9312. return &key->p;
  9313. if (idx == 1)
  9314. return &key->q;
  9315. if (idx == 2)
  9316. return &key->g;
  9317. if (idx == 3)
  9318. return &key->y;
  9319. if (idx == 4)
  9320. return &key->x;
  9321. return NULL;
  9322. }
  9323. #ifdef WOLFSSL_ASN_TEMPLATE
  9324. /* ASN.1 template for DSA public and private keys.
  9325. * Public key: seq, p, q, g, y
  9326. * Private key: seq, version, p, q, g, y, x
  9327. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9328. */
  9329. static const ASNItem dsaKeyASN[] = {
  9330. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9331. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  9332. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  9333. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  9334. /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
  9335. /* Y */ { 1, ASN_INTEGER, 0, 0, 0 },
  9336. /* X */ { 1, ASN_INTEGER, 0, 0, 0 },
  9337. };
  9338. enum {
  9339. DSAKEYASN_IDX_SEQ = 0,
  9340. DSAKEYASN_IDX_VER,
  9341. DSAKEYASN_IDX_P,
  9342. DSAKEYASN_IDX_Q,
  9343. DSAKEYASN_IDX_G,
  9344. DSAKEYASN_IDX_Y,
  9345. DSAKEYASN_IDX_X,
  9346. };
  9347. /* Number of items in ASN.1 template for DSA private key. */
  9348. #define dsaKeyASN_Length (sizeof(dsaKeyASN) / sizeof(ASNItem))
  9349. /* Number of items in ASN.1 template for DSA public key. */
  9350. #define dsaPublicKeyASN_Length ((sizeof(dsaKeyASN) / sizeof(ASNItem)) - 2)
  9351. /* ASN.1 template for PublicKeyInfo with DSA.
  9352. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  9353. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9354. */
  9355. static const ASNItem dsaPubKeyASN[] = {
  9356. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9357. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  9358. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  9359. /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  9360. /* p */
  9361. /* ALGOID_PARAMS_P */ { 3, ASN_INTEGER, 0, 0, 0 },
  9362. /* q */
  9363. /* ALGOID_PARAMS_Q */ { 3, ASN_INTEGER, 0, 0, 0 },
  9364. /* g */
  9365. /* ALGOID_PARAMS_G */ { 3, ASN_INTEGER, 0, 0, 0 },
  9366. /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 1 },
  9367. /* y */
  9368. /* PUBKEY_Y */ { 2, ASN_INTEGER, 0, 0, 0 },
  9369. };
  9370. enum {
  9371. DSAPUBKEYASN_IDX_SEQ = 0,
  9372. DSAPUBKEYASN_IDX_ALGOID_SEQ,
  9373. DSAPUBKEYASN_IDX_ALGOID_OID,
  9374. DSAPUBKEYASN_IDX_ALGOID_PARAMS,
  9375. DSAPUBKEYASN_IDX_ALGOID_PARAMS_P,
  9376. DSAPUBKEYASN_IDX_ALGOID_PARAMS_Q,
  9377. DSAPUBKEYASN_IDX_ALGOID_PARAMS_G,
  9378. DSAPUBKEYASN_IDX_PUBKEY_STR,
  9379. DSAPUBKEYASN_IDX_PUBKEY_Y,
  9380. };
  9381. /* Number of items in ASN.1 template for PublicKeyInfo with DSA. */
  9382. #define dsaPubKeyASN_Length (sizeof(dsaPubKeyASN) / sizeof(ASNItem))
  9383. #endif /* WOLFSSL_ASN_TEMPLATE */
  9384. /* Decode DSA public key.
  9385. *
  9386. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  9387. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9388. *
  9389. * @param [in] input Buffer holding BER encoded data.
  9390. * @param [in, out] inOutIdx On in, start of DSA public key.
  9391. * On out, start of ASN.1 item after DSA public key.
  9392. * @param [in, out] key DSA key object.
  9393. * @param [in] inSz Number of bytes in buffer.
  9394. * @return 0 on success.
  9395. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9396. * is invalid.
  9397. * @return BUFFER_E when data in buffer is too small.
  9398. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  9399. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  9400. * non-zero length.
  9401. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  9402. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  9403. */
  9404. int wc_DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9405. word32 inSz)
  9406. {
  9407. #ifndef WOLFSSL_ASN_TEMPLATE
  9408. int length;
  9409. int ret = 0;
  9410. word32 oid;
  9411. word32 maxIdx;
  9412. if (input == NULL || inOutIdx == NULL || key == NULL)
  9413. return BAD_FUNC_ARG;
  9414. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9415. return ASN_PARSE_E;
  9416. maxIdx = (word32)(*inOutIdx + length);
  9417. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  9418. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  9419. GetInt(&key->g, input, inOutIdx, maxIdx) < 0 ||
  9420. GetInt(&key->y, input, inOutIdx, maxIdx) < 0 )
  9421. ret = ASN_DH_KEY_E;
  9422. if (ret != 0) {
  9423. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9424. return ASN_PARSE_E;
  9425. ret = GetObjectId(input, inOutIdx, &oid, oidIgnoreType, inSz);
  9426. if (ret != 0)
  9427. return ret;
  9428. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9429. return ASN_PARSE_E;
  9430. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  9431. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  9432. GetInt(&key->g, input, inOutIdx, inSz) < 0)
  9433. return ASN_DH_KEY_E;
  9434. if (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) < 0)
  9435. return ASN_PARSE_E;
  9436. if (GetInt(&key->y, input, inOutIdx, inSz) < 0 )
  9437. return ASN_DH_KEY_E;
  9438. ret = 0;
  9439. }
  9440. key->type = DSA_PUBLIC;
  9441. return ret;
  9442. #else
  9443. /* dsaPubKeyASN is longer than dsaPublicKeyASN. */
  9444. DECL_ASNGETDATA(dataASN, dsaPubKeyASN_Length);
  9445. int ret = 0;
  9446. int i;
  9447. /* Validated parameters. */
  9448. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  9449. ret = BAD_FUNC_ARG;
  9450. }
  9451. ALLOC_ASNGETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  9452. if (ret == 0) {
  9453. /* Clear dynamic data items. */
  9454. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPublicKeyASN_Length);
  9455. /* seq
  9456. * p, q, g, y
  9457. * Start DSA ints from DSAKEYASN_IDX_VER instead of DSAKEYASN_IDX_P */
  9458. for (i = 0; i < DSA_INTS - 1; i++)
  9459. GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i], GetDsaInt(key, i));
  9460. /* Parse as simple form. */
  9461. ret = GetASN_Items(dsaKeyASN, dataASN, dsaPublicKeyASN_Length, 0, input,
  9462. inOutIdx, inSz);
  9463. if (ret != 0) {
  9464. /* Clear dynamic data items. */
  9465. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPubKeyASN_Length);
  9466. /* Set DSA OID to expect. */
  9467. GetASN_ExpBuffer(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID],
  9468. keyDsaOid, sizeof(keyDsaOid));
  9469. /* p, q, g */
  9470. for (i = 0; i < DSA_INTS - 2; i++)
  9471. GetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
  9472. GetDsaInt(key, i));
  9473. /* y */
  9474. GetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
  9475. /* Parse as SubjectPublicKeyInfo. */
  9476. ret = GetASN_Items(dsaPubKeyASN, dataASN, dsaPubKeyASN_Length, 1,
  9477. input, inOutIdx, inSz);
  9478. }
  9479. }
  9480. if (ret == 0) {
  9481. /* Data parsed - set type of key parsed. */
  9482. key->type = DSA_PUBLIC;
  9483. }
  9484. FREE_ASNGETDATA(dataASN, key->heap);
  9485. return ret;
  9486. #endif
  9487. }
  9488. int wc_DsaParamsDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9489. word32 inSz)
  9490. {
  9491. int length;
  9492. word32 maxIdx;
  9493. if (input == NULL || inOutIdx == NULL || key == NULL)
  9494. return BAD_FUNC_ARG;
  9495. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9496. return ASN_PARSE_E;
  9497. maxIdx = (word32)(*inOutIdx + length);
  9498. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  9499. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  9500. GetInt(&key->g, input, inOutIdx, maxIdx) < 0)
  9501. return ASN_DH_KEY_E;
  9502. return 0;
  9503. }
  9504. #ifdef WOLFSSL_ASN_TEMPLATE
  9505. /* ASN.1 template for a DSA key holding private key in an OCTET_STRING. */
  9506. static const ASNItem dsaKeyOctASN[] = {
  9507. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9508. /* p */
  9509. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  9510. /* q */
  9511. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  9512. /* g */
  9513. /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
  9514. /* Private key */
  9515. /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  9516. /* x */
  9517. /* X */ { 2, ASN_INTEGER, 0, 0, 0 },
  9518. };
  9519. enum {
  9520. DSAKEYOCTASN_IDX_SEQ = 0,
  9521. DSAKEYOCTASN_IDX_P,
  9522. DSAKEYOCTASN_IDX_Q,
  9523. DSAKEYOCTASN_IDX_G,
  9524. DSAKEYOCTASN_IDX_PKEY_STR,
  9525. DSAKEYOCTASN_IDX_X,
  9526. };
  9527. /* Number of items in ASN.1 template for a DSA key (OCTET_STRING version). */
  9528. #define dsaKeyOctASN_Length (sizeof(dsaKeyOctASN) / sizeof(ASNItem))
  9529. #endif
  9530. /* Decode DSA private key.
  9531. *
  9532. * @param [in] input Buffer holding BER encoded data.
  9533. * @param [in, out] inOutIdx On in, start of DSA public key.
  9534. * On out, start of ASN.1 item after DSA public key.
  9535. * @param [in, out] key DSA key object.
  9536. * @param [in] inSz Number of bytes in buffer.
  9537. * @return 0 on success.
  9538. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9539. * is invalid.
  9540. * @return BUFFER_E when data in buffer is too small.
  9541. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  9542. * non-zero length.
  9543. */
  9544. int wc_DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9545. word32 inSz)
  9546. {
  9547. #ifndef WOLFSSL_ASN_TEMPLATE
  9548. int length, version, ret = 0, temp = 0;
  9549. word32 algId = 0;
  9550. /* Sanity checks on input */
  9551. if (input == NULL || inOutIdx == NULL || key == NULL) {
  9552. return BAD_FUNC_ARG;
  9553. }
  9554. /* if has pkcs8 header skip it */
  9555. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  9556. /* ignore error, did not have pkcs8 header */
  9557. }
  9558. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9559. return ASN_PARSE_E;
  9560. temp = (int)*inOutIdx;
  9561. /* Default case expects a certificate with OctetString but no version ID */
  9562. ret = GetInt(&key->p, input, inOutIdx, inSz);
  9563. if (ret < 0) {
  9564. mp_clear(&key->p);
  9565. ret = ASN_PARSE_E;
  9566. }
  9567. else {
  9568. ret = GetInt(&key->q, input, inOutIdx, inSz);
  9569. if (ret < 0) {
  9570. mp_clear(&key->p);
  9571. mp_clear(&key->q);
  9572. ret = ASN_PARSE_E;
  9573. }
  9574. else {
  9575. ret = GetInt(&key->g, input, inOutIdx, inSz);
  9576. if (ret < 0) {
  9577. mp_clear(&key->p);
  9578. mp_clear(&key->q);
  9579. mp_clear(&key->g);
  9580. ret = ASN_PARSE_E;
  9581. }
  9582. else {
  9583. ret = GetOctetString(input, inOutIdx, &length, inSz);
  9584. if (ret < 0) {
  9585. mp_clear(&key->p);
  9586. mp_clear(&key->q);
  9587. mp_clear(&key->g);
  9588. ret = ASN_PARSE_E;
  9589. }
  9590. else {
  9591. ret = GetInt(&key->y, input, inOutIdx, inSz);
  9592. if (ret < 0) {
  9593. mp_clear(&key->p);
  9594. mp_clear(&key->q);
  9595. mp_clear(&key->g);
  9596. mp_clear(&key->y);
  9597. ret = ASN_PARSE_E;
  9598. }
  9599. }
  9600. }
  9601. }
  9602. }
  9603. /* An alternate pass if default certificate fails parsing */
  9604. if (ret == ASN_PARSE_E) {
  9605. *inOutIdx = temp;
  9606. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  9607. return ASN_PARSE_E;
  9608. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  9609. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  9610. GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
  9611. GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
  9612. GetInt(&key->x, input, inOutIdx, inSz) < 0 )
  9613. return ASN_DH_KEY_E;
  9614. }
  9615. key->type = DSA_PRIVATE;
  9616. return 0;
  9617. #else
  9618. /* dsaKeyASN is longer than dsaKeyOctASN. */
  9619. DECL_ASNGETDATA(dataASN, dsaKeyASN_Length);
  9620. int ret = 0;
  9621. int i;
  9622. byte version = 0;
  9623. /* Sanity checks on input */
  9624. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  9625. ret = BAD_FUNC_ARG;
  9626. }
  9627. CALLOC_ASNGETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  9628. if (ret == 0) {
  9629. /* Try dsaKeyOctASN */
  9630. /* Initialize key data and set mp_ints for params */
  9631. for (i = 0; i < DSA_INTS - 2; i++) {
  9632. GetASN_MP(&dataASN[(int)DSAKEYOCTASN_IDX_P + i], GetDsaInt(key, i));
  9633. }
  9634. /* and priv */
  9635. GetASN_MP(&dataASN[DSAKEYOCTASN_IDX_X], GetDsaInt(key, i));
  9636. /* Try simple form. */
  9637. ret = GetASN_Items(dsaKeyOctASN, dataASN, dsaKeyOctASN_Length, 1, input,
  9638. inOutIdx, inSz);
  9639. if (ret != 0) {
  9640. /* Try dsaKeyASN */
  9641. XMEMSET(dataASN, 0, sizeof(*dataASN) * dsaKeyASN_Length);
  9642. GetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], &version);
  9643. for (i = 0; i < DSA_INTS; i++) {
  9644. GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], GetDsaInt(key, i));
  9645. }
  9646. /* Try simple OCTET_STRING form. */
  9647. ret = GetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, 1, input,
  9648. inOutIdx, inSz);
  9649. }
  9650. }
  9651. if (ret == 0) {
  9652. /* Set the contents to be a private key. */
  9653. key->type = DSA_PRIVATE;
  9654. }
  9655. FREE_ASNGETDATA(dataASN, key->heap);
  9656. return ret;
  9657. #endif
  9658. }
  9659. #ifndef WOLFSSL_ASN_TEMPLATE
  9660. /* Release Tmp DSA resources */
  9661. static WC_INLINE void FreeTmpDsas(byte** tmps, void* heap, int ints)
  9662. {
  9663. int i;
  9664. for (i = 0; i < ints; i++)
  9665. XFREE(tmps[i], heap, DYNAMIC_TYPE_DSA);
  9666. (void)heap;
  9667. }
  9668. #endif /* !WOLFSSL_ASN_TEMPLATE */
  9669. #if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \
  9670. defined(WOLFSSL_CERT_GEN))
  9671. /* Encode a DSA public key into buffer.
  9672. *
  9673. * @param [out] output Buffer to hold encoded data.
  9674. * @param [in] key DSA key object.
  9675. * @param [out] outLen Length of buffer.
  9676. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  9677. * @return Size of encoded data in bytes on success.
  9678. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  9679. * than a minimal size (5 bytes), or buffer size is smaller than
  9680. * encoding size.
  9681. * @return MEMORY_E when dynamic memory allocation fails.
  9682. */
  9683. int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header)
  9684. {
  9685. #ifndef WOLFSSL_ASN_TEMPLATE
  9686. /* p, g, q = DSA params, y = public exponent */
  9687. #ifdef WOLFSSL_SMALL_STACK
  9688. byte* p = NULL;
  9689. byte* g = NULL;
  9690. byte* q = NULL;
  9691. byte* y = NULL;
  9692. #else
  9693. byte p[MAX_DSA_INT_SZ];
  9694. byte g[MAX_DSA_INT_SZ];
  9695. byte q[MAX_DSA_INT_SZ];
  9696. byte y[MAX_DSA_INT_SZ];
  9697. #endif
  9698. byte innerSeq[MAX_SEQ_SZ];
  9699. byte outerSeq[MAX_SEQ_SZ];
  9700. byte bitString[1 + MAX_LENGTH_SZ + 1];
  9701. int idx, pSz, gSz, qSz, ySz, innerSeqSz, outerSeqSz, bitStringSz = 0;
  9702. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  9703. if (output == NULL || key == NULL || outLen < MAX_SEQ_SZ) {
  9704. return BAD_FUNC_ARG;
  9705. }
  9706. /* p */
  9707. #ifdef WOLFSSL_SMALL_STACK
  9708. p = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9709. if (p == NULL)
  9710. return MEMORY_E;
  9711. #endif
  9712. if ((pSz = SetASNIntMP(&key->p, MAX_DSA_INT_SZ, p)) < 0) {
  9713. WOLFSSL_MSG("SetASNIntMP Error with p");
  9714. #ifdef WOLFSSL_SMALL_STACK
  9715. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9716. #endif
  9717. return pSz;
  9718. }
  9719. /* q */
  9720. #ifdef WOLFSSL_SMALL_STACK
  9721. q = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9722. if (q == NULL)
  9723. return MEMORY_E;
  9724. #endif
  9725. if ((qSz = SetASNIntMP(&key->q, MAX_DSA_INT_SZ, q)) < 0) {
  9726. WOLFSSL_MSG("SetASNIntMP Error with q");
  9727. #ifdef WOLFSSL_SMALL_STACK
  9728. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9729. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9730. #endif
  9731. return qSz;
  9732. }
  9733. /* g */
  9734. #ifdef WOLFSSL_SMALL_STACK
  9735. g = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9736. if (g == NULL)
  9737. return MEMORY_E;
  9738. #endif
  9739. if ((gSz = SetASNIntMP(&key->g, MAX_DSA_INT_SZ, g)) < 0) {
  9740. WOLFSSL_MSG("SetASNIntMP Error with g");
  9741. #ifdef WOLFSSL_SMALL_STACK
  9742. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9743. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9744. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9745. #endif
  9746. return gSz;
  9747. }
  9748. /* y */
  9749. #ifdef WOLFSSL_SMALL_STACK
  9750. y = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9751. if (y == NULL)
  9752. return MEMORY_E;
  9753. #endif
  9754. if ((ySz = SetASNIntMP(&key->y, MAX_DSA_INT_SZ, y)) < 0) {
  9755. WOLFSSL_MSG("SetASNIntMP Error with y");
  9756. #ifdef WOLFSSL_SMALL_STACK
  9757. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9758. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9759. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9760. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9761. #endif
  9762. return ySz;
  9763. }
  9764. if (with_header) {
  9765. int algoSz;
  9766. #ifdef WOLFSSL_SMALL_STACK
  9767. byte* algo = NULL;
  9768. algo = (byte*)XMALLOC(MAX_ALGO_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9769. if (algo == NULL) {
  9770. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9771. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9772. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9773. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9774. return MEMORY_E;
  9775. }
  9776. #else
  9777. byte algo[MAX_ALGO_SZ];
  9778. #endif
  9779. innerSeqSz = SetSequence(pSz + qSz + gSz, innerSeq);
  9780. algoSz = SetAlgoID(DSAk, algo, oidKeyType, 0);
  9781. bitStringSz = SetBitString(ySz, 0, bitString);
  9782. outerSeqSz = SetSequence(algoSz + innerSeqSz + pSz + qSz + gSz,
  9783. outerSeq);
  9784. idx = SetSequence(algoSz + innerSeqSz + pSz + qSz + gSz + bitStringSz +
  9785. ySz + outerSeqSz, output);
  9786. /* check output size */
  9787. if ((idx + algoSz + bitStringSz + innerSeqSz + pSz + qSz + gSz + ySz) >
  9788. outLen) {
  9789. #ifdef WOLFSSL_SMALL_STACK
  9790. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9791. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9792. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9793. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9794. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9795. #endif
  9796. WOLFSSL_MSG("Error, output size smaller than outlen");
  9797. return BUFFER_E;
  9798. }
  9799. /* outerSeq */
  9800. XMEMCPY(output + idx, outerSeq, outerSeqSz);
  9801. idx += outerSeqSz;
  9802. /* algo */
  9803. XMEMCPY(output + idx, algo, algoSz);
  9804. idx += algoSz;
  9805. #ifdef WOLFSSL_SMALL_STACK
  9806. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9807. #endif
  9808. } else {
  9809. innerSeqSz = SetSequence(pSz + qSz + gSz + ySz, innerSeq);
  9810. /* check output size */
  9811. if ((innerSeqSz + pSz + qSz + gSz + ySz) > outLen) {
  9812. #ifdef WOLFSSL_SMALL_STACK
  9813. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9814. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9815. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9816. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9817. #endif
  9818. WOLFSSL_MSG("Error, output size smaller than outlen");
  9819. return BUFFER_E;
  9820. }
  9821. idx = 0;
  9822. }
  9823. /* innerSeq */
  9824. XMEMCPY(output + idx, innerSeq, innerSeqSz);
  9825. idx += innerSeqSz;
  9826. /* p */
  9827. XMEMCPY(output + idx, p, pSz);
  9828. idx += pSz;
  9829. /* q */
  9830. XMEMCPY(output + idx, q, qSz);
  9831. idx += qSz;
  9832. /* g */
  9833. XMEMCPY(output + idx, g, gSz);
  9834. idx += gSz;
  9835. /* bit string */
  9836. if (bitStringSz > 0) {
  9837. XMEMCPY(output + idx, bitString, bitStringSz);
  9838. idx += bitStringSz;
  9839. }
  9840. /* y */
  9841. XMEMCPY(output + idx, y, ySz);
  9842. idx += ySz;
  9843. #ifdef WOLFSSL_SMALL_STACK
  9844. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9845. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9846. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9847. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9848. #endif
  9849. return idx;
  9850. #else
  9851. DECL_ASNSETDATA(dataASN, dsaPubKeyASN_Length);
  9852. int ret = 0;
  9853. int i;
  9854. int sz = 0;
  9855. const ASNItem *data = NULL;
  9856. int count = 0;
  9857. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  9858. if ((output == NULL) || (key == NULL) || (outLen < MAX_SEQ_SZ)) {
  9859. ret = BAD_FUNC_ARG;
  9860. }
  9861. CALLOC_ASNSETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  9862. if (ret == 0) {
  9863. if (with_header) {
  9864. /* Using dsaPubKeyASN */
  9865. data = dsaPubKeyASN;
  9866. count = dsaPubKeyASN_Length;
  9867. /* Set the algorithm OID to write out. */
  9868. SetASN_OID(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID], DSAk, oidKeyType);
  9869. /* Set the mp_ints to encode - parameters and public value. */
  9870. for (i = 0; i < DSA_INTS - 2; i++) {
  9871. SetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
  9872. GetDsaInt(key, i));
  9873. }
  9874. SetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
  9875. }
  9876. else {
  9877. /* Using dsaKeyASN */
  9878. data = dsaKeyASN;
  9879. count = dsaPublicKeyASN_Length;
  9880. /* Set the mp_ints to encode - parameters and public value. */
  9881. for (i = 0; i < DSA_INTS - 1; i++) {
  9882. /* Move all DSA ints up one slot (ignore VERSION so now
  9883. * it means P) */
  9884. SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i],
  9885. GetDsaInt(key, i));
  9886. }
  9887. }
  9888. ret = SizeASN_Items(data, dataASN, count, &sz);
  9889. }
  9890. /* Check buffer is big enough for encoding. */
  9891. if ((ret == 0) && (sz > (int)outLen)) {
  9892. ret = BAD_FUNC_ARG;
  9893. }
  9894. /* Encode the DSA public key into output buffer. */
  9895. if (ret == 0) {
  9896. ret = SetASN_Items(data, dataASN, count, output);
  9897. }
  9898. FREE_ASNSETDATA(dataASN, key->heap);
  9899. return ret;
  9900. #endif /* WOLFSSL_ASN_TEMPLATE */
  9901. }
  9902. /* Encode a DSA public key into buffer.
  9903. *
  9904. * @param [out] output Buffer to hold encoded data.
  9905. * @param [in] key DSA key object.
  9906. * @param [out] outLen Length of buffer.
  9907. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  9908. * @return Size of encoded data in bytes on success.
  9909. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  9910. * than a minimal size (5 bytes), or buffer size is smaller than
  9911. * encoding size.
  9912. * @return MEMORY_E when dynamic memory allocation fails.
  9913. */
  9914. int wc_DsaKeyToPublicDer(DsaKey* key, byte* output, word32 inLen)
  9915. {
  9916. return wc_SetDsaPublicKey(output, key, inLen, 1);
  9917. }
  9918. #endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */
  9919. static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen,
  9920. int ints, int includeVersion)
  9921. {
  9922. #ifndef WOLFSSL_ASN_TEMPLATE
  9923. word32 seqSz = 0, verSz = 0, rawLen, intTotalLen = 0;
  9924. word32 sizes[DSA_INTS];
  9925. int i, j, outLen, ret = 0, mpSz;
  9926. byte seq[MAX_SEQ_SZ];
  9927. byte ver[MAX_VERSION_SZ];
  9928. byte* tmps[DSA_INTS];
  9929. if (ints > DSA_INTS || inLen == NULL)
  9930. return BAD_FUNC_ARG;
  9931. XMEMSET(sizes, 0, sizeof(sizes));
  9932. for (i = 0; i < ints; i++)
  9933. tmps[i] = NULL;
  9934. /* write all big ints from key to DER tmps */
  9935. for (i = 0; i < ints; i++) {
  9936. mp_int* keyInt = GetDsaInt(key, i);
  9937. rawLen = mp_unsigned_bin_size(keyInt) + 1;
  9938. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  9939. DYNAMIC_TYPE_DSA);
  9940. if (tmps[i] == NULL) {
  9941. ret = MEMORY_E;
  9942. break;
  9943. }
  9944. mpSz = SetASNIntMP(keyInt, -1, tmps[i]);
  9945. if (mpSz < 0) {
  9946. ret = mpSz;
  9947. break;
  9948. }
  9949. intTotalLen += (sizes[i] = mpSz);
  9950. }
  9951. if (ret != 0) {
  9952. FreeTmpDsas(tmps, key->heap, ints);
  9953. return ret;
  9954. }
  9955. /* make headers */
  9956. if (includeVersion)
  9957. verSz = SetMyVersion(0, ver, FALSE);
  9958. seqSz = SetSequence(verSz + intTotalLen, seq);
  9959. outLen = seqSz + verSz + intTotalLen;
  9960. *inLen = outLen;
  9961. if (output == NULL) {
  9962. FreeTmpDsas(tmps, key->heap, ints);
  9963. return LENGTH_ONLY_E;
  9964. }
  9965. if (outLen > (int)*inLen) {
  9966. FreeTmpDsas(tmps, key->heap, ints);
  9967. return BAD_FUNC_ARG;
  9968. }
  9969. /* write to output */
  9970. XMEMCPY(output, seq, seqSz);
  9971. j = seqSz;
  9972. if (includeVersion) {
  9973. XMEMCPY(output + j, ver, verSz);
  9974. j += verSz;
  9975. }
  9976. for (i = 0; i < ints; i++) {
  9977. XMEMCPY(output + j, tmps[i], sizes[i]);
  9978. j += sizes[i];
  9979. }
  9980. FreeTmpDsas(tmps, key->heap, ints);
  9981. return outLen;
  9982. #else
  9983. DECL_ASNSETDATA(dataASN, dsaKeyASN_Length);
  9984. int ret = 0;
  9985. int i;
  9986. int sz = 0;
  9987. (void)ints;
  9988. if ((key == NULL) || (inLen == NULL)) {
  9989. ret = BAD_FUNC_ARG;
  9990. }
  9991. if ((ret == 0) && (ints > DSA_INTS)) {
  9992. ret = BAD_FUNC_ARG;
  9993. }
  9994. CALLOC_ASNSETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  9995. if (ret == 0) {
  9996. if (includeVersion) {
  9997. /* Set the version. */
  9998. SetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], 0);
  9999. }
  10000. else {
  10001. dataASN[DSAKEYASN_IDX_VER].noOut = 1;
  10002. }
  10003. dataASN[DSAKEYASN_IDX_Y].noOut = mp_iszero(&key->y);
  10004. dataASN[DSAKEYASN_IDX_X].noOut = mp_iszero(&key->x);
  10005. /* Set the mp_ints to encode - params, public and private value. */
  10006. for (i = 0; i < DSA_INTS; i++) {
  10007. if (i < ints)
  10008. SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], GetDsaInt(key, i));
  10009. else
  10010. dataASN[(int)DSAKEYASN_IDX_P + i].noOut = 1;
  10011. }
  10012. /* Calculate size of the encoding. */
  10013. ret = SizeASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, &sz);
  10014. }
  10015. if ((ret == 0) && (output == NULL)) {
  10016. *inLen = sz;
  10017. ret = LENGTH_ONLY_E;
  10018. }
  10019. /* Check buffer is big enough for encoding. */
  10020. if ((ret == 0) && (sz > (int)*inLen)) {
  10021. ret = BAD_FUNC_ARG;
  10022. }
  10023. if (ret == 0) {
  10024. /* Encode the DSA private key into output buffer. */
  10025. SetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, output);
  10026. /* Return the size of the encoding. */
  10027. ret = sz;
  10028. }
  10029. FREE_ASNSETDATA(dataASN, key->heap);
  10030. return ret;
  10031. #endif /* WOLFSSL_ASN_TEMPLATE */
  10032. }
  10033. /* Encode a DSA private key into buffer.
  10034. *
  10035. * @param [in] key DSA key object.
  10036. * @param [out] output Buffer to hold encoded data.
  10037. * @param [out] inLen Length of buffer.
  10038. * @return Size of encoded data in bytes on success.
  10039. * @return BAD_FUNC_ARG when key or output is NULL, or key is not a private key
  10040. * or, buffer size is smaller than encoding size.
  10041. * @return MEMORY_E when dynamic memory allocation fails.
  10042. */
  10043. int wc_DsaKeyToDer(DsaKey* key, byte* output, word32 inLen)
  10044. {
  10045. if (!key || !output)
  10046. return BAD_FUNC_ARG;
  10047. if (key->type != DSA_PRIVATE)
  10048. return BAD_FUNC_ARG;
  10049. return DsaKeyIntsToDer(key, output, &inLen, DSA_INTS, 1);
  10050. }
  10051. /* Convert DsaKey parameters to DER format, write to output (inLen),
  10052. return bytes written. Version is excluded to be compatible with
  10053. OpenSSL d2i_DSAparams */
  10054. int wc_DsaKeyToParamsDer(DsaKey* key, byte* output, word32 inLen)
  10055. {
  10056. if (!key || !output)
  10057. return BAD_FUNC_ARG;
  10058. return DsaKeyIntsToDer(key, output, &inLen, DSA_PARAM_INTS, 0);
  10059. }
  10060. /* This version of the function allows output to be NULL. In that case, the
  10061. DsaKeyIntsToDer will return LENGTH_ONLY_E and the required output buffer
  10062. size will be pointed to by inLen. */
  10063. int wc_DsaKeyToParamsDer_ex(DsaKey* key, byte* output, word32* inLen)
  10064. {
  10065. if (!key || !inLen)
  10066. return BAD_FUNC_ARG;
  10067. return DsaKeyIntsToDer(key, output, inLen, DSA_PARAM_INTS, 0);
  10068. }
  10069. #endif /* NO_DSA */
  10070. /* Initialize decoded certificate object with buffer of DER encoding.
  10071. *
  10072. * @param [in, out] cert Decoded certificate object.
  10073. * @param [in] source Buffer containing DER encoded certificate.
  10074. * @param [in] inSz Size of DER data in buffer in bytes.
  10075. * @param [in] heap Dynamic memory hint.
  10076. */
  10077. void InitDecodedCert(DecodedCert* cert,
  10078. const byte* source, word32 inSz, void* heap)
  10079. {
  10080. if (cert != NULL) {
  10081. XMEMSET(cert, 0, sizeof(DecodedCert));
  10082. cert->subjectCNEnc = CTC_UTF8;
  10083. cert->issuer[0] = '\0';
  10084. cert->subject[0] = '\0';
  10085. cert->source = source; /* don't own */
  10086. cert->maxIdx = inSz; /* can't go over this index */
  10087. cert->heap = heap;
  10088. cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
  10089. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10090. #ifdef WOLFSSL_CERT_NAME_ALL
  10091. cert->subjectNEnc = CTC_UTF8;
  10092. cert->subjectIEnc = CTC_UTF8;
  10093. cert->subjectDNQEnc = CTC_UTF8;
  10094. cert->subjectGNEnc = CTC_UTF8;
  10095. #endif
  10096. cert->subjectSNEnc = CTC_UTF8;
  10097. cert->subjectCEnc = CTC_PRINTABLE;
  10098. cert->subjectLEnc = CTC_UTF8;
  10099. cert->subjectSTEnc = CTC_UTF8;
  10100. cert->subjectOEnc = CTC_UTF8;
  10101. cert->subjectOUEnc = CTC_UTF8;
  10102. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  10103. cert->issuerSNEnc = CTC_UTF8;
  10104. cert->issuerCEnc = CTC_PRINTABLE;
  10105. cert->issuerLEnc = CTC_UTF8;
  10106. cert->issuerSTEnc = CTC_UTF8;
  10107. cert->issuerOEnc = CTC_UTF8;
  10108. cert->issuerOUEnc = CTC_UTF8;
  10109. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  10110. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  10111. #ifndef NO_CERTS
  10112. InitSignatureCtx(&cert->sigCtx, heap, INVALID_DEVID);
  10113. #endif
  10114. }
  10115. }
  10116. void wc_InitDecodedCert(DecodedCert* cert, const byte* source, word32 inSz,
  10117. void* heap)
  10118. {
  10119. InitDecodedCert(cert, source, inSz, heap);
  10120. }
  10121. /* Free the alternative names object.
  10122. *
  10123. * Frees each linked list items and its name.
  10124. *
  10125. * @param [in, out] altNames Alternative names.
  10126. * @param [in] heap Dynamic memory hint.
  10127. */
  10128. void FreeAltNames(DNS_entry* altNames, void* heap)
  10129. {
  10130. (void)heap;
  10131. while (altNames) {
  10132. DNS_entry* tmp = altNames->next;
  10133. XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
  10134. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  10135. XFREE(altNames->ipString, heap, DYNAMIC_TYPE_ALTNAME);
  10136. #endif
  10137. XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME);
  10138. altNames = tmp;
  10139. }
  10140. }
  10141. /* malloc and initialize a new alt name structure */
  10142. DNS_entry* AltNameNew(void* heap)
  10143. {
  10144. DNS_entry* ret;
  10145. ret = (DNS_entry*)XMALLOC(sizeof(DNS_entry), heap, DYNAMIC_TYPE_ALTNAME);
  10146. if (ret != NULL) {
  10147. XMEMSET(ret, 0, sizeof(DNS_entry));
  10148. }
  10149. (void)heap;
  10150. return ret;
  10151. }
  10152. #ifndef IGNORE_NAME_CONSTRAINTS
  10153. /* Free the subtree names object.
  10154. *
  10155. * Frees each linked list items and its name.
  10156. *
  10157. * @param [in, out] names Subtree names.
  10158. * @param [in] heap Dynamic memory hint.
  10159. */
  10160. void FreeNameSubtrees(Base_entry* names, void* heap)
  10161. {
  10162. (void)heap;
  10163. while (names) {
  10164. Base_entry* tmp = names->next;
  10165. XFREE(names->name, heap, DYNAMIC_TYPE_ALTNAME);
  10166. XFREE(names, heap, DYNAMIC_TYPE_ALTNAME);
  10167. names = tmp;
  10168. }
  10169. }
  10170. #endif /* IGNORE_NAME_CONSTRAINTS */
  10171. /* Free the decoded cert object's dynamic data.
  10172. *
  10173. * @param [in, out] cert Decoded certificate object.
  10174. */
  10175. void FreeDecodedCert(DecodedCert* cert)
  10176. {
  10177. if (cert == NULL)
  10178. return;
  10179. if (cert->subjectCNStored == 1) {
  10180. XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
  10181. }
  10182. if (cert->pubKeyStored == 1) {
  10183. XFREE((void*)cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  10184. }
  10185. if (cert->weOwnAltNames && cert->altNames)
  10186. FreeAltNames(cert->altNames, cert->heap);
  10187. #ifndef IGNORE_NAME_CONSTRAINTS
  10188. if (cert->altEmailNames)
  10189. FreeAltNames(cert->altEmailNames, cert->heap);
  10190. if (cert->altDirNames)
  10191. FreeAltNames(cert->altDirNames, cert->heap);
  10192. if (cert->permittedNames)
  10193. FreeNameSubtrees(cert->permittedNames, cert->heap);
  10194. if (cert->excludedNames)
  10195. FreeNameSubtrees(cert->excludedNames, cert->heap);
  10196. #endif /* IGNORE_NAME_CONSTRAINTS */
  10197. #ifdef WOLFSSL_SEP
  10198. XFREE(cert->deviceType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10199. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10200. XFREE(cert->hwSerialNum, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10201. #endif /* WOLFSSL_SEP */
  10202. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10203. if (cert->issuerName != NULL)
  10204. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->issuerName);
  10205. if (cert->subjectName != NULL)
  10206. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->subjectName);
  10207. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  10208. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10209. if (cert->sce_tsip_encRsaKeyIdx != NULL)
  10210. XFREE(cert->sce_tsip_encRsaKeyIdx, cert->heap, DYNAMIC_TYPE_RSA);
  10211. #endif
  10212. #ifndef NO_CERTS
  10213. FreeSignatureCtx(&cert->sigCtx);
  10214. #endif
  10215. }
  10216. void wc_FreeDecodedCert(DecodedCert* cert)
  10217. {
  10218. FreeDecodedCert(cert);
  10219. }
  10220. #ifndef WOLFSSL_ASN_TEMPLATE
  10221. static int GetCertHeader(DecodedCert* cert)
  10222. {
  10223. int ret = 0, len;
  10224. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  10225. return ASN_PARSE_E;
  10226. /* Reset the max index for the size indicated in the outer wrapper. */
  10227. cert->maxIdx = len + cert->srcIdx;
  10228. cert->certBegin = cert->srcIdx;
  10229. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  10230. return ASN_PARSE_E;
  10231. cert->sigIndex = len + cert->srcIdx;
  10232. if (cert->sigIndex > cert->maxIdx)
  10233. return ASN_PARSE_E;
  10234. if (GetExplicitVersion(cert->source, &cert->srcIdx, &cert->version,
  10235. cert->sigIndex) < 0)
  10236. return ASN_PARSE_E;
  10237. if (wc_GetSerialNumber(cert->source, &cert->srcIdx, cert->serial,
  10238. &cert->serialSz, cert->sigIndex) < 0)
  10239. return ASN_PARSE_E;
  10240. return ret;
  10241. }
  10242. #endif
  10243. #if defined(HAVE_ED25519) || defined(HAVE_ED448) || (defined(HAVE_PQC) && \
  10244. defined(HAVE_LIBOQS))
  10245. /* Store the key data under the BIT_STRING in dynamicly allocated data.
  10246. *
  10247. * @param [in, out] cert Certificate object.
  10248. * @param [in] source Buffer containing encoded key.
  10249. * @param [in, out] srcIdx On in, start of key data.
  10250. * On out, start of element after key data.
  10251. * @param [in] maxIdx Maximum index of certificate data.
  10252. */
  10253. static int StoreKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10254. word32 maxIdx)
  10255. {
  10256. int ret;
  10257. int length;
  10258. byte* publicKey;
  10259. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10260. if (ret == 0) {
  10261. #ifdef HAVE_OCSP
  10262. ret = CalcHashId(source + *srcIdx, length, cert->subjectKeyHash);
  10263. }
  10264. if (ret == 0) {
  10265. #endif
  10266. publicKey = (byte*)XMALLOC(length, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  10267. if (publicKey == NULL) {
  10268. ret = MEMORY_E;
  10269. }
  10270. else {
  10271. XMEMCPY(publicKey, &source[*srcIdx], length);
  10272. cert->publicKey = publicKey;
  10273. cert->pubKeyStored = 1;
  10274. cert->pubKeySize = length;
  10275. *srcIdx += length;
  10276. }
  10277. }
  10278. return ret;
  10279. }
  10280. #endif /* HAVE_ED25519 || HAVE_ED448 */
  10281. #if !defined(NO_RSA)
  10282. #ifdef WOLFSSL_ASN_TEMPLATE
  10283. /* ASN.1 template for header before RSA key in certificate. */
  10284. static const ASNItem rsaCertKeyASN[] = {
  10285. /* STR */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  10286. /* SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  10287. };
  10288. enum {
  10289. RSACERTKEYASN_IDX_STR = 0,
  10290. RSACERTKEYASN_IDX_SEQ,
  10291. };
  10292. /* Number of items in ASN.1 template for header before RSA key in cert. */
  10293. #define rsaCertKeyASN_Length (sizeof(rsaCertKeyASN) / sizeof(ASNItem))
  10294. #endif
  10295. /* Store RSA key pointer and length in certificate object.
  10296. *
  10297. * @param [in, out] cert Certificate object.
  10298. * @param [in] source Buffer containing encoded key.
  10299. * @param [in, out] srcIdx On in, start of RSA key data.
  10300. * On out, start of element after RSA key data.
  10301. * @param [in] maxIdx Maximum index of key data.
  10302. * @return 0 on success.
  10303. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10304. * is invalid.
  10305. * @return BUFFER_E when data in buffer is too small.
  10306. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10307. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10308. * non-zero length.
  10309. */
  10310. static int StoreRsaKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10311. word32 maxIdx)
  10312. {
  10313. #ifndef WOLFSSL_ASN_TEMPLATE
  10314. int length;
  10315. int pubLen;
  10316. word32 pubIdx;
  10317. if (CheckBitString(source, srcIdx, &pubLen, maxIdx, 1, NULL) != 0)
  10318. return ASN_PARSE_E;
  10319. pubIdx = *srcIdx;
  10320. if (GetSequence(source, srcIdx, &length, pubIdx + pubLen) < 0)
  10321. return ASN_PARSE_E;
  10322. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10323. cert->sigCtx.CertAtt.pubkey_n_start =
  10324. cert->sigCtx.CertAtt.pubkey_e_start = pubIdx;
  10325. #endif
  10326. cert->pubKeySize = pubLen;
  10327. cert->publicKey = source + pubIdx;
  10328. #ifdef WOLFSSL_MAXQ10XX_TLS
  10329. cert->publicKeyIndex = pubIdx;
  10330. #endif
  10331. *srcIdx += length;
  10332. #ifdef HAVE_OCSP
  10333. return CalcHashId(cert->publicKey, cert->pubKeySize, cert->subjectKeyHash);
  10334. #else
  10335. return 0;
  10336. #endif
  10337. #else
  10338. ASNGetData dataASN[rsaCertKeyASN_Length];
  10339. int ret;
  10340. /* No dynamic data. */
  10341. XMEMSET(dataASN, 0, sizeof(dataASN));
  10342. /* Decode the header before the key data. */
  10343. ret = GetASN_Items(rsaCertKeyASN, dataASN, rsaCertKeyASN_Length, 1, source,
  10344. srcIdx, maxIdx);
  10345. if (ret == 0) {
  10346. /* Store the pointer and length in certificate object starting at
  10347. * SEQUENCE. */
  10348. GetASN_GetConstRef(&dataASN[RSACERTKEYASN_IDX_STR],
  10349. &cert->publicKey, &cert->pubKeySize);
  10350. #ifdef WOLFSSL_MAXQ10XX_TLS
  10351. cert->publicKeyIndex = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
  10352. #endif
  10353. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10354. /* Start of SEQUENCE. */
  10355. cert->sigCtx.CertAtt.pubkey_n_start =
  10356. cert->sigCtx.CertAtt.pubkey_e_start = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
  10357. #endif
  10358. #ifdef HAVE_OCSP
  10359. /* Calculate the hash of the public key for OCSP. */
  10360. ret = CalcHashId(cert->publicKey, cert->pubKeySize,
  10361. cert->subjectKeyHash);
  10362. #endif
  10363. }
  10364. return ret;
  10365. #endif /* WOLFSSL_ASN_TEMPLATE */
  10366. }
  10367. #endif /* !NO_RSA */
  10368. #ifdef HAVE_ECC
  10369. #ifdef WOLFSSL_ASN_TEMPLATE
  10370. /* ASN.1 template for header before ECC key in certificate. */
  10371. static const ASNItem eccCertKeyASN[] = {
  10372. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 2 },
  10373. /* Algo parameters */
  10374. /* PARAMS */ { 1, ASN_SEQUENCE, 1, 0, 2 },
  10375. /* Subject public key */
  10376. /* SUBJPUBKEY */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  10377. };
  10378. enum {
  10379. ECCCERTKEYASN_IDX_OID = 0,
  10380. ECCCERTKEYASN_IDX_PARAMS,
  10381. ECCCERTKEYASN_IDX_SUBJPUBKEY,
  10382. };
  10383. /* Number of items in ASN.1 template for header before ECC key in cert. */
  10384. #define eccCertKeyASN_Length (sizeof(eccCertKeyASN) / sizeof(ASNItem))
  10385. #endif /* WOLFSSL_ASN_TEMPLATE */
  10386. /* Store public ECC key in certificate object.
  10387. *
  10388. * Parse parameters and store public key data.
  10389. *
  10390. * @param [in, out] cert Certificate object.
  10391. * @param [in] source Buffer containing encoded key.
  10392. * @param [in, out] srcIdx On in, start of ECC key data.
  10393. * On out, start of element after ECC key data.
  10394. * @param [in] maxIdx Maximum index of key data.
  10395. * @param [in] pubKey Buffer holding encoded public key.
  10396. * @param [in] pubKeyLen Length of encoded public key in bytes.
  10397. * @return 0 on success.
  10398. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10399. * is invalid.
  10400. * @return BUFFER_E when data in buffer is too small.
  10401. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  10402. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10403. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10404. * non-zero length.
  10405. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  10406. */
  10407. static int StoreEccKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10408. word32 maxIdx, const byte* pubKey, word32 pubKeyLen)
  10409. {
  10410. #ifndef WOLFSSL_ASN_TEMPLATE
  10411. int ret;
  10412. word32 localIdx;
  10413. byte* publicKey;
  10414. byte tag;
  10415. int length;
  10416. localIdx = *srcIdx;
  10417. if (GetASNTag(source, &localIdx, &tag, maxIdx) < 0)
  10418. return ASN_PARSE_E;
  10419. if (tag != (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  10420. if (GetObjectId(source, srcIdx, &cert->pkCurveOID, oidCurveType,
  10421. maxIdx) < 0)
  10422. return ASN_PARSE_E;
  10423. if ((ret = CheckCurve(cert->pkCurveOID)) < 0)
  10424. return ECC_CURVE_OID_E;
  10425. #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  10426. cert->sigCtx.CertAtt.curve_id = ret;
  10427. #else
  10428. (void)ret;
  10429. #endif
  10430. /* key header */
  10431. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10432. if (ret != 0)
  10433. return ret;
  10434. #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  10435. cert->sigCtx.CertAtt.pubkey_n_start =
  10436. cert->sigCtx.CertAtt.pubkey_e_start = (*srcIdx + 1);
  10437. cert->sigCtx.CertAtt.pubkey_n_len = ((length - 1) >> 1);
  10438. cert->sigCtx.CertAtt.pubkey_e_start +=
  10439. cert->sigCtx.CertAtt.pubkey_n_len;
  10440. cert->sigCtx.CertAtt.pubkey_e_len =
  10441. cert->sigCtx.CertAtt.pubkey_n_len;
  10442. #endif
  10443. #ifdef WOLFSSL_MAXQ10XX_TLS
  10444. cert->publicKeyIndex = *srcIdx + 1;
  10445. #endif
  10446. #ifdef HAVE_OCSP
  10447. ret = CalcHashId(source + *srcIdx, length, cert->subjectKeyHash);
  10448. if (ret != 0)
  10449. return ret;
  10450. #endif
  10451. *srcIdx += length;
  10452. }
  10453. publicKey = (byte*)XMALLOC(pubKeyLen, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  10454. if (publicKey == NULL)
  10455. return MEMORY_E;
  10456. XMEMCPY(publicKey, pubKey, pubKeyLen);
  10457. cert->publicKey = publicKey;
  10458. cert->pubKeyStored = 1;
  10459. cert->pubKeySize = pubKeyLen;
  10460. return 0;
  10461. #else
  10462. int ret = 0;
  10463. DECL_ASNGETDATA(dataASN, eccCertKeyASN_Length);
  10464. byte* publicKey;
  10465. /* Clear dynamic data and check OID is a curve. */
  10466. CALLOC_ASNGETDATA(dataASN, eccCertKeyASN_Length, ret, cert->heap);
  10467. if (ret == 0) {
  10468. GetASN_OID(&dataASN[ECCCERTKEYASN_IDX_OID], oidCurveType);
  10469. /* Parse ECC public key header. */
  10470. ret = GetASN_Items(eccCertKeyASN, dataASN, eccCertKeyASN_Length, 1,
  10471. source, srcIdx, maxIdx);
  10472. }
  10473. if (ret == 0) {
  10474. if (dataASN[ECCCERTKEYASN_IDX_OID].tag != 0) {
  10475. /* Store curve OID. */
  10476. cert->pkCurveOID = dataASN[ECCCERTKEYASN_IDX_OID].data.oid.sum;
  10477. }
  10478. /* Ignore explicit parameters. */
  10479. #ifdef WOLFSSL_MAXQ10XX_TLS
  10480. cert->publicKeyIndex =
  10481. GetASNItem_DataIdx(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY], source)
  10482. + 1;
  10483. #endif
  10484. #ifdef HAVE_OCSP
  10485. /* Calculate the hash of the subject public key for OCSP. */
  10486. ret = CalcHashId(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.data,
  10487. dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.length,
  10488. cert->subjectKeyHash);
  10489. }
  10490. if (ret == 0) {
  10491. #endif
  10492. /* Store public key data length. */
  10493. cert->pubKeySize = pubKeyLen;
  10494. /* Must allocated space for key.
  10495. * Don't memcpy into constant pointer so use temp. */
  10496. publicKey = (byte*)XMALLOC(cert->pubKeySize, cert->heap,
  10497. DYNAMIC_TYPE_PUBLIC_KEY);
  10498. if (publicKey == NULL) {
  10499. ret = MEMORY_E;
  10500. }
  10501. else {
  10502. /* Copy in whole public key and store pointer. */
  10503. XMEMCPY(publicKey, pubKey, cert->pubKeySize);
  10504. cert->publicKey = publicKey;
  10505. /* Indicate publicKey needs to be freed. */
  10506. cert->pubKeyStored = 1;
  10507. }
  10508. }
  10509. FREE_ASNGETDATA(dataASN, cert->heap);
  10510. return ret;
  10511. #endif /* WOLFSSL_ASN_TEMPLATE */
  10512. }
  10513. #endif /* HAVE_ECC */
  10514. #if !defined(NO_DSA)
  10515. #ifdef WOLFSSL_ASN_TEMPLATE
  10516. /* ASN.1 template for DSA key in certificate.
  10517. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  10518. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  10519. */
  10520. static const ASNItem dsaCertKeyASN[] = {
  10521. /* 0 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  10522. /* 1 */ { 2, ASN_INTEGER, 0, 0, 0 },
  10523. /* 2 */ { 2, ASN_INTEGER, 0, 0, 0 },
  10524. /* 3 */ { 2, ASN_INTEGER, 0, 0, 0 },
  10525. /* 4 */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  10526. /* 5 */ { 1, ASN_INTEGER, 0, 0, 0 },
  10527. };
  10528. /* Number of items in ASN.1 template for DSA key in certificate. */
  10529. #define dsaCertKeyASN_Length (sizeof(dsaCertKeyASN) / sizeof(ASNItem))
  10530. #endif /* WOLFSSL_ASN_TEMPLATE */
  10531. /* Parse DSA parameters to ensure valid.
  10532. *
  10533. * @param [in] source Buffer containing encoded key.
  10534. * @param [in, out] srcIdx On in, start of DSA key data.
  10535. * On out, start of element after DSA key data.
  10536. * @param [in] maxIdx Maximum index of key data.
  10537. * @param [in] heap Dynamic memory hint.
  10538. * @return 0 on success.
  10539. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10540. * is invalid.
  10541. * @return BUFFER_E when data in buffer is too small.
  10542. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10543. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10544. * non-zero length.
  10545. */
  10546. static int ParseDsaKey(const byte* source, word32* srcIdx, word32 maxIdx,
  10547. void* heap)
  10548. {
  10549. #ifndef WOLFSSL_ASN_TEMPLATE
  10550. int ret;
  10551. int length;
  10552. (void)heap;
  10553. ret = GetSequence(source, srcIdx, &length, maxIdx);
  10554. if (ret < 0)
  10555. return ret;
  10556. ret = SkipInt(source, srcIdx, maxIdx);
  10557. if (ret != 0)
  10558. return ret;
  10559. ret = SkipInt(source, srcIdx, maxIdx);
  10560. if (ret != 0)
  10561. return ret;
  10562. ret = SkipInt(source, srcIdx, maxIdx);
  10563. if (ret != 0)
  10564. return ret;
  10565. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10566. if (ret != 0)
  10567. return ret;
  10568. ret = GetASNInt(source, srcIdx, &length, maxIdx);
  10569. if (ret != 0)
  10570. return ASN_PARSE_E;
  10571. *srcIdx += length;
  10572. return 0;
  10573. #else
  10574. DECL_ASNGETDATA(dataASN, dsaCertKeyASN_Length);
  10575. int ret = 0;
  10576. (void)heap;
  10577. CALLOC_ASNGETDATA(dataASN, dsaCertKeyASN_Length, ret, heap);
  10578. if (ret == 0) {
  10579. /* Parse the DSA key data to ensure valid. */
  10580. ret = GetASN_Items(dsaCertKeyASN, dataASN, dsaCertKeyASN_Length, 1,
  10581. source, srcIdx, maxIdx);
  10582. }
  10583. FREE_ASNGETDATA(dataASN, heap);
  10584. return ret;
  10585. #endif /* WOLFSSL_ASN_TEMPLATE */
  10586. }
  10587. #endif /* !NO_DSA */
  10588. /* Decode the SubjectPublicKeyInfo block in a certificate.
  10589. *
  10590. * Stores the public key in fields of the certificate object.
  10591. * Validates the BER/DER items and does not store in a key object.
  10592. *
  10593. * @param [in, out] cert Decoded certificate oject.
  10594. * @param [in] source BER/DER encoded SubjectPublicKeyInfo block.
  10595. * @param [in, out] inOutIdx On in, start of public key.
  10596. * On out, start of ASN.1 item after public key.
  10597. * @param [in] maxIdx Maximum index of key data.
  10598. * @return 0 on success.
  10599. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10600. * is invalid.
  10601. * @return BUFFER_E when data in buffer is too small.
  10602. */
  10603. static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx,
  10604. word32 maxIdx)
  10605. {
  10606. word32 srcIdx = *inOutIdx;
  10607. #if defined(HAVE_ECC) || !defined(NO_DSA)
  10608. int pubLen;
  10609. #endif
  10610. #if defined(HAVE_ECC) || !defined(NO_DSA)
  10611. int pubIdx = srcIdx;
  10612. #endif
  10613. int ret = 0;
  10614. int length;
  10615. #ifndef WOLFSSL_ASN_TEMPLATE
  10616. if (GetSequence(source, &srcIdx, &length, maxIdx) < 0)
  10617. #else
  10618. /* Get SEQUENCE and expect all data to be accounted for. */
  10619. if (GetASN_Sequence(source, &srcIdx, &length, maxIdx, 1) != 0)
  10620. #endif
  10621. {
  10622. return ASN_PARSE_E;
  10623. }
  10624. #if defined(HAVE_ECC) || !defined(NO_DSA)
  10625. pubLen = srcIdx - pubIdx + length;
  10626. #endif
  10627. maxIdx = srcIdx + length;
  10628. /* Decode the algorithm identifier for the key. */
  10629. if (GetAlgoId(source, &srcIdx, &cert->keyOID, oidKeyType, maxIdx) < 0) {
  10630. return ASN_PARSE_E;
  10631. }
  10632. (void)length;
  10633. /* Parse each type of public key. */
  10634. switch (cert->keyOID) {
  10635. #ifndef NO_RSA
  10636. #ifdef WC_RSA_PSS
  10637. case RSAPSSk:
  10638. if (srcIdx != maxIdx &&
  10639. source[srcIdx] == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  10640. word32 seqIdx = srcIdx;
  10641. int seqLen;
  10642. /* Not set when -1. */
  10643. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  10644. int mgf = -1;
  10645. int saltLen = 0;
  10646. /* Defaults for sig algorithm parameters. */
  10647. enum wc_HashType sigHash = WC_HASH_TYPE_SHA;
  10648. int sigMgf = WC_MGF1SHA1;
  10649. int sigSaltLen = 20;
  10650. if (GetSequence(source, &srcIdx, &seqLen, maxIdx) < 0) {
  10651. return ASN_PARSE_E;
  10652. }
  10653. /* Get the pubic key parameters. */
  10654. ret = DecodeRsaPssParams(source + seqIdx,
  10655. seqLen + srcIdx - seqIdx, &hash, &mgf, &saltLen);
  10656. if (ret != 0) {
  10657. return ASN_PARSE_E;
  10658. }
  10659. /* Get the signature parameters. */
  10660. ret = DecodeRsaPssParams(source + cert->sigParamsIndex,
  10661. cert->sigParamsLength, &sigHash, &sigMgf, &sigSaltLen);
  10662. if (ret != 0) {
  10663. return ASN_PARSE_E;
  10664. }
  10665. /* Validated signature params match public key params. */
  10666. if (hash != WC_HASH_TYPE_NONE && hash != sigHash) {
  10667. WOLFSSL_MSG("RSA PSS: hash not matching signature hash");
  10668. return ASN_PARSE_E;
  10669. }
  10670. if (mgf != -1 && mgf != sigMgf) {
  10671. WOLFSSL_MSG("RSA PSS: MGF not matching signature MGF");
  10672. return ASN_PARSE_E;
  10673. }
  10674. if (saltLen > sigSaltLen) {
  10675. WOLFSSL_MSG("RSA PSS: sig salt length too small");
  10676. return ASN_PARSE_E;
  10677. }
  10678. srcIdx += seqLen;
  10679. }
  10680. FALL_THROUGH;
  10681. #endif /* WC_RSA_PSS */
  10682. case RSAk:
  10683. ret = StoreRsaKey(cert, source, &srcIdx, maxIdx);
  10684. break;
  10685. #endif /* NO_RSA */
  10686. #ifdef HAVE_ECC
  10687. case ECDSAk:
  10688. ret = StoreEccKey(cert, source, &srcIdx, maxIdx, source + pubIdx,
  10689. pubLen);
  10690. break;
  10691. #endif /* HAVE_ECC */
  10692. #ifdef HAVE_ED25519
  10693. case ED25519k:
  10694. cert->pkCurveOID = ED25519k;
  10695. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10696. break;
  10697. #endif /* HAVE_ED25519 */
  10698. #ifdef HAVE_ED448
  10699. case ED448k:
  10700. cert->pkCurveOID = ED448k;
  10701. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10702. break;
  10703. #endif /* HAVE_ED448 */
  10704. #if defined(HAVE_PQC) && defined(HAVE_LIBOQS)
  10705. #ifdef HAVE_FALCON
  10706. case FALCON_LEVEL1k:
  10707. cert->pkCurveOID = FALCON_LEVEL1k;
  10708. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10709. break;
  10710. case FALCON_LEVEL5k:
  10711. cert->pkCurveOID = FALCON_LEVEL5k;
  10712. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10713. break;
  10714. #endif /* HAVE_FALCON */
  10715. #ifdef HAVE_DILITHIUM
  10716. case DILITHIUM_LEVEL2k:
  10717. cert->pkCurveOID = DILITHIUM_LEVEL2k;
  10718. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10719. break;
  10720. case DILITHIUM_LEVEL3k:
  10721. cert->pkCurveOID = DILITHIUM_LEVEL3k;
  10722. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10723. break;
  10724. case DILITHIUM_LEVEL5k:
  10725. cert->pkCurveOID = DILITHIUM_LEVEL5k;
  10726. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10727. break;
  10728. case DILITHIUM_AES_LEVEL2k:
  10729. cert->pkCurveOID = DILITHIUM_AES_LEVEL2k;
  10730. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10731. break;
  10732. case DILITHIUM_AES_LEVEL3k:
  10733. cert->pkCurveOID = DILITHIUM_AES_LEVEL3k;
  10734. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10735. break;
  10736. case DILITHIUM_AES_LEVEL5k:
  10737. cert->pkCurveOID = DILITHIUM_AES_LEVEL5k;
  10738. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10739. break;
  10740. #endif /* HAVE_DILITHIUM */
  10741. #ifdef HAVE_SPHINCS
  10742. case SPHINCS_FAST_LEVEL1k:
  10743. cert->pkCurveOID = SPHINCS_FAST_LEVEL1k;
  10744. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10745. break;
  10746. case SPHINCS_FAST_LEVEL3k:
  10747. cert->pkCurveOID = SPHINCS_FAST_LEVEL3k;
  10748. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10749. break;
  10750. case SPHINCS_FAST_LEVEL5k:
  10751. cert->pkCurveOID = SPHINCS_FAST_LEVEL5k;
  10752. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10753. break;
  10754. case SPHINCS_SMALL_LEVEL1k:
  10755. cert->pkCurveOID = SPHINCS_SMALL_LEVEL1k;
  10756. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10757. break;
  10758. case SPHINCS_SMALL_LEVEL3k:
  10759. cert->pkCurveOID = SPHINCS_SMALL_LEVEL3k;
  10760. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10761. break;
  10762. case SPHINCS_SMALL_LEVEL5k:
  10763. cert->pkCurveOID = SPHINCS_SMALL_LEVEL5k;
  10764. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10765. break;
  10766. #endif /* HAVE_SPHINCS */
  10767. #endif /* HAVE_PQC */
  10768. #ifndef NO_DSA
  10769. case DSAk:
  10770. cert->publicKey = source + pubIdx;
  10771. cert->pubKeySize = pubLen;
  10772. ret = ParseDsaKey(source, &srcIdx, maxIdx, cert->heap);
  10773. break;
  10774. #endif /* NO_DSA */
  10775. default:
  10776. WOLFSSL_MSG("Unknown or not compiled in key OID");
  10777. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  10778. ret = ASN_UNKNOWN_OID_E;
  10779. }
  10780. /* Return index after public key. */
  10781. *inOutIdx = srcIdx;
  10782. /* Return error code. */
  10783. return ret;
  10784. }
  10785. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  10786. #if defined(HAVE_ECC)
  10787. /* Converts ECC curve enum values in ecc_curve_id to the associated OpenSSL NID
  10788. * value.
  10789. *
  10790. * @param [in] n ECC curve id.
  10791. * @return ECC curve NID (OpenSSL compatable value).
  10792. */
  10793. WOLFSSL_API int EccEnumToNID(int n)
  10794. {
  10795. WOLFSSL_ENTER("EccEnumToNID()");
  10796. switch(n) {
  10797. case ECC_SECP192R1:
  10798. return NID_X9_62_prime192v1;
  10799. case ECC_PRIME192V2:
  10800. return NID_X9_62_prime192v2;
  10801. case ECC_PRIME192V3:
  10802. return NID_X9_62_prime192v3;
  10803. case ECC_PRIME239V1:
  10804. return NID_X9_62_prime239v1;
  10805. case ECC_PRIME239V2:
  10806. return NID_X9_62_prime239v2;
  10807. case ECC_PRIME239V3:
  10808. return NID_X9_62_prime239v3;
  10809. case ECC_SECP256R1:
  10810. return NID_X9_62_prime256v1;
  10811. case ECC_SECP112R1:
  10812. return NID_secp112r1;
  10813. case ECC_SECP112R2:
  10814. return NID_secp112r2;
  10815. case ECC_SECP128R1:
  10816. return NID_secp128r1;
  10817. case ECC_SECP128R2:
  10818. return NID_secp128r2;
  10819. case ECC_SECP160R1:
  10820. return NID_secp160r1;
  10821. case ECC_SECP160R2:
  10822. return NID_secp160r2;
  10823. case ECC_SECP224R1:
  10824. return NID_secp224r1;
  10825. case ECC_SECP384R1:
  10826. return NID_secp384r1;
  10827. case ECC_SECP521R1:
  10828. return NID_secp521r1;
  10829. case ECC_SECP160K1:
  10830. return NID_secp160k1;
  10831. case ECC_SECP192K1:
  10832. return NID_secp192k1;
  10833. case ECC_SECP224K1:
  10834. return NID_secp224k1;
  10835. case ECC_SECP256K1:
  10836. return NID_secp256k1;
  10837. case ECC_BRAINPOOLP160R1:
  10838. return NID_brainpoolP160r1;
  10839. case ECC_BRAINPOOLP192R1:
  10840. return NID_brainpoolP192r1;
  10841. case ECC_BRAINPOOLP224R1:
  10842. return NID_brainpoolP224r1;
  10843. case ECC_BRAINPOOLP256R1:
  10844. return NID_brainpoolP256r1;
  10845. case ECC_BRAINPOOLP320R1:
  10846. return NID_brainpoolP320r1;
  10847. case ECC_BRAINPOOLP384R1:
  10848. return NID_brainpoolP384r1;
  10849. case ECC_BRAINPOOLP512R1:
  10850. return NID_brainpoolP512r1;
  10851. default:
  10852. WOLFSSL_MSG("NID not found");
  10853. return -1;
  10854. }
  10855. }
  10856. #endif /* HAVE_ECC */
  10857. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  10858. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  10859. && !defined(WOLFCRYPT_ONLY)
  10860. /* Convert shortname to NID.
  10861. *
  10862. * For OpenSSL compatability.
  10863. *
  10864. * @param [in] sn Short name of OID.
  10865. * @return NID corresponding to shortname on success.
  10866. * @return NID_undef when not recognized.
  10867. */
  10868. int wc_OBJ_sn2nid(const char *sn)
  10869. {
  10870. const struct {
  10871. const char *sn;
  10872. int nid;
  10873. } sn2nid[] = {
  10874. {WOLFSSL_COMMON_NAME, NID_commonName},
  10875. {WOLFSSL_COUNTRY_NAME, NID_countryName},
  10876. {WOLFSSL_LOCALITY_NAME, NID_localityName},
  10877. {WOLFSSL_STATE_NAME, NID_stateOrProvinceName},
  10878. {WOLFSSL_ORG_NAME, NID_organizationName},
  10879. {WOLFSSL_ORGUNIT_NAME, NID_organizationalUnitName},
  10880. #ifdef WOLFSSL_CERT_NAME_ALL
  10881. {WOLFSSL_NAME, NID_name},
  10882. {WOLFSSL_INITIALS, NID_initials},
  10883. {WOLFSSL_GIVEN_NAME, NID_givenName},
  10884. {WOLFSSL_DNQUALIFIER, NID_dnQualifier},
  10885. #endif
  10886. {WOLFSSL_EMAIL_ADDR, NID_emailAddress},
  10887. {"SHA1", NID_sha1},
  10888. {NULL, -1}};
  10889. int i;
  10890. #ifdef HAVE_ECC
  10891. char curveName[ECC_MAXNAME + 1];
  10892. int eccEnum;
  10893. #endif
  10894. WOLFSSL_ENTER("OBJ_sn2nid");
  10895. for(i=0; sn2nid[i].sn != NULL; i++) {
  10896. if (XSTRCMP(sn, sn2nid[i].sn) == 0) {
  10897. return sn2nid[i].nid;
  10898. }
  10899. }
  10900. #ifdef HAVE_ECC
  10901. if (XSTRLEN(sn) > ECC_MAXNAME)
  10902. return NID_undef;
  10903. /* Nginx uses this OpenSSL string. */
  10904. if (XSTRCMP(sn, "prime256v1") == 0)
  10905. sn = "SECP256R1";
  10906. /* OpenSSL allows lowercase curve names */
  10907. for (i = 0; i < (int)(sizeof(curveName) - 1) && *sn; i++) {
  10908. curveName[i] = (char)XTOUPPER((unsigned char) *sn++);
  10909. }
  10910. curveName[i] = '\0';
  10911. /* find based on name and return NID */
  10912. for (i = 0;
  10913. #ifndef WOLFSSL_ECC_CURVE_STATIC
  10914. ecc_sets[i].size != 0 && ecc_sets[i].name != NULL;
  10915. #else
  10916. ecc_sets[i].size != 0;
  10917. #endif
  10918. i++) {
  10919. if (XSTRCMP(curveName, ecc_sets[i].name) == 0) {
  10920. eccEnum = ecc_sets[i].id;
  10921. /* Convert enum value in ecc_curve_id to OpenSSL NID */
  10922. return EccEnumToNID(eccEnum);
  10923. }
  10924. }
  10925. #endif /* HAVE_ECC */
  10926. return NID_undef;
  10927. }
  10928. #endif
  10929. /* Calculate hash of the id using the SHA-1 or SHA-256.
  10930. *
  10931. * @param [in] data Data to hash.
  10932. * @param [in] len Length of data to hash.
  10933. * @param [out] hash Buffer to hold hash.
  10934. * @return 0 on success.
  10935. * @return MEMORY_E when dynamic memory allocation fails.
  10936. */
  10937. int CalcHashId(const byte* data, word32 len, byte* hash)
  10938. {
  10939. int ret;
  10940. #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
  10941. ret = wc_Sha256Hash(data, len, hash);
  10942. #elif !defined(NO_SHA)
  10943. ret = wc_ShaHash(data, len, hash);
  10944. #else
  10945. ret = NOT_COMPILED_IN;
  10946. (void)data;
  10947. (void)len;
  10948. (void)hash;
  10949. #endif
  10950. return ret;
  10951. }
  10952. #ifndef NO_CERTS
  10953. /* Get the hash of the id using the SHA-1 or SHA-256.
  10954. *
  10955. * If the id is not the length of the hash, then hash it.
  10956. *
  10957. * @param [in] id Id to get hash for.
  10958. * @param [in] len Length of id in bytes.
  10959. * @param [out] hash Buffer to hold hash.
  10960. * @return 0 on success.
  10961. * @return MEMORY_E when dynamic memory allocation fails.
  10962. */
  10963. static int GetHashId(const byte* id, int length, byte* hash)
  10964. {
  10965. int ret;
  10966. if (length == KEYID_SIZE) {
  10967. XMEMCPY(hash, id, length);
  10968. ret = 0;
  10969. }
  10970. else {
  10971. ret = CalcHashId(id, length, hash);
  10972. }
  10973. return ret;
  10974. }
  10975. #endif /* !NO_CERTS */
  10976. #ifdef WOLFSSL_ASN_TEMPLATE
  10977. /* Id for email address. */
  10978. #define ASN_EMAIL 0x100
  10979. /* Id for domain component. */
  10980. #define ASN_DC 0x102
  10981. /* Id for jurisdiction country. */
  10982. #define ASN_JURIS_C 0x203
  10983. /* Id for jurisdiction state. */
  10984. #define ASN_JURIS_ST 0x202
  10985. /* Set the string for a name component into the subject name. */
  10986. #define SetCertNameSubject(cert, id, val) \
  10987. *((char**)(((byte *)(cert)) + certNameSubject[(id) - 3].data)) = (val)
  10988. /* Set the string length for a name component into the subject name. */
  10989. #define SetCertNameSubjectLen(cert, id, val) \
  10990. *((int*)(((byte *)(cert)) + certNameSubject[(id) - 3].len)) = (val)
  10991. /* Set the encoding for a name component into the subject name. */
  10992. #define SetCertNameSubjectEnc(cert, id, val) \
  10993. *((byte*)(((byte *)(cert)) + certNameSubject[(id) - 3].enc)) = (val)
  10994. /* Get the string of a name component from the subject name. */
  10995. #define GetCertNameSubjectStr(id) \
  10996. (certNameSubject[(id) - 3].str)
  10997. /* Get the string length of a name component from the subject name. */
  10998. #define GetCertNameSubjectStrLen(id) \
  10999. (certNameSubject[(id) - 3].strLen)
  11000. /* Get the NID of a name component from the subject name. */
  11001. #define GetCertNameSubjectNID(id) \
  11002. (certNameSubject[(id) - 3].nid)
  11003. #define ValidCertNameSubject(id) \
  11004. (((id) - 3) >= 0 && ((id) - 3) < certNameSubjectSz && \
  11005. (certNameSubject[(id) - 3].strLen > 0))
  11006. /* Mapping of certificate name component to useful information. */
  11007. typedef struct CertNameData {
  11008. /* Type string of name component. */
  11009. const char* str;
  11010. /* Length of type string of name component. */
  11011. byte strLen;
  11012. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11013. /* Offset of data in subject name component. */
  11014. size_t data;
  11015. /* Offset of length in subject name component. */
  11016. size_t len;
  11017. /* Offset of encoding in subject name component. */
  11018. size_t enc;
  11019. #endif
  11020. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11021. /* NID of type for subject name component. */
  11022. int nid;
  11023. #endif
  11024. } CertNameData;
  11025. /* List of data for common name components. */
  11026. static const CertNameData certNameSubject[] = {
  11027. /* Common Name */
  11028. {
  11029. "/CN=", 4,
  11030. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11031. OFFSETOF(DecodedCert, subjectCN),
  11032. OFFSETOF(DecodedCert, subjectCNLen),
  11033. OFFSETOF(DecodedCert, subjectCNEnc),
  11034. #endif
  11035. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11036. NID_commonName
  11037. #endif
  11038. },
  11039. /* Surname */
  11040. {
  11041. "/SN=", 4,
  11042. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11043. OFFSETOF(DecodedCert, subjectSN),
  11044. OFFSETOF(DecodedCert, subjectSNLen),
  11045. OFFSETOF(DecodedCert, subjectSNEnc),
  11046. #endif
  11047. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11048. NID_surname
  11049. #endif
  11050. },
  11051. /* Serial Number */
  11052. {
  11053. "/serialNumber=", 14,
  11054. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11055. OFFSETOF(DecodedCert, subjectSND),
  11056. OFFSETOF(DecodedCert, subjectSNDLen),
  11057. OFFSETOF(DecodedCert, subjectSNDEnc),
  11058. #endif
  11059. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11060. NID_serialNumber
  11061. #endif
  11062. },
  11063. /* Country Name */
  11064. {
  11065. "/C=", 3,
  11066. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11067. OFFSETOF(DecodedCert, subjectC),
  11068. OFFSETOF(DecodedCert, subjectCLen),
  11069. OFFSETOF(DecodedCert, subjectCEnc),
  11070. #endif
  11071. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11072. NID_countryName
  11073. #endif
  11074. },
  11075. /* Locality Name */
  11076. {
  11077. "/L=", 3,
  11078. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11079. OFFSETOF(DecodedCert, subjectL),
  11080. OFFSETOF(DecodedCert, subjectLLen),
  11081. OFFSETOF(DecodedCert, subjectLEnc),
  11082. #endif
  11083. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11084. NID_localityName
  11085. #endif
  11086. },
  11087. /* State Name */
  11088. {
  11089. "/ST=", 4,
  11090. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11091. OFFSETOF(DecodedCert, subjectST),
  11092. OFFSETOF(DecodedCert, subjectSTLen),
  11093. OFFSETOF(DecodedCert, subjectSTEnc),
  11094. #endif
  11095. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11096. NID_stateOrProvinceName
  11097. #endif
  11098. },
  11099. /* Street Address */
  11100. {
  11101. "/street=", 8,
  11102. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11103. OFFSETOF(DecodedCert, subjectStreet),
  11104. OFFSETOF(DecodedCert, subjectStreetLen),
  11105. OFFSETOF(DecodedCert, subjectStreetEnc),
  11106. #endif
  11107. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11108. NID_streetAddress
  11109. #endif
  11110. },
  11111. /* Organization Name */
  11112. {
  11113. "/O=", 3,
  11114. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11115. OFFSETOF(DecodedCert, subjectO),
  11116. OFFSETOF(DecodedCert, subjectOLen),
  11117. OFFSETOF(DecodedCert, subjectOEnc),
  11118. #endif
  11119. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11120. NID_organizationName
  11121. #endif
  11122. },
  11123. /* Organization Unit Name */
  11124. {
  11125. "/OU=", 4,
  11126. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11127. OFFSETOF(DecodedCert, subjectOU),
  11128. OFFSETOF(DecodedCert, subjectOULen),
  11129. OFFSETOF(DecodedCert, subjectOUEnc),
  11130. #endif
  11131. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11132. NID_organizationalUnitName
  11133. #endif
  11134. },
  11135. /* Title */
  11136. {
  11137. NULL, 0,
  11138. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11139. 0,
  11140. 0,
  11141. 0,
  11142. #endif
  11143. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11144. 0,
  11145. #endif
  11146. },
  11147. /* Undefined */
  11148. {
  11149. NULL, 0,
  11150. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11151. 0,
  11152. 0,
  11153. 0,
  11154. #endif
  11155. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11156. 0,
  11157. #endif
  11158. },
  11159. /* Undefined */
  11160. {
  11161. NULL, 0,
  11162. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11163. 0,
  11164. 0,
  11165. 0,
  11166. #endif
  11167. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11168. 0,
  11169. #endif
  11170. },
  11171. /* Business Category */
  11172. {
  11173. "/businessCategory=", 18,
  11174. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11175. OFFSETOF(DecodedCert, subjectBC),
  11176. OFFSETOF(DecodedCert, subjectBCLen),
  11177. OFFSETOF(DecodedCert, subjectBCEnc),
  11178. #endif
  11179. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11180. NID_businessCategory
  11181. #endif
  11182. },
  11183. /* Undefined */
  11184. {
  11185. NULL, 0,
  11186. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11187. 0,
  11188. 0,
  11189. 0,
  11190. #endif
  11191. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11192. 0,
  11193. #endif
  11194. },
  11195. /* Postal Code */
  11196. {
  11197. "/postalCode=", 12,
  11198. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11199. OFFSETOF(DecodedCert, subjectPC),
  11200. OFFSETOF(DecodedCert, subjectPCLen),
  11201. OFFSETOF(DecodedCert, subjectPCEnc),
  11202. #endif
  11203. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11204. NID_postalCode
  11205. #endif
  11206. },
  11207. /* User Id */
  11208. {
  11209. "/userid=", 8,
  11210. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11211. OFFSETOF(DecodedCert, subjectUID),
  11212. OFFSETOF(DecodedCert, subjectUIDLen),
  11213. OFFSETOF(DecodedCert, subjectUIDEnc),
  11214. #endif
  11215. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11216. NID_userId
  11217. #endif
  11218. },
  11219. #ifdef WOLFSSL_CERT_NAME_ALL
  11220. /* Name, id 41 */
  11221. {
  11222. "/N=", 3,
  11223. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11224. OFFSETOF(DecodedCert, subjectN),
  11225. OFFSETOF(DecodedCert, subjectNLen),
  11226. OFFSETOF(DecodedCert, subjectNEnc),
  11227. #endif
  11228. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11229. NID_name
  11230. #endif
  11231. },
  11232. /* Given Name, id 42 */
  11233. {
  11234. "/GN=", 4,
  11235. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11236. OFFSETOF(DecodedCert, subjectGN),
  11237. OFFSETOF(DecodedCert, subjectGNLen),
  11238. OFFSETOF(DecodedCert, subjectGNEnc),
  11239. #endif
  11240. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11241. NID_givenName
  11242. #endif
  11243. },
  11244. /* initials, id 43 */
  11245. {
  11246. "/initials=", 10,
  11247. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11248. OFFSETOF(DecodedCert, subjectI),
  11249. OFFSETOF(DecodedCert, subjectILen),
  11250. OFFSETOF(DecodedCert, subjectIEnc),
  11251. #endif
  11252. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11253. NID_initials
  11254. #endif
  11255. },
  11256. /* DN Qualifier Name, id 46 */
  11257. {
  11258. "/dnQualifier=", 13,
  11259. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11260. OFFSETOF(DecodedCert, subjectDNQ),
  11261. OFFSETOF(DecodedCert, subjectDNQLen),
  11262. OFFSETOF(DecodedCert, subjectDNQEnc),
  11263. #endif
  11264. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11265. NID_dnQualifier
  11266. #endif
  11267. },
  11268. #endif /* WOLFSSL_CERT_NAME_ALL */
  11269. };
  11270. static const int certNameSubjectSz =
  11271. (int) (sizeof(certNameSubject) / sizeof(CertNameData));
  11272. /* ASN.1 template for an RDN.
  11273. * X.509: RFC 5280, 4.1.2.4 - RelativeDistinguishedName
  11274. */
  11275. static const ASNItem rdnASN[] = {
  11276. /* SET */ { 1, ASN_SET, 1, 1, 0 },
  11277. /* AttributeTypeAndValue */
  11278. /* ATTR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  11279. /* AttributeType */
  11280. /* ATTR_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  11281. /* AttributeValue: Choice of tags - rdnChoice. */
  11282. /* ATTR_VAL */ { 3, 0, 0, 0, 0 },
  11283. };
  11284. enum {
  11285. RDNASN_IDX_SET = 0,
  11286. RDNASN_IDX_ATTR_SEQ,
  11287. RDNASN_IDX_ATTR_TYPE,
  11288. RDNASN_IDX_ATTR_VAL,
  11289. };
  11290. /* Number of items in ASN.1 template for an RDN. */
  11291. #define rdnASN_Length (sizeof(rdnASN) / sizeof(ASNItem))
  11292. /* Supported types of encodings (tags) for RDN strings.
  11293. * X.509: RFC 5280, 4.1.2.4 - DirectoryString
  11294. * (IA5 String not listed in RFC but required for alternative types)
  11295. */
  11296. static const byte rdnChoice[] = {
  11297. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, ASN_T61STRING,
  11298. ASN_UNIVERSALSTRING, ASN_BMPSTRING, 0
  11299. };
  11300. #endif
  11301. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  11302. /* used to set the human readable string for the IP address with a ASN_IP_TYPE
  11303. * DNS entry
  11304. * return 0 on success
  11305. */
  11306. static int GenerateDNSEntryIPString(DNS_entry* entry, void* heap)
  11307. {
  11308. int ret = 0;
  11309. int nameSz;
  11310. char tmpName[WOLFSSL_MAX_IPSTR] = {0};
  11311. char* ip;
  11312. if (entry == NULL || entry->type != ASN_IP_TYPE) {
  11313. return BAD_FUNC_ARG;
  11314. }
  11315. if (entry->len != WOLFSSL_IP4_ADDR_LEN &&
  11316. entry->len != WOLFSSL_IP6_ADDR_LEN) {
  11317. WOLFSSL_MSG("Unexpected IP size");
  11318. return BAD_FUNC_ARG;
  11319. }
  11320. ip = entry->name;
  11321. /* store IP addresses as a string */
  11322. if (entry->len == WOLFSSL_IP4_ADDR_LEN) {
  11323. if (XSNPRINTF(tmpName, sizeof(tmpName), "%u.%u.%u.%u", 0xFFU & ip[0],
  11324. 0xFFU & ip[1], 0xFFU & ip[2], 0xFFU & ip[3])
  11325. >= (int)sizeof(tmpName))
  11326. {
  11327. WOLFSSL_MSG("IP buffer overrun");
  11328. return BUFFER_E;
  11329. }
  11330. }
  11331. if (entry->len == WOLFSSL_IP6_ADDR_LEN) {
  11332. int i;
  11333. for (i = 0; i < 8; i++) {
  11334. if (XSNPRINTF(tmpName + i * 5, sizeof(tmpName) - i * 5,
  11335. "%02X%02X%s", 0xFF & ip[2 * i], 0xFF & ip[2 * i + 1],
  11336. (i < 7) ? ":" : "")
  11337. >= (int)sizeof(tmpName))
  11338. {
  11339. WOLFSSL_MSG("IPv6 buffer overrun");
  11340. return BUFFER_E;
  11341. }
  11342. }
  11343. }
  11344. nameSz = (int)XSTRLEN(tmpName);
  11345. entry->ipString = (char*)XMALLOC(nameSz + 1, heap, DYNAMIC_TYPE_ALTNAME);
  11346. if (entry->ipString == NULL) {
  11347. ret = MEMORY_E;
  11348. }
  11349. if (ret == 0) {
  11350. XMEMCPY(entry->ipString, tmpName, nameSz);
  11351. entry->ipString[nameSz] = '\0';
  11352. }
  11353. (void)heap;
  11354. return ret;
  11355. }
  11356. #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  11357. #ifdef WOLFSSL_ASN_TEMPLATE
  11358. #if defined(WOLFSSL_CERT_GEN) || !defined(NO_CERTS)
  11359. /* Adds a DNS entry to a list of DNS entries
  11360. *
  11361. * @param [in, out] lst Linked list of DNS name entries.
  11362. * @param [in] entry Entry to add to the list
  11363. * @return 0 on success.
  11364. */
  11365. static int AddDNSEntryToList(DNS_entry** lst, DNS_entry* entry)
  11366. {
  11367. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  11368. entry->next = NULL;
  11369. if (*lst == NULL) {
  11370. /* First on list */
  11371. *lst = entry;
  11372. }
  11373. else {
  11374. DNS_entry* temp = *lst;
  11375. /* Find end */
  11376. for (; (temp->next != NULL); temp = temp->next);
  11377. /* Add to end */
  11378. temp->next = entry;
  11379. }
  11380. #else
  11381. /* Prepend entry to linked list. */
  11382. entry->next = *lst;
  11383. *lst = entry;
  11384. #endif
  11385. return 0;
  11386. }
  11387. /* Allocate a DNS entry and set the fields.
  11388. *
  11389. * @param [in] cert Certificate object.
  11390. * @param [in] str DNS name string.
  11391. * @param [in] strLen Length of DNS name string.
  11392. * @param [in] type Type of DNS name string.
  11393. * @param [in, out] entries Linked list of DNS name entries.
  11394. * @return 0 on success.
  11395. * @return MEMORY_E when dynamic memory allocation fails.
  11396. */
  11397. static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen,
  11398. int type, DNS_entry** entries)
  11399. {
  11400. DNS_entry* dnsEntry;
  11401. int ret = 0;
  11402. /* Only used for heap. */
  11403. (void)cert;
  11404. /* TODO: consider one malloc. */
  11405. /* Allocate DNS Entry object. */
  11406. dnsEntry = AltNameNew(cert->heap);
  11407. if (dnsEntry == NULL) {
  11408. ret = MEMORY_E;
  11409. }
  11410. if (ret == 0) {
  11411. /* Allocate DNS Entry name - length of string plus 1 for NUL. */
  11412. dnsEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  11413. DYNAMIC_TYPE_ALTNAME);
  11414. if (dnsEntry->name == NULL) {
  11415. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11416. ret = MEMORY_E;
  11417. }
  11418. }
  11419. if (ret == 0) {
  11420. /* Set tag type, name length, name and NUL terminate name. */
  11421. dnsEntry->type = type;
  11422. dnsEntry->len = strLen;
  11423. XMEMCPY(dnsEntry->name, str, strLen);
  11424. dnsEntry->name[strLen] = '\0';
  11425. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  11426. /* store IP addresses as a string */
  11427. if (type == ASN_IP_TYPE) {
  11428. if ((ret = GenerateDNSEntryIPString(dnsEntry, cert->heap)) != 0) {
  11429. XFREE(dnsEntry->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11430. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11431. }
  11432. }
  11433. #endif
  11434. }
  11435. if (ret == 0) {
  11436. ret = AddDNSEntryToList(entries, dnsEntry);
  11437. }
  11438. return ret;
  11439. }
  11440. #endif
  11441. /* Set the details of a subject name component into a certificate.
  11442. *
  11443. * @param [in, out] cert Certificate object.
  11444. * @param [in] id Id of component.
  11445. * @param [in] str String for component.
  11446. * @param [in] strLen Length of string.
  11447. * @param [in] tag BER tag representing encoding of string.
  11448. * @return 0 on success, negative values on failure.
  11449. */
  11450. static int SetSubject(DecodedCert* cert, int id, byte* str, word32 strLen,
  11451. byte tag)
  11452. {
  11453. int ret = 0;
  11454. /* Put string and encoding into certificate. */
  11455. if (id == ASN_COMMON_NAME) {
  11456. cert->subjectCN = (char *)str;
  11457. cert->subjectCNLen = strLen;
  11458. cert->subjectCNEnc = tag;
  11459. }
  11460. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11461. else if (id > ASN_COMMON_NAME && id <= ASN_USER_ID) {
  11462. /* Use table and offsets to put data into appropriate fields. */
  11463. SetCertNameSubject(cert, id, (char*)str);
  11464. SetCertNameSubjectLen(cert, id, strLen);
  11465. SetCertNameSubjectEnc(cert, id, tag);
  11466. }
  11467. #endif
  11468. #if !defined(IGNORE_NAME_CONSTRAINTS) || \
  11469. defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11470. else if (id == ASN_EMAIL) {
  11471. cert->subjectEmail = (char*)str;
  11472. cert->subjectEmailLen = strLen;
  11473. }
  11474. #endif
  11475. #ifdef WOLFSSL_CERT_EXT
  11476. /* TODO: consider mapping id to an index and using SetCertNameSubect*(). */
  11477. else if (id == ASN_JURIS_C) {
  11478. cert->subjectJC = (char*)str;
  11479. cert->subjectJCLen = strLen;
  11480. cert->subjectJCEnc = tag;
  11481. }
  11482. else if (id == ASN_JURIS_ST) {
  11483. cert->subjectJS = (char*)str;
  11484. cert->subjectJSLen = strLen;
  11485. cert->subjectJSEnc = tag;
  11486. }
  11487. #endif
  11488. return ret;
  11489. }
  11490. /* Get a RelativeDistinguishedName from the encoding and put in certificate.
  11491. *
  11492. * @param [in, out] cert Certificate object.
  11493. * @param [in, out] full Full name string. ([/<type>=<value>]*)
  11494. * @param [in, out] idx Index int full name to place next component.
  11495. * @param [in, out] nid NID of component type.
  11496. * @param [in] isSubject Whether this data is for a subject name.
  11497. * @param [in] dataASN Decoded data of RDN. Expected rdnASN type.
  11498. * @return 0 on success.
  11499. * @return MEMORY_E when dynamic memory allocation fails.
  11500. * @return ASN_PARSE_E when type not supported.
  11501. */
  11502. static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid,
  11503. int isSubject, ASNGetData* dataASN)
  11504. {
  11505. int ret = 0;
  11506. const char* typeStr = NULL;
  11507. byte typeStrLen = 0;
  11508. byte* oid;
  11509. word32 oidSz;
  11510. int id = 0;
  11511. (void)nid;
  11512. /* Get name type OID from data items. */
  11513. GetASN_OIDData(&dataASN[RDNASN_IDX_ATTR_TYPE], &oid, &oidSz);
  11514. /* v1 name types */
  11515. if ((oidSz == 3) && (oid[0] == 0x55) && (oid[1] == 0x04)) {
  11516. id = oid[2];
  11517. /* Check range of supported ids in table. */
  11518. if (ValidCertNameSubject(id)) {
  11519. /* Get the type string, length and NID from table. */
  11520. typeStr = GetCertNameSubjectStr(id);
  11521. typeStrLen = GetCertNameSubjectStrLen(id);
  11522. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11523. *nid = GetCertNameSubjectNID(id);
  11524. #endif
  11525. }
  11526. }
  11527. else if (oidSz == sizeof(attrEmailOid) && XMEMCMP(oid, attrEmailOid, oidSz) == 0) {
  11528. /* Set the email id, type string, length and NID. */
  11529. id = ASN_EMAIL;
  11530. typeStr = WOLFSSL_EMAIL_ADDR;
  11531. typeStrLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  11532. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11533. *nid = NID_emailAddress;
  11534. #endif
  11535. }
  11536. else if (oidSz == sizeof(uidOid) && XMEMCMP(oid, uidOid, oidSz) == 0) {
  11537. /* Set the user id, type string, length and NID. */
  11538. id = ASN_USER_ID;
  11539. typeStr = WOLFSSL_USER_ID;
  11540. typeStrLen = sizeof(WOLFSSL_USER_ID) - 1;
  11541. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11542. *nid = NID_userId;
  11543. #endif
  11544. }
  11545. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz) == 0) {
  11546. /* Set the domain component, type string, length and NID. */
  11547. id = ASN_DC;
  11548. typeStr = WOLFSSL_DOMAIN_COMPONENT;
  11549. typeStrLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  11550. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11551. *nid = NID_domainComponent;
  11552. #endif
  11553. }
  11554. /* Other OIDs that start with the same values. */
  11555. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz-1) == 0) {
  11556. WOLFSSL_MSG("Unknown pilot attribute type");
  11557. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  11558. ret = ASN_PARSE_E;
  11559. }
  11560. else if (oidSz == ASN_JOI_PREFIX_SZ + 1 &&
  11561. XMEMCMP(oid, ASN_JOI_PREFIX, ASN_JOI_PREFIX_SZ) == 0) {
  11562. /* Set the jurisdiction id. */
  11563. id = 0x200 + oid[ASN_JOI_PREFIX_SZ];
  11564. /* Set the jurisdiction type string, length and NID if known. */
  11565. if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_C) {
  11566. typeStr = WOLFSSL_JOI_C;
  11567. typeStrLen = sizeof(WOLFSSL_JOI_C) - 1;
  11568. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11569. *nid = NID_jurisdictionCountryName;
  11570. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  11571. }
  11572. else if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_ST) {
  11573. typeStr = WOLFSSL_JOI_ST;
  11574. typeStrLen = sizeof(WOLFSSL_JOI_ST) - 1;
  11575. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11576. *nid = NID_jurisdictionStateOrProvinceName;
  11577. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  11578. }
  11579. else {
  11580. WOLFSSL_MSG("Unknown Jurisdiction, skipping");
  11581. }
  11582. }
  11583. if ((ret == 0) && (typeStr != NULL)) {
  11584. /* OID type to store for subject name and add to full string. */
  11585. byte* str;
  11586. word32 strLen;
  11587. byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
  11588. /* Get the string reference and length. */
  11589. GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
  11590. if (isSubject) {
  11591. /* Store subject field components. */
  11592. ret = SetSubject(cert, id, str, strLen, tag);
  11593. }
  11594. if (ret == 0) {
  11595. /* Check there is space for this in the full name string and
  11596. * terminating NUL character. */
  11597. if ((typeStrLen + strLen) < (word32)(WC_ASN_NAME_MAX - *idx))
  11598. {
  11599. /* Add RDN to full string. */
  11600. XMEMCPY(&full[*idx], typeStr, typeStrLen);
  11601. *idx += typeStrLen;
  11602. XMEMCPY(&full[*idx], str, strLen);
  11603. *idx += strLen;
  11604. }
  11605. else {
  11606. WOLFSSL_MSG("ASN Name too big, skipping");
  11607. }
  11608. }
  11609. }
  11610. return ret;
  11611. }
  11612. #endif /* WOLFSSL_ASN_TEMPLATE */
  11613. /* Get a certificate name into the certificate object.
  11614. *
  11615. * @param [in, out] cert Decoded certificate object.
  11616. * @param [out] full Buffer to hold full name as a string.
  11617. * @param [out] hash Buffer to hold hash of name.
  11618. * @param [in] nameType ISSUER or SUBJECT.
  11619. * @param [in] input Buffer holding certificate name.
  11620. * @param [in, out] inOutIdx On in, start of certificate name.
  11621. * On out, start of ASN.1 item after cert name.
  11622. * @param [in] maxIdx Index of next item after certificate name.
  11623. * @return 0 on success.
  11624. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  11625. * is invalid.
  11626. * @return BUFFER_E when data in buffer is too small.
  11627. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  11628. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  11629. * @return MEMORY_E when dynamic memory allocation fails.
  11630. */
  11631. static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType,
  11632. const byte* input, word32* inOutIdx, word32 maxIdx)
  11633. {
  11634. #ifndef WOLFSSL_ASN_TEMPLATE
  11635. int length; /* length of all distinguished names */
  11636. int dummy;
  11637. int ret;
  11638. word32 idx;
  11639. word32 srcIdx = *inOutIdx;
  11640. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11641. !defined(WOLFCRYPT_ONLY)
  11642. WOLFSSL_X509_NAME* dName = NULL;
  11643. #endif
  11644. WOLFSSL_MSG("Getting Cert Name");
  11645. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  11646. * calculated over the entire DER encoding of the Name field, including
  11647. * the tag and length. */
  11648. if (CalcHashId(input + *inOutIdx, maxIdx - *inOutIdx, hash) != 0)
  11649. return ASN_PARSE_E;
  11650. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11651. !defined(WOLFCRYPT_ONLY)
  11652. dName = wolfSSL_X509_NAME_new();
  11653. if (dName == NULL) {
  11654. return MEMORY_E;
  11655. }
  11656. #endif /* OPENSSL_EXTRA */
  11657. if (GetSequence(input, &srcIdx, &length, maxIdx) < 0) {
  11658. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11659. !defined(WOLFCRYPT_ONLY)
  11660. wolfSSL_X509_NAME_free(dName);
  11661. #endif /* OPENSSL_EXTRA */
  11662. return ASN_PARSE_E;
  11663. }
  11664. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  11665. /* store pointer to raw issuer */
  11666. if (nameType == ISSUER) {
  11667. cert->issuerRaw = &input[srcIdx];
  11668. cert->issuerRawLen = length;
  11669. }
  11670. #endif
  11671. #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
  11672. if (nameType == SUBJECT) {
  11673. cert->subjectRaw = &input[srcIdx];
  11674. cert->subjectRawLen = length;
  11675. }
  11676. #endif
  11677. length += srcIdx;
  11678. idx = 0;
  11679. while (srcIdx < (word32)length) {
  11680. byte b = 0;
  11681. byte joint[3];
  11682. byte tooBig = FALSE;
  11683. int oidSz;
  11684. const char* copy = NULL;
  11685. int copyLen = 0;
  11686. int strLen = 0;
  11687. byte id = 0;
  11688. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  11689. && !defined(WOLFCRYPT_ONLY)
  11690. int nid = NID_undef;
  11691. int enc;
  11692. #endif /* OPENSSL_EXTRA */
  11693. if (GetSet(input, &srcIdx, &dummy, maxIdx) < 0) {
  11694. WOLFSSL_MSG("Cert name lacks set header, trying sequence");
  11695. }
  11696. if (GetSequence(input, &srcIdx, &dummy, maxIdx) <= 0) {
  11697. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11698. !defined(WOLFCRYPT_ONLY)
  11699. wolfSSL_X509_NAME_free(dName);
  11700. #endif /* OPENSSL_EXTRA */
  11701. return ASN_PARSE_E;
  11702. }
  11703. ret = GetASNObjectId(input, &srcIdx, &oidSz, maxIdx);
  11704. if (ret != 0) {
  11705. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11706. !defined(WOLFCRYPT_ONLY)
  11707. wolfSSL_X509_NAME_free(dName);
  11708. #endif /* OPENSSL_EXTRA */
  11709. return ret;
  11710. }
  11711. /* make sure there is room for joint */
  11712. if ((srcIdx + sizeof(joint)) > (word32)maxIdx) {
  11713. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11714. !defined(WOLFCRYPT_ONLY)
  11715. wolfSSL_X509_NAME_free(dName);
  11716. #endif /* OPENSSL_EXTRA */
  11717. return ASN_PARSE_E;
  11718. }
  11719. XMEMCPY(joint, &input[srcIdx], sizeof(joint));
  11720. /* v1 name types */
  11721. if (joint[0] == 0x55 && joint[1] == 0x04) {
  11722. srcIdx += 3;
  11723. id = joint[2];
  11724. if (GetHeader(input, &b, &srcIdx, &strLen, maxIdx, 1) < 0) {
  11725. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11726. !defined(WOLFCRYPT_ONLY)
  11727. wolfSSL_X509_NAME_free(dName);
  11728. #endif /* OPENSSL_EXTRA */
  11729. return ASN_PARSE_E;
  11730. }
  11731. if (id == ASN_COMMON_NAME) {
  11732. if (nameType == SUBJECT) {
  11733. cert->subjectCN = (char *)&input[srcIdx];
  11734. cert->subjectCNLen = strLen;
  11735. cert->subjectCNEnc = b;
  11736. }
  11737. #if (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)) && \
  11738. defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11739. else if (nameType == ISSUER) {
  11740. cert->issuerCN = (char*)&input[srcIdx];
  11741. cert->issuerCNLen = strLen;
  11742. cert->issuerCNEnc = b;
  11743. }
  11744. #endif
  11745. copy = WOLFSSL_COMMON_NAME;
  11746. copyLen = sizeof(WOLFSSL_COMMON_NAME) - 1;
  11747. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  11748. && !defined(WOLFCRYPT_ONLY)
  11749. nid = NID_commonName;
  11750. #endif /* OPENSSL_EXTRA */
  11751. }
  11752. #ifdef WOLFSSL_CERT_NAME_ALL
  11753. else if (id == ASN_NAME) {
  11754. copy = WOLFSSL_NAME;
  11755. copyLen = sizeof(WOLFSSL_NAME) - 1;
  11756. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11757. if (nameType == SUBJECT) {
  11758. cert->subjectN = (char*)&input[srcIdx];
  11759. cert->subjectNLen = strLen;
  11760. cert->subjectNEnc = b;
  11761. }
  11762. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11763. #if (defined(OPENSSL_EXTRA) || \
  11764. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11765. && !defined(WOLFCRYPT_ONLY)
  11766. nid = NID_name;
  11767. #endif /* OPENSSL_EXTRA */
  11768. }
  11769. else if (id == ASN_INITIALS) {
  11770. copy = WOLFSSL_INITIALS;
  11771. copyLen = sizeof(WOLFSSL_INITIALS) - 1;
  11772. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11773. if (nameType == SUBJECT) {
  11774. cert->subjectI = (char*)&input[srcIdx];
  11775. cert->subjectILen = strLen;
  11776. cert->subjectIEnc = b;
  11777. }
  11778. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11779. #if (defined(OPENSSL_EXTRA) || \
  11780. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11781. && !defined(WOLFCRYPT_ONLY)
  11782. nid = NID_initials;
  11783. #endif /* OPENSSL_EXTRA */
  11784. }
  11785. else if (id == ASN_GIVEN_NAME) {
  11786. copy = WOLFSSL_GIVEN_NAME;
  11787. copyLen = sizeof(WOLFSSL_GIVEN_NAME) - 1;
  11788. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11789. if (nameType == SUBJECT) {
  11790. cert->subjectGN = (char*)&input[srcIdx];
  11791. cert->subjectGNLen = strLen;
  11792. cert->subjectGNEnc = b;
  11793. }
  11794. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11795. #if (defined(OPENSSL_EXTRA) || \
  11796. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11797. && !defined(WOLFCRYPT_ONLY)
  11798. nid = NID_givenName;
  11799. #endif /* OPENSSL_EXTRA */
  11800. }
  11801. else if (id == ASN_DNQUALIFIER) {
  11802. copy = WOLFSSL_DNQUALIFIER;
  11803. copyLen = sizeof(WOLFSSL_DNQUALIFIER) - 1;
  11804. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11805. if (nameType == SUBJECT) {
  11806. cert->subjectDNQ = (char*)&input[srcIdx];
  11807. cert->subjectDNQLen = strLen;
  11808. cert->subjectDNQEnc = b;
  11809. }
  11810. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11811. #if (defined(OPENSSL_EXTRA) || \
  11812. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11813. && !defined(WOLFCRYPT_ONLY)
  11814. nid = NID_dnQualifier;
  11815. #endif /* OPENSSL_EXTRA */
  11816. }
  11817. #endif /* WOLFSSL_CERT_NAME_ALL */
  11818. else if (id == ASN_SUR_NAME) {
  11819. copy = WOLFSSL_SUR_NAME;
  11820. copyLen = sizeof(WOLFSSL_SUR_NAME) - 1;
  11821. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11822. if (nameType == SUBJECT) {
  11823. cert->subjectSN = (char*)&input[srcIdx];
  11824. cert->subjectSNLen = strLen;
  11825. cert->subjectSNEnc = b;
  11826. }
  11827. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11828. else if (nameType == ISSUER) {
  11829. cert->issuerSN = (char*)&input[srcIdx];
  11830. cert->issuerSNLen = strLen;
  11831. cert->issuerSNEnc = b;
  11832. }
  11833. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11834. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11835. #if (defined(OPENSSL_EXTRA) || \
  11836. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11837. && !defined(WOLFCRYPT_ONLY)
  11838. nid = NID_surname;
  11839. #endif /* OPENSSL_EXTRA */
  11840. }
  11841. else if (id == ASN_COUNTRY_NAME) {
  11842. copy = WOLFSSL_COUNTRY_NAME;
  11843. copyLen = sizeof(WOLFSSL_COUNTRY_NAME) - 1;
  11844. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11845. if (nameType == SUBJECT) {
  11846. cert->subjectC = (char*)&input[srcIdx];
  11847. cert->subjectCLen = strLen;
  11848. cert->subjectCEnc = b;
  11849. }
  11850. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11851. else if (nameType == ISSUER) {
  11852. cert->issuerC = (char*)&input[srcIdx];
  11853. cert->issuerCLen = strLen;
  11854. cert->issuerCEnc = b;
  11855. }
  11856. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11857. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11858. #if (defined(OPENSSL_EXTRA) || \
  11859. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11860. && !defined(WOLFCRYPT_ONLY)
  11861. nid = NID_countryName;
  11862. #endif /* OPENSSL_EXTRA */
  11863. }
  11864. else if (id == ASN_LOCALITY_NAME) {
  11865. copy = WOLFSSL_LOCALITY_NAME;
  11866. copyLen = sizeof(WOLFSSL_LOCALITY_NAME) - 1;
  11867. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11868. if (nameType == SUBJECT) {
  11869. cert->subjectL = (char*)&input[srcIdx];
  11870. cert->subjectLLen = strLen;
  11871. cert->subjectLEnc = b;
  11872. }
  11873. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11874. else if (nameType == ISSUER) {
  11875. cert->issuerL = (char*)&input[srcIdx];
  11876. cert->issuerLLen = strLen;
  11877. cert->issuerLEnc = b;
  11878. }
  11879. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11880. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11881. #if (defined(OPENSSL_EXTRA) || \
  11882. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11883. && !defined(WOLFCRYPT_ONLY)
  11884. nid = NID_localityName;
  11885. #endif /* OPENSSL_EXTRA */
  11886. }
  11887. else if (id == ASN_STATE_NAME) {
  11888. copy = WOLFSSL_STATE_NAME;
  11889. copyLen = sizeof(WOLFSSL_STATE_NAME) - 1;
  11890. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11891. if (nameType == SUBJECT) {
  11892. cert->subjectST = (char*)&input[srcIdx];
  11893. cert->subjectSTLen = strLen;
  11894. cert->subjectSTEnc = b;
  11895. }
  11896. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11897. else if (nameType == ISSUER) {
  11898. cert->issuerST = (char*)&input[srcIdx];
  11899. cert->issuerSTLen = strLen;
  11900. cert->issuerSTEnc = b;
  11901. }
  11902. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11903. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
  11904. #if (defined(OPENSSL_EXTRA) || \
  11905. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11906. && !defined(WOLFCRYPT_ONLY)
  11907. nid = NID_stateOrProvinceName;
  11908. #endif /* OPENSSL_EXTRA */
  11909. }
  11910. else if (id == ASN_ORG_NAME) {
  11911. copy = WOLFSSL_ORG_NAME;
  11912. copyLen = sizeof(WOLFSSL_ORG_NAME) - 1;
  11913. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11914. if (nameType == SUBJECT) {
  11915. cert->subjectO = (char*)&input[srcIdx];
  11916. cert->subjectOLen = strLen;
  11917. cert->subjectOEnc = b;
  11918. }
  11919. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11920. else if (nameType == ISSUER) {
  11921. cert->issuerO = (char*)&input[srcIdx];
  11922. cert->issuerOLen = strLen;
  11923. cert->issuerOEnc = b;
  11924. }
  11925. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11926. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11927. #if (defined(OPENSSL_EXTRA) || \
  11928. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11929. && !defined(WOLFCRYPT_ONLY)
  11930. nid = NID_organizationName;
  11931. #endif /* OPENSSL_EXTRA */
  11932. }
  11933. else if (id == ASN_ORGUNIT_NAME) {
  11934. copy = WOLFSSL_ORGUNIT_NAME;
  11935. copyLen = sizeof(WOLFSSL_ORGUNIT_NAME) - 1;
  11936. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11937. if (nameType == SUBJECT) {
  11938. cert->subjectOU = (char*)&input[srcIdx];
  11939. cert->subjectOULen = strLen;
  11940. cert->subjectOUEnc = b;
  11941. }
  11942. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11943. else if (nameType == ISSUER) {
  11944. cert->issuerOU = (char*)&input[srcIdx];
  11945. cert->issuerOULen = strLen;
  11946. cert->issuerOUEnc = b;
  11947. }
  11948. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11949. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11950. #if (defined(OPENSSL_EXTRA) || \
  11951. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11952. && !defined(WOLFCRYPT_ONLY)
  11953. nid = NID_organizationalUnitName;
  11954. #endif /* OPENSSL_EXTRA */
  11955. }
  11956. else if (id == ASN_SERIAL_NUMBER) {
  11957. copy = WOLFSSL_SERIAL_NUMBER;
  11958. copyLen = sizeof(WOLFSSL_SERIAL_NUMBER) - 1;
  11959. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11960. if (nameType == SUBJECT) {
  11961. cert->subjectSND = (char*)&input[srcIdx];
  11962. cert->subjectSNDLen = strLen;
  11963. cert->subjectSNDEnc = b;
  11964. }
  11965. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11966. else if (nameType == ISSUER) {
  11967. cert->issuerSND = (char*)&input[srcIdx];
  11968. cert->issuerSNDLen = strLen;
  11969. cert->issuerSNDEnc = b;
  11970. }
  11971. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11972. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11973. #if (defined(OPENSSL_EXTRA) || \
  11974. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11975. && !defined(WOLFCRYPT_ONLY)
  11976. nid = NID_serialNumber;
  11977. #endif /* OPENSSL_EXTRA */
  11978. }
  11979. else if (id == ASN_USER_ID) {
  11980. copy = WOLFSSL_USER_ID;
  11981. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  11982. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11983. if (nameType == SUBJECT) {
  11984. cert->subjectUID = (char*)&input[srcIdx];
  11985. cert->subjectUIDLen = strLen;
  11986. cert->subjectUIDEnc = b;
  11987. }
  11988. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11989. #if (defined(OPENSSL_EXTRA) || \
  11990. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11991. && !defined(WOLFCRYPT_ONLY)
  11992. nid = NID_userId;
  11993. #endif /* OPENSSL_EXTRA */
  11994. }
  11995. #ifdef WOLFSSL_CERT_EXT
  11996. else if (id == ASN_STREET_ADDR) {
  11997. copy = WOLFSSL_STREET_ADDR_NAME;
  11998. copyLen = sizeof(WOLFSSL_STREET_ADDR_NAME) - 1;
  11999. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12000. if (nameType == SUBJECT) {
  12001. cert->subjectStreet = (char*)&input[srcIdx];
  12002. cert->subjectStreetLen = strLen;
  12003. cert->subjectStreetEnc = b;
  12004. }
  12005. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12006. #if (defined(OPENSSL_EXTRA) || \
  12007. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12008. && !defined(WOLFCRYPT_ONLY)
  12009. nid = NID_streetAddress;
  12010. #endif /* OPENSSL_EXTRA */
  12011. }
  12012. else if (id == ASN_BUS_CAT) {
  12013. copy = WOLFSSL_BUS_CAT;
  12014. copyLen = sizeof(WOLFSSL_BUS_CAT) - 1;
  12015. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12016. if (nameType == SUBJECT) {
  12017. cert->subjectBC = (char*)&input[srcIdx];
  12018. cert->subjectBCLen = strLen;
  12019. cert->subjectBCEnc = b;
  12020. }
  12021. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12022. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  12023. && !defined(WOLFCRYPT_ONLY)
  12024. nid = NID_businessCategory;
  12025. #endif /* OPENSSL_EXTRA */
  12026. }
  12027. else if (id == ASN_POSTAL_CODE) {
  12028. copy = WOLFSSL_POSTAL_NAME;
  12029. copyLen = sizeof(WOLFSSL_POSTAL_NAME) - 1;
  12030. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12031. if (nameType == SUBJECT) {
  12032. cert->subjectPC = (char*)&input[srcIdx];
  12033. cert->subjectPCLen = strLen;
  12034. cert->subjectPCEnc = b;
  12035. }
  12036. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
  12037. #if (defined(OPENSSL_EXTRA) || \
  12038. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12039. && !defined(WOLFCRYPT_ONLY)
  12040. nid = NID_postalCode;
  12041. #endif /* OPENSSL_EXTRA */
  12042. }
  12043. #endif /* WOLFSSL_CERT_EXT */
  12044. }
  12045. #ifdef WOLFSSL_CERT_EXT
  12046. else if ((srcIdx + ASN_JOI_PREFIX_SZ + 2 <= (word32)maxIdx) &&
  12047. (0 == XMEMCMP(&input[srcIdx], ASN_JOI_PREFIX,
  12048. ASN_JOI_PREFIX_SZ)) &&
  12049. ((input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_C) ||
  12050. (input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_ST)))
  12051. {
  12052. srcIdx += ASN_JOI_PREFIX_SZ;
  12053. id = input[srcIdx++];
  12054. b = input[srcIdx++]; /* encoding */
  12055. if (GetLength(input, &srcIdx, &strLen,
  12056. maxIdx) < 0) {
  12057. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12058. !defined(WOLFCRYPT_ONLY)
  12059. wolfSSL_X509_NAME_free(dName);
  12060. #endif /* OPENSSL_EXTRA */
  12061. return ASN_PARSE_E;
  12062. }
  12063. /* Check for jurisdiction of incorporation country name */
  12064. if (id == ASN_JOI_C) {
  12065. copy = WOLFSSL_JOI_C;
  12066. copyLen = sizeof(WOLFSSL_JOI_C) - 1;
  12067. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12068. if (nameType == SUBJECT) {
  12069. cert->subjectJC = (char*)&input[srcIdx];
  12070. cert->subjectJCLen = strLen;
  12071. cert->subjectJCEnc = b;
  12072. }
  12073. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12074. #if (defined(OPENSSL_EXTRA) || \
  12075. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12076. && !defined(WOLFCRYPT_ONLY)
  12077. nid = NID_jurisdictionCountryName;
  12078. #endif /* OPENSSL_EXTRA */
  12079. }
  12080. /* Check for jurisdiction of incorporation state name */
  12081. else if (id == ASN_JOI_ST) {
  12082. copy = WOLFSSL_JOI_ST;
  12083. copyLen = sizeof(WOLFSSL_JOI_ST) - 1;
  12084. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12085. if (nameType == SUBJECT) {
  12086. cert->subjectJS = (char*)&input[srcIdx];
  12087. cert->subjectJSLen = strLen;
  12088. cert->subjectJSEnc = b;
  12089. }
  12090. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12091. #if (defined(OPENSSL_EXTRA) || \
  12092. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12093. && !defined(WOLFCRYPT_ONLY)
  12094. nid = NID_jurisdictionStateOrProvinceName;
  12095. #endif /* OPENSSL_EXTRA */
  12096. }
  12097. if ((strLen + copyLen) > (int)(WC_ASN_NAME_MAX - idx)) {
  12098. WOLFSSL_MSG("ASN Name too big, skipping");
  12099. tooBig = TRUE;
  12100. }
  12101. }
  12102. #endif /* WOLFSSL_CERT_EXT */
  12103. else {
  12104. /* skip */
  12105. byte email = FALSE;
  12106. byte pilot = FALSE;
  12107. if (joint[0] == 0x2a && joint[1] == 0x86) { /* email id hdr 42.134.* */
  12108. id = ASN_EMAIL_NAME;
  12109. email = TRUE;
  12110. }
  12111. if (joint[0] == 0x9 && joint[1] == 0x92) { /* uid id hdr 9.146.* */
  12112. /* last value of OID is the type of pilot attribute */
  12113. id = input[srcIdx + oidSz - 1];
  12114. if (id == 0x01)
  12115. id = ASN_USER_ID;
  12116. pilot = TRUE;
  12117. }
  12118. srcIdx += oidSz + 1;
  12119. if (GetLength(input, &srcIdx, &strLen, maxIdx) < 0) {
  12120. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12121. !defined(WOLFCRYPT_ONLY)
  12122. wolfSSL_X509_NAME_free(dName);
  12123. #endif /* OPENSSL_EXTRA */
  12124. return ASN_PARSE_E;
  12125. }
  12126. if (strLen > (int)(WC_ASN_NAME_MAX - idx)) {
  12127. WOLFSSL_MSG("ASN name too big, skipping");
  12128. tooBig = TRUE;
  12129. }
  12130. if (email) {
  12131. copyLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  12132. if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx)) {
  12133. WOLFSSL_MSG("ASN name too big, skipping");
  12134. tooBig = TRUE;
  12135. }
  12136. else {
  12137. copy = WOLFSSL_EMAIL_ADDR;
  12138. }
  12139. #if !defined(IGNORE_NAME_CONSTRAINTS) || \
  12140. defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12141. if (nameType == SUBJECT) {
  12142. cert->subjectEmail = (char*)&input[srcIdx];
  12143. cert->subjectEmailLen = strLen;
  12144. }
  12145. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12146. else if (nameType == ISSUER) {
  12147. cert->issuerEmail = (char*)&input[srcIdx];
  12148. cert->issuerEmailLen = strLen;
  12149. }
  12150. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12151. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12152. #if (defined(OPENSSL_EXTRA) || \
  12153. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12154. && !defined(WOLFCRYPT_ONLY)
  12155. nid = NID_emailAddress;
  12156. #endif /* OPENSSL_EXTRA */
  12157. }
  12158. if (pilot) {
  12159. switch (id) {
  12160. case ASN_USER_ID:
  12161. copy = WOLFSSL_USER_ID;
  12162. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  12163. #if (defined(OPENSSL_EXTRA) || \
  12164. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12165. && !defined(WOLFCRYPT_ONLY)
  12166. nid = NID_userId;
  12167. #endif /* OPENSSL_EXTRA */
  12168. break;
  12169. case ASN_DOMAIN_COMPONENT:
  12170. copy = WOLFSSL_DOMAIN_COMPONENT;
  12171. copyLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  12172. #if (defined(OPENSSL_EXTRA) || \
  12173. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12174. && !defined(WOLFCRYPT_ONLY)
  12175. nid = NID_domainComponent;
  12176. #endif /* OPENSSL_EXTRA */
  12177. break;
  12178. case ASN_FAVOURITE_DRINK:
  12179. copy = WOLFSSL_FAVOURITE_DRINK;
  12180. copyLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
  12181. #if (defined(OPENSSL_EXTRA) || \
  12182. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12183. && !defined(WOLFCRYPT_ONLY)
  12184. nid = NID_favouriteDrink;
  12185. #endif /* OPENSSL_EXTRA */
  12186. break;
  12187. default:
  12188. WOLFSSL_MSG("Unknown pilot attribute type");
  12189. #if (defined(OPENSSL_EXTRA) || \
  12190. defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12191. !defined(WOLFCRYPT_ONLY)
  12192. wolfSSL_X509_NAME_free(dName);
  12193. #endif /* OPENSSL_EXTRA */
  12194. return ASN_PARSE_E;
  12195. }
  12196. }
  12197. }
  12198. if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx))
  12199. {
  12200. WOLFSSL_MSG("ASN Name too big, skipping");
  12201. tooBig = TRUE;
  12202. }
  12203. if ((copy != NULL) && !tooBig) {
  12204. XMEMCPY(&full[idx], copy, copyLen);
  12205. idx += copyLen;
  12206. XMEMCPY(&full[idx], &input[srcIdx], strLen);
  12207. idx += strLen;
  12208. }
  12209. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12210. !defined(WOLFCRYPT_ONLY)
  12211. switch (b) {
  12212. case CTC_UTF8:
  12213. enc = MBSTRING_UTF8;
  12214. break;
  12215. case CTC_PRINTABLE:
  12216. enc = V_ASN1_PRINTABLESTRING;
  12217. break;
  12218. default:
  12219. WOLFSSL_MSG("Unknown encoding type, using UTF8 by default");
  12220. enc = MBSTRING_UTF8;
  12221. }
  12222. if (nid != NID_undef) {
  12223. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc,
  12224. &input[srcIdx], strLen, -1, -1) !=
  12225. WOLFSSL_SUCCESS) {
  12226. wolfSSL_X509_NAME_free(dName);
  12227. return ASN_PARSE_E;
  12228. }
  12229. }
  12230. #endif /* OPENSSL_EXTRA */
  12231. srcIdx += strLen;
  12232. }
  12233. full[idx++] = 0;
  12234. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12235. !defined(WOLFCRYPT_ONLY)
  12236. if (nameType == ISSUER) {
  12237. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)) && \
  12238. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  12239. dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX);
  12240. XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
  12241. #endif
  12242. cert->issuerName = dName;
  12243. }
  12244. else {
  12245. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  12246. dName->rawLen = min(cert->subjectRawLen, WC_ASN_NAME_MAX);
  12247. XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
  12248. #endif
  12249. cert->subjectName = dName;
  12250. }
  12251. #endif
  12252. *inOutIdx = srcIdx;
  12253. return 0;
  12254. #else
  12255. DECL_ASNGETDATA(dataASN, rdnASN_Length);
  12256. int ret = 0;
  12257. word32 idx = 0;
  12258. int len;
  12259. word32 srcIdx = *inOutIdx;
  12260. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12261. WOLFSSL_X509_NAME* dName = NULL;
  12262. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12263. WOLFSSL_MSG("Getting Cert Name");
  12264. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  12265. * calculated over the entire DER encoding of the Name field, including
  12266. * the tag and length. */
  12267. if (CalcHashId(input + srcIdx, maxIdx - srcIdx, hash) != 0) {
  12268. ret = ASN_PARSE_E;
  12269. }
  12270. CALLOC_ASNGETDATA(dataASN, rdnASN_Length, ret, cert->heap);
  12271. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12272. if (ret == 0) {
  12273. /* Create an X509_NAME to hold data for OpenSSL compatability APIs. */
  12274. dName = wolfSSL_X509_NAME_new();
  12275. if (dName == NULL) {
  12276. ret = MEMORY_E;
  12277. }
  12278. }
  12279. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12280. if (ret == 0) {
  12281. /* Expecting a SEQUENCE using up all data. */
  12282. ret = GetASN_Sequence(input, &srcIdx, &len, maxIdx, 1);
  12283. }
  12284. if (ret == 0) {
  12285. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  12286. /* Store pointer and length to raw issuer. */
  12287. if (nameType == ISSUER) {
  12288. cert->issuerRaw = &input[srcIdx];
  12289. cert->issuerRawLen = len;
  12290. }
  12291. #endif
  12292. #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
  12293. /* Store pointer and length to raw subject. */
  12294. if (nameType == SUBJECT) {
  12295. cert->subjectRaw = &input[srcIdx];
  12296. cert->subjectRawLen = len;
  12297. }
  12298. #endif
  12299. /* Process all RDNs in name. */
  12300. while ((ret == 0) && (srcIdx < maxIdx)) {
  12301. int nid = 0;
  12302. /* Initialize for data and setup RDN choice. */
  12303. GetASN_Choice(&dataASN[RDNASN_IDX_ATTR_VAL], rdnChoice);
  12304. /* Ignore type OID as too many to store in table. */
  12305. GetASN_OID(&dataASN[RDNASN_IDX_ATTR_TYPE], oidIgnoreType);
  12306. /* Parse RDN. */
  12307. ret = GetASN_Items(rdnASN, dataASN, rdnASN_Length, 1, input,
  12308. &srcIdx, maxIdx);
  12309. if (ret == 0) {
  12310. /* Put RDN data into certificate. */
  12311. ret = GetRDN(cert, full, &idx, &nid, nameType == SUBJECT,
  12312. dataASN);
  12313. }
  12314. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12315. /* TODO: push this back up to ssl.c
  12316. * (do parsing for WOLFSSL_X509_NAME on demand) */
  12317. if (ret == 0) {
  12318. int enc;
  12319. byte* str;
  12320. word32 strLen;
  12321. byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
  12322. /* Get string reference. */
  12323. GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
  12324. /* Convert BER tag to a OpenSSL type. */
  12325. switch (tag) {
  12326. case CTC_UTF8:
  12327. enc = MBSTRING_UTF8;
  12328. break;
  12329. case CTC_PRINTABLE:
  12330. enc = V_ASN1_PRINTABLESTRING;
  12331. break;
  12332. default:
  12333. WOLFSSL_MSG("Unknown encoding type, default UTF8");
  12334. enc = MBSTRING_UTF8;
  12335. }
  12336. if (nid != 0) {
  12337. /* Add an entry to the X509_NAME. */
  12338. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc, str,
  12339. strLen, -1, -1) != WOLFSSL_SUCCESS) {
  12340. ret = ASN_PARSE_E;
  12341. }
  12342. }
  12343. }
  12344. #endif
  12345. }
  12346. }
  12347. if (ret == 0) {
  12348. /* Terminate string. */
  12349. full[idx] = 0;
  12350. /* Return index into encoding after name. */
  12351. *inOutIdx = srcIdx;
  12352. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12353. /* Store X509_NAME in certificate. */
  12354. if (nameType == ISSUER) {
  12355. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  12356. defined(HAVE_LIGHTY)) && \
  12357. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  12358. dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX);
  12359. XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
  12360. #endif
  12361. cert->issuerName = dName;
  12362. }
  12363. else {
  12364. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  12365. dName->rawLen = min(cert->subjectRawLen, WC_ASN_NAME_MAX);
  12366. XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
  12367. #endif
  12368. cert->subjectName = dName;
  12369. }
  12370. }
  12371. else {
  12372. /* Dispose of unused X509_NAME. */
  12373. wolfSSL_X509_NAME_free(dName);
  12374. #endif
  12375. }
  12376. FREE_ASNGETDATA(dataASN, cert->heap);
  12377. return ret;
  12378. #endif /* WOLFSSL_ASN_TEMPLATE */
  12379. }
  12380. #ifdef WOLFSSL_ASN_TEMPLATE
  12381. /* ASN.1 template for certificate name. */
  12382. static const ASNItem certNameASN[] = {
  12383. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  12384. /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  12385. };
  12386. enum {
  12387. CERTNAMEASN_IDX_OID = 0,
  12388. CERTNAMEASN_IDX_NAME,
  12389. };
  12390. /* Number of items in ASN.1 template for certificate name. */
  12391. #define certNameASN_Length (sizeof(certNameASN) / sizeof(ASNItem))
  12392. #endif
  12393. /* Get a certificate name into the certificate object.
  12394. *
  12395. * Either the issuer or subject name.
  12396. *
  12397. * @param [in, out] cert Decoded certificate object.
  12398. * @param [in] nameType Type of name being decoded: ISSUER or SUBJECT.
  12399. * @param [in] maxIdx Index of next item after certificate name.
  12400. * @return 0 on success.
  12401. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12402. * is invalid.
  12403. * @return BUFFER_E when data in buffer is too small.
  12404. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  12405. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  12406. * @return MEMORY_E when dynamic memory allocation fails.
  12407. */
  12408. int GetName(DecodedCert* cert, int nameType, int maxIdx)
  12409. {
  12410. #ifndef WOLFSSL_ASN_TEMPLATE
  12411. char* full;
  12412. byte* hash;
  12413. int length;
  12414. word32 localIdx;
  12415. byte tag;
  12416. WOLFSSL_MSG("Getting Name");
  12417. if (nameType == ISSUER) {
  12418. full = cert->issuer;
  12419. hash = cert->issuerHash;
  12420. }
  12421. else {
  12422. full = cert->subject;
  12423. hash = cert->subjectHash;
  12424. }
  12425. if (cert->srcIdx >= (word32)maxIdx) {
  12426. return BUFFER_E;
  12427. }
  12428. localIdx = cert->srcIdx;
  12429. if (GetASNTag(cert->source, &localIdx, &tag, maxIdx) < 0) {
  12430. return ASN_PARSE_E;
  12431. }
  12432. if (tag == ASN_OBJECT_ID) {
  12433. WOLFSSL_MSG("Trying optional prefix...");
  12434. if (SkipObjectId(cert->source, &cert->srcIdx, maxIdx) < 0)
  12435. return ASN_PARSE_E;
  12436. WOLFSSL_MSG("Got optional prefix");
  12437. }
  12438. localIdx = cert->srcIdx;
  12439. if (GetASNTag(cert->source, &localIdx, &tag, maxIdx) < 0) {
  12440. return ASN_PARSE_E;
  12441. }
  12442. localIdx = cert->srcIdx + 1;
  12443. if (GetLength(cert->source, &localIdx, &length, maxIdx) < 0) {
  12444. return ASN_PARSE_E;
  12445. }
  12446. length += localIdx - cert->srcIdx;
  12447. return GetCertName(cert, full, hash, nameType, cert->source, &cert->srcIdx,
  12448. cert->srcIdx + length);
  12449. #else
  12450. ASNGetData dataASN[certNameASN_Length];
  12451. word32 idx = cert->srcIdx;
  12452. int ret = 0;
  12453. char* full;
  12454. byte* hash;
  12455. WOLFSSL_MSG("Getting Name");
  12456. XMEMSET(dataASN, 0, sizeof(dataASN));
  12457. /* Initialize for data and don't check optional prefix OID. */
  12458. GetASN_OID(&dataASN[CERTNAMEASN_IDX_OID], oidIgnoreType);
  12459. ret = GetASN_Items(certNameASN, dataASN, certNameASN_Length, 0,
  12460. cert->source, &idx, maxIdx);
  12461. if (ret == 0) {
  12462. /* Store offset of SEQUENCE that is start of name. */
  12463. cert->srcIdx = dataASN[CERTNAMEASN_IDX_NAME].offset;
  12464. /* Get fields to fill in based on name type. */
  12465. if (nameType == ISSUER) {
  12466. full = cert->issuer;
  12467. hash = cert->issuerHash;
  12468. }
  12469. else {
  12470. full = cert->subject;
  12471. hash = cert->subjectHash;
  12472. }
  12473. /* Parse certificate name. */
  12474. ret = GetCertName(cert, full, hash, nameType, cert->source,
  12475. &cert->srcIdx, idx);
  12476. }
  12477. return ret;
  12478. #endif
  12479. }
  12480. #ifndef NO_ASN_TIME
  12481. /* two byte date/time, add to value */
  12482. static WC_INLINE int GetTime(int* value, const byte* date, int* idx)
  12483. {
  12484. int i = *idx;
  12485. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  12486. date[i+1] > 0x39) {
  12487. return ASN_PARSE_E;
  12488. }
  12489. *value += btoi(date[i++]) * 10;
  12490. *value += btoi(date[i++]);
  12491. *idx = i;
  12492. return 0;
  12493. }
  12494. #ifdef WOLFSSL_LINUXKM
  12495. static WC_INLINE int GetTime_Long(long* value, const byte* date, int* idx)
  12496. {
  12497. int i = *idx;
  12498. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  12499. date[i+1] > 0x39) {
  12500. return ASN_PARSE_E;
  12501. }
  12502. *value += (long)btoi(date[i++]) * 10;
  12503. *value += (long)btoi(date[i++]);
  12504. *idx = i;
  12505. return 0;
  12506. }
  12507. #endif
  12508. int ExtractDate(const unsigned char* date, unsigned char format,
  12509. struct tm* certTime, int* idx)
  12510. {
  12511. XMEMSET(certTime, 0, sizeof(struct tm));
  12512. if (format == ASN_UTC_TIME) {
  12513. if (btoi(date[*idx]) >= 5)
  12514. certTime->tm_year = 1900;
  12515. else
  12516. certTime->tm_year = 2000;
  12517. }
  12518. else { /* format == GENERALIZED_TIME */
  12519. #ifdef WOLFSSL_LINUXKM
  12520. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  12521. #else
  12522. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  12523. #endif
  12524. certTime->tm_year *= 100;
  12525. }
  12526. #ifdef AVR
  12527. /* Extract the time from the struct tm and adjust tm_year, tm_mon */
  12528. /* AVR libc stores these as uint8_t instead of int */
  12529. /* AVR time_t also offsets from midnight 1 Jan 2000 */
  12530. int tm_year = certTime->tm_year - 2000;
  12531. int tm_mon = certTime->tm_mon - 1;
  12532. int tm_mday = certTime->tm_mday;
  12533. int tm_hour = certTime->tm_hour;
  12534. int tm_min = certTime->tm_min;
  12535. int tm_sec = certTime->tm_sec;
  12536. #ifdef WOLFSSL_LINUXKM
  12537. if (GetTime_Long(&tm_year, date, idx) != 0) return 0;
  12538. #else
  12539. if (GetTime(&tm_year, date, idx) != 0) return 0;
  12540. #endif
  12541. if (GetTime(&tm_mon , date, idx) != 0) return 0;
  12542. if (GetTime(&tm_mday, date, idx) != 0) return 0;
  12543. if (GetTime(&tm_hour, date, idx) != 0) return 0;
  12544. if (GetTime(&tm_min , date, idx) != 0) return 0;
  12545. if (GetTime(&tm_sec , date, idx) != 0) return 0;
  12546. /* Re-populate certTime with computed values */
  12547. certTime->tm_year = tm_year;
  12548. certTime->tm_mon = tm_mon;
  12549. certTime->tm_mday = tm_mday;
  12550. certTime->tm_hour = tm_hour;
  12551. certTime->tm_min = tm_min;
  12552. certTime->tm_sec = tm_sec;
  12553. #else
  12554. /* adjust tm_year, tm_mon */
  12555. #ifdef WOLFSSL_LINUXKM
  12556. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  12557. #else
  12558. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  12559. #endif
  12560. certTime->tm_year -= 1900;
  12561. if (GetTime(&certTime->tm_mon , date, idx) != 0) return 0;
  12562. certTime->tm_mon -= 1;
  12563. if (GetTime(&certTime->tm_mday, date, idx) != 0) return 0;
  12564. if (GetTime(&certTime->tm_hour, date, idx) != 0) return 0;
  12565. if (GetTime(&certTime->tm_min , date, idx) != 0) return 0;
  12566. if (GetTime(&certTime->tm_sec , date, idx) != 0) return 0;
  12567. #endif
  12568. return 1;
  12569. }
  12570. #if defined(OPENSSL_ALL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
  12571. defined(OPENSSL_EXTRA) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  12572. int GetTimeString(byte* date, int format, char* buf, int len)
  12573. {
  12574. struct tm t;
  12575. int idx = 0;
  12576. if (!ExtractDate(date, (unsigned char)format, &t, &idx)) {
  12577. return 0;
  12578. }
  12579. if (date[idx] != 'Z') {
  12580. WOLFSSL_MSG("UTCtime, not Zulu") ;
  12581. return 0;
  12582. }
  12583. /* place month in buffer */
  12584. buf[0] = '\0';
  12585. switch(t.tm_mon) {
  12586. case 0: XSTRNCAT(buf, "Jan ", 5); break;
  12587. case 1: XSTRNCAT(buf, "Feb ", 5); break;
  12588. case 2: XSTRNCAT(buf, "Mar ", 5); break;
  12589. case 3: XSTRNCAT(buf, "Apr ", 5); break;
  12590. case 4: XSTRNCAT(buf, "May ", 5); break;
  12591. case 5: XSTRNCAT(buf, "Jun ", 5); break;
  12592. case 6: XSTRNCAT(buf, "Jul ", 5); break;
  12593. case 7: XSTRNCAT(buf, "Aug ", 5); break;
  12594. case 8: XSTRNCAT(buf, "Sep ", 5); break;
  12595. case 9: XSTRNCAT(buf, "Oct ", 5); break;
  12596. case 10: XSTRNCAT(buf, "Nov ", 5); break;
  12597. case 11: XSTRNCAT(buf, "Dec ", 5); break;
  12598. default:
  12599. return 0;
  12600. }
  12601. idx = 4; /* use idx now for char buffer */
  12602. if (XSNPRINTF(buf + idx, len - idx, "%2d %02d:%02d:%02d %d GMT",
  12603. t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, (int)t.tm_year + 1900)
  12604. >= len - idx)
  12605. {
  12606. WOLFSSL_MSG("buffer overrun in GetTimeString");
  12607. return 0;
  12608. }
  12609. return 1;
  12610. }
  12611. #endif /* OPENSSL_ALL || WOLFSSL_MYSQL_COMPATIBLE || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
  12612. #if !defined(NO_ASN_TIME) && !defined(USER_TIME) && \
  12613. !defined(TIME_OVERRIDES) && (defined(OPENSSL_EXTRA) || defined(HAVE_PKCS7))
  12614. /* Set current time string, either UTC or GeneralizedTime.
  12615. * (void*) tm should be a pointer to time_t, output is placed in buf.
  12616. *
  12617. * Return time string length placed in buf on success, negative on error */
  12618. int GetAsnTimeString(void* currTime, byte* buf, word32 len)
  12619. {
  12620. byte* data_ptr = buf;
  12621. byte uf_time[ASN_GENERALIZED_TIME_SIZE];
  12622. word32 data_len = 0;
  12623. WOLFSSL_ENTER("GetAsnTimeString");
  12624. if (buf == NULL || len == 0)
  12625. return BAD_FUNC_ARG;
  12626. XMEMSET(uf_time, 0, sizeof(uf_time));
  12627. /* GetFormattedTime returns length with null terminator */
  12628. data_len = GetFormattedTime(currTime, uf_time, len);
  12629. if (data_len <= 0) {
  12630. return ASN_TIME_E;
  12631. }
  12632. /* ensure room to add 2 bytes (ASN type and length) before proceeding */
  12633. else if (len < data_len + 2) {
  12634. return BUFFER_E;
  12635. }
  12636. if (data_len == ASN_UTC_TIME_SIZE-1) {
  12637. /* increment data_len for ASN length byte after adding the data_ptr */
  12638. *data_ptr = (byte)ASN_UTC_TIME; data_ptr++; data_len++;
  12639. /* -1 below excludes null terminator */
  12640. *data_ptr = (byte)ASN_UTC_TIME_SIZE - 1; data_ptr++; data_len++;
  12641. XMEMCPY(data_ptr, (byte *)uf_time, ASN_UTC_TIME_SIZE - 1);
  12642. *data_ptr += ASN_UTC_TIME_SIZE - 1;
  12643. }
  12644. else if (data_len == ASN_GENERALIZED_TIME_SIZE-1) {
  12645. /* increment data_len for ASN length byte after adding the data_ptr */
  12646. *data_ptr = (byte)ASN_GENERALIZED_TIME; data_ptr++; data_len++;
  12647. /* -1 below excludes null terminator */
  12648. *data_ptr = (byte)ASN_GENERALIZED_TIME_SIZE - 1; data_ptr++; data_len++;
  12649. XMEMCPY(data_ptr, (byte*)uf_time, ASN_GENERALIZED_TIME_SIZE - 1);
  12650. *data_ptr += ASN_GENERALIZED_TIME_SIZE - 1;
  12651. }
  12652. else {
  12653. WOLFSSL_MSG("Invalid time size returned");
  12654. return ASN_TIME_E;
  12655. }
  12656. /* append null terminator */
  12657. *data_ptr = 0;
  12658. /* return length without null terminator */
  12659. return data_len;
  12660. }
  12661. /* return just the time string as either UTC or Generalized Time*/
  12662. int GetFormattedTime(void* currTime, byte* buf, word32 len)
  12663. {
  12664. struct tm* ts = NULL;
  12665. struct tm* tmpTime = NULL;
  12666. int year, mon, day, hour, mini, sec;
  12667. int ret;
  12668. #if defined(NEED_TMP_TIME)
  12669. struct tm tmpTimeStorage;
  12670. tmpTime = &tmpTimeStorage;
  12671. #else
  12672. (void)tmpTime;
  12673. #endif
  12674. WOLFSSL_ENTER("GetFormattedTime");
  12675. if (buf == NULL || len == 0)
  12676. return BAD_FUNC_ARG;
  12677. ts = (struct tm *)XGMTIME((time_t*)currTime, tmpTime);
  12678. if (ts == NULL) {
  12679. WOLFSSL_MSG("failed to get time data.");
  12680. return ASN_TIME_E;
  12681. }
  12682. /* Note ASN_UTC_TIME_SIZE and ASN_GENERALIZED_TIME_SIZE include space for
  12683. * the null terminator. ASN encoded values leave off the terminator. */
  12684. if (ts->tm_year >= 50 && ts->tm_year < 150) {
  12685. /* UTC Time */
  12686. if (ts->tm_year >= 50 && ts->tm_year < 100) {
  12687. year = ts->tm_year;
  12688. }
  12689. else if (ts->tm_year >= 100 && ts->tm_year < 150) {
  12690. year = ts->tm_year - 100;
  12691. }
  12692. else {
  12693. WOLFSSL_MSG("unsupported year range");
  12694. return BAD_FUNC_ARG;
  12695. }
  12696. mon = ts->tm_mon + 1;
  12697. day = ts->tm_mday;
  12698. hour = ts->tm_hour;
  12699. mini = ts->tm_min;
  12700. sec = ts->tm_sec;
  12701. #if defined(WOLF_C89)
  12702. if (len < 14) {
  12703. WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
  12704. return BUFFER_E;
  12705. }
  12706. ret = XSPRINTF((char*)buf,
  12707. #else
  12708. ret = XSNPRINTF((char*)buf, len,
  12709. #endif
  12710. "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
  12711. hour, mini, sec);
  12712. }
  12713. else {
  12714. /* GeneralizedTime */
  12715. year = ts->tm_year + 1900;
  12716. mon = ts->tm_mon + 1;
  12717. day = ts->tm_mday;
  12718. hour = ts->tm_hour;
  12719. mini = ts->tm_min;
  12720. sec = ts->tm_sec;
  12721. #if defined(WOLF_C89)
  12722. if (len < 16) {
  12723. WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
  12724. return BUFFER_E;
  12725. }
  12726. ret = XSPRINTF((char*)buf,
  12727. #else
  12728. ret = XSNPRINTF((char*)buf, len,
  12729. #endif
  12730. "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
  12731. hour, mini, sec);
  12732. }
  12733. return ret;
  12734. }
  12735. #endif /* !NO_ASN_TIME && !USER_TIME && !TIME_OVERRIDES &&
  12736. * (OPENSSL_EXTRA || HAVE_PKCS7) */
  12737. #if defined(USE_WOLF_VALIDDATE)
  12738. /* to the second */
  12739. int DateGreaterThan(const struct tm* a, const struct tm* b)
  12740. {
  12741. if (a->tm_year > b->tm_year)
  12742. return 1;
  12743. if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
  12744. return 1;
  12745. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  12746. a->tm_mday > b->tm_mday)
  12747. return 1;
  12748. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  12749. a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
  12750. return 1;
  12751. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  12752. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  12753. a->tm_min > b->tm_min)
  12754. return 1;
  12755. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  12756. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  12757. a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
  12758. return 1;
  12759. return 0; /* false */
  12760. }
  12761. static WC_INLINE int DateLessThan(const struct tm* a, const struct tm* b)
  12762. {
  12763. return DateGreaterThan(b,a);
  12764. }
  12765. /* like atoi but only use first byte */
  12766. /* Make sure before and after dates are valid */
  12767. int wc_ValidateDate(const byte* date, byte format, int dateType)
  12768. {
  12769. time_t ltime;
  12770. struct tm certTime;
  12771. struct tm* localTime;
  12772. struct tm* tmpTime;
  12773. int i = 0;
  12774. int timeDiff = 0;
  12775. int diffHH = 0, diffMM = 0;
  12776. int diffSign = 0;
  12777. #if defined(NEED_TMP_TIME)
  12778. struct tm tmpTimeStorage;
  12779. tmpTime = &tmpTimeStorage;
  12780. #else
  12781. tmpTime = NULL;
  12782. #endif
  12783. (void)tmpTime;
  12784. ltime = wc_Time(0);
  12785. if (ltime < 0){
  12786. /* A negative response here could be due to a 32-bit time_t
  12787. * where the year is 2038 or later. */
  12788. WOLFSSL_MSG("wc_Time failed to return a valid value");
  12789. return 0;
  12790. }
  12791. #ifdef WOLFSSL_BEFORE_DATE_CLOCK_SKEW
  12792. if (dateType == BEFORE) {
  12793. WOLFSSL_MSG("Skewing local time for before date check");
  12794. ltime += WOLFSSL_BEFORE_DATE_CLOCK_SKEW;
  12795. }
  12796. #endif
  12797. #ifdef WOLFSSL_AFTER_DATE_CLOCK_SKEW
  12798. if (dateType == AFTER) {
  12799. WOLFSSL_MSG("Skewing local time for after date check");
  12800. ltime -= WOLFSSL_AFTER_DATE_CLOCK_SKEW;
  12801. }
  12802. #endif
  12803. if (!ExtractDate(date, format, &certTime, &i)) {
  12804. WOLFSSL_MSG("Error extracting the date");
  12805. return 0;
  12806. }
  12807. if ((date[i] == '+') || (date[i] == '-')) {
  12808. WOLFSSL_MSG("Using time differential, not Zulu") ;
  12809. diffSign = date[i++] == '+' ? 1 : -1 ;
  12810. if (GetTime(&diffHH, date, &i) != 0)
  12811. return 0;
  12812. if (GetTime(&diffMM, date, &i) != 0)
  12813. return 0;
  12814. timeDiff = diffSign * (diffHH*60 + diffMM) * 60 ;
  12815. } else if (date[i] != 'Z') {
  12816. WOLFSSL_MSG("UTCtime, neither Zulu or time differential") ;
  12817. return 0;
  12818. }
  12819. ltime -= (time_t)timeDiff ;
  12820. localTime = XGMTIME(&ltime, tmpTime);
  12821. if (localTime == NULL) {
  12822. WOLFSSL_MSG("XGMTIME failed");
  12823. return 0;
  12824. }
  12825. if (dateType == BEFORE) {
  12826. if (DateLessThan(localTime, &certTime)) {
  12827. WOLFSSL_MSG("Date BEFORE check failed");
  12828. return 0;
  12829. }
  12830. }
  12831. else { /* dateType == AFTER */
  12832. if (DateGreaterThan(localTime, &certTime)) {
  12833. WOLFSSL_MSG("Date AFTER check failed");
  12834. return 0;
  12835. }
  12836. }
  12837. return 1;
  12838. }
  12839. #endif /* USE_WOLF_VALIDDATE */
  12840. int wc_GetTime(void* timePtr, word32 timeSize)
  12841. {
  12842. time_t* ltime = (time_t*)timePtr;
  12843. if (timePtr == NULL) {
  12844. return BAD_FUNC_ARG;
  12845. }
  12846. if ((word32)sizeof(time_t) > timeSize) {
  12847. return BUFFER_E;
  12848. }
  12849. *ltime = wc_Time(0);
  12850. return 0;
  12851. }
  12852. #ifdef TIME_OVERRIDES
  12853. #ifndef HAVE_TIME_T_TYPE
  12854. typedef long time_t;
  12855. #endif
  12856. extern time_t XTIME(time_t* t);
  12857. #endif
  12858. static wc_time_cb timeFunc = NULL;
  12859. int wc_SetTimeCb(wc_time_cb f)
  12860. {
  12861. timeFunc = f;
  12862. return 0;
  12863. }
  12864. time_t wc_Time(time_t* t)
  12865. {
  12866. if (timeFunc != NULL) {
  12867. return timeFunc(t);
  12868. }
  12869. return XTIME(t);
  12870. }
  12871. #endif /* !NO_ASN_TIME */
  12872. #ifdef WOLFSSL_ASN_TEMPLATE
  12873. /* TODO: use a CHOICE instead of two items? */
  12874. /* ASN.1 template for a date - either UTC or Generalized Time. */
  12875. static const ASNItem dateASN[] = {
  12876. /* UTC */ { 0, ASN_UTC_TIME, 0, 0, 2 },
  12877. /* GT */ { 0, ASN_GENERALIZED_TIME, 0, 0, 2 },
  12878. };
  12879. enum {
  12880. DATEASN_IDX_UTC = 0,
  12881. DATEASN_IDX_GT,
  12882. };
  12883. /* Number of items in ASN.1 template for a date. */
  12884. #define dateASN_Length (sizeof(dateASN) / sizeof(ASNItem))
  12885. #endif /* WOLFSSL_ASN_TEMPLATE */
  12886. /* Get date buffer, format and length. Returns 0=success or error */
  12887. /* Decode a DateInfo - choice of UTC TIME or GENERALIZED TIME.
  12888. *
  12889. * @param [in] source Buffer containing encoded date.
  12890. * @param [in, out] idx On in, the index of the date.
  12891. * On out, index after date.
  12892. * @param [out] pDate Pointer into buffer of data bytes.
  12893. * @param [out] pFormat Format of date - BER/DER tag.
  12894. * @param [out] pLength Length of date bytes.
  12895. * @param [in] maxIdx Index of next item after date.
  12896. * @return 0 on success.
  12897. * @return BAD_FUNC_ARG when source or idx is NULL.
  12898. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12899. * is invalid.
  12900. * @return BUFFER_E when data in buffer is too small.
  12901. */
  12902. static int GetDateInfo(const byte* source, word32* idx, const byte** pDate,
  12903. byte* pFormat, int* pLength, word32 maxIdx)
  12904. {
  12905. #ifndef WOLFSSL_ASN_TEMPLATE
  12906. int length;
  12907. byte format;
  12908. if (source == NULL || idx == NULL)
  12909. return BAD_FUNC_ARG;
  12910. /* get ASN format header */
  12911. if (*idx+1 > maxIdx)
  12912. return BUFFER_E;
  12913. format = source[*idx];
  12914. *idx += 1;
  12915. if (format != ASN_UTC_TIME && format != ASN_GENERALIZED_TIME) {
  12916. WOLFSSL_ERROR_VERBOSE(ASN_TIME_E);
  12917. return ASN_TIME_E;
  12918. }
  12919. /* get length */
  12920. if (GetLength(source, idx, &length, maxIdx) < 0)
  12921. return ASN_PARSE_E;
  12922. if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
  12923. return ASN_DATE_SZ_E;
  12924. /* return format, date and length */
  12925. if (pFormat)
  12926. *pFormat = format;
  12927. if (pDate)
  12928. *pDate = &source[*idx];
  12929. if (pLength)
  12930. *pLength = length;
  12931. *idx += length;
  12932. return 0;
  12933. #else
  12934. ASNGetData dataASN[dateASN_Length];
  12935. int i;
  12936. int ret = 0;
  12937. if ((source == NULL) || (idx == NULL)) {
  12938. ret = BAD_FUNC_ARG;
  12939. }
  12940. if (ret == 0) {
  12941. /* Initialize data. */
  12942. XMEMSET(dataASN, 0, sizeof(dataASN));
  12943. /* Parse date. */
  12944. ret = GetASN_Items(dateASN, dataASN, dateASN_Length, 0, source, idx,
  12945. maxIdx);
  12946. }
  12947. if (ret == 0) {
  12948. /* Determine which tag was seen. */
  12949. i = (dataASN[DATEASN_IDX_UTC].tag != 0) ? DATEASN_IDX_UTC
  12950. : DATEASN_IDX_GT;
  12951. /* Return data from seen item. */
  12952. if (pFormat != NULL) {
  12953. *pFormat = dataASN[i].tag;
  12954. }
  12955. if (pDate != NULL) {
  12956. *pDate = dataASN[i].data.ref.data;
  12957. }
  12958. if (pLength != NULL) {
  12959. *pLength = dataASN[i].data.ref.length;
  12960. }
  12961. }
  12962. return ret;
  12963. #endif
  12964. }
  12965. #ifndef WOLFSSL_ASN_TEMPLATE
  12966. static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx)
  12967. {
  12968. int ret, length;
  12969. const byte *datePtr = NULL;
  12970. byte date[MAX_DATE_SIZE];
  12971. byte format;
  12972. word32 startIdx = 0;
  12973. if (dateType == BEFORE)
  12974. cert->beforeDate = &cert->source[cert->srcIdx];
  12975. else
  12976. cert->afterDate = &cert->source[cert->srcIdx];
  12977. startIdx = cert->srcIdx;
  12978. ret = GetDateInfo(cert->source, &cert->srcIdx, &datePtr, &format,
  12979. &length, maxIdx);
  12980. if (ret < 0)
  12981. return ret;
  12982. XMEMSET(date, 0, MAX_DATE_SIZE);
  12983. XMEMCPY(date, datePtr, length);
  12984. if (dateType == BEFORE)
  12985. cert->beforeDateLen = cert->srcIdx - startIdx;
  12986. else
  12987. cert->afterDateLen = cert->srcIdx - startIdx;
  12988. #ifndef NO_ASN_TIME
  12989. if (verify != NO_VERIFY && verify != VERIFY_SKIP_DATE &&
  12990. !XVALIDATE_DATE(date, format, dateType)) {
  12991. if (dateType == BEFORE) {
  12992. WOLFSSL_ERROR_VERBOSE(ASN_BEFORE_DATE_E);
  12993. return ASN_BEFORE_DATE_E;
  12994. }
  12995. else {
  12996. WOLFSSL_ERROR_VERBOSE(ASN_AFTER_DATE_E);
  12997. return ASN_AFTER_DATE_E;
  12998. }
  12999. }
  13000. #else
  13001. (void)verify;
  13002. #endif
  13003. return 0;
  13004. }
  13005. static int GetValidity(DecodedCert* cert, int verify, int maxIdx)
  13006. {
  13007. int length;
  13008. int badDate = 0;
  13009. if (GetSequence(cert->source, &cert->srcIdx, &length, maxIdx) < 0)
  13010. return ASN_PARSE_E;
  13011. maxIdx = cert->srcIdx + length;
  13012. if (GetDate(cert, BEFORE, verify, maxIdx) < 0)
  13013. badDate = ASN_BEFORE_DATE_E; /* continue parsing */
  13014. if (GetDate(cert, AFTER, verify, maxIdx) < 0)
  13015. return ASN_AFTER_DATE_E;
  13016. if (badDate != 0)
  13017. return badDate;
  13018. return 0;
  13019. }
  13020. #endif /* !WOLFSSL_ASN_TEMPLATE */
  13021. int wc_GetDateInfo(const byte* certDate, int certDateSz, const byte** date,
  13022. byte* format, int* length)
  13023. {
  13024. int ret;
  13025. word32 idx = 0;
  13026. ret = GetDateInfo(certDate, &idx, date, format, length, certDateSz);
  13027. return ret;
  13028. }
  13029. #ifndef NO_ASN_TIME
  13030. int wc_GetDateAsCalendarTime(const byte* date, int length, byte format,
  13031. struct tm* timearg)
  13032. {
  13033. int idx = 0;
  13034. (void)length;
  13035. if (!ExtractDate(date, format, timearg, &idx))
  13036. return ASN_TIME_E;
  13037. return 0;
  13038. }
  13039. #if defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_ALT_NAMES)
  13040. int wc_GetCertDates(Cert* cert, struct tm* before, struct tm* after)
  13041. {
  13042. int ret = 0;
  13043. const byte* date;
  13044. byte format;
  13045. int length;
  13046. if (cert == NULL)
  13047. return BAD_FUNC_ARG;
  13048. if (before && cert->beforeDateSz > 0) {
  13049. ret = wc_GetDateInfo(cert->beforeDate, cert->beforeDateSz, &date,
  13050. &format, &length);
  13051. if (ret == 0)
  13052. ret = wc_GetDateAsCalendarTime(date, length, format, before);
  13053. }
  13054. if (after && cert->afterDateSz > 0) {
  13055. ret = wc_GetDateInfo(cert->afterDate, cert->afterDateSz, &date,
  13056. &format, &length);
  13057. if (ret == 0)
  13058. ret = wc_GetDateAsCalendarTime(date, length, format, after);
  13059. }
  13060. return ret;
  13061. }
  13062. #endif /* WOLFSSL_CERT_GEN && WOLFSSL_ALT_NAMES */
  13063. #endif /* !NO_ASN_TIME */
  13064. #ifndef WOLFSSL_ASN_TEMPLATE
  13065. static int GetSigAlg(DecodedCert* cert, word32* sigOid, word32 maxIdx)
  13066. {
  13067. int length;
  13068. word32 endSeqIdx;
  13069. if (GetSequence(cert->source, &cert->srcIdx, &length, maxIdx) < 0)
  13070. return ASN_PARSE_E;
  13071. endSeqIdx = cert->srcIdx + length;
  13072. if (GetObjectId(cert->source, &cert->srcIdx, sigOid, oidSigType,
  13073. maxIdx) < 0) {
  13074. return ASN_OBJECT_ID_E;
  13075. }
  13076. if (cert->srcIdx != endSeqIdx) {
  13077. #ifdef WC_RSA_PSS
  13078. if (*sigOid == CTC_RSASSAPSS) {
  13079. cert->sigParamsIndex = cert->srcIdx;
  13080. cert->sigParamsLength = endSeqIdx - cert->srcIdx;
  13081. }
  13082. else
  13083. #endif
  13084. /* Only allowed a ASN NULL header with zero length. */
  13085. if (endSeqIdx - cert->srcIdx != 2)
  13086. return ASN_PARSE_E;
  13087. else {
  13088. byte tag;
  13089. if (GetASNTag(cert->source, &cert->srcIdx, &tag, endSeqIdx) != 0)
  13090. return ASN_PARSE_E;
  13091. if (tag != ASN_TAG_NULL)
  13092. return ASN_PARSE_E;
  13093. }
  13094. }
  13095. cert->srcIdx = endSeqIdx;
  13096. return 0;
  13097. }
  13098. #endif
  13099. #ifdef WOLFSSL_ASN_TEMPLATE
  13100. /* TODO: move code around to not require this. */
  13101. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  13102. int* badDateRet, int stopAtPubKey,
  13103. int stopAfterPubKey);
  13104. #endif
  13105. /* Parse the certificate up to the X.509 public key.
  13106. *
  13107. * If cert data is invalid then badDate get set to error value.
  13108. *
  13109. * @param [in, out] cert Decoded certificate object.
  13110. * @param [in] verify Whether to verify dates.
  13111. * @param [out] badDate Error code when verify dates.
  13112. * @return 0 on success.
  13113. * @return BAD_FUNC_ARG when cert or badDate is NULL.
  13114. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  13115. * @return ASN_DATE_SZ_E when time data is not supported.
  13116. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13117. * is invalid.
  13118. * @return BUFFER_E when data in buffer is too small.
  13119. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  13120. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  13121. */
  13122. int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate)
  13123. {
  13124. #ifndef WOLFSSL_ASN_TEMPLATE
  13125. int ret;
  13126. if (cert == NULL || badDate == NULL)
  13127. return BAD_FUNC_ARG;
  13128. *badDate = 0;
  13129. if ( (ret = GetCertHeader(cert)) < 0)
  13130. return ret;
  13131. WOLFSSL_MSG("Got Cert Header");
  13132. #ifdef WOLFSSL_CERT_REQ
  13133. if (!cert->isCSR) {
  13134. #endif
  13135. /* Using the sigIndex as the upper bound because that's where the
  13136. * actual certificate data ends. */
  13137. if ((ret = GetSigAlg(cert, &cert->signatureOID, cert->sigIndex)) < 0)
  13138. return ret;
  13139. WOLFSSL_MSG("Got Algo ID");
  13140. if ( (ret = GetName(cert, ISSUER, cert->sigIndex)) < 0)
  13141. return ret;
  13142. if ( (ret = GetValidity(cert, verify, cert->sigIndex)) < 0)
  13143. *badDate = ret;
  13144. #ifdef WOLFSSL_CERT_REQ
  13145. }
  13146. #endif
  13147. if ( (ret = GetName(cert, SUBJECT, cert->sigIndex)) < 0)
  13148. return ret;
  13149. WOLFSSL_MSG("Got Subject Name");
  13150. return ret;
  13151. #else
  13152. /* Use common decode routine and stop at public key. */
  13153. int ret;
  13154. *badDate = 0;
  13155. ret = DecodeCertInternal(cert, verify, NULL, badDate, 1, 0);
  13156. if (ret >= 0) {
  13157. /* Store current index: public key. */
  13158. cert->srcIdx = ret;
  13159. }
  13160. return ret;
  13161. #endif /* WOLFSSL_ASN_TEMPLATE */
  13162. }
  13163. /* Parse the certificate up to and including X.509 public key.
  13164. *
  13165. * @param [in, out] cert Decoded certificate object.
  13166. * @param [in] verify Whether to verify dates.
  13167. * @return 0 on success.
  13168. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  13169. * @return ASN_DATE_SZ_E when time data is not supported.
  13170. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  13171. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  13172. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13173. * is invalid.
  13174. * @return BUFFER_E when data in buffer is too small.
  13175. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  13176. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  13177. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  13178. */
  13179. int DecodeToKey(DecodedCert* cert, int verify)
  13180. {
  13181. #ifndef WOLFSSL_ASN_TEMPLATE
  13182. int badDate = 0;
  13183. int ret;
  13184. if ( (ret = wc_GetPubX509(cert, verify, &badDate)) < 0)
  13185. return ret;
  13186. /* Determine if self signed */
  13187. #ifdef WOLFSSL_CERT_REQ
  13188. if (cert->isCSR)
  13189. cert->selfSigned = 1;
  13190. else
  13191. #endif
  13192. {
  13193. cert->selfSigned = XMEMCMP(cert->issuerHash,
  13194. cert->subjectHash,
  13195. KEYID_SIZE) == 0 ? 1 : 0;
  13196. }
  13197. ret = GetCertKey(cert, cert->source, &cert->srcIdx, cert->maxIdx);
  13198. if (ret != 0)
  13199. return ret;
  13200. WOLFSSL_MSG("Got Key");
  13201. if (badDate != 0)
  13202. return badDate;
  13203. return ret;
  13204. #else
  13205. int ret;
  13206. int badDate = 0;
  13207. /* Call internal version and stop after public key. */
  13208. ret = DecodeCertInternal(cert, verify, NULL, &badDate, 0, 1);
  13209. /* Always return date errors. */
  13210. if (ret == 0) {
  13211. ret = badDate;
  13212. }
  13213. return ret;
  13214. #endif /* WOLFSSL_ASN_TEMPLATE */
  13215. }
  13216. #if !defined(NO_CERTS) && !defined(WOLFSSL_ASN_TEMPLATE)
  13217. static int GetSignature(DecodedCert* cert)
  13218. {
  13219. int length;
  13220. int ret;
  13221. ret = CheckBitString(cert->source, &cert->srcIdx, &length, cert->maxIdx, 1,
  13222. NULL);
  13223. if (ret != 0)
  13224. return ret;
  13225. cert->sigLength = length;
  13226. cert->signature = &cert->source[cert->srcIdx];
  13227. cert->srcIdx += cert->sigLength;
  13228. if (cert->srcIdx != cert->maxIdx)
  13229. return ASN_PARSE_E;
  13230. return 0;
  13231. }
  13232. #endif /* !NO_CERTS && !WOLFSSL_ASN_TEMPLATE */
  13233. #ifndef WOLFSSL_ASN_TEMPLATE
  13234. static word32 SetOctetString8Bit(word32 len, byte* output)
  13235. {
  13236. output[0] = ASN_OCTET_STRING;
  13237. output[1] = (byte)len;
  13238. return 2;
  13239. }
  13240. static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
  13241. {
  13242. word32 idx = SetOctetString8Bit(digSz, output);
  13243. XMEMCPY(&output[idx], digest, digSz);
  13244. return idx + digSz;
  13245. }
  13246. #endif
  13247. /* Encode a length for DER.
  13248. *
  13249. * @param [in] length Value to encode.
  13250. * @param [out] output Buffer to encode into.
  13251. * @return Number of bytes encoded.
  13252. */
  13253. word32 SetLength(word32 length, byte* output)
  13254. {
  13255. /* Start encoding at start of buffer. */
  13256. word32 i = 0;
  13257. if (length < ASN_LONG_LENGTH) {
  13258. /* Only one byte needed to encode. */
  13259. if (output) {
  13260. /* Write out length value. */
  13261. output[i] = (byte)length;
  13262. }
  13263. /* Skip over length. */
  13264. i++;
  13265. }
  13266. else {
  13267. /* Calculate the number of bytes required to encode value. */
  13268. byte j = (byte)BytePrecision(length);
  13269. if (output) {
  13270. /* Encode count byte. */
  13271. output[i] = j | ASN_LONG_LENGTH;
  13272. }
  13273. /* Skip over count byte. */
  13274. i++;
  13275. /* Encode value as a big-endian byte array. */
  13276. for (; j > 0; --j) {
  13277. if (output) {
  13278. /* Encode next most-significant byte. */
  13279. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  13280. }
  13281. /* Skip over byte. */
  13282. i++;
  13283. }
  13284. }
  13285. /* Return number of bytes in encoded length. */
  13286. return i;
  13287. }
  13288. /* Encode a DER header - type/tag and length.
  13289. *
  13290. * @param [in] tag DER tag of ASN.1 item.
  13291. * @param [in] len Length of data in ASN.1 item.
  13292. * @param [out] output Buffer to encode into.
  13293. * @return Number of bytes encoded.
  13294. */
  13295. static word32 SetHeader(byte tag, word32 len, byte* output)
  13296. {
  13297. if (output) {
  13298. /* Encode tag first. */
  13299. output[0] = tag;
  13300. }
  13301. /* Encode the length. */
  13302. return SetLength(len, output ? output + ASN_TAG_SZ : NULL) + ASN_TAG_SZ;
  13303. }
  13304. /* Encode a SEQUENCE header in DER.
  13305. *
  13306. * @param [in] len Length of data in SEQUENCE.
  13307. * @param [out] output Buffer to encode into.
  13308. * @return Number of bytes encoded.
  13309. */
  13310. word32 SetSequence(word32 len, byte* output)
  13311. {
  13312. return SetHeader(ASN_SEQUENCE | ASN_CONSTRUCTED, len, output);
  13313. }
  13314. /* Encode an OCTET STRING header in DER.
  13315. *
  13316. * @param [in] len Length of data in OCTET STRING.
  13317. * @param [out] output Buffer to encode into.
  13318. * @return Number of bytes encoded.
  13319. */
  13320. word32 SetOctetString(word32 len, byte* output)
  13321. {
  13322. return SetHeader(ASN_OCTET_STRING, len, output);
  13323. }
  13324. /* Encode a SET header in DER.
  13325. *
  13326. * @param [in] len Length of data in SET.
  13327. * @param [out] output Buffer to encode into.
  13328. * @return Number of bytes encoded.
  13329. */
  13330. word32 SetSet(word32 len, byte* output)
  13331. {
  13332. return SetHeader(ASN_SET | ASN_CONSTRUCTED, len, output);
  13333. }
  13334. /* Encode an implicit context specific header in DER.
  13335. *
  13336. * Implicit means that it is constructed only if the included ASN.1 item is.
  13337. *
  13338. * @param [in] tag Tag for the implicit ASN.1 item.
  13339. * @param [in] number Context specific number.
  13340. * @param [in] len Length of data in SET.
  13341. * @param [out] output Buffer to encode into.
  13342. * @return Number of bytes encoded.
  13343. */
  13344. word32 SetImplicit(byte tag, byte number, word32 len, byte* output)
  13345. {
  13346. tag = ((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0)
  13347. | ASN_CONTEXT_SPECIFIC | number;
  13348. return SetHeader(tag, len, output);
  13349. }
  13350. /* Encode an explicit context specific header in DER.
  13351. *
  13352. * Explicit means that there will be an ASN.1 item underneath.
  13353. *
  13354. * @param [in] number Context specific number.
  13355. * @param [in] len Length of data in SET.
  13356. * @param [out] output Buffer to encode into.
  13357. * @return Number of bytes encoded.
  13358. */
  13359. word32 SetExplicit(byte number, word32 len, byte* output)
  13360. {
  13361. return SetHeader(ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | number, len,
  13362. output);
  13363. }
  13364. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  13365. static int SetCurve(ecc_key* key, byte* output, size_t outSz)
  13366. {
  13367. #ifdef HAVE_OID_ENCODING
  13368. int ret;
  13369. #endif
  13370. int idx;
  13371. word32 oidSz = 0;
  13372. /* validate key */
  13373. if (key == NULL || key->dp == NULL) {
  13374. return BAD_FUNC_ARG;
  13375. }
  13376. #ifdef HAVE_OID_ENCODING
  13377. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, NULL, &oidSz);
  13378. if (ret != 0) {
  13379. return ret;
  13380. }
  13381. #else
  13382. oidSz = key->dp->oidSz;
  13383. #endif
  13384. idx = SetObjectId(oidSz, output);
  13385. /* length only */
  13386. if (output == NULL) {
  13387. return idx + oidSz;
  13388. }
  13389. /* verify output buffer has room */
  13390. if (oidSz > outSz)
  13391. return BUFFER_E;
  13392. #ifdef HAVE_OID_ENCODING
  13393. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, output+idx, &oidSz);
  13394. if (ret != 0) {
  13395. return ret;
  13396. }
  13397. #else
  13398. XMEMCPY(output+idx, key->dp->oid, oidSz);
  13399. #endif
  13400. idx += oidSz;
  13401. return idx;
  13402. }
  13403. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  13404. #ifdef HAVE_ECC
  13405. /* Determines whether the signature algorithm is using ECDSA.
  13406. *
  13407. * @param [in] algoOID Signature algorithm identifier.
  13408. * @return 1 when algorithm is using ECDSA.
  13409. * @return 0 otherwise.
  13410. */
  13411. static WC_INLINE int IsSigAlgoECDSA(int algoOID)
  13412. {
  13413. /* ECDSA sigAlgo must not have ASN1 NULL parameters */
  13414. if (algoOID == CTC_SHAwECDSA || algoOID == CTC_SHA256wECDSA ||
  13415. algoOID == CTC_SHA384wECDSA || algoOID == CTC_SHA512wECDSA) {
  13416. return 1;
  13417. }
  13418. return 0;
  13419. }
  13420. #endif
  13421. /* Determines if OID is for an EC signing algorithm including ECDSA and EdDSA
  13422. * and post-quantum algorithms.
  13423. *
  13424. * @param [in] algoOID Algorithm OID.
  13425. * @return 1 when is EC signing algorithm.
  13426. * @return 0 otherwise.
  13427. */
  13428. static WC_INLINE int IsSigAlgoECC(int algoOID)
  13429. {
  13430. (void)algoOID;
  13431. return (0
  13432. #ifdef HAVE_ECC
  13433. || IsSigAlgoECDSA(algoOID)
  13434. #endif
  13435. #ifdef HAVE_ED25519
  13436. || (algoOID == ED25519k)
  13437. #endif
  13438. #ifdef HAVE_CURVE25519
  13439. || (algoOID == X25519k)
  13440. #endif
  13441. #ifdef HAVE_ED448
  13442. || (algoOID == ED448k)
  13443. #endif
  13444. #ifdef HAVE_CURVE448
  13445. || (algoOID == X448k)
  13446. #endif
  13447. #ifdef HAVE_PQC
  13448. #ifdef HAVE_FACON
  13449. || (algoOID == FALCON_LEVEL1k)
  13450. || (algoOID == FALCON_LEVEL5k)
  13451. #endif
  13452. #ifdef HAVE_DILITHIUM
  13453. || (algoOID == DILITHIUM_LEVEL2k)
  13454. || (algoOID == DILITHIUM_LEVEL3k)
  13455. || (algoOID == DILITHIUM_LEVEL5k)
  13456. || (algoOID == DILITHIUM_AES_LEVEL2k)
  13457. || (algoOID == DILITHIUM_AES_LEVEL3k)
  13458. || (algoOID == DILITHIUM_AES_LEVEL5k)
  13459. #endif
  13460. #ifdef HAVE_SPHINCS
  13461. || (algoOID == SPHINCS_FAST_LEVEL1k)
  13462. || (algoOID == SPHINCS_FAST_LEVEL3k)
  13463. || (algoOID == SPHINCS_FAST_LEVEL5k)
  13464. || (algoOID == SPHINCS_SMALL_LEVEL1k)
  13465. || (algoOID == SPHINCS_SMALL_LEVEL3k)
  13466. || (algoOID == SPHINCS_SMALL_LEVEL5k)
  13467. #endif
  13468. #endif /* HAVE_PQC */
  13469. );
  13470. }
  13471. /* Encode an algorithm identifier.
  13472. *
  13473. * [algoOID, type] is unique.
  13474. *
  13475. * @param [in] algoOID Algorithm identifier.
  13476. * @param [out] output Buffer to hold encoding.
  13477. * @param [in] type Type of OID being encoded.
  13478. * @param [in] curveSz Add extra space for curve data.
  13479. * @return Encoded data size on success.
  13480. * @return 0 when dynamic memory allocation fails.
  13481. */
  13482. word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz)
  13483. {
  13484. #ifndef WOLFSSL_ASN_TEMPLATE
  13485. word32 tagSz, idSz, seqSz, algoSz = 0;
  13486. const byte* algoName = 0;
  13487. byte ID_Length[1 + MAX_LENGTH_SZ];
  13488. byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
  13489. int length = 0;
  13490. tagSz = (type == oidHashType ||
  13491. (type == oidSigType && !IsSigAlgoECC(algoOID)) ||
  13492. (type == oidKeyType && algoOID == RSAk)) ? 2 : 0;
  13493. algoName = OidFromId(algoOID, type, &algoSz);
  13494. if (algoName == NULL) {
  13495. WOLFSSL_MSG("Unknown Algorithm");
  13496. return 0;
  13497. }
  13498. idSz = SetObjectId(algoSz, ID_Length);
  13499. seqSz = SetSequence(idSz + algoSz + tagSz + curveSz, seqArray);
  13500. /* Copy only algo to output for DSA keys */
  13501. if (algoOID == DSAk && output) {
  13502. XMEMCPY(output, ID_Length, idSz);
  13503. XMEMCPY(output + idSz, algoName, algoSz);
  13504. if (tagSz == 2)
  13505. SetASNNull(&output[seqSz + idSz + algoSz]);
  13506. }
  13507. else if (output) {
  13508. XMEMCPY(output, seqArray, seqSz);
  13509. XMEMCPY(output + seqSz, ID_Length, idSz);
  13510. XMEMCPY(output + seqSz + idSz, algoName, algoSz);
  13511. if (tagSz == 2)
  13512. SetASNNull(&output[seqSz + idSz + algoSz]);
  13513. }
  13514. if (algoOID == DSAk)
  13515. length = idSz + algoSz + tagSz;
  13516. else
  13517. length = seqSz + idSz + algoSz + tagSz;
  13518. return length;
  13519. #else
  13520. DECL_ASNSETDATA(dataASN, algoIdASN_Length);
  13521. int sz;
  13522. int ret = 0;
  13523. int o = 0;
  13524. CALLOC_ASNSETDATA(dataASN, algoIdASN_Length, ret, NULL);
  13525. /* Set the OID and OID type to encode. */
  13526. SetASN_OID(&dataASN[ALGOIDASN_IDX_OID], algoOID, type);
  13527. /* Hashes, signatures not ECC and keys not RSA put put NULL tag. */
  13528. if (!(type == oidHashType ||
  13529. (type == oidSigType && !IsSigAlgoECC(algoOID)) ||
  13530. (type == oidKeyType && algoOID == RSAk))) {
  13531. /* Don't put out NULL DER item. */
  13532. dataASN[ALGOIDASN_IDX_NULL].noOut = 1;
  13533. }
  13534. if (algoOID == DSAk) {
  13535. /* Don't include SEQUENCE for DSA keys. */
  13536. o = 1;
  13537. }
  13538. else if (curveSz > 0) {
  13539. /* Don't put out NULL DER item. */
  13540. dataASN[ALGOIDASN_IDX_NULL].noOut = 0;
  13541. /* Include space for extra data of length curveSz.
  13542. * Subtract 1 for sequence and 1 for length encoding. */
  13543. SetASN_Buffer(&dataASN[ALGOIDASN_IDX_NULL], NULL, curveSz - 2);
  13544. }
  13545. /* Calculate size of encoding. */
  13546. ret = SizeASN_Items(algoIdASN + o, dataASN + o, algoIdASN_Length - o, &sz);
  13547. if (ret == 0 && output != NULL) {
  13548. /* Encode into buffer. */
  13549. SetASN_Items(algoIdASN + o, dataASN + o, algoIdASN_Length - o, output);
  13550. if (curveSz > 0) {
  13551. /* Return size excluding curve data. */
  13552. sz = dataASN[o].offset - dataASN[ALGOIDASN_IDX_NULL].offset;
  13553. }
  13554. }
  13555. if (ret == 0) {
  13556. /* Return encoded size. */
  13557. ret = sz;
  13558. }
  13559. else {
  13560. /* Unsigned return type so 0 indicates error. */
  13561. ret = 0;
  13562. }
  13563. FREE_ASNSETDATA(dataASN, NULL);
  13564. return ret;
  13565. #endif /* WOLFSSL_ASN_TEMPLATE */
  13566. }
  13567. #ifdef WOLFSSL_ASN_TEMPLATE
  13568. /* Always encode PKCS#1 v1.5 RSA signature and compare to encoded data. */
  13569. /* ASN.1 template for DigestInfo for a PKCS#1 v1.5 RSA signature.
  13570. * PKCS#1 v2.2: RFC 8017, A.2.4 - DigestInfo
  13571. */
  13572. static const ASNItem digestInfoASN[] = {
  13573. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  13574. /* digestAlgorithm */
  13575. /* DIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  13576. /* DIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  13577. /* DIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  13578. /* digest */
  13579. /* DIGEST */ { 1, ASN_OCTET_STRING, 0, 0, 0 }
  13580. };
  13581. enum {
  13582. DIGESTINFOASN_IDX_SEQ = 0,
  13583. DIGESTINFOASN_IDX_DIGALGO_SEQ,
  13584. DIGESTINFOASN_IDX_DIGALGO_OID,
  13585. DIGESTINFOASN_IDX_DIGALGO_NULL,
  13586. DIGESTINFOASN_IDX_DIGEST,
  13587. };
  13588. /* Number of items in ASN.1 template for DigestInfo for RSA. */
  13589. #define digestInfoASN_Length (sizeof(digestInfoASN) / sizeof(ASNItem))
  13590. #endif
  13591. /* Encode signature.
  13592. *
  13593. * @param [out] out Buffer to hold encoding.
  13594. * @param [in] digest Buffer holding digest.
  13595. * @param [in] digSz Length of digest in bytes.
  13596. * @return Encoded data size on success.
  13597. * @return 0 when dynamic memory allocation fails.
  13598. */
  13599. word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz,
  13600. int hashOID)
  13601. {
  13602. #ifndef WOLFSSL_ASN_TEMPLATE
  13603. byte digArray[MAX_ENCODED_DIG_SZ];
  13604. byte algoArray[MAX_ALGO_SZ];
  13605. byte seqArray[MAX_SEQ_SZ];
  13606. word32 encDigSz, algoSz, seqSz;
  13607. encDigSz = SetDigest(digest, digSz, digArray);
  13608. algoSz = SetAlgoID(hashOID, algoArray, oidHashType, 0);
  13609. seqSz = SetSequence(encDigSz + algoSz, seqArray);
  13610. XMEMCPY(out, seqArray, seqSz);
  13611. XMEMCPY(out + seqSz, algoArray, algoSz);
  13612. XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
  13613. return encDigSz + algoSz + seqSz;
  13614. #else
  13615. DECL_ASNSETDATA(dataASN, digestInfoASN_Length);
  13616. int ret = 0;
  13617. int sz;
  13618. CALLOC_ASNSETDATA(dataASN, digestInfoASN_Length, ret, NULL);
  13619. if (ret == 0) {
  13620. /* Set hash OID and type. */
  13621. SetASN_OID(&dataASN[DIGESTINFOASN_IDX_DIGALGO_OID], hashOID, oidHashType);
  13622. /* Set digest. */
  13623. SetASN_Buffer(&dataASN[DIGESTINFOASN_IDX_DIGEST], digest, digSz);
  13624. /* Calculate size of encoding. */
  13625. ret = SizeASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, &sz);
  13626. }
  13627. if (ret == 0) {
  13628. /* Encode PKCS#1 v1.5 RSA signature. */
  13629. SetASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, out);
  13630. ret = sz;
  13631. }
  13632. else {
  13633. /* Unsigned return type so 0 indicates error. */
  13634. ret = 0;
  13635. }
  13636. FREE_ASNSETDATA(dataASN, NULL);
  13637. return ret;
  13638. #endif
  13639. }
  13640. #ifndef NO_CERTS
  13641. int wc_GetCTC_HashOID(int type)
  13642. {
  13643. int ret;
  13644. enum wc_HashType hType;
  13645. hType = wc_HashTypeConvert(type);
  13646. ret = wc_HashGetOID(hType);
  13647. if (ret < 0) {
  13648. ret = 0; /* backwards compatibility */
  13649. }
  13650. return ret;
  13651. }
  13652. /* Initialize a signature context object.
  13653. *
  13654. * Object used for signing and verifying a certificate signature.
  13655. *
  13656. * @param [in, out] sigCtx Signature context object.
  13657. * @param [in] heap Dynamic memory hint.
  13658. * @param [in] devId Hardware device identifier.
  13659. */
  13660. void InitSignatureCtx(SignatureCtx* sigCtx, void* heap, int devId)
  13661. {
  13662. if (sigCtx) {
  13663. XMEMSET(sigCtx, 0, sizeof(SignatureCtx));
  13664. sigCtx->devId = devId;
  13665. sigCtx->heap = heap;
  13666. }
  13667. }
  13668. /* Free dynamic data in a signature context object.
  13669. *
  13670. * @param [in, out] sigCtx Signature context object.
  13671. */
  13672. void FreeSignatureCtx(SignatureCtx* sigCtx)
  13673. {
  13674. if (sigCtx == NULL)
  13675. return;
  13676. if (sigCtx->digest) {
  13677. XFREE(sigCtx->digest, sigCtx->heap, DYNAMIC_TYPE_DIGEST);
  13678. sigCtx->digest = NULL;
  13679. }
  13680. #if !(defined(NO_RSA) && defined(NO_DSA))
  13681. if (sigCtx->sigCpy) {
  13682. XFREE(sigCtx->sigCpy, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  13683. sigCtx->sigCpy = NULL;
  13684. }
  13685. #endif
  13686. #ifndef NO_ASN_CRYPT
  13687. if (sigCtx->key.ptr) {
  13688. switch (sigCtx->keyOID) {
  13689. #ifndef NO_RSA
  13690. #ifdef WC_RSA_PSS
  13691. case RSAPSSk:
  13692. #endif
  13693. case RSAk:
  13694. wc_FreeRsaKey(sigCtx->key.rsa);
  13695. XFREE(sigCtx->key.rsa, sigCtx->heap, DYNAMIC_TYPE_RSA);
  13696. sigCtx->key.rsa = NULL;
  13697. break;
  13698. #endif /* !NO_RSA */
  13699. #ifndef NO_DSA
  13700. case DSAk:
  13701. wc_FreeDsaKey(sigCtx->key.dsa);
  13702. XFREE(sigCtx->key.dsa, sigCtx->heap, DYNAMIC_TYPE_DSA);
  13703. sigCtx->key.dsa = NULL;
  13704. break;
  13705. #endif
  13706. #ifdef HAVE_ECC
  13707. case ECDSAk:
  13708. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  13709. defined(WC_ASYNC_ENABLE_ECC)
  13710. if (sigCtx->key.ecc->nb_ctx != NULL) {
  13711. XFREE(sigCtx->key.ecc->nb_ctx, sigCtx->heap,
  13712. DYNAMIC_TYPE_TMP_BUFFER);
  13713. }
  13714. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  13715. WC_ASYNC_ENABLE_ECC */
  13716. wc_ecc_free(sigCtx->key.ecc);
  13717. XFREE(sigCtx->key.ecc, sigCtx->heap, DYNAMIC_TYPE_ECC);
  13718. sigCtx->key.ecc = NULL;
  13719. break;
  13720. #endif /* HAVE_ECC */
  13721. #ifdef HAVE_ED25519
  13722. case ED25519k:
  13723. wc_ed25519_free(sigCtx->key.ed25519);
  13724. XFREE(sigCtx->key.ed25519, sigCtx->heap, DYNAMIC_TYPE_ED25519);
  13725. sigCtx->key.ed25519 = NULL;
  13726. break;
  13727. #endif /* HAVE_ED25519 */
  13728. #ifdef HAVE_ED448
  13729. case ED448k:
  13730. wc_ed448_free(sigCtx->key.ed448);
  13731. XFREE(sigCtx->key.ed448, sigCtx->heap, DYNAMIC_TYPE_ED448);
  13732. sigCtx->key.ed448 = NULL;
  13733. break;
  13734. #endif /* HAVE_ED448 */
  13735. #if defined(HAVE_PQC)
  13736. #if defined(HAVE_FALCON)
  13737. case FALCON_LEVEL1k:
  13738. case FALCON_LEVEL5k:
  13739. wc_falcon_free(sigCtx->key.falcon);
  13740. XFREE(sigCtx->key.falcon, sigCtx->heap,
  13741. DYNAMIC_TYPE_FALCON);
  13742. sigCtx->key.falcon = NULL;
  13743. break;
  13744. #endif /* HAVE_FALCON */
  13745. #if defined(HAVE_DILITHIUM)
  13746. case DILITHIUM_LEVEL2k:
  13747. case DILITHIUM_LEVEL3k:
  13748. case DILITHIUM_LEVEL5k:
  13749. case DILITHIUM_AES_LEVEL2k:
  13750. case DILITHIUM_AES_LEVEL3k:
  13751. case DILITHIUM_AES_LEVEL5k:
  13752. wc_dilithium_free(sigCtx->key.dilithium);
  13753. XFREE(sigCtx->key.dilithium, sigCtx->heap,
  13754. DYNAMIC_TYPE_DILITHIUM);
  13755. sigCtx->key.dilithium = NULL;
  13756. break;
  13757. #endif /* HAVE_DILITHIUM */
  13758. #if defined(HAVE_SPHINCS)
  13759. case SPHINCS_FAST_LEVEL1k:
  13760. case SPHINCS_FAST_LEVEL3k:
  13761. case SPHINCS_FAST_LEVEL5k:
  13762. case SPHINCS_SMALL_LEVEL1k:
  13763. case SPHINCS_SMALL_LEVEL3k:
  13764. case SPHINCS_SMALL_LEVEL5k:
  13765. wc_sphincs_free(sigCtx->key.sphincs);
  13766. XFREE(sigCtx->key.sphincs, sigCtx->heap,
  13767. DYNAMIC_TYPE_SPHINCS);
  13768. sigCtx->key.sphincs = NULL;
  13769. break;
  13770. #endif /* HAVE_SPHINCS */
  13771. #endif /* HAVE_PQC */
  13772. default:
  13773. break;
  13774. } /* switch (keyOID) */
  13775. sigCtx->key.ptr = NULL;
  13776. }
  13777. #endif
  13778. /* reset state, we are done */
  13779. sigCtx->state = SIG_STATE_BEGIN;
  13780. }
  13781. #ifndef NO_ASN_CRYPT
  13782. static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID,
  13783. byte* digest, int* typeH, int* digestSz, int verify)
  13784. {
  13785. int ret = 0;
  13786. switch (sigOID) {
  13787. #if defined(WOLFSSL_MD2)
  13788. case CTC_MD2wRSA:
  13789. if (!verify) {
  13790. ret = HASH_TYPE_E;
  13791. WOLFSSL_MSG("MD2 not supported for signing");
  13792. }
  13793. else if ((ret = wc_Md2Hash(buf, bufSz, digest)) == 0) {
  13794. *typeH = MD2h;
  13795. *digestSz = MD2_DIGEST_SIZE;
  13796. }
  13797. break;
  13798. #endif
  13799. #ifndef NO_MD5
  13800. case CTC_MD5wRSA:
  13801. if ((ret = wc_Md5Hash(buf, bufSz, digest)) == 0) {
  13802. *typeH = MD5h;
  13803. *digestSz = WC_MD5_DIGEST_SIZE;
  13804. }
  13805. break;
  13806. #endif
  13807. #ifndef NO_SHA
  13808. case CTC_SHAwRSA:
  13809. case CTC_SHAwDSA:
  13810. case CTC_SHAwECDSA:
  13811. if ((ret = wc_ShaHash(buf, bufSz, digest)) == 0) {
  13812. *typeH = SHAh;
  13813. *digestSz = WC_SHA_DIGEST_SIZE;
  13814. }
  13815. break;
  13816. #endif
  13817. #ifdef WOLFSSL_SHA224
  13818. case CTC_SHA224wRSA:
  13819. case CTC_SHA224wECDSA:
  13820. if ((ret = wc_Sha224Hash(buf, bufSz, digest)) == 0) {
  13821. *typeH = SHA224h;
  13822. *digestSz = WC_SHA224_DIGEST_SIZE;
  13823. }
  13824. break;
  13825. #endif
  13826. #ifndef NO_SHA256
  13827. case CTC_SHA256wRSA:
  13828. case CTC_SHA256wECDSA:
  13829. case CTC_SHA256wDSA:
  13830. if ((ret = wc_Sha256Hash(buf, bufSz, digest)) == 0) {
  13831. *typeH = SHA256h;
  13832. *digestSz = WC_SHA256_DIGEST_SIZE;
  13833. }
  13834. break;
  13835. #endif
  13836. #ifdef WOLFSSL_SHA384
  13837. case CTC_SHA384wRSA:
  13838. case CTC_SHA384wECDSA:
  13839. if ((ret = wc_Sha384Hash(buf, bufSz, digest)) == 0) {
  13840. *typeH = SHA384h;
  13841. *digestSz = WC_SHA384_DIGEST_SIZE;
  13842. }
  13843. break;
  13844. #endif
  13845. #ifdef WOLFSSL_SHA512
  13846. case CTC_SHA512wRSA:
  13847. case CTC_SHA512wECDSA:
  13848. if ((ret = wc_Sha512Hash(buf, bufSz, digest)) == 0) {
  13849. *typeH = SHA512h;
  13850. *digestSz = WC_SHA512_DIGEST_SIZE;
  13851. }
  13852. break;
  13853. #endif
  13854. #ifdef WOLFSSL_SHA3
  13855. #ifndef WOLFSSL_NOSHA3_224
  13856. case CTC_SHA3_224wRSA:
  13857. case CTC_SHA3_224wECDSA:
  13858. if ((ret = wc_Sha3_224Hash(buf, bufSz, digest)) == 0) {
  13859. *typeH = SHA3_224h;
  13860. *digestSz = WC_SHA3_224_DIGEST_SIZE;
  13861. }
  13862. break;
  13863. #endif
  13864. #ifndef WOLFSSL_NOSHA3_256
  13865. case CTC_SHA3_256wRSA:
  13866. case CTC_SHA3_256wECDSA:
  13867. if ((ret = wc_Sha3_256Hash(buf, bufSz, digest)) == 0) {
  13868. *typeH = SHA3_256h;
  13869. *digestSz = WC_SHA3_256_DIGEST_SIZE;
  13870. }
  13871. break;
  13872. #endif
  13873. #ifndef WOLFSSL_NOSHA3_384
  13874. case CTC_SHA3_384wRSA:
  13875. case CTC_SHA3_384wECDSA:
  13876. if ((ret = wc_Sha3_384Hash(buf, bufSz, digest)) == 0) {
  13877. *typeH = SHA3_384h;
  13878. *digestSz = WC_SHA3_384_DIGEST_SIZE;
  13879. }
  13880. break;
  13881. #endif
  13882. #ifndef WOLFSSL_NOSHA3_512
  13883. case CTC_SHA3_512wRSA:
  13884. case CTC_SHA3_512wECDSA:
  13885. if ((ret = wc_Sha3_512Hash(buf, bufSz, digest)) == 0) {
  13886. *typeH = SHA3_512h;
  13887. *digestSz = WC_SHA3_512_DIGEST_SIZE;
  13888. }
  13889. break;
  13890. #endif
  13891. #endif
  13892. #ifdef HAVE_ED25519
  13893. case CTC_ED25519:
  13894. /* Hashes done in signing operation.
  13895. * Two dependent hashes with prefixes performed.
  13896. */
  13897. break;
  13898. #endif
  13899. #ifdef HAVE_ED448
  13900. case CTC_ED448:
  13901. /* Hashes done in signing operation.
  13902. * Two dependent hashes with prefixes performed.
  13903. */
  13904. break;
  13905. #endif
  13906. #ifdef HAVE_PQC
  13907. #ifdef HAVE_FALCON
  13908. case CTC_FALCON_LEVEL1:
  13909. case CTC_FALCON_LEVEL5:
  13910. /* Hashes done in signing operation. */
  13911. break;
  13912. #endif
  13913. #ifdef HAVE_DILITHIUM
  13914. case CTC_DILITHIUM_LEVEL2:
  13915. case CTC_DILITHIUM_LEVEL3:
  13916. case CTC_DILITHIUM_LEVEL5:
  13917. case CTC_DILITHIUM_AES_LEVEL2:
  13918. case CTC_DILITHIUM_AES_LEVEL3:
  13919. case CTC_DILITHIUM_AES_LEVEL5:
  13920. /* Hashes done in signing operation. */
  13921. break;
  13922. #endif
  13923. #ifdef HAVE_SPHINCS
  13924. case CTC_SPHINCS_FAST_LEVEL1:
  13925. case CTC_SPHINCS_FAST_LEVEL3:
  13926. case CTC_SPHINCS_FAST_LEVEL5:
  13927. case CTC_SPHINCS_SMALL_LEVEL1:
  13928. case CTC_SPHINCS_SMALL_LEVEL3:
  13929. case CTC_SPHINCS_SMALL_LEVEL5:
  13930. /* Hashes done in signing operation. */
  13931. break;
  13932. #endif
  13933. #endif /* HAVE_PQC */
  13934. default:
  13935. ret = HASH_TYPE_E;
  13936. WOLFSSL_MSG("Hash for Signature has unsupported type");
  13937. }
  13938. (void)buf;
  13939. (void)bufSz;
  13940. (void)sigOID;
  13941. (void)digest;
  13942. (void)digestSz;
  13943. (void)typeH;
  13944. (void)verify;
  13945. return ret;
  13946. }
  13947. #endif /* !NO_ASN_CRYPT */
  13948. /* Return codes: 0=Success, Negative (see error-crypt.h), ASN_SIG_CONFIRM_E */
  13949. static int ConfirmSignature(SignatureCtx* sigCtx,
  13950. const byte* buf, word32 bufSz,
  13951. const byte* key, word32 keySz, word32 keyOID,
  13952. const byte* sig, word32 sigSz, word32 sigOID,
  13953. const byte* sigParams, word32 sigParamsSz,
  13954. byte* rsaKeyIdx)
  13955. {
  13956. int ret = 0;
  13957. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  13958. CertAttribute* certatt = NULL;
  13959. #endif
  13960. if (sigCtx == NULL || buf == NULL || bufSz == 0 || key == NULL ||
  13961. keySz == 0 || sig == NULL || sigSz == 0) {
  13962. return BAD_FUNC_ARG;
  13963. }
  13964. (void)key;
  13965. (void)keySz;
  13966. (void)sig;
  13967. (void)sigSz;
  13968. (void)sigParams;
  13969. (void)sigParamsSz;
  13970. WOLFSSL_ENTER("ConfirmSignature");
  13971. #if !defined(WOLFSSL_RENESAS_TSIP_TLS) && !defined(WOLFSSL_RENESAS_SCEPROTECT)
  13972. (void)rsaKeyIdx;
  13973. #else
  13974. #if !defined(NO_RSA) || defined(HAVE_ECC)
  13975. certatt = (CertAttribute*)&sigCtx->CertAtt;
  13976. #endif
  13977. if (certatt) {
  13978. certatt->keyIndex = rsaKeyIdx;
  13979. certatt->cert = buf;
  13980. certatt->certSz = bufSz;
  13981. }
  13982. #endif
  13983. #ifndef NO_ASN_CRYPT
  13984. switch (sigCtx->state) {
  13985. case SIG_STATE_BEGIN:
  13986. {
  13987. sigCtx->keyOID = keyOID; /* must set early for cleanup */
  13988. sigCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, sigCtx->heap,
  13989. DYNAMIC_TYPE_DIGEST);
  13990. if (sigCtx->digest == NULL) {
  13991. ERROR_OUT(MEMORY_E, exit_cs);
  13992. }
  13993. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  13994. /* RSA PSS Defaults */
  13995. sigCtx->hash = WC_HASH_TYPE_SHA;
  13996. sigCtx->mgf = WC_MGF1SHA1;
  13997. sigCtx->saltLen = 20;
  13998. #endif
  13999. sigCtx->state = SIG_STATE_HASH;
  14000. } /* SIG_STATE_BEGIN */
  14001. FALL_THROUGH;
  14002. case SIG_STATE_HASH:
  14003. {
  14004. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  14005. if (sigOID == RSAPSSk) {
  14006. word32 fakeSigOID = 0;
  14007. ret = DecodeRsaPssParams(sigParams, sigParamsSz, &sigCtx->hash,
  14008. &sigCtx->mgf, &sigCtx->saltLen);
  14009. if (ret != 0) {
  14010. goto exit_cs;
  14011. }
  14012. ret = RsaPssHashOidToSigOid(sigCtx->hash, &fakeSigOID);
  14013. if (ret != 0) {
  14014. goto exit_cs;
  14015. }
  14016. /* Decode parameters. */
  14017. ret = HashForSignature(buf, bufSz, fakeSigOID, sigCtx->digest,
  14018. &sigCtx->typeH, &sigCtx->digestSz, 1);
  14019. if (ret != 0) {
  14020. goto exit_cs;
  14021. }
  14022. }
  14023. else
  14024. #endif
  14025. {
  14026. ret = HashForSignature(buf, bufSz, sigOID, sigCtx->digest,
  14027. &sigCtx->typeH, &sigCtx->digestSz, 1);
  14028. if (ret != 0) {
  14029. goto exit_cs;
  14030. }
  14031. }
  14032. sigCtx->state = SIG_STATE_KEY;
  14033. } /* SIG_STATE_HASH */
  14034. FALL_THROUGH;
  14035. case SIG_STATE_KEY:
  14036. {
  14037. switch (keyOID) {
  14038. #ifndef NO_RSA
  14039. #ifdef WC_RSA_PSS
  14040. case RSAPSSk:
  14041. #endif
  14042. case RSAk:
  14043. {
  14044. word32 idx = 0;
  14045. sigCtx->key.rsa = (RsaKey*)XMALLOC(sizeof(RsaKey),
  14046. sigCtx->heap, DYNAMIC_TYPE_RSA);
  14047. sigCtx->sigCpy = (byte*)XMALLOC(sigSz, sigCtx->heap,
  14048. DYNAMIC_TYPE_SIGNATURE);
  14049. if (sigCtx->key.rsa == NULL || sigCtx->sigCpy == NULL) {
  14050. ERROR_OUT(MEMORY_E, exit_cs);
  14051. }
  14052. if ((ret = wc_InitRsaKey_ex(sigCtx->key.rsa, sigCtx->heap,
  14053. sigCtx->devId)) != 0) {
  14054. goto exit_cs;
  14055. }
  14056. if (sigSz > MAX_ENCODED_SIG_SZ) {
  14057. WOLFSSL_MSG("Verify Signature is too big");
  14058. ERROR_OUT(BUFFER_E, exit_cs);
  14059. }
  14060. if ((ret = wc_RsaPublicKeyDecode(key, &idx, sigCtx->key.rsa,
  14061. keySz)) != 0) {
  14062. WOLFSSL_MSG("ASN Key decode error RSA");
  14063. WOLFSSL_ERROR_VERBOSE(ret);
  14064. goto exit_cs;
  14065. }
  14066. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  14067. sigCtx->out = NULL;
  14068. #ifdef WOLFSSL_ASYNC_CRYPT
  14069. sigCtx->asyncDev = &sigCtx->key.rsa->asyncDev;
  14070. #endif
  14071. break;
  14072. }
  14073. #endif /* !NO_RSA */
  14074. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  14075. case DSAk:
  14076. {
  14077. word32 idx = 0;
  14078. if (sigSz < DSA_MIN_SIG_SIZE) {
  14079. WOLFSSL_MSG("Verify Signature is too small");
  14080. ERROR_OUT(BUFFER_E, exit_cs);
  14081. }
  14082. sigCtx->key.dsa = (DsaKey*)XMALLOC(sizeof(DsaKey),
  14083. sigCtx->heap, DYNAMIC_TYPE_DSA);
  14084. sigCtx->sigCpy = (byte*)XMALLOC(sigSz,
  14085. sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  14086. if (sigCtx->key.dsa == NULL || sigCtx->sigCpy == NULL) {
  14087. ERROR_OUT(MEMORY_E, exit_cs);
  14088. }
  14089. if ((ret = wc_InitDsaKey_h(sigCtx->key.dsa, sigCtx->heap)) != 0) {
  14090. WOLFSSL_MSG("wc_InitDsaKey_h error");
  14091. goto exit_cs;
  14092. }
  14093. if ((ret = wc_DsaPublicKeyDecode(key, &idx, sigCtx->key.dsa,
  14094. keySz)) != 0) {
  14095. WOLFSSL_MSG("ASN Key decode error DSA");
  14096. WOLFSSL_ERROR_VERBOSE(ret);
  14097. goto exit_cs;
  14098. }
  14099. if (sigSz != DSA_160_SIG_SIZE &&
  14100. sigSz != DSA_256_SIG_SIZE) {
  14101. /* Try to parse it as the contents of a bitstring */
  14102. #ifdef WOLFSSL_SMALL_STACK
  14103. mp_int* r;
  14104. mp_int* s;
  14105. #else
  14106. mp_int r[1];
  14107. mp_int s[1];
  14108. #endif
  14109. int rSz;
  14110. int sSz;
  14111. #ifdef WOLFSSL_SMALL_STACK
  14112. r = (mp_int*)XMALLOC(sizeof(*r), sigCtx->heap,
  14113. DYNAMIC_TYPE_TMP_BUFFER);
  14114. if (r == NULL) {
  14115. ERROR_OUT(MEMORY_E, exit_cs);
  14116. }
  14117. s = (mp_int*)XMALLOC(sizeof(*s), sigCtx->heap,
  14118. DYNAMIC_TYPE_TMP_BUFFER);
  14119. if (s == NULL) {
  14120. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14121. ERROR_OUT(MEMORY_E, exit_cs);
  14122. }
  14123. #endif
  14124. mp_init(r);
  14125. mp_init(s);
  14126. idx = 0;
  14127. if (DecodeECC_DSA_Sig(sig + idx, sigSz - idx, r, s)
  14128. != 0) {
  14129. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14130. "incorrect format");
  14131. mp_free(r);
  14132. mp_free(s);
  14133. #ifdef WOLFSSL_SMALL_STACK
  14134. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14135. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14136. #endif
  14137. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14138. }
  14139. rSz = mp_unsigned_bin_size(r);
  14140. sSz = mp_unsigned_bin_size(s);
  14141. if (rSz + sSz > (int)sigSz) {
  14142. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14143. "incorrect format");
  14144. mp_free(r);
  14145. mp_free(s);
  14146. #ifdef WOLFSSL_SMALL_STACK
  14147. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14148. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14149. #endif
  14150. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14151. }
  14152. if (mp_to_unsigned_bin(r, sigCtx->sigCpy) != MP_OKAY ||
  14153. mp_to_unsigned_bin(s,
  14154. sigCtx->sigCpy + rSz) != MP_OKAY) {
  14155. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14156. "incorrect format");
  14157. mp_free(r);
  14158. mp_free(s);
  14159. #ifdef WOLFSSL_SMALL_STACK
  14160. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14161. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14162. #endif
  14163. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14164. }
  14165. mp_free(r);
  14166. mp_free(s);
  14167. #ifdef WOLFSSL_SMALL_STACK
  14168. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14169. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14170. #endif
  14171. }
  14172. else {
  14173. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  14174. }
  14175. break;
  14176. }
  14177. #endif /* !NO_DSA && !HAVE_SELFTEST */
  14178. #ifdef HAVE_ECC
  14179. case ECDSAk:
  14180. {
  14181. word32 idx = 0;
  14182. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14183. defined(WC_ASYNC_ENABLE_ECC)
  14184. ecc_nb_ctx_t* nbCtx;
  14185. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14186. WC_ASYNC_ENABLE_ECC */
  14187. sigCtx->verify = 0;
  14188. sigCtx->key.ecc = (ecc_key*)XMALLOC(sizeof(ecc_key),
  14189. sigCtx->heap, DYNAMIC_TYPE_ECC);
  14190. if (sigCtx->key.ecc == NULL) {
  14191. ERROR_OUT(MEMORY_E, exit_cs);
  14192. }
  14193. if ((ret = wc_ecc_init_ex(sigCtx->key.ecc, sigCtx->heap,
  14194. sigCtx->devId)) < 0) {
  14195. goto exit_cs;
  14196. }
  14197. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14198. defined(WC_ASYNC_ENABLE_ECC)
  14199. nbCtx = (ecc_nb_ctx_t*)XMALLOC(sizeof(ecc_nb_ctx_t),
  14200. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14201. if (nbCtx == NULL) {
  14202. ERROR_OUT(MEMORY_E, exit_cs);
  14203. }
  14204. else {
  14205. ret = wc_ecc_set_nonblock(sigCtx->key.ecc, nbCtx);
  14206. if (ret != 0) {
  14207. goto exit_cs;
  14208. }
  14209. }
  14210. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14211. WC_ASYNC_ENABLE_ECC */
  14212. ret = wc_EccPublicKeyDecode(key, &idx, sigCtx->key.ecc,
  14213. keySz);
  14214. if (ret < 0) {
  14215. WOLFSSL_MSG("ASN Key import error ECC");
  14216. WOLFSSL_ERROR_VERBOSE(ret);
  14217. goto exit_cs;
  14218. }
  14219. #ifdef WOLFSSL_ASYNC_CRYPT
  14220. sigCtx->asyncDev = &sigCtx->key.ecc->asyncDev;
  14221. #endif
  14222. break;
  14223. }
  14224. #endif /* HAVE_ECC */
  14225. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  14226. case ED25519k:
  14227. {
  14228. sigCtx->verify = 0;
  14229. sigCtx->key.ed25519 = (ed25519_key*)XMALLOC(
  14230. sizeof(ed25519_key), sigCtx->heap,
  14231. DYNAMIC_TYPE_ED25519);
  14232. if (sigCtx->key.ed25519 == NULL) {
  14233. ERROR_OUT(MEMORY_E, exit_cs);
  14234. }
  14235. if ((ret = wc_ed25519_init_ex(sigCtx->key.ed25519,
  14236. sigCtx->heap, sigCtx->devId)) < 0) {
  14237. goto exit_cs;
  14238. }
  14239. if ((ret = wc_ed25519_import_public(key, keySz,
  14240. sigCtx->key.ed25519)) < 0) {
  14241. WOLFSSL_MSG("ASN Key import error ED25519");
  14242. WOLFSSL_ERROR_VERBOSE(ret);
  14243. goto exit_cs;
  14244. }
  14245. #ifdef WOLFSSL_ASYNC_CRYPT
  14246. sigCtx->asyncDev = &sigCtx->key.ed25519->asyncDev;
  14247. #endif
  14248. break;
  14249. }
  14250. #endif
  14251. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  14252. case ED448k:
  14253. {
  14254. sigCtx->verify = 0;
  14255. sigCtx->key.ed448 = (ed448_key*)XMALLOC(
  14256. sizeof(ed448_key), sigCtx->heap,
  14257. DYNAMIC_TYPE_ED448);
  14258. if (sigCtx->key.ed448 == NULL) {
  14259. ERROR_OUT(MEMORY_E, exit_cs);
  14260. }
  14261. if ((ret = wc_ed448_init(sigCtx->key.ed448)) < 0) {
  14262. goto exit_cs;
  14263. }
  14264. if ((ret = wc_ed448_import_public(key, keySz,
  14265. sigCtx->key.ed448)) < 0) {
  14266. WOLFSSL_MSG("ASN Key import error ED448");
  14267. WOLFSSL_ERROR_VERBOSE(ret);
  14268. goto exit_cs;
  14269. }
  14270. #ifdef WOLFSSL_ASYNC_CRYPT
  14271. sigCtx->asyncDev = &sigCtx->key.ed448->asyncDev;
  14272. #endif
  14273. break;
  14274. }
  14275. #endif
  14276. #if defined(HAVE_PQC)
  14277. #if defined(HAVE_FALCON)
  14278. case FALCON_LEVEL1k:
  14279. {
  14280. sigCtx->verify = 0;
  14281. sigCtx->key.falcon =
  14282. (falcon_key*)XMALLOC(sizeof(falcon_key),
  14283. sigCtx->heap,
  14284. DYNAMIC_TYPE_FALCON);
  14285. if (sigCtx->key.falcon == NULL) {
  14286. ERROR_OUT(MEMORY_E, exit_cs);
  14287. }
  14288. if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
  14289. goto exit_cs;
  14290. }
  14291. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 1))
  14292. < 0) {
  14293. goto exit_cs;
  14294. }
  14295. if ((ret = wc_falcon_import_public(key, keySz,
  14296. sigCtx->key.falcon)) < 0) {
  14297. WOLFSSL_MSG("ASN Key import error Falcon Level 1");
  14298. WOLFSSL_ERROR_VERBOSE(ret);
  14299. goto exit_cs;
  14300. }
  14301. break;
  14302. }
  14303. case FALCON_LEVEL5k:
  14304. {
  14305. sigCtx->verify = 0;
  14306. sigCtx->key.falcon =
  14307. (falcon_key*)XMALLOC(sizeof(falcon_key),
  14308. sigCtx->heap,
  14309. DYNAMIC_TYPE_FALCON);
  14310. if (sigCtx->key.falcon == NULL) {
  14311. ERROR_OUT(MEMORY_E, exit_cs);
  14312. }
  14313. if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
  14314. goto exit_cs;
  14315. }
  14316. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 5))
  14317. < 0) {
  14318. goto exit_cs;
  14319. }
  14320. if ((ret = wc_falcon_import_public(key, keySz,
  14321. sigCtx->key.falcon)) < 0) {
  14322. WOLFSSL_MSG("ASN Key import error Falcon Level 5");
  14323. WOLFSSL_ERROR_VERBOSE(ret);
  14324. goto exit_cs;
  14325. }
  14326. break;
  14327. }
  14328. #endif /* HAVE_FALCON */
  14329. #if defined(HAVE_DILITHIUM)
  14330. case DILITHIUM_LEVEL2k:
  14331. {
  14332. sigCtx->verify = 0;
  14333. sigCtx->key.dilithium =
  14334. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14335. sigCtx->heap,
  14336. DYNAMIC_TYPE_DILITHIUM);
  14337. if (sigCtx->key.dilithium == NULL) {
  14338. ERROR_OUT(MEMORY_E, exit_cs);
  14339. }
  14340. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14341. goto exit_cs;
  14342. }
  14343. if ((ret = wc_dilithium_set_level_and_sym(
  14344. sigCtx->key.dilithium, 2, SHAKE_VARIANT))
  14345. < 0) {
  14346. goto exit_cs;
  14347. }
  14348. if ((ret = wc_dilithium_import_public(key, keySz,
  14349. sigCtx->key.dilithium)) < 0) {
  14350. WOLFSSL_MSG("ASN Key import error Dilithium Level 2");
  14351. goto exit_cs;
  14352. }
  14353. break;
  14354. }
  14355. case DILITHIUM_LEVEL3k:
  14356. {
  14357. sigCtx->verify = 0;
  14358. sigCtx->key.dilithium =
  14359. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14360. sigCtx->heap,
  14361. DYNAMIC_TYPE_DILITHIUM);
  14362. if (sigCtx->key.dilithium == NULL) {
  14363. ERROR_OUT(MEMORY_E, exit_cs);
  14364. }
  14365. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14366. goto exit_cs;
  14367. }
  14368. if ((ret = wc_dilithium_set_level_and_sym(
  14369. sigCtx->key.dilithium, 3, SHAKE_VARIANT))
  14370. < 0) {
  14371. goto exit_cs;
  14372. }
  14373. if ((ret = wc_dilithium_import_public(key, keySz,
  14374. sigCtx->key.dilithium)) < 0) {
  14375. WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
  14376. goto exit_cs;
  14377. }
  14378. break;
  14379. }
  14380. case DILITHIUM_LEVEL5k:
  14381. {
  14382. sigCtx->verify = 0;
  14383. sigCtx->key.dilithium =
  14384. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14385. sigCtx->heap,
  14386. DYNAMIC_TYPE_DILITHIUM);
  14387. if (sigCtx->key.dilithium == NULL) {
  14388. ERROR_OUT(MEMORY_E, exit_cs);
  14389. }
  14390. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14391. goto exit_cs;
  14392. }
  14393. if ((ret = wc_dilithium_set_level_and_sym(
  14394. sigCtx->key.dilithium, 5, SHAKE_VARIANT))
  14395. < 0) {
  14396. goto exit_cs;
  14397. }
  14398. if ((ret = wc_dilithium_import_public(key, keySz,
  14399. sigCtx->key.dilithium)) < 0) {
  14400. WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
  14401. goto exit_cs;
  14402. }
  14403. break;
  14404. }
  14405. case DILITHIUM_AES_LEVEL2k:
  14406. {
  14407. sigCtx->verify = 0;
  14408. sigCtx->key.dilithium =
  14409. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14410. sigCtx->heap,
  14411. DYNAMIC_TYPE_DILITHIUM);
  14412. if (sigCtx->key.dilithium == NULL) {
  14413. ERROR_OUT(MEMORY_E, exit_cs);
  14414. }
  14415. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14416. goto exit_cs;
  14417. }
  14418. if ((ret = wc_dilithium_set_level_and_sym(
  14419. sigCtx->key.dilithium, 2, AES_VARIANT))
  14420. < 0) {
  14421. goto exit_cs;
  14422. }
  14423. if ((ret = wc_dilithium_import_public(key, keySz,
  14424. sigCtx->key.dilithium)) < 0) {
  14425. WOLFSSL_MSG("ASN Key import error Dilithium Level 2");
  14426. goto exit_cs;
  14427. }
  14428. break;
  14429. }
  14430. case DILITHIUM_AES_LEVEL3k:
  14431. {
  14432. sigCtx->verify = 0;
  14433. sigCtx->key.dilithium =
  14434. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14435. sigCtx->heap,
  14436. DYNAMIC_TYPE_DILITHIUM);
  14437. if (sigCtx->key.dilithium == NULL) {
  14438. ERROR_OUT(MEMORY_E, exit_cs);
  14439. }
  14440. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14441. goto exit_cs;
  14442. }
  14443. if ((ret = wc_dilithium_set_level_and_sym(
  14444. sigCtx->key.dilithium, 3, AES_VARIANT))
  14445. < 0) {
  14446. goto exit_cs;
  14447. }
  14448. if ((ret = wc_dilithium_import_public(key, keySz,
  14449. sigCtx->key.dilithium)) < 0) {
  14450. WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
  14451. goto exit_cs;
  14452. }
  14453. break;
  14454. }
  14455. case DILITHIUM_AES_LEVEL5k:
  14456. {
  14457. sigCtx->verify = 0;
  14458. sigCtx->key.dilithium =
  14459. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14460. sigCtx->heap,
  14461. DYNAMIC_TYPE_DILITHIUM);
  14462. if (sigCtx->key.dilithium == NULL) {
  14463. ERROR_OUT(MEMORY_E, exit_cs);
  14464. }
  14465. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14466. goto exit_cs;
  14467. }
  14468. if ((ret = wc_dilithium_set_level_and_sym(
  14469. sigCtx->key.dilithium, 5, AES_VARIANT))
  14470. < 0) {
  14471. goto exit_cs;
  14472. }
  14473. if ((ret = wc_dilithium_import_public(key, keySz,
  14474. sigCtx->key.dilithium)) < 0) {
  14475. WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
  14476. goto exit_cs;
  14477. }
  14478. break;
  14479. }
  14480. #endif /* HAVE_DILITHIUM */
  14481. #if defined(HAVE_SPHINCS)
  14482. case SPHINCS_FAST_LEVEL1k:
  14483. {
  14484. sigCtx->verify = 0;
  14485. sigCtx->key.sphincs =
  14486. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14487. sigCtx->heap,
  14488. DYNAMIC_TYPE_SPHINCS);
  14489. if (sigCtx->key.sphincs == NULL) {
  14490. ERROR_OUT(MEMORY_E, exit_cs);
  14491. }
  14492. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14493. goto exit_cs;
  14494. }
  14495. if ((ret = wc_sphincs_set_level_and_optim(
  14496. sigCtx->key.sphincs, 1, FAST_VARIANT))
  14497. < 0) {
  14498. goto exit_cs;
  14499. }
  14500. if ((ret = wc_sphincs_import_public(key, keySz,
  14501. sigCtx->key.sphincs)) < 0) {
  14502. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
  14503. goto exit_cs;
  14504. }
  14505. break;
  14506. }
  14507. case SPHINCS_FAST_LEVEL3k:
  14508. {
  14509. sigCtx->verify = 0;
  14510. sigCtx->key.sphincs =
  14511. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14512. sigCtx->heap,
  14513. DYNAMIC_TYPE_SPHINCS);
  14514. if (sigCtx->key.sphincs == NULL) {
  14515. ERROR_OUT(MEMORY_E, exit_cs);
  14516. }
  14517. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14518. goto exit_cs;
  14519. }
  14520. if ((ret = wc_sphincs_set_level_and_optim(
  14521. sigCtx->key.sphincs, 3, FAST_VARIANT))
  14522. < 0) {
  14523. goto exit_cs;
  14524. }
  14525. if ((ret = wc_sphincs_import_public(key, keySz,
  14526. sigCtx->key.sphincs)) < 0) {
  14527. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
  14528. goto exit_cs;
  14529. }
  14530. break;
  14531. }
  14532. case SPHINCS_FAST_LEVEL5k:
  14533. {
  14534. sigCtx->verify = 0;
  14535. sigCtx->key.sphincs =
  14536. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14537. sigCtx->heap,
  14538. DYNAMIC_TYPE_SPHINCS);
  14539. if (sigCtx->key.sphincs == NULL) {
  14540. ERROR_OUT(MEMORY_E, exit_cs);
  14541. }
  14542. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14543. goto exit_cs;
  14544. }
  14545. if ((ret = wc_sphincs_set_level_and_optim(
  14546. sigCtx->key.sphincs, 5, FAST_VARIANT))
  14547. < 0) {
  14548. goto exit_cs;
  14549. }
  14550. if ((ret = wc_sphincs_import_public(key, keySz,
  14551. sigCtx->key.sphincs)) < 0) {
  14552. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
  14553. goto exit_cs;
  14554. }
  14555. break;
  14556. }
  14557. case SPHINCS_SMALL_LEVEL1k:
  14558. {
  14559. sigCtx->verify = 0;
  14560. sigCtx->key.sphincs =
  14561. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14562. sigCtx->heap,
  14563. DYNAMIC_TYPE_SPHINCS);
  14564. if (sigCtx->key.sphincs == NULL) {
  14565. ERROR_OUT(MEMORY_E, exit_cs);
  14566. }
  14567. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14568. goto exit_cs;
  14569. }
  14570. if ((ret = wc_sphincs_set_level_and_optim(
  14571. sigCtx->key.sphincs, 1, SMALL_VARIANT))
  14572. < 0) {
  14573. goto exit_cs;
  14574. }
  14575. if ((ret = wc_sphincs_import_public(key, keySz,
  14576. sigCtx->key.sphincs)) < 0) {
  14577. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
  14578. goto exit_cs;
  14579. }
  14580. break;
  14581. }
  14582. case SPHINCS_SMALL_LEVEL3k:
  14583. {
  14584. sigCtx->verify = 0;
  14585. sigCtx->key.sphincs =
  14586. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14587. sigCtx->heap,
  14588. DYNAMIC_TYPE_SPHINCS);
  14589. if (sigCtx->key.sphincs == NULL) {
  14590. ERROR_OUT(MEMORY_E, exit_cs);
  14591. }
  14592. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14593. goto exit_cs;
  14594. }
  14595. if ((ret = wc_sphincs_set_level_and_optim(
  14596. sigCtx->key.sphincs, 3, SMALL_VARIANT))
  14597. < 0) {
  14598. goto exit_cs;
  14599. }
  14600. if ((ret = wc_sphincs_import_public(key, keySz,
  14601. sigCtx->key.sphincs)) < 0) {
  14602. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
  14603. goto exit_cs;
  14604. }
  14605. break;
  14606. }
  14607. case SPHINCS_SMALL_LEVEL5k:
  14608. {
  14609. sigCtx->verify = 0;
  14610. sigCtx->key.sphincs =
  14611. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14612. sigCtx->heap,
  14613. DYNAMIC_TYPE_SPHINCS);
  14614. if (sigCtx->key.sphincs == NULL) {
  14615. ERROR_OUT(MEMORY_E, exit_cs);
  14616. }
  14617. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14618. goto exit_cs;
  14619. }
  14620. if ((ret = wc_sphincs_set_level_and_optim(
  14621. sigCtx->key.sphincs, 5, SMALL_VARIANT))
  14622. < 0) {
  14623. goto exit_cs;
  14624. }
  14625. if ((ret = wc_sphincs_import_public(key, keySz,
  14626. sigCtx->key.sphincs)) < 0) {
  14627. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
  14628. goto exit_cs;
  14629. }
  14630. break;
  14631. }
  14632. #endif /* HAVE_SPHINCS */
  14633. #endif /* HAVE_PQC */
  14634. default:
  14635. WOLFSSL_MSG("Verify Key type unknown");
  14636. ret = ASN_UNKNOWN_OID_E;
  14637. WOLFSSL_ERROR_VERBOSE(ret);
  14638. break;
  14639. } /* switch (keyOID) */
  14640. if (ret != 0) {
  14641. goto exit_cs;
  14642. }
  14643. sigCtx->state = SIG_STATE_DO;
  14644. #ifdef WOLFSSL_ASYNC_CRYPT
  14645. if (sigCtx->devId != INVALID_DEVID && sigCtx->asyncDev && sigCtx->asyncCtx) {
  14646. /* make sure event is initialized */
  14647. WOLF_EVENT* event = &sigCtx->asyncDev->event;
  14648. ret = wolfAsync_EventInit(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL,
  14649. sigCtx->asyncCtx, WC_ASYNC_FLAG_CALL_AGAIN);
  14650. }
  14651. #endif
  14652. } /* SIG_STATE_KEY */
  14653. FALL_THROUGH;
  14654. case SIG_STATE_DO:
  14655. {
  14656. switch (keyOID) {
  14657. #ifndef NO_RSA
  14658. case RSAk:
  14659. #ifdef WC_RSA_PSS
  14660. case RSAPSSk:
  14661. if (sigOID == RSAPSSk) {
  14662. /* TODO: pkCbRsaPss - RSA PSS callback. */
  14663. ret = wc_RsaPSS_VerifyInline_ex(sigCtx->sigCpy, sigSz,
  14664. &sigCtx->out, sigCtx->hash, sigCtx->mgf,
  14665. sigCtx->saltLen, sigCtx->key.rsa);
  14666. }
  14667. else
  14668. #endif
  14669. {
  14670. #if defined(HAVE_PK_CALLBACKS)
  14671. if (sigCtx->pkCbRsa) {
  14672. ret = sigCtx->pkCbRsa(
  14673. sigCtx->sigCpy, sigSz, &sigCtx->out,
  14674. key, keySz,
  14675. sigCtx->pkCtxRsa);
  14676. }
  14677. #if !defined(WOLFSSL_RENESAS_SCEPROTECT) && \
  14678. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  14679. else
  14680. #else
  14681. if (!sigCtx->pkCbRsa || ret == CRYPTOCB_UNAVAILABLE)
  14682. #endif /* WOLFSSL_RENESAS_SCEPROTECT */
  14683. #endif /* HAVE_PK_CALLBACKS */
  14684. {
  14685. ret = wc_RsaSSL_VerifyInline(sigCtx->sigCpy, sigSz,
  14686. &sigCtx->out, sigCtx->key.rsa);
  14687. }
  14688. }
  14689. break;
  14690. #endif /* !NO_RSA */
  14691. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  14692. case DSAk:
  14693. {
  14694. ret = wc_DsaVerify(sigCtx->digest, sigCtx->sigCpy,
  14695. sigCtx->key.dsa, &sigCtx->verify);
  14696. break;
  14697. }
  14698. #endif /* !NO_DSA && !HAVE_SELFTEST */
  14699. #if defined(HAVE_ECC)
  14700. case ECDSAk:
  14701. {
  14702. #if defined(HAVE_PK_CALLBACKS)
  14703. if (sigCtx->pkCbEcc) {
  14704. ret = sigCtx->pkCbEcc(
  14705. sig, sigSz,
  14706. sigCtx->digest, sigCtx->digestSz,
  14707. key, keySz, &sigCtx->verify,
  14708. sigCtx->pkCtxEcc);
  14709. }
  14710. #if !defined(WOLFSSL_RENESAS_SCEPROTECT) && \
  14711. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  14712. else
  14713. #else
  14714. if (!sigCtx->pkCbEcc || ret == CRYPTOCB_UNAVAILABLE)
  14715. #endif /* WOLFSSL_RENESAS_SCEPROTECT */
  14716. #endif /* HAVE_PK_CALLBACKS */
  14717. {
  14718. ret = wc_ecc_verify_hash(sig, sigSz, sigCtx->digest,
  14719. sigCtx->digestSz, &sigCtx->verify,
  14720. sigCtx->key.ecc);
  14721. }
  14722. break;
  14723. }
  14724. #endif /* HAVE_ECC */
  14725. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_VERIFY)
  14726. case ED25519k:
  14727. {
  14728. ret = wc_ed25519_verify_msg(sig, sigSz, buf, bufSz,
  14729. &sigCtx->verify, sigCtx->key.ed25519);
  14730. break;
  14731. }
  14732. #endif
  14733. #if defined(HAVE_ED448) && defined(HAVE_ED448_VERIFY)
  14734. case ED448k:
  14735. {
  14736. ret = wc_ed448_verify_msg(sig, sigSz, buf, bufSz,
  14737. &sigCtx->verify, sigCtx->key.ed448,
  14738. NULL, 0);
  14739. break;
  14740. }
  14741. #endif
  14742. #if defined(HAVE_PQC)
  14743. #if defined(HAVE_FALCON)
  14744. case FALCON_LEVEL1k:
  14745. case FALCON_LEVEL5k:
  14746. {
  14747. ret = wc_falcon_verify_msg(sig, sigSz, buf, bufSz,
  14748. &sigCtx->verify,
  14749. sigCtx->key.falcon);
  14750. break;
  14751. }
  14752. #endif /* HAVE_FALCON */
  14753. #if defined(HAVE_DILITHIUM)
  14754. case DILITHIUM_LEVEL2k:
  14755. case DILITHIUM_LEVEL3k:
  14756. case DILITHIUM_LEVEL5k:
  14757. case DILITHIUM_AES_LEVEL2k:
  14758. case DILITHIUM_AES_LEVEL3k:
  14759. case DILITHIUM_AES_LEVEL5k:
  14760. {
  14761. ret = wc_dilithium_verify_msg(sig, sigSz, buf, bufSz,
  14762. &sigCtx->verify,
  14763. sigCtx->key.dilithium);
  14764. break;
  14765. }
  14766. #endif /* HAVE_DILITHIUM */
  14767. #if defined(HAVE_SPHINCS)
  14768. case SPHINCS_FAST_LEVEL1k:
  14769. case SPHINCS_FAST_LEVEL3k:
  14770. case SPHINCS_FAST_LEVEL5k:
  14771. case SPHINCS_SMALL_LEVEL1k:
  14772. case SPHINCS_SMALL_LEVEL3k:
  14773. case SPHINCS_SMALL_LEVEL5k:
  14774. {
  14775. ret = wc_sphincs_verify_msg(sig, sigSz, buf, bufSz,
  14776. &sigCtx->verify,
  14777. sigCtx->key.sphincs);
  14778. break;
  14779. }
  14780. #endif /* HAVE_SPHINCS */
  14781. #endif /* HAVE_PQC */
  14782. default:
  14783. break;
  14784. } /* switch (keyOID) */
  14785. #ifdef WOLFSSL_ASYNC_CRYPT
  14786. if (ret == WC_PENDING_E) {
  14787. goto exit_cs;
  14788. }
  14789. #endif
  14790. if (ret < 0) {
  14791. /* treat all errors as ASN_SIG_CONFIRM_E */
  14792. ret = ASN_SIG_CONFIRM_E;
  14793. WOLFSSL_ERROR_VERBOSE(ret);
  14794. goto exit_cs;
  14795. }
  14796. sigCtx->state = SIG_STATE_CHECK;
  14797. } /* SIG_STATE_DO */
  14798. FALL_THROUGH;
  14799. case SIG_STATE_CHECK:
  14800. {
  14801. switch (keyOID) {
  14802. #ifndef NO_RSA
  14803. case RSAk:
  14804. #ifdef WC_RSA_PSS
  14805. case RSAPSSk:
  14806. if (sigOID == RSAPSSk) {
  14807. #if (defined(HAVE_SELFTEST) && \
  14808. (!defined(HAVE_SELFTEST_VERSION) || \
  14809. (HAVE_SELFTEST_VERSION < 2))) || \
  14810. (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  14811. (HAVE_FIPS_VERSION < 2))
  14812. ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
  14813. sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
  14814. sigCtx->saltLen);
  14815. #elif (defined(HAVE_SELFTEST) && \
  14816. (HAVE_SELFTEST_VERSION == 2)) || \
  14817. (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  14818. (HAVE_FIPS_VERSION == 2))
  14819. ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
  14820. sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
  14821. sigCtx->saltLen, 0);
  14822. #else
  14823. ret = wc_RsaPSS_CheckPadding_ex2(sigCtx->digest,
  14824. sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
  14825. sigCtx->saltLen, wc_RsaEncryptSize(sigCtx->key.rsa) * 8,
  14826. sigCtx->heap);
  14827. #endif
  14828. break;
  14829. }
  14830. else
  14831. #endif
  14832. {
  14833. int encodedSigSz, verifySz;
  14834. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || \
  14835. defined(WOLFSSL_RENESAS_SCEPROTECT)
  14836. if (sigCtx->CertAtt.verifyByTSIP_SCE == 1) break;
  14837. #endif
  14838. #ifdef WOLFSSL_SMALL_STACK
  14839. byte* encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  14840. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14841. if (encodedSig == NULL) {
  14842. ERROR_OUT(MEMORY_E, exit_cs);
  14843. }
  14844. #else
  14845. byte encodedSig[MAX_ENCODED_SIG_SZ];
  14846. #endif
  14847. verifySz = ret;
  14848. /* make sure we're right justified */
  14849. encodedSigSz = wc_EncodeSignature(encodedSig,
  14850. sigCtx->digest, sigCtx->digestSz, sigCtx->typeH);
  14851. if (encodedSigSz == verifySz && sigCtx->out != NULL &&
  14852. XMEMCMP(sigCtx->out, encodedSig, encodedSigSz) == 0) {
  14853. ret = 0;
  14854. }
  14855. else {
  14856. WOLFSSL_MSG("RSA SSL verify match encode error");
  14857. ret = ASN_SIG_CONFIRM_E;
  14858. WOLFSSL_ERROR_VERBOSE(ret);
  14859. }
  14860. #ifdef WOLFSSL_SMALL_STACK
  14861. XFREE(encodedSig, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14862. #endif
  14863. break;
  14864. }
  14865. #endif /* NO_RSA */
  14866. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  14867. case DSAk:
  14868. {
  14869. if (sigCtx->verify == 1) {
  14870. ret = 0;
  14871. }
  14872. else {
  14873. WOLFSSL_MSG("DSA Verify didn't match");
  14874. ret = ASN_SIG_CONFIRM_E;
  14875. WOLFSSL_ERROR_VERBOSE(ret);
  14876. }
  14877. break;
  14878. }
  14879. #endif /* !NO_DSA && !HAVE_SELFTEST */
  14880. #ifdef HAVE_ECC
  14881. case ECDSAk:
  14882. {
  14883. if (sigCtx->verify == 1) {
  14884. ret = 0;
  14885. }
  14886. else {
  14887. WOLFSSL_MSG("ECC Verify didn't match");
  14888. ret = ASN_SIG_CONFIRM_E;
  14889. WOLFSSL_ERROR_VERBOSE(ret);
  14890. }
  14891. break;
  14892. }
  14893. #endif /* HAVE_ECC */
  14894. #ifdef HAVE_ED25519
  14895. case ED25519k:
  14896. {
  14897. if (sigCtx->verify == 1) {
  14898. ret = 0;
  14899. }
  14900. else {
  14901. WOLFSSL_MSG("ED25519 Verify didn't match");
  14902. ret = ASN_SIG_CONFIRM_E;
  14903. WOLFSSL_ERROR_VERBOSE(ret);
  14904. }
  14905. break;
  14906. }
  14907. #endif /* HAVE_ED25519 */
  14908. #ifdef HAVE_ED448
  14909. case ED448k:
  14910. {
  14911. if (sigCtx->verify == 1) {
  14912. ret = 0;
  14913. }
  14914. else {
  14915. WOLFSSL_MSG("ED448 Verify didn't match");
  14916. ret = ASN_SIG_CONFIRM_E;
  14917. WOLFSSL_ERROR_VERBOSE(ret);
  14918. }
  14919. break;
  14920. }
  14921. #endif /* HAVE_ED448 */
  14922. #ifdef HAVE_PQC
  14923. #ifdef HAVE_FALCON
  14924. case FALCON_LEVEL1k:
  14925. {
  14926. if (sigCtx->verify == 1) {
  14927. ret = 0;
  14928. }
  14929. else {
  14930. WOLFSSL_MSG("FALCON_LEVEL1 Verify didn't match");
  14931. ret = ASN_SIG_CONFIRM_E;
  14932. WOLFSSL_ERROR_VERBOSE(ret);
  14933. }
  14934. break;
  14935. }
  14936. case FALCON_LEVEL5k:
  14937. {
  14938. if (sigCtx->verify == 1) {
  14939. ret = 0;
  14940. }
  14941. else {
  14942. WOLFSSL_MSG("FALCON_LEVEL5 Verify didn't match");
  14943. ret = ASN_SIG_CONFIRM_E;
  14944. WOLFSSL_ERROR_VERBOSE(ret);
  14945. }
  14946. break;
  14947. }
  14948. #endif /* HAVE_FALCON */
  14949. #ifdef HAVE_DILITHIUM
  14950. case DILITHIUM_LEVEL2k:
  14951. {
  14952. if (sigCtx->verify == 1) {
  14953. ret = 0;
  14954. }
  14955. else {
  14956. WOLFSSL_MSG("DILITHIUM_LEVEL2 Verify didn't match");
  14957. ret = ASN_SIG_CONFIRM_E;
  14958. }
  14959. break;
  14960. }
  14961. case DILITHIUM_LEVEL3k:
  14962. {
  14963. if (sigCtx->verify == 1) {
  14964. ret = 0;
  14965. }
  14966. else {
  14967. WOLFSSL_MSG("DILITHIUM_LEVEL3 Verify didn't match");
  14968. ret = ASN_SIG_CONFIRM_E;
  14969. }
  14970. break;
  14971. }
  14972. case DILITHIUM_LEVEL5k:
  14973. {
  14974. if (sigCtx->verify == 1) {
  14975. ret = 0;
  14976. }
  14977. else {
  14978. WOLFSSL_MSG("DILITHIUM_LEVEL5 Verify didn't match");
  14979. ret = ASN_SIG_CONFIRM_E;
  14980. }
  14981. break;
  14982. }
  14983. case DILITHIUM_AES_LEVEL2k:
  14984. {
  14985. if (sigCtx->verify == 1) {
  14986. ret = 0;
  14987. }
  14988. else {
  14989. WOLFSSL_MSG("DILITHIUM_AES_LEVEL2 Verify didn't match");
  14990. ret = ASN_SIG_CONFIRM_E;
  14991. }
  14992. break;
  14993. }
  14994. case DILITHIUM_AES_LEVEL3k:
  14995. {
  14996. if (sigCtx->verify == 1) {
  14997. ret = 0;
  14998. }
  14999. else {
  15000. WOLFSSL_MSG("DILITHIUM_AES_LEVEL3 Verify didn't match");
  15001. ret = ASN_SIG_CONFIRM_E;
  15002. }
  15003. break;
  15004. }
  15005. case DILITHIUM_AES_LEVEL5k:
  15006. {
  15007. if (sigCtx->verify == 1) {
  15008. ret = 0;
  15009. }
  15010. else {
  15011. WOLFSSL_MSG("DILITHIUM_AES_LEVEL5 Verify didn't match");
  15012. ret = ASN_SIG_CONFIRM_E;
  15013. }
  15014. break;
  15015. }
  15016. #endif /* HAVE_DILITHIUM */
  15017. #ifdef HAVE_SPHINCS
  15018. case SPHINCS_FAST_LEVEL1k:
  15019. {
  15020. if (sigCtx->verify == 1) {
  15021. ret = 0;
  15022. }
  15023. else {
  15024. WOLFSSL_MSG("SPHINCS_FAST_LEVEL1 Verify didn't match");
  15025. ret = ASN_SIG_CONFIRM_E;
  15026. }
  15027. break;
  15028. }
  15029. case SPHINCS_FAST_LEVEL3k:
  15030. {
  15031. if (sigCtx->verify == 1) {
  15032. ret = 0;
  15033. }
  15034. else {
  15035. WOLFSSL_MSG("SPHINCS_FAST_LEVEL3 Verify didn't match");
  15036. ret = ASN_SIG_CONFIRM_E;
  15037. }
  15038. break;
  15039. }
  15040. case SPHINCS_FAST_LEVEL5k:
  15041. {
  15042. if (sigCtx->verify == 1) {
  15043. ret = 0;
  15044. }
  15045. else {
  15046. WOLFSSL_MSG("SPHINCS_FAST_LEVEL5 Verify didn't match");
  15047. ret = ASN_SIG_CONFIRM_E;
  15048. }
  15049. break;
  15050. }
  15051. case SPHINCS_SMALL_LEVEL1k:
  15052. {
  15053. if (sigCtx->verify == 1) {
  15054. ret = 0;
  15055. }
  15056. else {
  15057. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL1 Verify didn't match");
  15058. ret = ASN_SIG_CONFIRM_E;
  15059. }
  15060. break;
  15061. }
  15062. case SPHINCS_SMALL_LEVEL3k:
  15063. {
  15064. if (sigCtx->verify == 1) {
  15065. ret = 0;
  15066. }
  15067. else {
  15068. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL3 Verify didn't match");
  15069. ret = ASN_SIG_CONFIRM_E;
  15070. }
  15071. break;
  15072. }
  15073. case SPHINCS_SMALL_LEVEL5k:
  15074. {
  15075. if (sigCtx->verify == 1) {
  15076. ret = 0;
  15077. }
  15078. else {
  15079. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL5 Verify didn't match");
  15080. ret = ASN_SIG_CONFIRM_E;
  15081. }
  15082. break;
  15083. }
  15084. #endif /* HAVE_SPHINCS */
  15085. #endif /* HAVE_PQC */
  15086. default:
  15087. break;
  15088. } /* switch (keyOID) */
  15089. break;
  15090. } /* SIG_STATE_CHECK */
  15091. default:
  15092. break;
  15093. } /* switch (sigCtx->state) */
  15094. exit_cs:
  15095. #endif /* !NO_ASN_CRYPT */
  15096. (void)keyOID;
  15097. (void)sigOID;
  15098. WOLFSSL_LEAVE("ConfirmSignature", ret);
  15099. #ifdef WOLFSSL_ASYNC_CRYPT
  15100. if (ret == WC_PENDING_E)
  15101. return ret;
  15102. #endif
  15103. FreeSignatureCtx(sigCtx);
  15104. return ret;
  15105. }
  15106. #ifndef IGNORE_NAME_CONSTRAINTS
  15107. static int MatchBaseName(int type, const char* name, int nameSz,
  15108. const char* base, int baseSz)
  15109. {
  15110. if (base == NULL || baseSz <= 0 || name == NULL || nameSz <= 0 ||
  15111. name[0] == '.' || nameSz < baseSz ||
  15112. (type != ASN_RFC822_TYPE && type != ASN_DNS_TYPE &&
  15113. type != ASN_DIR_TYPE)) {
  15114. return 0;
  15115. }
  15116. if (type == ASN_DIR_TYPE)
  15117. return XMEMCMP(name, base, baseSz) == 0;
  15118. /* If an email type, handle special cases where the base is only
  15119. * a domain, or is an email address itself. */
  15120. if (type == ASN_RFC822_TYPE) {
  15121. const char* p = NULL;
  15122. int count = 0;
  15123. if (base[0] != '.') {
  15124. p = base;
  15125. count = 0;
  15126. /* find the '@' in the base */
  15127. while (*p != '@' && count < baseSz) {
  15128. count++;
  15129. p++;
  15130. }
  15131. /* No '@' in base, reset p to NULL */
  15132. if (count >= baseSz)
  15133. p = NULL;
  15134. }
  15135. if (p == NULL) {
  15136. /* Base isn't an email address, it is a domain name,
  15137. * wind the name forward one character past its '@'. */
  15138. p = name;
  15139. count = 0;
  15140. while (*p != '@' && count < baseSz) {
  15141. count++;
  15142. p++;
  15143. }
  15144. if (count < baseSz && *p == '@') {
  15145. name = p + 1;
  15146. nameSz -= count + 1;
  15147. }
  15148. }
  15149. }
  15150. /* RFC 5280 section 4.2.1.10
  15151. * "...Any DNS name that can be constructed by simply adding zero or more
  15152. * labels to the left-hand side of the name satisfies the name constraint."
  15153. * i.e www.host.example.com works for host.example.com name constraint and
  15154. * host1.example.com does not. */
  15155. if (type == ASN_DNS_TYPE || (type == ASN_RFC822_TYPE && base[0] == '.')) {
  15156. int szAdjust = nameSz - baseSz;
  15157. name += szAdjust;
  15158. nameSz -= szAdjust;
  15159. }
  15160. while (nameSz > 0) {
  15161. if (XTOLOWER((unsigned char)*name++) !=
  15162. XTOLOWER((unsigned char)*base++))
  15163. return 0;
  15164. nameSz--;
  15165. }
  15166. return 1;
  15167. }
  15168. /* Search through the list to find if the name is permitted.
  15169. * name The DNS name to search for
  15170. * dnsList The list to search through
  15171. * nameType Type of DNS name to currently searching
  15172. * return 1 if found in list or if not needed
  15173. * return 0 if not found in the list but is needed
  15174. */
  15175. static int PermittedListOk(DNS_entry* name, Base_entry* dnsList, byte nameType)
  15176. {
  15177. Base_entry* current = dnsList;
  15178. int match = 0;
  15179. int need = 0;
  15180. int ret = 1; /* is ok unless needed and no match found */
  15181. while (current != NULL) {
  15182. if (current->type == nameType) {
  15183. need = 1; /* restriction on permitted names is set for this type */
  15184. if (name->len >= current->nameSz &&
  15185. MatchBaseName(nameType, name->name, name->len,
  15186. current->name, current->nameSz)) {
  15187. match = 1; /* found the current name in the permitted list*/
  15188. break;
  15189. }
  15190. }
  15191. current = current->next;
  15192. }
  15193. /* check if permitted name restriction was set and no matching name found */
  15194. if (need && !match)
  15195. ret = 0;
  15196. return ret;
  15197. }
  15198. /* Search through the list to find if the name is excluded.
  15199. * name The DNS name to search for
  15200. * dnsList The list to search through
  15201. * nameType Type of DNS name to currently searching
  15202. * return 1 if found in list and 0 if not found in the list
  15203. */
  15204. static int IsInExcludedList(DNS_entry* name, Base_entry* dnsList, byte nameType)
  15205. {
  15206. int ret = 0; /* default of not found in the list */
  15207. Base_entry* current = dnsList;
  15208. while (current != NULL) {
  15209. if (current->type == nameType) {
  15210. if (name->len >= current->nameSz &&
  15211. MatchBaseName(nameType, name->name, name->len,
  15212. current->name, current->nameSz)) {
  15213. ret = 1;
  15214. break;
  15215. }
  15216. }
  15217. current = current->next;
  15218. }
  15219. return ret;
  15220. }
  15221. static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert)
  15222. {
  15223. const byte nameTypes[] = {ASN_RFC822_TYPE, ASN_DNS_TYPE, ASN_DIR_TYPE};
  15224. int i;
  15225. if (signer == NULL || cert == NULL)
  15226. return 0;
  15227. if (signer->excludedNames == NULL && signer->permittedNames == NULL)
  15228. return 1;
  15229. for (i=0; i < (int)sizeof(nameTypes); i++) {
  15230. byte nameType = nameTypes[i];
  15231. DNS_entry* name = NULL;
  15232. DNS_entry subjectDnsName; /* temporary node used for subject name */
  15233. XMEMSET(&subjectDnsName, 0, sizeof(DNS_entry));
  15234. switch (nameType) {
  15235. case ASN_DNS_TYPE:
  15236. /* Should it also consider CN in subject? It could use
  15237. * subjectDnsName too */
  15238. name = cert->altNames;
  15239. break;
  15240. case ASN_RFC822_TYPE:
  15241. /* Shouldn't it validade E= in subject as well? */
  15242. name = cert->altEmailNames;
  15243. /* Add subject email for checking. */
  15244. if (cert->subjectEmail != NULL) {
  15245. /* RFC 5280 section 4.2.1.10
  15246. * "When constraints are imposed on the rfc822Name name
  15247. * form, but the certificate does not include a subject
  15248. * alternative name, the rfc822Name constraint MUST be
  15249. * applied to the attribute of type emailAddress in the
  15250. * subject distinguished name" */
  15251. subjectDnsName.next = NULL;
  15252. subjectDnsName.type = ASN_RFC822_TYPE;
  15253. subjectDnsName.len = cert->subjectEmailLen;
  15254. subjectDnsName.name = (char *)cert->subjectEmail;
  15255. }
  15256. break;
  15257. case ASN_DIR_TYPE:
  15258. name = cert->altDirNames;
  15259. #ifndef WOLFSSL_NO_ASN_STRICT
  15260. /* RFC 5280 section 4.2.1.10
  15261. "Restrictions of the form directoryName MUST be
  15262. applied to the subject field .... and to any names
  15263. of type directoryName in the subjectAltName
  15264. extension"
  15265. */
  15266. if (cert->subjectRaw != NULL) {
  15267. subjectDnsName.next = NULL;
  15268. subjectDnsName.type = ASN_DIR_TYPE;
  15269. subjectDnsName.len = cert->subjectRawLen;
  15270. subjectDnsName.name = (char *)cert->subjectRaw;
  15271. }
  15272. #endif
  15273. break;
  15274. default:
  15275. /* Other types of names are ignored for now.
  15276. * Shouldn't it be rejected if it there is a altNamesByType[nameType]
  15277. * and signer->extNameConstraintCrit is set? */
  15278. return 0;
  15279. }
  15280. while (name != NULL) {
  15281. if (IsInExcludedList(name, signer->excludedNames, nameType) == 1) {
  15282. WOLFSSL_MSG("Excluded name was found!");
  15283. return 0;
  15284. }
  15285. /* Check against the permitted list */
  15286. if (PermittedListOk(name, signer->permittedNames, nameType) != 1) {
  15287. WOLFSSL_MSG("Permitted name was not found!");
  15288. return 0;
  15289. }
  15290. name = name->next;
  15291. }
  15292. /* handle comparing against subject name too */
  15293. if (subjectDnsName.len > 0 && subjectDnsName.name != NULL) {
  15294. if (IsInExcludedList(&subjectDnsName, signer->excludedNames,
  15295. nameType) == 1) {
  15296. WOLFSSL_MSG("Excluded name was found!");
  15297. return 0;
  15298. }
  15299. /* Check against the permitted list */
  15300. if (PermittedListOk(&subjectDnsName, signer->permittedNames,
  15301. nameType) != 1) {
  15302. WOLFSSL_MSG("Permitted name was not found!");
  15303. return 0;
  15304. }
  15305. }
  15306. }
  15307. return 1;
  15308. }
  15309. #endif /* IGNORE_NAME_CONSTRAINTS */
  15310. #ifndef WOLFSSL_ASN_TEMPLATE
  15311. static void AddAltName(DecodedCert* cert, DNS_entry* dnsEntry)
  15312. {
  15313. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  15314. dnsEntry->next = NULL;
  15315. if (cert->altNames == NULL) {
  15316. /* First on list */
  15317. cert->altNames = dnsEntry;
  15318. }
  15319. else {
  15320. DNS_entry* temp = cert->altNames;
  15321. /* Find end */
  15322. for (; (temp->next != NULL); temp = temp->next);
  15323. /* Add to end */
  15324. temp->next = dnsEntry;
  15325. }
  15326. #else
  15327. dnsEntry->next = cert->altNames;
  15328. cert->altNames = dnsEntry;
  15329. #endif
  15330. }
  15331. #endif
  15332. #ifdef WOLFSSL_ASN_TEMPLATE
  15333. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
  15334. /* ASN.1 template for OtherName of an X.509 certificate.
  15335. * X.509: RFC 5280, 4.2.1.6 - OtherName (without implicit outer SEQUENCE).
  15336. * HW Name: RFC 4108, 5 - Hardware Module Name
  15337. * Only support HW Name where the type is a HW serial number.
  15338. *
  15339. * Other Names handled for FPKI (Federal PKI) use:
  15340. * UPN (Universal Principal Name), a non-standard Other Name
  15341. * (RFC3280 sec 4.2.1.7). Often used with FIPS 201 smartcard login.
  15342. * FASC-N (Federal Agency Smart Credential Number), defined in the document
  15343. * fpki-x509-cert-policy-common.pdf. Used for a smart card ID.
  15344. */
  15345. static const ASNItem otherNameASN[] = {
  15346. /* TYPEID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  15347. /* VALUE */ { 0, ASN_CONTEXT_SPECIFIC | ASN_OTHERNAME_VALUE, 1, 1, 0 },
  15348. /* UPN */ { 1, ASN_UTF8STRING, 0, 0, 2 },
  15349. /* FASC-N */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
  15350. /* HWN_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 2 },
  15351. /* HWN_TYPE */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  15352. /* HWN_NUM */ { 2, ASN_OCTET_STRING, 0, 0, 0 }
  15353. };
  15354. enum {
  15355. OTHERNAMEASN_IDX_TYPEID = 0,
  15356. OTHERNAMEASN_IDX_VALUE,
  15357. OTHERNAMEASN_IDX_UPN,
  15358. OTHERNAMEASN_IDX_FASCN,
  15359. OTHERNAMEASN_IDX_HWN_SEQ,
  15360. OTHERNAMEASN_IDX_HWN_TYPE,
  15361. OTHERNAMEASN_IDX_HWN_NUM,
  15362. };
  15363. /* Number of items in ASN.1 template for OtherName of an X.509 certificate. */
  15364. #define otherNameASN_Length (sizeof(otherNameASN) / sizeof(ASNItem))
  15365. #ifdef WOLFSSL_SEP
  15366. static int DecodeSEP(ASNGetData* dataASN, DecodedCert* cert)
  15367. {
  15368. int ret = 0;
  15369. word32 oidLen, serialLen;
  15370. oidLen = dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.length;
  15371. serialLen = dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.length;
  15372. /* Allocate space for HW type OID. */
  15373. cert->hwType = (byte*)XMALLOC(oidLen, cert->heap,
  15374. DYNAMIC_TYPE_X509_EXT);
  15375. if (cert->hwType == NULL)
  15376. ret = MEMORY_E;
  15377. if (ret == 0) {
  15378. /* Copy, into cert HW type OID */
  15379. XMEMCPY(cert->hwType,
  15380. dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.data, oidLen);
  15381. cert->hwTypeSz = oidLen;
  15382. /* TODO: check this is the HW serial number OID - no test data. */
  15383. /* Allocate space for HW serial number. */
  15384. cert->hwSerialNum = (byte*)XMALLOC(serialLen, cert->heap,
  15385. DYNAMIC_TYPE_X509_EXT);
  15386. if (cert->hwSerialNum == NULL) {
  15387. WOLFSSL_MSG("\tOut of Memory");
  15388. ret = MEMORY_E;
  15389. }
  15390. }
  15391. if (ret == 0) {
  15392. /* Copy into cert HW serial number. */
  15393. XMEMCPY(cert->hwSerialNum,
  15394. dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.data, serialLen);
  15395. cert->hwSerialNum[serialLen] = '\0';
  15396. cert->hwSerialNumSz = serialLen;
  15397. }
  15398. return ret;
  15399. }
  15400. #endif /* WOLFSSL_SEP */
  15401. #ifdef WOLFSSL_FPKI
  15402. static int DecodeOtherHelper(ASNGetData* dataASN, DecodedCert* cert, int oid)
  15403. {
  15404. DNS_entry* entry = NULL;
  15405. int ret = 0;
  15406. word32 bufLen = 0;
  15407. const char* buf = NULL;
  15408. switch (oid) {
  15409. case FASCN_OID:
  15410. bufLen = dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.length;
  15411. buf = (const char*)dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.data;
  15412. break;
  15413. case UPN_OID:
  15414. bufLen = dataASN[OTHERNAMEASN_IDX_UPN].data.ref.length;
  15415. buf = (const char*)dataASN[OTHERNAMEASN_IDX_UPN].data.ref.data;
  15416. break;
  15417. default:
  15418. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  15419. ret = ASN_UNKNOWN_OID_E;
  15420. break;
  15421. }
  15422. if (ret == 0) {
  15423. ret = SetDNSEntry(cert, buf, bufLen, ASN_OTHER_TYPE, &entry);
  15424. if (ret == 0) {
  15425. entry->oidSum = oid;
  15426. AddDNSEntryToList(&cert->altNames, entry);
  15427. }
  15428. }
  15429. return ret;
  15430. }
  15431. #endif /* WOLFSSL_FPKI */
  15432. /* Decode data with OtherName format from after implicit SEQUENCE.
  15433. *
  15434. * @param [in, out] cert Certificate object.
  15435. * @param [in] input Buffer containing encoded OtherName.
  15436. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  15437. * On out, index after OtherName.
  15438. * @param [in] maxIdx Maximum index of data in buffer.
  15439. * @return 0 on success.
  15440. * @return MEMORY_E on dynamic memory allocation failure.
  15441. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15442. * is invalid.
  15443. * @return ASN_PARSE_E when OID does is not HW Name.
  15444. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15445. * @return BUFFER_E when data in buffer is too small.
  15446. */
  15447. static int DecodeOtherName(DecodedCert* cert, const byte* input,
  15448. word32* inOutIdx, word32 maxIdx)
  15449. {
  15450. DECL_ASNGETDATA(dataASN, otherNameASN_Length);
  15451. int ret = 0;
  15452. CALLOC_ASNGETDATA(dataASN, otherNameASN_Length, ret, cert->heap);
  15453. if (ret == 0) {
  15454. /* Check the first OID is a recognized Alt Cert Name type. */
  15455. GetASN_OID(&dataASN[OTHERNAMEASN_IDX_TYPEID], oidCertAltNameType);
  15456. /* Parse OtherName. */
  15457. ret = GetASN_Items(otherNameASN, dataASN, otherNameASN_Length, 1, input,
  15458. inOutIdx, maxIdx);
  15459. }
  15460. if (ret == 0) {
  15461. /* Ensure expected OID. */
  15462. switch (dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum) {
  15463. #ifdef WOLFSSL_SEP
  15464. case HW_NAME_OID:
  15465. /* Only support HW serial number. */
  15466. GetASN_OID(&dataASN[OTHERNAMEASN_IDX_HWN_TYPE], oidIgnoreType);
  15467. ret = DecodeSEP(dataASN, cert);
  15468. break;
  15469. #endif /* WOLFSSL_SEP */
  15470. #ifdef WOLFSSL_FPKI
  15471. case FASCN_OID:
  15472. case UPN_OID:
  15473. ret = DecodeOtherHelper(dataASN, cert,
  15474. dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum);
  15475. break;
  15476. #endif /* WOLFSSL_FPKI */
  15477. default:
  15478. WOLFSSL_MSG("\tunsupported OID");
  15479. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  15480. ret = ASN_PARSE_E;
  15481. }
  15482. }
  15483. FREE_ASNGETDATA(dataASN, cert->heap);
  15484. return ret;
  15485. }
  15486. #endif /* WOLFSSL_SEP || WOLFSSL_FPKI */
  15487. /* Decode a GeneralName.
  15488. *
  15489. * @param [in] input Buffer containing encoded OtherName.
  15490. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  15491. * On out, index after OtherName.
  15492. * @param [in] len Length of data in buffer.
  15493. * @param [in] cert Decoded certificate object.
  15494. * @return 0 on success.
  15495. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15496. * is invalid.
  15497. * @return BUFFER_E when data in buffer is too small.
  15498. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15499. * @return MEMORY_E when dynamic memory allocation fails.
  15500. */
  15501. static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag,
  15502. int len, DecodedCert* cert)
  15503. {
  15504. int ret = 0;
  15505. word32 idx = *inOutIdx;
  15506. /* GeneralName choice: dnsName */
  15507. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  15508. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_DNS_TYPE,
  15509. &cert->altNames);
  15510. if (ret == 0) {
  15511. idx += len;
  15512. }
  15513. }
  15514. #ifndef IGNORE_NAME_CONSTRAINTS
  15515. /* GeneralName choice: directoryName */
  15516. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  15517. int strLen;
  15518. word32 idxDir = idx;
  15519. /* Expecting a SEQUENCE using up all data. */
  15520. if (GetASN_Sequence(input, &idxDir, &strLen, idx + len, 1) < 0) {
  15521. WOLFSSL_MSG("\tfail: seq length");
  15522. return ASN_PARSE_E;
  15523. }
  15524. ret = SetDNSEntry(cert, (const char*)(input + idxDir), strLen,
  15525. ASN_DIR_TYPE, &cert->altDirNames);
  15526. if (ret == 0) {
  15527. idx += len;
  15528. }
  15529. }
  15530. /* GeneralName choice: rfc822Name */
  15531. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  15532. ret = SetDNSEntry(cert, (const char*)(input + idx), len,
  15533. ASN_RFC822_TYPE, &cert->altEmailNames);
  15534. if (ret == 0) {
  15535. idx += len;
  15536. }
  15537. }
  15538. /* GeneralName choice: uniformResourceIdentifier */
  15539. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  15540. WOLFSSL_MSG("\tPutting URI into list but not using");
  15541. #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
  15542. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  15543. "The name MUST NOT be a relative URI" */
  15544. {
  15545. int i;
  15546. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  15547. for (i = 0; i < len; i++) {
  15548. if (input[idx + i] == ':') {
  15549. break;
  15550. }
  15551. if (input[idx + i] == '/') {
  15552. i = len; /* error, found relative path since '/' was
  15553. * encountered before ':'. Returning error
  15554. * value in next if statement. */
  15555. }
  15556. }
  15557. /* test if no ':' char was found and test that the next two
  15558. * chars are "//" to match the pattern "://" */
  15559. if (i >= len - 2 || (input[idx + i + 1] != '/' ||
  15560. input[idx + i + 2] != '/')) {
  15561. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  15562. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15563. return ASN_ALT_NAME_E;
  15564. }
  15565. }
  15566. #endif
  15567. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_URI_TYPE,
  15568. &cert->altNames);
  15569. if (ret == 0) {
  15570. idx += len;
  15571. }
  15572. }
  15573. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || \
  15574. defined(WOLFSSL_IP_ALT_NAME)
  15575. /* GeneralName choice: iPAddress */
  15576. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  15577. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_IP_TYPE,
  15578. &cert->altNames);
  15579. if (ret == 0) {
  15580. idx += len;
  15581. }
  15582. }
  15583. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  15584. #endif /* IGNORE_NAME_CONSTRAINTS */
  15585. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
  15586. /* GeneralName choice: otherName */
  15587. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
  15588. /* TODO: test data for code path */
  15589. ret = DecodeOtherName(cert, input, &idx, idx + len);
  15590. }
  15591. #endif
  15592. /* GeneralName choice: dNSName, x400Address, ediPartyName,
  15593. * registeredID */
  15594. else {
  15595. WOLFSSL_MSG("\tUnsupported name type, skipping");
  15596. idx += len;
  15597. }
  15598. if (ret == 0) {
  15599. /* Return index of next encoded byte. */
  15600. *inOutIdx = idx;
  15601. }
  15602. return ret;
  15603. }
  15604. /* ASN.1 choices for GeneralName.
  15605. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  15606. */
  15607. static const byte generalNameChoice[] = {
  15608. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0,
  15609. ASN_CONTEXT_SPECIFIC | 1,
  15610. ASN_CONTEXT_SPECIFIC | 2,
  15611. ASN_CONTEXT_SPECIFIC | 3,
  15612. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 4,
  15613. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 5,
  15614. ASN_CONTEXT_SPECIFIC | 6,
  15615. ASN_CONTEXT_SPECIFIC | 7,
  15616. ASN_CONTEXT_SPECIFIC | 8,
  15617. 0
  15618. };
  15619. /* ASN.1 template for GeneralName.
  15620. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  15621. */
  15622. static const ASNItem altNameASN[] = {
  15623. { 0, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 0 }
  15624. };
  15625. enum {
  15626. ALTNAMEASN_IDX_GN = 0,
  15627. };
  15628. /* Number of items in ASN.1 template for GeneralName. */
  15629. #define altNameASN_Length (sizeof(altNameASN) / sizeof(ASNItem))
  15630. #endif /* WOLFSSL_ASN_TEMPLATE */
  15631. #if defined(WOLFSSL_SEP) && !defined(WOLFSSL_ASN_TEMPLATE)
  15632. /* return 0 on success */
  15633. static int DecodeSepHwAltName(DecodedCert* cert, const byte* input,
  15634. word32* idxIn, int sz)
  15635. {
  15636. word32 idx = *idxIn;
  15637. int strLen;
  15638. int ret;
  15639. byte tag;
  15640. /* Certificates issued with this OID in the subject alt name are for
  15641. * verifying signatures created on a module.
  15642. * RFC 4108 Section 5. */
  15643. if (cert->hwType != NULL) {
  15644. WOLFSSL_MSG("\tAlready seen Hardware Module Name");
  15645. return ASN_PARSE_E;
  15646. }
  15647. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  15648. return ASN_PARSE_E;
  15649. }
  15650. if (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  15651. WOLFSSL_MSG("\twrong type");
  15652. return ASN_PARSE_E;
  15653. }
  15654. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15655. WOLFSSL_MSG("\tfail: str len");
  15656. return ASN_PARSE_E;
  15657. }
  15658. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  15659. WOLFSSL_MSG("\tBad Sequence");
  15660. return ASN_PARSE_E;
  15661. }
  15662. ret = GetASNObjectId(input, &idx, &strLen, sz);
  15663. if (ret != 0) {
  15664. WOLFSSL_MSG("\tbad OID");
  15665. return ret;
  15666. }
  15667. cert->hwType = (byte*)XMALLOC(strLen, cert->heap,
  15668. DYNAMIC_TYPE_X509_EXT);
  15669. if (cert->hwType == NULL) {
  15670. WOLFSSL_MSG("\tOut of Memory");
  15671. return MEMORY_E;
  15672. }
  15673. XMEMCPY(cert->hwType, &input[idx], strLen);
  15674. cert->hwTypeSz = strLen;
  15675. idx += strLen;
  15676. ret = GetOctetString(input, &idx, &strLen, sz);
  15677. if (ret < 0) {
  15678. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  15679. cert->hwType = NULL;
  15680. return ret;
  15681. }
  15682. cert->hwSerialNum = (byte*)XMALLOC(strLen + 1, cert->heap,
  15683. DYNAMIC_TYPE_X509_EXT);
  15684. if (cert->hwSerialNum == NULL) {
  15685. WOLFSSL_MSG("\tOut of Memory");
  15686. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  15687. cert->hwType = NULL;
  15688. return MEMORY_E;
  15689. }
  15690. XMEMCPY(cert->hwSerialNum, &input[idx], strLen);
  15691. cert->hwSerialNum[strLen] = '\0';
  15692. cert->hwSerialNumSz = strLen;
  15693. idx += strLen;
  15694. *idxIn = idx;
  15695. return 0;
  15696. }
  15697. #endif /* WOLFSSL_SEP */
  15698. #if !defined(WOLFSSL_ASN_TEMPLATE)
  15699. /* return 0 on success */
  15700. static int DecodeConstructedOtherName(DecodedCert* cert, const byte* input,
  15701. word32* idx, int sz, int oid)
  15702. {
  15703. int ret = 0;
  15704. int strLen = 0;
  15705. byte tag;
  15706. DNS_entry* dnsEntry = NULL;
  15707. if (GetASNTag(input, idx, &tag, sz) < 0) {
  15708. ret = ASN_PARSE_E;
  15709. }
  15710. if (ret == 0 && (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))) {
  15711. ret = ASN_PARSE_E;
  15712. }
  15713. if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
  15714. ret = ASN_PARSE_E;
  15715. }
  15716. if (ret == 0) {
  15717. dnsEntry = AltNameNew(cert->heap);
  15718. if (dnsEntry == NULL) {
  15719. WOLFSSL_MSG("\tOut of Memory");
  15720. return MEMORY_E;
  15721. }
  15722. }
  15723. if (ret == 0) {
  15724. switch (oid) {
  15725. #ifdef WOLFSSL_FPKI
  15726. case FASCN_OID:
  15727. ret = GetOctetString(input, idx, &strLen, sz);
  15728. if (ret > 0) {
  15729. ret = 0;
  15730. }
  15731. break;
  15732. #endif /* WOLFSSL_FPKI */
  15733. case UPN_OID:
  15734. if (GetASNTag(input, idx, &tag, sz) < 0) {
  15735. ret = ASN_PARSE_E;
  15736. }
  15737. if (ret == 0 &&
  15738. tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  15739. tag != ASN_IA5_STRING) {
  15740. WOLFSSL_MSG("Was expecting a string for UPN");
  15741. ret = ASN_PARSE_E;
  15742. }
  15743. if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
  15744. WOLFSSL_MSG("Was expecting a string for UPN");
  15745. ret = ASN_PARSE_E;
  15746. }
  15747. break;
  15748. default:
  15749. WOLFSSL_MSG("Unknown constructed other name, skipping");
  15750. *idx += strLen;
  15751. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15752. dnsEntry = NULL;
  15753. }
  15754. }
  15755. if (ret == 0 && dnsEntry != NULL) {
  15756. dnsEntry->type = ASN_OTHER_TYPE;
  15757. dnsEntry->len = strLen;
  15758. dnsEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  15759. DYNAMIC_TYPE_ALTNAME);
  15760. #ifdef WOLFSSL_FPKI
  15761. dnsEntry->oidSum = oid;
  15762. #endif /* WOLFSSL_FPKI */
  15763. if (dnsEntry->name == NULL) {
  15764. WOLFSSL_MSG("\tOut of Memory");
  15765. ret = MEMORY_E;
  15766. }
  15767. else {
  15768. XMEMCPY(dnsEntry->name, &input[*idx], strLen);
  15769. dnsEntry->name[strLen] = '\0';
  15770. AddAltName(cert, dnsEntry);
  15771. }
  15772. }
  15773. if (ret == 0) {
  15774. *idx += strLen;
  15775. }
  15776. else {
  15777. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15778. }
  15779. return ret;
  15780. }
  15781. #endif
  15782. /* Decode subject alternative names extension.
  15783. *
  15784. * RFC 5280 4.2.1.6. Subject Alternative Name
  15785. *
  15786. * @param [in] input Buffer holding encoded data.
  15787. * @param [in] sz Size of encoded data in bytes.
  15788. * @param [in, out] cert Decoded certificate object.
  15789. * @return 0 on success.
  15790. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15791. * is invalid.
  15792. * @return BUFFER_E when data in buffer is too small.
  15793. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15794. * @return MEMORY_E when dynamic memory allocation fails.
  15795. */
  15796. static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert)
  15797. {
  15798. #ifndef WOLFSSL_ASN_TEMPLATE
  15799. word32 idx = 0;
  15800. int length = 0;
  15801. WOLFSSL_ENTER("DecodeAltNames");
  15802. if (GetSequence(input, &idx, &length, sz) < 0) {
  15803. WOLFSSL_MSG("\tBad Sequence");
  15804. return ASN_PARSE_E;
  15805. }
  15806. if (length == 0) {
  15807. /* RFC 5280 4.2.1.6. Subject Alternative Name
  15808. If the subjectAltName extension is present, the sequence MUST
  15809. contain at least one entry. */
  15810. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  15811. return ASN_PARSE_E;
  15812. }
  15813. #ifdef OPENSSL_ALL
  15814. cert->extSubjAltNameSrc = input;
  15815. cert->extSubjAltNameSz = sz;
  15816. #endif
  15817. cert->weOwnAltNames = 1;
  15818. while (length > 0) {
  15819. byte b = input[idx++];
  15820. length--;
  15821. /* Save DNS Type names in the altNames list. */
  15822. /* Save Other Type names in the cert's OidMap */
  15823. if (b == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  15824. DNS_entry* dnsEntry;
  15825. int strLen;
  15826. word32 lenStartIdx = idx;
  15827. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15828. WOLFSSL_MSG("\tfail: str length");
  15829. return ASN_PARSE_E;
  15830. }
  15831. length -= (idx - lenStartIdx);
  15832. dnsEntry = AltNameNew(cert->heap);
  15833. if (dnsEntry == NULL) {
  15834. WOLFSSL_MSG("\tOut of Memory");
  15835. return MEMORY_E;
  15836. }
  15837. dnsEntry->type = ASN_DNS_TYPE;
  15838. dnsEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  15839. DYNAMIC_TYPE_ALTNAME);
  15840. if (dnsEntry->name == NULL) {
  15841. WOLFSSL_MSG("\tOut of Memory");
  15842. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15843. return MEMORY_E;
  15844. }
  15845. dnsEntry->len = strLen;
  15846. XMEMCPY(dnsEntry->name, &input[idx], strLen);
  15847. dnsEntry->name[strLen] = '\0';
  15848. AddAltName(cert, dnsEntry);
  15849. length -= strLen;
  15850. idx += strLen;
  15851. }
  15852. #ifndef IGNORE_NAME_CONSTRAINTS
  15853. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  15854. DNS_entry* dirEntry;
  15855. int strLen;
  15856. word32 lenStartIdx = idx;
  15857. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15858. WOLFSSL_MSG("\tfail: str length");
  15859. return ASN_PARSE_E;
  15860. }
  15861. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  15862. WOLFSSL_MSG("\tfail: seq length");
  15863. return ASN_PARSE_E;
  15864. }
  15865. length -= (idx - lenStartIdx);
  15866. dirEntry = AltNameNew(cert->heap);
  15867. if (dirEntry == NULL) {
  15868. WOLFSSL_MSG("\tOut of Memory");
  15869. return MEMORY_E;
  15870. }
  15871. dirEntry->type = ASN_DIR_TYPE;
  15872. dirEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  15873. DYNAMIC_TYPE_ALTNAME);
  15874. if (dirEntry->name == NULL) {
  15875. WOLFSSL_MSG("\tOut of Memory");
  15876. XFREE(dirEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15877. return MEMORY_E;
  15878. }
  15879. dirEntry->len = strLen;
  15880. XMEMCPY(dirEntry->name, &input[idx], strLen);
  15881. dirEntry->name[strLen] = '\0';
  15882. dirEntry->next = cert->altDirNames;
  15883. cert->altDirNames = dirEntry;
  15884. length -= strLen;
  15885. idx += strLen;
  15886. }
  15887. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  15888. DNS_entry* emailEntry;
  15889. int strLen;
  15890. word32 lenStartIdx = idx;
  15891. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15892. WOLFSSL_MSG("\tfail: str length");
  15893. return ASN_PARSE_E;
  15894. }
  15895. length -= (idx - lenStartIdx);
  15896. emailEntry = AltNameNew(cert->heap);
  15897. if (emailEntry == NULL) {
  15898. WOLFSSL_MSG("\tOut of Memory");
  15899. return MEMORY_E;
  15900. }
  15901. emailEntry->type = ASN_RFC822_TYPE;
  15902. emailEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  15903. DYNAMIC_TYPE_ALTNAME);
  15904. if (emailEntry->name == NULL) {
  15905. WOLFSSL_MSG("\tOut of Memory");
  15906. XFREE(emailEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15907. return MEMORY_E;
  15908. }
  15909. emailEntry->len = strLen;
  15910. XMEMCPY(emailEntry->name, &input[idx], strLen);
  15911. emailEntry->name[strLen] = '\0';
  15912. emailEntry->next = cert->altEmailNames;
  15913. cert->altEmailNames = emailEntry;
  15914. length -= strLen;
  15915. idx += strLen;
  15916. }
  15917. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  15918. DNS_entry* uriEntry;
  15919. int strLen;
  15920. word32 lenStartIdx = idx;
  15921. WOLFSSL_MSG("\tPutting URI into list but not using");
  15922. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15923. WOLFSSL_MSG("\tfail: str length");
  15924. return ASN_PARSE_E;
  15925. }
  15926. length -= (idx - lenStartIdx);
  15927. /* check that strLen at index is not past input buffer */
  15928. if (strLen + (int)idx > sz) {
  15929. return BUFFER_E;
  15930. }
  15931. #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
  15932. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  15933. "The name MUST NOT be a relative URI" */
  15934. {
  15935. int i;
  15936. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  15937. for (i = 0; i < strLen; i++) {
  15938. if (input[idx + i] == ':') {
  15939. break;
  15940. }
  15941. if (input[idx + i] == '/') {
  15942. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  15943. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15944. return ASN_ALT_NAME_E;
  15945. }
  15946. }
  15947. /* test if no ':' char was found and test that the next two
  15948. * chars are "//" to match the pattern "://" */
  15949. if (i >= strLen - 2 || (input[idx + i + 1] != '/' ||
  15950. input[idx + i + 2] != '/')) {
  15951. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  15952. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15953. return ASN_ALT_NAME_E;
  15954. }
  15955. }
  15956. #endif
  15957. uriEntry = AltNameNew(cert->heap);
  15958. if (uriEntry == NULL) {
  15959. WOLFSSL_MSG("\tOut of Memory");
  15960. return MEMORY_E;
  15961. }
  15962. uriEntry->type = ASN_URI_TYPE;
  15963. uriEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  15964. DYNAMIC_TYPE_ALTNAME);
  15965. if (uriEntry->name == NULL) {
  15966. WOLFSSL_MSG("\tOut of Memory");
  15967. XFREE(uriEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15968. return MEMORY_E;
  15969. }
  15970. uriEntry->len = strLen;
  15971. XMEMCPY(uriEntry->name, &input[idx], strLen);
  15972. uriEntry->name[strLen] = '\0';
  15973. AddAltName(cert, uriEntry);
  15974. length -= strLen;
  15975. idx += strLen;
  15976. }
  15977. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  15978. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  15979. DNS_entry* ipAddr;
  15980. int strLen;
  15981. word32 lenStartIdx = idx;
  15982. WOLFSSL_MSG("Decoding Subject Alt. Name: IP Address");
  15983. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15984. WOLFSSL_MSG("\tfail: str length");
  15985. return ASN_PARSE_E;
  15986. }
  15987. length -= (idx - lenStartIdx);
  15988. /* check that strLen at index is not past input buffer */
  15989. if (strLen + (int)idx > sz) {
  15990. return BUFFER_E;
  15991. }
  15992. ipAddr = AltNameNew(cert->heap);
  15993. if (ipAddr == NULL) {
  15994. WOLFSSL_MSG("\tOut of Memory");
  15995. return MEMORY_E;
  15996. }
  15997. ipAddr->type = ASN_IP_TYPE;
  15998. ipAddr->name = (char*)XMALLOC(strLen + 1, cert->heap,
  15999. DYNAMIC_TYPE_ALTNAME);
  16000. if (ipAddr->name == NULL) {
  16001. WOLFSSL_MSG("\tOut of Memory");
  16002. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16003. return MEMORY_E;
  16004. }
  16005. ipAddr->len = strLen;
  16006. XMEMCPY(ipAddr->name, &input[idx], strLen);
  16007. ipAddr->name[strLen] = '\0';
  16008. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  16009. if (GenerateDNSEntryIPString(ipAddr, cert->heap) != 0) {
  16010. WOLFSSL_MSG("\tOut of Memory for IP string");
  16011. XFREE(ipAddr->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16012. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16013. return MEMORY_E;
  16014. }
  16015. #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  16016. AddAltName(cert, ipAddr);
  16017. length -= strLen;
  16018. idx += strLen;
  16019. }
  16020. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  16021. #endif /* IGNORE_NAME_CONSTRAINTS */
  16022. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE))
  16023. {
  16024. int strLen;
  16025. word32 lenStartIdx = idx;
  16026. word32 oid = 0;
  16027. int ret = 0;
  16028. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16029. WOLFSSL_MSG("\tfail: other name length");
  16030. return ASN_PARSE_E;
  16031. }
  16032. /* Consume the rest of this sequence. */
  16033. length -= (strLen + idx - lenStartIdx);
  16034. if (GetObjectId(input, &idx, &oid, oidCertAltNameType, sz) < 0) {
  16035. WOLFSSL_MSG("\tbad OID");
  16036. return ASN_PARSE_E;
  16037. }
  16038. /* handle parsing other type alt names */
  16039. switch (oid) {
  16040. #ifdef WOLFSSL_SEP
  16041. case HW_NAME_OID:
  16042. ret = DecodeSepHwAltName(cert, input, &idx, sz);
  16043. if (ret != 0)
  16044. return ret;
  16045. break;
  16046. #endif /* WOLFSSL_SEP */
  16047. #ifdef WOLFSSL_FPKI
  16048. case FASCN_OID:
  16049. case UPN_OID:
  16050. ret = DecodeConstructedOtherName(cert, input, &idx, sz,
  16051. oid);
  16052. if (ret != 0)
  16053. return ret;
  16054. break;
  16055. #endif /* WOLFSSL_FPKI */
  16056. default:
  16057. WOLFSSL_MSG("\tUnsupported other name type, skipping");
  16058. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16059. /* check to skip constructed other names too */
  16060. if (DecodeConstructedOtherName(cert, input, &idx, sz,
  16061. oid) != 0) {
  16062. WOLFSSL_MSG("\tfail: unsupported other name length");
  16063. return ASN_PARSE_E;
  16064. }
  16065. else {
  16066. /* idx will have been advanced to end of alt name */
  16067. length -= (idx - lenStartIdx);
  16068. }
  16069. }
  16070. else {
  16071. length -= (strLen + idx - lenStartIdx);
  16072. idx += strLen;
  16073. }
  16074. }
  16075. (void)ret;
  16076. }
  16077. else {
  16078. int strLen;
  16079. word32 lenStartIdx = idx;
  16080. WOLFSSL_MSG("\tUnsupported name type, skipping");
  16081. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16082. WOLFSSL_MSG("\tfail: unsupported name length");
  16083. return ASN_PARSE_E;
  16084. }
  16085. length -= (strLen + idx - lenStartIdx);
  16086. idx += strLen;
  16087. }
  16088. }
  16089. return 0;
  16090. #else
  16091. word32 idx = 0;
  16092. int length = 0;
  16093. int ret = 0;
  16094. WOLFSSL_ENTER("DecodeAltNames");
  16095. /* Get SEQUENCE and expect all data to be accounted for. */
  16096. if (GetASN_Sequence(input, &idx, &length, sz, 1) != 0) {
  16097. WOLFSSL_MSG("\tBad Sequence");
  16098. ret = ASN_PARSE_E;
  16099. }
  16100. if ((ret == 0) && (length == 0)) {
  16101. /* RFC 5280 4.2.1.6. Subject Alternative Name
  16102. If the subjectAltName extension is present, the sequence MUST
  16103. contain at least one entry. */
  16104. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16105. ret = ASN_PARSE_E;
  16106. }
  16107. if (ret == 0) {
  16108. #ifdef OPENSSL_ALL
  16109. cert->extSubjAltNameSrc = input;
  16110. cert->extSubjAltNameSz = sz;
  16111. #endif
  16112. cert->weOwnAltNames = 1;
  16113. if (length + (int)idx != sz) {
  16114. ret = ASN_PARSE_E;
  16115. }
  16116. }
  16117. while ((ret == 0) && ((int)idx < sz)) {
  16118. ASNGetData dataASN[altNameASN_Length];
  16119. /* Clear dynamic data items. */
  16120. XMEMSET(dataASN, 0, sizeof(dataASN));
  16121. /* Parse GeneralName with the choices supported. */
  16122. GetASN_Choice(&dataASN[ALTNAMEASN_IDX_GN], generalNameChoice);
  16123. /* Decode a GeneralName choice. */
  16124. ret = GetASN_Items(altNameASN, dataASN, altNameASN_Length, 0, input,
  16125. &idx, sz);
  16126. if (ret == 0) {
  16127. ret = DecodeGeneralName(input, &idx, dataASN[ALTNAMEASN_IDX_GN].tag,
  16128. dataASN[ALTNAMEASN_IDX_GN].length, cert);
  16129. }
  16130. }
  16131. return ret;
  16132. #endif
  16133. }
  16134. #ifdef WOLFSSL_ASN_TEMPLATE
  16135. /* ASN.1 template for BasicContraints.
  16136. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  16137. */
  16138. static const ASNItem basicConsASN[] = {
  16139. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16140. /* CA */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  16141. /* PLEN */ { 1, ASN_INTEGER, 0, 0, 1 }
  16142. };
  16143. enum {
  16144. BASICCONSASN_IDX_SEQ = 0,
  16145. BASICCONSASN_IDX_CA,
  16146. BASICCONSASN_IDX_PLEN,
  16147. };
  16148. /* Number of items in ASN.1 template for BasicContraints. */
  16149. #define basicConsASN_Length (sizeof(basicConsASN) / sizeof(ASNItem))
  16150. #endif
  16151. /* Decode basic constraints extension in a certificate.
  16152. *
  16153. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  16154. *
  16155. * @param [in] input Buffer holding data.
  16156. * @param [in] sz Size of data in buffer.
  16157. * @param [in, out] cert Certificate object.
  16158. * @return 0 on success.
  16159. * @return MEMORY_E on dynamic memory allocation failure.
  16160. * @return ASN_PARSE_E when CA boolean is present and false (default is false).
  16161. * @return ASN_PARSE_E when CA boolean is not present unless
  16162. * WOLFSSL_X509_BASICCONS_INT is defined. Only a CA extension.
  16163. * @return ASN_PARSE_E when path length more than 7 bits.
  16164. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16165. * is invalid.
  16166. * @return BUFFER_E when data in buffer is too small.
  16167. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  16168. * non-zero length.
  16169. */
  16170. static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert)
  16171. {
  16172. #ifndef WOLFSSL_ASN_TEMPLATE
  16173. word32 idx = 0;
  16174. int length = 0;
  16175. int ret;
  16176. WOLFSSL_ENTER("DecodeBasicCaConstraint");
  16177. if (GetSequence(input, &idx, &length, sz) < 0) {
  16178. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  16179. return ASN_PARSE_E;
  16180. }
  16181. if (length == 0)
  16182. return 0;
  16183. /* If the basic ca constraint is false, this extension may be named, but
  16184. * left empty. So, if the length is 0, just return. */
  16185. ret = GetBoolean(input, &idx, sz);
  16186. /* Removed logic for WOLFSSL_X509_BASICCONS_INT which was mistreating the
  16187. * pathlen value as if it were the CA Boolean value 7/2/2021 - KH.
  16188. * When CA Boolean not asserted use the default value "False" */
  16189. if (ret < 0) {
  16190. WOLFSSL_MSG("\tfail: constraint not valid BOOLEAN, set default FALSE");
  16191. ret = 0;
  16192. }
  16193. cert->isCA = (byte)ret;
  16194. /* If there isn't any more data, return. */
  16195. if (idx >= (word32)sz) {
  16196. return 0;
  16197. }
  16198. ret = GetInteger7Bit(input, &idx, sz);
  16199. if (ret < 0)
  16200. return ret;
  16201. cert->pathLength = (byte)ret;
  16202. cert->pathLengthSet = 1;
  16203. return 0;
  16204. #else
  16205. DECL_ASNGETDATA(dataASN, basicConsASN_Length);
  16206. int ret = 0;
  16207. word32 idx = 0;
  16208. byte isCA = 0;
  16209. WOLFSSL_ENTER("DecodeBasicCaConstraints");
  16210. CALLOC_ASNGETDATA(dataASN, basicConsASN_Length, ret, cert->heap);
  16211. if (ret == 0) {
  16212. /* Get the CA boolean and path length when present. */
  16213. GetASN_Boolean(&dataASN[BASICCONSASN_IDX_CA], &isCA);
  16214. GetASN_Int8Bit(&dataASN[BASICCONSASN_IDX_PLEN], &cert->pathLength);
  16215. ret = GetASN_Items(basicConsASN, dataASN, basicConsASN_Length, 1, input,
  16216. &idx, sz);
  16217. }
  16218. /* Empty SEQUENCE is OK - nothing to store. */
  16219. if ((ret == 0) && (dataASN[BASICCONSASN_IDX_SEQ].length != 0)) {
  16220. /* Bad encoding when CA Boolean is false
  16221. * (default when not present). */
  16222. if ((dataASN[BASICCONSASN_IDX_CA].length != 0) && (!isCA)) {
  16223. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16224. ret = ASN_PARSE_E;
  16225. }
  16226. /* Path length must be a 7-bit value. */
  16227. if ((ret == 0) && (cert->pathLength >= (1 << 7))) {
  16228. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16229. ret = ASN_PARSE_E;
  16230. }
  16231. /* Store CA boolean and whether a path length was seen. */
  16232. if (ret == 0) {
  16233. /* isCA in certificate is a 1 bit of a byte. */
  16234. cert->isCA = isCA;
  16235. cert->pathLengthSet = (dataASN[BASICCONSASN_IDX_PLEN].length > 0);
  16236. }
  16237. }
  16238. FREE_ASNGETDATA(dataASN, cert->heap);
  16239. return ret;
  16240. #endif
  16241. }
  16242. static int DecodePolicyConstraints(const byte* input, int sz, DecodedCert* cert)
  16243. {
  16244. word32 idx = 0;
  16245. int length = 0;
  16246. int skipLength = 0;
  16247. int ret;
  16248. byte tag;
  16249. WOLFSSL_ENTER("DecodePolicyConstraints");
  16250. if (GetSequence(input, &idx, &length, sz) < 0) {
  16251. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  16252. return ASN_PARSE_E;
  16253. }
  16254. if (length == 0)
  16255. return ASN_PARSE_E;
  16256. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  16257. WOLFSSL_MSG("\tfail: bad TAG");
  16258. return ASN_PARSE_E;
  16259. }
  16260. if (tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  16261. /* requireExplicitPolicy */
  16262. cert->extPolicyConstRxpSet = 1;
  16263. }
  16264. else if (tag == (ASN_CONTEXT_SPECIFIC | 1)) {
  16265. /* inhibitPolicyMapping */
  16266. cert->extPolicyConstIpmSet = 1;
  16267. }
  16268. else {
  16269. WOLFSSL_MSG("\tfail: invalid TAG");
  16270. return ASN_PARSE_E;
  16271. }
  16272. ret = GetLength(input, &idx, &skipLength, sz);
  16273. if (ret < 0) {
  16274. WOLFSSL_MSG("\tfail: invalid length");
  16275. return ret;
  16276. }
  16277. if (skipLength > 1) {
  16278. WOLFSSL_MSG("\tfail: skip value too big");
  16279. return BUFFER_E;
  16280. }
  16281. if (idx >= (word32)sz) {
  16282. WOLFSSL_MSG("\tfail: no policy const skip to read");
  16283. return BUFFER_E;
  16284. }
  16285. cert->policyConstSkip = input[idx];
  16286. return 0;
  16287. }
  16288. /* Context-Specific value for: DistributionPoint.distributionPoint
  16289. * From RFC5280 SS4.2.1.13, Distribution Point */
  16290. #define DISTRIBUTION_POINT (ASN_CONTEXT_SPECIFIC | 0)
  16291. /* Context-Specific value for: DistributionPoint.DistributionPointName.fullName
  16292. * From RFC3280 SS4.2.1.13, Distribution Point Name */
  16293. #define CRLDP_FULL_NAME (ASN_CONTEXT_SPECIFIC | 0)
  16294. /* Context-Specific value for choice: GeneralName.uniformResourceIdentifier
  16295. * From RFC3280 SS4.2.1.7, GeneralName */
  16296. #define GENERALNAME_URI (ASN_CONTEXT_SPECIFIC | 6)
  16297. #ifdef WOLFSSL_ASN_TEMPLATE
  16298. /* ASN.1 template for CRL distribution points.
  16299. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  16300. */
  16301. static const ASNItem crlDistASN[] = {
  16302. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16303. /* DP_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  16304. /* Distribution point name */
  16305. /* DP_DISTPOINT */ { 2, DISTRIBUTION_POINT, 1, 1, 1 },
  16306. /* fullName */
  16307. /* DP_DISTPOINT_FN */ { 3, CRLDP_FULL_NAME, 1, 1, 2 },
  16308. /* DP_DISTPOINT_FN_GN */ { 4, GENERALNAME_URI, 0, 0, 0 },
  16309. /* nameRelativeToCRLIssuer */
  16310. /* DP_DISTPOINT_RN */ { 3, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  16311. /* reasons: IMPLICIT BIT STRING */
  16312. /* DP_REASONS */ { 2, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  16313. /* cRLIssuer */
  16314. /* DP_CRLISSUER */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 1 },
  16315. };
  16316. enum {
  16317. CRLDISTASN_IDX_SEQ = 0,
  16318. CRLDISTASN_IDX_DP_SEQ,
  16319. CRLDISTASN_IDX_DP_DISTPOINT,
  16320. CRLDISTASN_IDX_DP_DISTPOINT_FN,
  16321. CRLDISTASN_IDX_DP_DISTPOINT_FN_GN,
  16322. CRLDISTASN_IDX_DP_DISTPOINT_RN, /* Relative name */
  16323. CRLDISTASN_IDX_DP_REASONS,
  16324. CRLDISTASN_IDX_DP_CRLISSUER,
  16325. };
  16326. /* Number of items in ASN.1 template for CRL distribution points. */
  16327. #define crlDistASN_Length (sizeof(crlDistASN) / sizeof(ASNItem))
  16328. #endif
  16329. /* Decode CRL distribution point extension in a certificate.
  16330. *
  16331. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  16332. *
  16333. * @param [in] input Buffer holding data.
  16334. * @param [in] sz Size of data in buffer.
  16335. * @param [in, out] cert Certificate object.
  16336. * @return 0 on success.
  16337. * @return MEMORY_E on dynamic memory allocation failure.
  16338. * @return ASN_PARSE_E when invalid bits of reason are set.
  16339. * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
  16340. * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
  16341. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16342. * is invalid.
  16343. * @return BUFFER_E when data in buffer is too small.
  16344. */
  16345. static int DecodeCrlDist(const byte* input, int sz, DecodedCert* cert)
  16346. {
  16347. #ifndef WOLFSSL_ASN_TEMPLATE
  16348. word32 idx = 0, localIdx;
  16349. int length = 0;
  16350. byte tag = 0;
  16351. WOLFSSL_ENTER("DecodeCrlDist");
  16352. cert->extCrlInfoRaw = input;
  16353. cert->extCrlInfoRawSz = sz;
  16354. /* Unwrap the list of Distribution Points*/
  16355. if (GetSequence(input, &idx, &length, sz) < 0)
  16356. return ASN_PARSE_E;
  16357. /* Unwrap a single Distribution Point */
  16358. if (GetSequence(input, &idx, &length, sz) < 0)
  16359. return ASN_PARSE_E;
  16360. /* The Distribution Point has three explicit optional members
  16361. * First check for a DistributionPointName
  16362. */
  16363. localIdx = idx;
  16364. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16365. tag == (ASN_CONSTRUCTED | DISTRIBUTION_POINT))
  16366. {
  16367. idx++;
  16368. if (GetLength(input, &idx, &length, sz) < 0)
  16369. return ASN_PARSE_E;
  16370. localIdx = idx;
  16371. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16372. tag == (ASN_CONSTRUCTED | CRLDP_FULL_NAME))
  16373. {
  16374. idx++;
  16375. if (GetLength(input, &idx, &length, sz) < 0)
  16376. return ASN_PARSE_E;
  16377. localIdx = idx;
  16378. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16379. tag == GENERALNAME_URI)
  16380. {
  16381. idx++;
  16382. if (GetLength(input, &idx, &length, sz) < 0)
  16383. return ASN_PARSE_E;
  16384. cert->extCrlInfoSz = length;
  16385. cert->extCrlInfo = input + idx;
  16386. idx += length;
  16387. }
  16388. else
  16389. /* This isn't a URI, skip it. */
  16390. idx += length;
  16391. }
  16392. else {
  16393. /* This isn't a FULLNAME, skip it. */
  16394. idx += length;
  16395. }
  16396. }
  16397. /* Check for reasonFlags */
  16398. localIdx = idx;
  16399. if (idx < (word32)sz &&
  16400. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16401. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  16402. {
  16403. idx++;
  16404. if (GetLength(input, &idx, &length, sz) < 0)
  16405. return ASN_PARSE_E;
  16406. idx += length;
  16407. }
  16408. /* Check for cRLIssuer */
  16409. localIdx = idx;
  16410. if (idx < (word32)sz &&
  16411. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16412. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
  16413. {
  16414. idx++;
  16415. if (GetLength(input, &idx, &length, sz) < 0)
  16416. return ASN_PARSE_E;
  16417. idx += length;
  16418. }
  16419. if (idx < (word32)sz)
  16420. {
  16421. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  16422. "but we only use the first one.");
  16423. }
  16424. return 0;
  16425. #else
  16426. DECL_ASNGETDATA(dataASN, crlDistASN_Length);
  16427. word32 idx = 0;
  16428. int ret = 0;
  16429. #ifdef CRLDP_VALIDATE_DATA
  16430. word16 reason;
  16431. #endif
  16432. WOLFSSL_ENTER("DecodeCrlDist");
  16433. CALLOC_ASNGETDATA(dataASN, crlDistASN_Length, ret, cert->heap);
  16434. cert->extCrlInfoRaw = input;
  16435. cert->extCrlInfoRawSz = sz;
  16436. if (ret == 0) {
  16437. /* Get the GeneralName choice */
  16438. GetASN_Choice(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN], generalNameChoice);
  16439. /* Parse CRL distribtion point. */
  16440. ret = GetASN_Items(crlDistASN, dataASN, crlDistASN_Length, 0, input,
  16441. &idx, sz);
  16442. }
  16443. if (ret == 0) {
  16444. /* If the choice was a URI, store it in certificate. */
  16445. if (dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN].tag == GENERALNAME_URI) {
  16446. word32 sz32;
  16447. GetASN_GetConstRef(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN],
  16448. &cert->extCrlInfo, &sz32);
  16449. cert->extCrlInfoSz = sz32;
  16450. }
  16451. #ifdef CRLDP_VALIDATE_DATA
  16452. if (dataASN[CRLDISTASN_IDX_DP_REASONS].data.ref.data != NULL) {
  16453. /* TODO: test case */
  16454. /* Validate ReasonFlags. */
  16455. ret = GetASN_BitString_Int16Bit(&dataASN[CRLDISTASN_IDX_DP_REASONS],
  16456. &reason);
  16457. /* First bit (LSB) unused and eight other bits defined. */
  16458. if ((ret == 0) && ((reason >> 9) || (reason & 0x01))) {
  16459. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16460. ret = ASN_PARSE_E;
  16461. }
  16462. }
  16463. #endif
  16464. }
  16465. /* Only parsing the first one. */
  16466. if (ret == 0 && idx < (word32)sz) {
  16467. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  16468. "but we only use the first one.");
  16469. }
  16470. /* TODO: validate other points. */
  16471. FREE_ASNGETDATA(dataASN, cert->heap);
  16472. return ret;
  16473. #endif /* WOLFSSL_ASN_TEMPLATE */
  16474. }
  16475. #ifdef WOLFSSL_ASN_TEMPLATE
  16476. /* ASN.1 template for the access description.
  16477. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16478. */
  16479. static const ASNItem accessDescASN[] = {
  16480. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16481. /* accessMethod */
  16482. /* METH */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  16483. /* accessLocation: GeneralName */
  16484. /* LOC */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  16485. };
  16486. enum {
  16487. ACCESSDESCASN_IDX_SEQ = 0,
  16488. ACCESSDESCASN_IDX_METH,
  16489. ACCESSDESCASN_IDX_LOC,
  16490. };
  16491. /* Number of items in ASN.1 template for the access description. */
  16492. #define accessDescASN_Length (sizeof(accessDescASN) / sizeof(ASNItem))
  16493. #endif
  16494. /* Decode authority information access extension in a certificate.
  16495. *
  16496. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16497. *
  16498. * @param [in] input Buffer holding data.
  16499. * @param [in] sz Size of data in buffer.
  16500. * @param [in, out] cert Certificate object.
  16501. * @return 0 on success.
  16502. * @return MEMORY_E on dynamic memory allocation failure.
  16503. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16504. * is invalid.
  16505. * @return BUFFER_E when data in buffer is too small.
  16506. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  16507. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  16508. */
  16509. static int DecodeAuthInfo(const byte* input, int sz, DecodedCert* cert)
  16510. {
  16511. #ifndef WOLFSSL_ASN_TEMPLATE
  16512. word32 idx = 0;
  16513. int length = 0;
  16514. int count = 0;
  16515. byte b = 0;
  16516. word32 oid;
  16517. WOLFSSL_ENTER("DecodeAuthInfo");
  16518. /* Unwrap the list of AIAs */
  16519. if (GetSequence(input, &idx, &length, sz) < 0)
  16520. return ASN_PARSE_E;
  16521. while ((idx < (word32)sz) && (count < MAX_AIA_SZ)) {
  16522. /* Unwrap a single AIA */
  16523. if (GetSequence(input, &idx, &length, sz) < 0)
  16524. return ASN_PARSE_E;
  16525. oid = 0;
  16526. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0) {
  16527. return ASN_PARSE_E;
  16528. }
  16529. /* Only supporting URIs right now. */
  16530. if (GetASNTag(input, &idx, &b, sz) < 0)
  16531. return ASN_PARSE_E;
  16532. if (GetLength(input, &idx, &length, sz) < 0)
  16533. return ASN_PARSE_E;
  16534. /* Set ocsp entry */
  16535. if (b == GENERALNAME_URI && oid == AIA_OCSP_OID)
  16536. {
  16537. cert->extAuthInfoSz = length;
  16538. cert->extAuthInfo = input + idx;
  16539. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16540. count++;
  16541. #else
  16542. break;
  16543. #endif
  16544. }
  16545. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16546. /* Set CaIssuers entry */
  16547. else if ((b == GENERALNAME_URI) && oid == AIA_CA_ISSUER_OID)
  16548. {
  16549. cert->extAuthInfoCaIssuerSz = length;
  16550. cert->extAuthInfoCaIssuer = input + idx;
  16551. count++;
  16552. }
  16553. #endif
  16554. idx += length;
  16555. }
  16556. return 0;
  16557. #else
  16558. word32 idx = 0;
  16559. int length = 0;
  16560. int count = 0;
  16561. int ret = 0;
  16562. WOLFSSL_ENTER("DecodeAuthInfo");
  16563. /* Unwrap the list of AIAs */
  16564. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  16565. ret = ASN_PARSE_E;
  16566. }
  16567. while ((ret == 0) && (idx < (word32)sz) && (count < MAX_AIA_SZ)) {
  16568. ASNGetData dataASN[accessDescASN_Length];
  16569. word32 sz32;
  16570. /* Clear dynamic data and retrieve OID and name. */
  16571. XMEMSET(dataASN, 0, sizeof(dataASN));
  16572. GetASN_OID(&dataASN[ACCESSDESCASN_IDX_METH], oidCertAuthInfoType);
  16573. GetASN_Choice(&dataASN[ACCESSDESCASN_IDX_LOC], generalNameChoice);
  16574. /* Parse AccessDescription. */
  16575. ret = GetASN_Items(accessDescASN, dataASN, accessDescASN_Length, 0,
  16576. input, &idx, sz);
  16577. if (ret == 0) {
  16578. /* Check we have OCSP and URI. */
  16579. if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum == AIA_OCSP_OID) &&
  16580. (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
  16581. /* Store URI for OCSP lookup. */
  16582. GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
  16583. &cert->extAuthInfo, &sz32);
  16584. cert->extAuthInfoSz = sz32;
  16585. count++;
  16586. #if !defined(OPENSSL_ALL) || !defined(WOLFSSL_QT)
  16587. break;
  16588. #endif
  16589. }
  16590. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16591. /* Check we have CA Issuer and URI. */
  16592. else if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum ==
  16593. AIA_CA_ISSUER_OID) &&
  16594. (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
  16595. /* Set CaIssuers entry */
  16596. GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
  16597. &cert->extAuthInfoCaIssuer, &sz32);
  16598. cert->extAuthInfoCaIssuerSz = sz32;
  16599. count++;
  16600. }
  16601. #endif
  16602. /* Otherwise skip. */
  16603. }
  16604. }
  16605. return ret;
  16606. #endif
  16607. }
  16608. #ifdef WOLFSSL_ASN_TEMPLATE
  16609. /* ASN.1 template for AuthorityKeyIdentifier.
  16610. * X.509: RFC 5280, 4.2.1.1 - Authority Key Identifier.
  16611. */
  16612. static const ASNItem authKeyIdASN[] = {
  16613. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16614. /* keyIdentifier */
  16615. /* KEYID */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_KEYID, 0, 0, 1 },
  16616. /* authorityCertIssuer */
  16617. /* ISSUER */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_ISSUER, 1, 0, 1 },
  16618. /* authorityCertSerialNumber */
  16619. /* SERIAL */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_SERIAL, 0, 0, 1 },
  16620. };
  16621. enum {
  16622. AUTHKEYIDASN_IDX_SEQ = 0,
  16623. AUTHKEYIDASN_IDX_KEYID,
  16624. AUTHKEYIDASN_IDX_ISSUER,
  16625. AUTHKEYIDASN_IDX_SERIAL,
  16626. };
  16627. /* Number of items in ASN.1 template for AuthorityKeyIdentifier. */
  16628. #define authKeyIdASN_Length (sizeof(authKeyIdASN) / sizeof(ASNItem))
  16629. #endif
  16630. /* Decode authority information access extension in a certificate.
  16631. *
  16632. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16633. *
  16634. * @param [in] input Buffer holding data.
  16635. * @param [in] sz Size of data in buffer.
  16636. * @param [in, out] cert Certificate object.
  16637. * @return 0 on success.
  16638. * @return MEMORY_E on dynamic memory allocation failure.
  16639. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16640. * is invalid.
  16641. * @return BUFFER_E when data in buffer is too small.
  16642. */
  16643. static int DecodeAuthKeyId(const byte* input, int sz, DecodedCert* cert)
  16644. {
  16645. #ifndef WOLFSSL_ASN_TEMPLATE
  16646. word32 idx = 0;
  16647. int length = 0;
  16648. byte tag;
  16649. WOLFSSL_ENTER("DecodeAuthKeyId");
  16650. if (GetSequence(input, &idx, &length, sz) < 0) {
  16651. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  16652. return ASN_PARSE_E;
  16653. }
  16654. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  16655. return ASN_PARSE_E;
  16656. }
  16657. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  16658. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  16659. cert->extAuthKeyIdSet = 0;
  16660. return 0;
  16661. }
  16662. if (GetLength(input, &idx, &length, sz) <= 0) {
  16663. WOLFSSL_MSG("\tfail: extension data length");
  16664. return ASN_PARSE_E;
  16665. }
  16666. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16667. #ifdef WOLFSSL_AKID_NAME
  16668. cert->extRawAuthKeyIdSrc = input;
  16669. cert->extRawAuthKeyIdSz = sz;
  16670. #endif
  16671. cert->extAuthKeyIdSrc = &input[idx];
  16672. cert->extAuthKeyIdSz = length;
  16673. #endif /* OPENSSL_EXTRA */
  16674. return GetHashId(input + idx, length, cert->extAuthKeyId);
  16675. #else
  16676. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  16677. int ret = 0;
  16678. word32 idx = 0;
  16679. WOLFSSL_ENTER("DecodeAuthKeyId");
  16680. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, cert->heap);
  16681. if (ret == 0) {
  16682. /* Parse an authority key identifier. */
  16683. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  16684. &idx, sz);
  16685. }
  16686. if (ret == 0) {
  16687. /* Key id is optional. */
  16688. if (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data == NULL) {
  16689. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  16690. }
  16691. else {
  16692. #ifdef OPENSSL_EXTRA
  16693. /* Store the authority key id. */
  16694. #ifdef WOLFSSL_AKID_NAME
  16695. cert->extRawAuthKeyIdSrc = input;
  16696. cert->extRawAuthKeyIdSz = sz;
  16697. #endif
  16698. GetASN_GetConstRef(&dataASN[AUTHKEYIDASN_IDX_KEYID], &cert->extAuthKeyIdSrc,
  16699. &cert->extAuthKeyIdSz);
  16700. #endif /* OPENSSL_EXTRA */
  16701. /* Get the hash or hash of the hash if wrong size. */
  16702. ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  16703. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  16704. cert->extAuthKeyId);
  16705. }
  16706. }
  16707. FREE_ASNGETDATA(dataASN, cert->heap);
  16708. return ret;
  16709. #endif /* WOLFSSL_ASN_TEMPLATE */
  16710. }
  16711. /* Decode subject key id extension in a certificate.
  16712. *
  16713. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16714. *
  16715. * @param [in] input Buffer holding data.
  16716. * @param [in] sz Size of data in buffer.
  16717. * @param [in, out] cert Certificate object.
  16718. * @return 0 on success.
  16719. * @return ASN_PARSE_E when the OCTET_STRING tag is not found or length is
  16720. * invalid.
  16721. * @return MEMORY_E on dynamic memory allocation failure.
  16722. */
  16723. static int DecodeSubjKeyId(const byte* input, int sz, DecodedCert* cert)
  16724. {
  16725. word32 idx = 0;
  16726. int length = 0;
  16727. int ret = 0;
  16728. WOLFSSL_ENTER("DecodeSubjKeyId");
  16729. if (sz <= 0) {
  16730. ret = ASN_PARSE_E;
  16731. }
  16732. if (ret == 0) {
  16733. ret = GetOctetString(input, &idx, &length, sz);
  16734. }
  16735. if (ret > 0) {
  16736. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16737. cert->extSubjKeyIdSrc = &input[idx];
  16738. cert->extSubjKeyIdSz = length;
  16739. #endif /* OPENSSL_EXTRA */
  16740. /* Get the hash or hash of the hash if wrong size. */
  16741. ret = GetHashId(input + idx, length, cert->extSubjKeyId);
  16742. }
  16743. return ret;
  16744. }
  16745. #ifdef WOLFSSL_ASN_TEMPLATE
  16746. /* ASN.1 template for KeyUsage.
  16747. * X.509: RFC 5280, 4.2.1.3 - Key Usage.
  16748. */
  16749. static const ASNItem keyUsageASN[] = {
  16750. /* STR */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  16751. };
  16752. enum {
  16753. KEYUSAGEASN_IDX_STR = 0,
  16754. };
  16755. /* Number of items in ASN.1 template for KeyUsage. */
  16756. #define keyUsageASN_Length (sizeof(keyUsageASN) / sizeof(ASNItem))
  16757. #endif
  16758. /* Decode key usage extension in a certificate.
  16759. *
  16760. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16761. *
  16762. * @param [in] input Buffer holding data.
  16763. * @param [in] sz Size of data in buffer.
  16764. * @param [in, out] cert Certificate object.
  16765. * @return 0 on success.
  16766. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  16767. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16768. * is invalid.
  16769. * @return MEMORY_E on dynamic memory allocation failure.
  16770. */
  16771. static int DecodeKeyUsage(const byte* input, int sz, DecodedCert* cert)
  16772. {
  16773. #ifndef WOLFSSL_ASN_TEMPLATE
  16774. word32 idx = 0;
  16775. int length;
  16776. int ret;
  16777. WOLFSSL_ENTER("DecodeKeyUsage");
  16778. ret = CheckBitString(input, &idx, &length, sz, 0, NULL);
  16779. if (ret != 0)
  16780. return ret;
  16781. if (length == 0 || length > 2)
  16782. return ASN_PARSE_E;
  16783. cert->extKeyUsage = (word16)(input[idx]);
  16784. if (length == 2)
  16785. cert->extKeyUsage |= (word16)(input[idx+1] << 8);
  16786. return 0;
  16787. #else
  16788. ASNGetData dataASN[keyUsageASN_Length];
  16789. word32 idx = 0;
  16790. WOLFSSL_ENTER("DecodeKeyUsage");
  16791. /* Clear dynamic data and set where to store extended key usage. */
  16792. XMEMSET(dataASN, 0, sizeof(dataASN));
  16793. GetASN_Int16Bit(&dataASN[KEYUSAGEASN_IDX_STR], &cert->extKeyUsage);
  16794. /* Parse key usage. */
  16795. return GetASN_Items(keyUsageASN, dataASN, keyUsageASN_Length, 0, input,
  16796. &idx, sz);
  16797. #endif /* WOLFSSL_ASN_TEMPLATE */
  16798. }
  16799. #ifdef WOLFSSL_ASN_TEMPLATE
  16800. /* ASN.1 template for KeyPurposeId.
  16801. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  16802. */
  16803. static const ASNItem keyPurposeIdASN[] = {
  16804. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  16805. };
  16806. enum {
  16807. KEYPURPOSEIDASN_IDX_OID = 0,
  16808. };
  16809. /* Number of items in ASN.1 template for KeyPurposeId. */
  16810. #define keyPurposeIdASN_Length (sizeof(keyPurposeIdASN) / sizeof(ASNItem))
  16811. #endif
  16812. /* Decode extended key usage extension in a certificate.
  16813. *
  16814. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  16815. *
  16816. * @param [in] input Buffer holding data.
  16817. * @param [in] sz Size of data in buffer.
  16818. * @param [in, out] cert Certificate object.
  16819. * @return 0 on success.
  16820. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  16821. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16822. * is invalid.
  16823. * @return MEMORY_E on dynamic memory allocation failure.
  16824. */
  16825. static int DecodeExtKeyUsage(const byte* input, int sz, DecodedCert* cert)
  16826. {
  16827. #ifndef WOLFSSL_ASN_TEMPLATE
  16828. word32 idx = 0, oid;
  16829. int length, ret;
  16830. WOLFSSL_ENTER("DecodeExtKeyUsage");
  16831. if (GetSequence(input, &idx, &length, sz) < 0) {
  16832. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  16833. return ASN_PARSE_E;
  16834. }
  16835. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16836. cert->extExtKeyUsageSrc = input + idx;
  16837. cert->extExtKeyUsageSz = length;
  16838. #endif
  16839. while (idx < (word32)sz) {
  16840. ret = GetObjectId(input, &idx, &oid, oidCertKeyUseType, sz);
  16841. if (ret == ASN_UNKNOWN_OID_E)
  16842. continue;
  16843. else if (ret < 0)
  16844. return ret;
  16845. switch (oid) {
  16846. case EKU_ANY_OID:
  16847. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  16848. break;
  16849. case EKU_SERVER_AUTH_OID:
  16850. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  16851. break;
  16852. case EKU_CLIENT_AUTH_OID:
  16853. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  16854. break;
  16855. case EKU_CODESIGNING_OID:
  16856. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  16857. break;
  16858. case EKU_EMAILPROTECT_OID:
  16859. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  16860. break;
  16861. case EKU_TIMESTAMP_OID:
  16862. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  16863. break;
  16864. case EKU_OCSP_SIGN_OID:
  16865. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  16866. break;
  16867. #ifdef WOLFSSL_WOLFSSH
  16868. case EKU_SSH_CLIENT_AUTH_OID:
  16869. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_CLIENT_AUTH;
  16870. break;
  16871. case EKU_SSH_MSCL_OID:
  16872. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_MSCL;
  16873. break;
  16874. case EKU_SSH_KP_CLIENT_AUTH_OID:
  16875. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_KP_CLIENT_AUTH;
  16876. break;
  16877. #endif /* WOLFSSL_WOLFSSH */
  16878. default:
  16879. break;
  16880. }
  16881. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16882. cert->extExtKeyUsageCount++;
  16883. #endif
  16884. }
  16885. return 0;
  16886. #else
  16887. word32 idx = 0;
  16888. int length;
  16889. int ret = 0;
  16890. WOLFSSL_ENTER("DecodeExtKeyUsage");
  16891. /* Strip SEQUENCE OF and expect to account for all the data. */
  16892. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  16893. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  16894. ret = ASN_PARSE_E;
  16895. }
  16896. if (ret == 0) {
  16897. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16898. /* Keep reference for WOLFSSL_X509. */
  16899. cert->extExtKeyUsageSrc = input + idx;
  16900. cert->extExtKeyUsageSz = length;
  16901. #endif
  16902. }
  16903. /* Check all OIDs. */
  16904. while ((ret == 0) && (idx < (word32)sz)) {
  16905. ASNGetData dataASN[keyPurposeIdASN_Length];
  16906. /* Clear dynamic data items and set OID type expected. */
  16907. XMEMSET(dataASN, 0, sizeof(dataASN));
  16908. GetASN_OID(&dataASN[KEYPURPOSEIDASN_IDX_OID], oidIgnoreType);
  16909. /* Decode KeyPurposeId. */
  16910. ret = GetASN_Items(keyPurposeIdASN, dataASN, keyPurposeIdASN_Length, 0,
  16911. input, &idx, sz);
  16912. /* Skip unknown OIDs. */
  16913. if (ret == ASN_UNKNOWN_OID_E) {
  16914. ret = 0;
  16915. }
  16916. else if (ret == 0) {
  16917. /* Store the bit for the OID. */
  16918. switch (dataASN[KEYPURPOSEIDASN_IDX_OID].data.oid.sum) {
  16919. case EKU_ANY_OID:
  16920. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  16921. break;
  16922. case EKU_SERVER_AUTH_OID:
  16923. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  16924. break;
  16925. case EKU_CLIENT_AUTH_OID:
  16926. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  16927. break;
  16928. case EKU_CODESIGNING_OID:
  16929. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  16930. break;
  16931. case EKU_EMAILPROTECT_OID:
  16932. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  16933. break;
  16934. case EKU_TIMESTAMP_OID:
  16935. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  16936. break;
  16937. case EKU_OCSP_SIGN_OID:
  16938. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  16939. break;
  16940. }
  16941. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16942. /* Keep count for WOLFSSL_X509. */
  16943. cert->extExtKeyUsageCount++;
  16944. #endif
  16945. }
  16946. }
  16947. return ret;
  16948. #endif /* WOLFSSL_ASN_TEMPLATE */
  16949. }
  16950. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  16951. static int DecodeNsCertType(const byte* input, int sz, DecodedCert* cert)
  16952. {
  16953. word32 idx = 0;
  16954. int len = 0;
  16955. WOLFSSL_ENTER("DecodeNsCertType");
  16956. if (CheckBitString(input, &idx, &len, (word32)sz, 0, NULL) < 0)
  16957. return ASN_PARSE_E;
  16958. /* Don't need to worry about unused bits as CheckBitString makes sure
  16959. * they're zero. */
  16960. if (idx < (word32)sz)
  16961. cert->nsCertType = input[idx];
  16962. else
  16963. return ASN_PARSE_E;
  16964. return 0;
  16965. }
  16966. #endif
  16967. #ifndef IGNORE_NAME_CONSTRAINTS
  16968. #ifdef WOLFSSL_ASN_TEMPLATE
  16969. /* ASN.1 template for GeneralSubtree.
  16970. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  16971. */
  16972. static const ASNItem subTreeASN[] = {
  16973. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16974. /* base GeneralName */
  16975. /* BASE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  16976. /* minimum BaseDistance DEFAULT 0*/
  16977. /* MIN */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MIN, 0, 0, 1 },
  16978. /* maximum BaseDistance OPTIONAL */
  16979. /* MAX */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MAX, 0, 0, 1 },
  16980. };
  16981. enum {
  16982. SUBTREEASN_IDX_SEQ = 0,
  16983. SUBTREEASN_IDX_BASE,
  16984. SUBTREEASN_IDX_MIN,
  16985. SUBTREEASN_IDX_MAX,
  16986. };
  16987. /* Number of items in ASN.1 template for GeneralSubtree. */
  16988. #define subTreeASN_Length (sizeof(subTreeASN) / sizeof(ASNItem))
  16989. #endif
  16990. #ifdef WOLFSSL_ASN_TEMPLATE
  16991. /* Decode the Subtree's GeneralName.
  16992. *
  16993. * @param [in] input Buffer holding data.
  16994. * @param [in] sz Size of data in buffer.
  16995. * @param [in] tag BER tag on GeneralName.
  16996. * @param [in, out] head Linked list of subtree names.
  16997. * @param [in] heap Dynamic memory hint.
  16998. * @return 0 on success.
  16999. * @return MEMORY_E when dynamic memory allocation fails.
  17000. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  17001. */
  17002. static int DecodeSubtreeGeneralName(const byte* input, int sz, byte tag,
  17003. Base_entry** head, void* heap)
  17004. {
  17005. Base_entry* entry;
  17006. word32 nameIdx = 0;
  17007. word32 len = sz;
  17008. int strLen;
  17009. int ret = 0;
  17010. (void)heap;
  17011. /* if constructed has leading sequence */
  17012. if ((tag & ASN_CONSTRUCTED) == ASN_CONSTRUCTED) {
  17013. ret = GetASN_Sequence(input, &nameIdx, &strLen, sz, 0);
  17014. if (ret < 0) {
  17015. ret = ASN_PARSE_E;
  17016. }
  17017. else {
  17018. len = strLen;
  17019. ret = 0;
  17020. }
  17021. }
  17022. if (ret == 0) {
  17023. /* TODO: consider one malloc. */
  17024. /* Allocate Base Entry object. */
  17025. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  17026. DYNAMIC_TYPE_ALTNAME);
  17027. if (entry == NULL) {
  17028. ret = MEMORY_E;
  17029. }
  17030. }
  17031. if (ret == 0) {
  17032. /* Allocate name. */
  17033. entry->name = (char*)XMALLOC(len + 1, heap, DYNAMIC_TYPE_ALTNAME);
  17034. if (entry->name == NULL) {
  17035. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  17036. ret = MEMORY_E;
  17037. }
  17038. }
  17039. if (ret == 0) {
  17040. /* Store name, size and tag in object. */
  17041. XMEMCPY(entry->name, &input[nameIdx], len);
  17042. entry->name[len] = '\0';
  17043. entry->nameSz = len;
  17044. entry->type = tag & ASN_TYPE_MASK;
  17045. /* Put entry at front of linked list. */
  17046. entry->next = *head;
  17047. *head = entry;
  17048. }
  17049. return ret;
  17050. }
  17051. #endif
  17052. /* Decode a subtree of a name constraints in a certificate.
  17053. *
  17054. * X.509: RFC 5280, 4.2.1.10 - Name Contraints.
  17055. *
  17056. * @param [in] input Buffer holding data.
  17057. * @param [in] sz Size of data in buffer.
  17058. * @param [in, out] head Linked list of subtree names.
  17059. * @param [in] heap Dynamic memory hint.
  17060. * @return 0 on success.
  17061. * @return MEMORY_E when dynamic memory allocation fails.
  17062. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  17063. */
  17064. static int DecodeSubtree(const byte* input, int sz, Base_entry** head,
  17065. void* heap)
  17066. {
  17067. #ifndef WOLFSSL_ASN_TEMPLATE
  17068. word32 idx = 0;
  17069. int ret = 0;
  17070. (void)heap;
  17071. while (idx < (word32)sz) {
  17072. int seqLength, strLength;
  17073. word32 nameIdx;
  17074. byte b, bType;
  17075. if (GetSequence(input, &idx, &seqLength, sz) < 0) {
  17076. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17077. return ASN_PARSE_E;
  17078. }
  17079. if (idx >= (word32)sz) {
  17080. WOLFSSL_MSG("\tfail: expecting tag");
  17081. return ASN_PARSE_E;
  17082. }
  17083. nameIdx = idx;
  17084. b = input[nameIdx++];
  17085. if (GetLength(input, &nameIdx, &strLength, sz) <= 0) {
  17086. WOLFSSL_MSG("\tinvalid length");
  17087. return ASN_PARSE_E;
  17088. }
  17089. /* Get type, LSB 4-bits */
  17090. bType = (b & ASN_TYPE_MASK);
  17091. if (bType == ASN_DNS_TYPE || bType == ASN_RFC822_TYPE ||
  17092. bType == ASN_DIR_TYPE) {
  17093. Base_entry* entry;
  17094. /* if constructed has leading sequence */
  17095. if (b & ASN_CONSTRUCTED) {
  17096. if (GetSequence(input, &nameIdx, &strLength, sz) < 0) {
  17097. WOLFSSL_MSG("\tfail: constructed be a SEQUENCE");
  17098. return ASN_PARSE_E;
  17099. }
  17100. }
  17101. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  17102. DYNAMIC_TYPE_ALTNAME);
  17103. if (entry == NULL) {
  17104. WOLFSSL_MSG("allocate error");
  17105. return MEMORY_E;
  17106. }
  17107. entry->name = (char*)XMALLOC(strLength+1, heap, DYNAMIC_TYPE_ALTNAME);
  17108. if (entry->name == NULL) {
  17109. WOLFSSL_MSG("allocate error");
  17110. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  17111. return MEMORY_E;
  17112. }
  17113. XMEMCPY(entry->name, &input[nameIdx], strLength);
  17114. entry->name[strLength] = '\0';
  17115. entry->nameSz = strLength;
  17116. entry->type = bType;
  17117. entry->next = *head;
  17118. *head = entry;
  17119. }
  17120. idx += seqLength;
  17121. }
  17122. return ret;
  17123. #else
  17124. DECL_ASNGETDATA(dataASN, subTreeASN_Length);
  17125. word32 idx = 0;
  17126. int ret = 0;
  17127. (void)heap;
  17128. ALLOC_ASNGETDATA(dataASN, subTreeASN_Length, ret, heap);
  17129. /* Process all subtrees. */
  17130. while ((ret == 0) && (idx < (word32)sz)) {
  17131. byte minVal = 0;
  17132. byte maxVal = 0;
  17133. /* Clear dynamic data and set choice for GeneralName and location to
  17134. * store minimum and maximum.
  17135. */
  17136. XMEMSET(dataASN, 0, sizeof(*dataASN) * subTreeASN_Length);
  17137. GetASN_Choice(&dataASN[SUBTREEASN_IDX_BASE], generalNameChoice);
  17138. GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MIN], &minVal);
  17139. GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MAX], &maxVal);
  17140. /* Parse GeneralSubtree. */
  17141. ret = GetASN_Items(subTreeASN, dataASN, subTreeASN_Length, 0, input,
  17142. &idx, sz);
  17143. if (ret == 0) {
  17144. byte t = dataASN[SUBTREEASN_IDX_BASE].tag;
  17145. /* Check GeneralName tag is one of the types we can handle. */
  17146. if (t == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE) ||
  17147. t == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE) ||
  17148. t == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  17149. /* Parse the general name and store a new entry. */
  17150. ret = DecodeSubtreeGeneralName(input +
  17151. GetASNItem_DataIdx(dataASN[SUBTREEASN_IDX_BASE], input),
  17152. dataASN[SUBTREEASN_IDX_BASE].length, t, head, heap);
  17153. }
  17154. /* Skip entry. */
  17155. }
  17156. }
  17157. FREE_ASNGETDATA(dataASN, heap);
  17158. return ret;
  17159. #endif
  17160. }
  17161. #ifdef WOLFSSL_ASN_TEMPLATE
  17162. /* ASN.1 template for NameConstraints.
  17163. * X.509: RFC 5280, 4.2.1.10 - Name Contraints.
  17164. */
  17165. static const ASNItem nameConstraintsASN[] = {
  17166. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17167. /* permittedSubtrees */
  17168. /* PERMIT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  17169. /* excludededSubtrees */
  17170. /* EXCLUDE */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  17171. };
  17172. enum {
  17173. NAMECONSTRAINTSASN_IDX_SEQ = 0,
  17174. NAMECONSTRAINTSASN_IDX_PERMIT,
  17175. NAMECONSTRAINTSASN_IDX_EXCLUDE,
  17176. };
  17177. /* Number of items in ASN.1 template for NameConstraints. */
  17178. #define nameConstraintsASN_Length (sizeof(nameConstraintsASN) / sizeof(ASNItem))
  17179. #endif
  17180. /* Decode name constraints extension in a certificate.
  17181. *
  17182. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  17183. *
  17184. * @param [in] input Buffer holding data.
  17185. * @param [in] sz Size of data in buffer.
  17186. * @param [in, out] cert Certificate object.
  17187. * @return 0 on success.
  17188. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17189. * is invalid.
  17190. * @return MEMORY_E on dynamic memory allocation failure.
  17191. */
  17192. static int DecodeNameConstraints(const byte* input, int sz, DecodedCert* cert)
  17193. {
  17194. #ifndef WOLFSSL_ASN_TEMPLATE
  17195. word32 idx = 0;
  17196. int length = 0;
  17197. WOLFSSL_ENTER("DecodeNameConstraints");
  17198. if (GetSequence(input, &idx, &length, sz) < 0) {
  17199. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17200. return ASN_PARSE_E;
  17201. }
  17202. while (idx < (word32)sz) {
  17203. byte b = input[idx++];
  17204. Base_entry** subtree = NULL;
  17205. if (GetLength(input, &idx, &length, sz) <= 0) {
  17206. WOLFSSL_MSG("\tinvalid length");
  17207. return ASN_PARSE_E;
  17208. }
  17209. if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
  17210. subtree = &cert->permittedNames;
  17211. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
  17212. subtree = &cert->excludedNames;
  17213. else {
  17214. WOLFSSL_MSG("\tinvalid subtree");
  17215. return ASN_PARSE_E;
  17216. }
  17217. if (DecodeSubtree(input + idx, length, subtree, cert->heap) < 0) {
  17218. WOLFSSL_MSG("\terror parsing subtree");
  17219. return ASN_PARSE_E;
  17220. }
  17221. idx += length;
  17222. }
  17223. return 0;
  17224. #else
  17225. DECL_ASNGETDATA(dataASN, nameConstraintsASN_Length);
  17226. word32 idx = 0;
  17227. int ret = 0;
  17228. CALLOC_ASNGETDATA(dataASN, nameConstraintsASN_Length, ret, cert->heap);
  17229. if (ret == 0) {
  17230. /* Parse NameConstraints. */
  17231. ret = GetASN_Items(nameConstraintsASN, dataASN,
  17232. nameConstraintsASN_Length, 1, input, &idx, sz);
  17233. }
  17234. if (ret == 0) {
  17235. /* If there was a permittedSubtrees then parse it. */
  17236. if (dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data != NULL) {
  17237. ret = DecodeSubtree(
  17238. dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data,
  17239. dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.length,
  17240. &cert->permittedNames, cert->heap);
  17241. }
  17242. }
  17243. if (ret == 0) {
  17244. /* If there was a excludedSubtrees then parse it. */
  17245. if (dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data != NULL) {
  17246. ret = DecodeSubtree(
  17247. dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data,
  17248. dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.length,
  17249. &cert->excludedNames, cert->heap);
  17250. }
  17251. }
  17252. FREE_ASNGETDATA(dataASN, cert->heap);
  17253. return ret;
  17254. #endif /* WOLFSSL_ASN_TEMPLATE */
  17255. }
  17256. #endif /* IGNORE_NAME_CONSTRAINTS */
  17257. #if (defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_SEP)) || \
  17258. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17259. /* Decode ITU-T X.690 OID format to a string representation
  17260. * return string length */
  17261. int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz)
  17262. {
  17263. word32 val, inIdx = 0, outIdx = 0;
  17264. int w = 0;
  17265. if (out == NULL || in == NULL || outSz < 4 || inSz < 2)
  17266. return BAD_FUNC_ARG;
  17267. /* The first byte expands into b/40 dot b%40. */
  17268. val = in[inIdx++];
  17269. w = XSNPRINTF(out, outSz, "%u.%u", val / 40, val % 40);
  17270. if (w < 0) {
  17271. w = BUFFER_E;
  17272. goto exit;
  17273. }
  17274. outIdx += w;
  17275. val = 0;
  17276. while (inIdx < inSz && outIdx < outSz) {
  17277. /* extract the next OID digit from in to val */
  17278. /* first bit is used to set if value is coded on 1 or multiple bytes */
  17279. if (in[inIdx] & 0x80) {
  17280. val += in[inIdx] & 0x7F;
  17281. val *= 128;
  17282. }
  17283. else {
  17284. /* write val as text into out */
  17285. val += in[inIdx];
  17286. w = XSNPRINTF(out + outIdx, outSz - outIdx, ".%u", val);
  17287. if (w < 0 || (word32)w > outSz - outIdx) {
  17288. w = BUFFER_E;
  17289. goto exit;
  17290. }
  17291. outIdx += w;
  17292. val = 0;
  17293. }
  17294. inIdx++;
  17295. }
  17296. if (outIdx == outSz)
  17297. outIdx--;
  17298. out[outIdx] = 0;
  17299. w = (int)outIdx;
  17300. exit:
  17301. return w;
  17302. }
  17303. #endif /* WOLFSSL_CERT_EXT && !WOLFSSL_SEP */
  17304. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_QT)
  17305. #ifdef WOLFSSL_ASN_TEMPLATE
  17306. /* ASN.1 template for PolicyInformation.
  17307. * X.509: RFC 5280, 4.2.1.4 - Certificate Policies.
  17308. */
  17309. static const ASNItem policyInfoASN[] = {
  17310. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17311. /* policyIdentifier */
  17312. /* ID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  17313. /* policyQualifiers */
  17314. /* QUALI */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  17315. };
  17316. enum {
  17317. POLICYINFOASN_IDX_SEQ = 0,
  17318. POLICYINFOASN_IDX_ID,
  17319. POLICYINFOASN_IDX_QUALI,
  17320. };
  17321. /* Number of items in ASN.1 template for PolicyInformation. */
  17322. #define policyInfoASN_Length (sizeof(policyInfoASN) / sizeof(ASNItem))
  17323. #endif
  17324. /* Reference: https://tools.ietf.org/html/rfc5280#section-4.2.1.4 */
  17325. static int DecodeCertPolicy(const byte* input, int sz, DecodedCert* cert)
  17326. {
  17327. #ifndef WOLFSSL_ASN_TEMPLATE
  17328. word32 idx = 0;
  17329. word32 oldIdx;
  17330. int policy_length = 0;
  17331. int ret;
  17332. int total_length = 0;
  17333. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  17334. !defined(WOLFSSL_DUP_CERTPOL)
  17335. int i;
  17336. #endif
  17337. WOLFSSL_ENTER("DecodeCertPolicy");
  17338. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  17339. /* Check if cert is null before dereferencing below */
  17340. if (cert == NULL)
  17341. return BAD_FUNC_ARG;
  17342. #else
  17343. (void)cert;
  17344. #endif
  17345. #if defined(WOLFSSL_CERT_EXT)
  17346. cert->extCertPoliciesNb = 0;
  17347. #endif
  17348. if (GetSequence(input, &idx, &total_length, sz) < 0) {
  17349. WOLFSSL_MSG("\tGet CertPolicy total seq failed");
  17350. return ASN_PARSE_E;
  17351. }
  17352. /* Validate total length */
  17353. if (total_length > (sz - (int)idx)) {
  17354. WOLFSSL_MSG("\tCertPolicy length mismatch");
  17355. return ASN_PARSE_E;
  17356. }
  17357. /* Unwrap certificatePolicies */
  17358. do {
  17359. int length = 0;
  17360. if (GetSequence(input, &idx, &policy_length, sz) < 0) {
  17361. WOLFSSL_MSG("\tGet CertPolicy seq failed");
  17362. return ASN_PARSE_E;
  17363. }
  17364. oldIdx = idx;
  17365. ret = GetASNObjectId(input, &idx, &length, sz);
  17366. if (ret != 0)
  17367. return ret;
  17368. policy_length -= idx - oldIdx;
  17369. if (length > 0) {
  17370. /* Verify length won't overrun buffer */
  17371. if (length > (sz - (int)idx)) {
  17372. WOLFSSL_MSG("\tCertPolicy length exceeds input buffer");
  17373. return ASN_PARSE_E;
  17374. }
  17375. #if defined(WOLFSSL_SEP)
  17376. cert->deviceType = (byte*)XMALLOC(length, cert->heap,
  17377. DYNAMIC_TYPE_X509_EXT);
  17378. if (cert->deviceType == NULL) {
  17379. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  17380. return MEMORY_E;
  17381. }
  17382. cert->deviceTypeSz = length;
  17383. XMEMCPY(cert->deviceType, input + idx, length);
  17384. break;
  17385. #elif defined(WOLFSSL_CERT_EXT)
  17386. /* decode cert policy */
  17387. if (DecodePolicyOID(cert->extCertPolicies[
  17388. cert->extCertPoliciesNb], MAX_CERTPOL_SZ,
  17389. input + idx, length) <= 0) {
  17390. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  17391. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17392. return ASN_PARSE_E;
  17393. }
  17394. #ifndef WOLFSSL_DUP_CERTPOL
  17395. /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
  17396. * NOT appear more than once in a certificate policies
  17397. * extension". This is a sanity check for duplicates.
  17398. * extCertPolicies should only have OID values, additional
  17399. * qualifiers need to be stored in a separate array. */
  17400. for (i = 0; i < cert->extCertPoliciesNb; i++) {
  17401. if (XMEMCMP(cert->extCertPolicies[i],
  17402. cert->extCertPolicies[cert->extCertPoliciesNb],
  17403. MAX_CERTPOL_SZ) == 0) {
  17404. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  17405. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  17406. WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
  17407. return CERTPOLICIES_E;
  17408. }
  17409. }
  17410. #endif /* !WOLFSSL_DUP_CERTPOL */
  17411. cert->extCertPoliciesNb++;
  17412. #else
  17413. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  17414. return 0;
  17415. #endif
  17416. }
  17417. idx += policy_length;
  17418. } while((int)idx < total_length
  17419. #if defined(WOLFSSL_CERT_EXT)
  17420. && cert->extCertPoliciesNb < MAX_CERTPOL_NB
  17421. #endif
  17422. );
  17423. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  17424. return 0;
  17425. #else /* WOLFSSL_ASN_TEMPLATE */
  17426. word32 idx = 0;
  17427. int ret = 0;
  17428. int total_length = 0;
  17429. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  17430. !defined(WOLFSSL_DUP_CERTPOL)
  17431. int i;
  17432. #endif
  17433. WOLFSSL_ENTER("DecodeCertPolicy");
  17434. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  17435. /* Check if cert is null before dereferencing below */
  17436. if (cert == NULL)
  17437. ret = BAD_FUNC_ARG;
  17438. #endif
  17439. if (ret == 0) {
  17440. #if defined(WOLFSSL_CERT_EXT)
  17441. cert->extCertPoliciesNb = 0;
  17442. #endif
  17443. /* Strip SEQUENCE OF and check using all data. */
  17444. if (GetASN_Sequence(input, &idx, &total_length, sz, 1) < 0) {
  17445. ret = ASN_PARSE_E;
  17446. }
  17447. }
  17448. /* Unwrap certificatePolicies */
  17449. while ((ret == 0) && ((int)idx < total_length)
  17450. #if defined(WOLFSSL_CERT_EXT)
  17451. && (cert->extCertPoliciesNb < MAX_CERTPOL_NB)
  17452. #endif
  17453. ) {
  17454. ASNGetData dataASN[policyInfoASN_Length];
  17455. byte* data;
  17456. word32 length = 0;
  17457. /* Clear dynamic data and check OID is a cert policy type. */
  17458. XMEMSET(dataASN, 0, sizeof(dataASN));
  17459. GetASN_OID(&dataASN[POLICYINFOASN_IDX_ID], oidCertPolicyType);
  17460. ret = GetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length, 1,
  17461. input, &idx, sz);
  17462. if (ret == 0) {
  17463. /* Get the OID. */
  17464. GetASN_OIDData(&dataASN[POLICYINFOASN_IDX_ID], &data, &length);
  17465. if (length == 0) {
  17466. ret = ASN_PARSE_E;
  17467. }
  17468. }
  17469. #if defined(WOLFSSL_SEP)
  17470. /* Store OID in device type. */
  17471. if (ret == 0) {
  17472. cert->deviceType = (byte*)XMALLOC(length, cert->heap,
  17473. DYNAMIC_TYPE_X509_EXT);
  17474. if (cert->deviceType == NULL) {
  17475. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  17476. ret = MEMORY_E;
  17477. }
  17478. }
  17479. if (ret == 0) {
  17480. /* Store device type data and length. */
  17481. cert->deviceTypeSz = length;
  17482. XMEMCPY(cert->deviceType, data, length);
  17483. break;
  17484. }
  17485. #elif defined(WOLFSSL_CERT_EXT)
  17486. if (ret == 0) {
  17487. /* Decode cert policy. */
  17488. if (DecodePolicyOID(
  17489. cert->extCertPolicies[cert->extCertPoliciesNb],
  17490. MAX_CERTPOL_SZ, data, length) <= 0) {
  17491. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  17492. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17493. ret = ASN_PARSE_E;
  17494. }
  17495. }
  17496. #ifndef WOLFSSL_DUP_CERTPOL
  17497. /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
  17498. * NOT appear more than once in a certificate policies
  17499. * extension". This is a sanity check for duplicates.
  17500. * extCertPolicies should only have OID values, additional
  17501. * qualifiers need to be stored in a seperate array. */
  17502. for (i = 0; (ret == 0) && (i < cert->extCertPoliciesNb); i++) {
  17503. if (XMEMCMP(cert->extCertPolicies[i],
  17504. cert->extCertPolicies[cert->extCertPoliciesNb],
  17505. MAX_CERTPOL_SZ) == 0) {
  17506. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  17507. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  17508. WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
  17509. ret = CERTPOLICIES_E;
  17510. }
  17511. }
  17512. #endif /* !defined(WOLFSSL_DUP_CERTPOL) */
  17513. if (ret == 0) {
  17514. /* Keep count of policies seen. */
  17515. cert->extCertPoliciesNb++;
  17516. }
  17517. #else
  17518. (void)data;
  17519. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  17520. break;
  17521. #endif
  17522. }
  17523. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  17524. return ret;
  17525. #endif /* WOLFSSL_ASN_TEMPLATE */
  17526. }
  17527. #endif /* WOLFSSL_SEP */
  17528. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  17529. #ifdef WOLFSSL_ASN_TEMPLATE
  17530. /* ASN.1 template for subject dir attribute.
  17531. * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
  17532. */
  17533. static const ASNItem subjDirAttrASN[] = {
  17534. /* SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  17535. /* OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  17536. /* PLEN */ { 2, ASN_SET, 1, 0, 0 },
  17537. };
  17538. enum {
  17539. SUBJDIRATTRASN_IDX_SEQ = 0,
  17540. SUBJDIRATTRASN_IDX_OID,
  17541. SUBJDIRATTRASN_IDX_SET,
  17542. };
  17543. /* Number of items in ASN.1 template for BasicContraints. */
  17544. #define subjDirAttrASN_Length (sizeof(subjDirAttrASN) / sizeof(ASNItem))
  17545. #endif
  17546. /* Decode subject directory attributes extension in a certificate.
  17547. *
  17548. * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
  17549. *
  17550. * @param [in] input Buffer holding data.
  17551. * @param [in] sz Size of data in buffer.
  17552. * @param [in, out] cert Certificate object.
  17553. * @return 0 on success.
  17554. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17555. * is invalid.
  17556. */
  17557. static int DecodeSubjDirAttr(const byte* input, int sz, DecodedCert* cert)
  17558. {
  17559. #ifndef WOLFSSL_ASN_TEMPLATE
  17560. word32 idx = 0;
  17561. int length = 0;
  17562. int ret = 0;
  17563. WOLFSSL_ENTER("DecodeSubjDirAttr");
  17564. #ifdef OPENSSL_ALL
  17565. cert->extSubjDirAttrSrc = input;
  17566. cert->extSubjDirAttrSz = sz;
  17567. #endif /* OPENSSL_ALL */
  17568. /* Unwrap the list of Attributes */
  17569. if (GetSequence(input, &idx, &length, sz) < 0)
  17570. return ASN_PARSE_E;
  17571. if (length == 0) {
  17572. /* RFC 5280 4.2.1.8. Subject Directory Attributes
  17573. If the subjectDirectoryAttributes extension is present, the
  17574. sequence MUST contain at least one entry. */
  17575. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17576. return ASN_PARSE_E;
  17577. }
  17578. /* length is the length of the list contents */
  17579. while (idx < (word32)sz) {
  17580. word32 oid;
  17581. if (GetSequence(input, &idx, &length, sz) < 0)
  17582. return ASN_PARSE_E;
  17583. if (GetObjectId(input, &idx, &oid, oidSubjDirAttrType, sz) < 0)
  17584. return ASN_PARSE_E;
  17585. if (GetSet(input, &idx, &length, sz) < 0)
  17586. return ASN_PARSE_E;
  17587. /* There may be more than one countryOfCitizenship, but save the
  17588. * first one for now. */
  17589. if (oid == SDA_COC_OID) {
  17590. byte tag;
  17591. if (GetHeader(input, &tag, &idx, &length, sz, 1) < 0)
  17592. return ASN_PARSE_E;
  17593. if (length != COUNTRY_CODE_LEN)
  17594. return ASN_PARSE_E;
  17595. if (tag == ASN_PRINTABLE_STRING) {
  17596. XMEMCPY(cert->countryOfCitizenship,
  17597. input + idx, COUNTRY_CODE_LEN);
  17598. cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
  17599. }
  17600. }
  17601. idx += length;
  17602. }
  17603. return ret;
  17604. #else
  17605. DECL_ASNGETDATA(dataASN, subjDirAttrASN_Length);
  17606. int ret = 0;
  17607. word32 idx = 0;
  17608. int length;
  17609. WOLFSSL_ENTER("DecodeSubjDirAttr");
  17610. CALLOC_ASNGETDATA(dataASN, subjDirAttrASN_Length, ret, cert->heap);
  17611. /* Strip outer SEQUENCE. */
  17612. if ((ret == 0) && (GetSequence(input, &idx, &length, sz) < 0)) {
  17613. ret = ASN_PARSE_E;
  17614. }
  17615. /* Handle each inner SEQUENCE. */
  17616. while ((ret == 0) && (idx < (word32)sz)) {
  17617. ret = GetASN_Items(subjDirAttrASN, dataASN, subjDirAttrASN_Length, 1,
  17618. input, &idx, sz);
  17619. /* There may be more than one countryOfCitizenship, but save the
  17620. * first one for now. */
  17621. if ((ret == 0) &&
  17622. (dataASN[SUBJDIRATTRASN_IDX_OID].data.oid.sum == SDA_COC_OID)) {
  17623. int cuLen;
  17624. word32 setIdx = 0;
  17625. byte* setData;
  17626. word32 setLen;
  17627. GetASN_GetRef(&dataASN[SUBJDIRATTRASN_IDX_SET], &setData, &setLen);
  17628. if (GetASNHeader(setData, ASN_PRINTABLE_STRING, &setIdx, &cuLen,
  17629. setLen) < 0) {
  17630. ret = ASN_PARSE_E;
  17631. }
  17632. if ((ret == 0) && (cuLen != COUNTRY_CODE_LEN)) {
  17633. ret = ASN_PARSE_E;
  17634. }
  17635. if (ret == 0) {
  17636. XMEMCPY(cert->countryOfCitizenship, setData + setIdx, cuLen);
  17637. cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
  17638. }
  17639. }
  17640. }
  17641. FREE_ASNGETDATA(dataASN, cert->heap);
  17642. return ret;
  17643. #endif /* WOLFSSL_ASN_TEMPLATE */
  17644. }
  17645. #endif /* WOLFSSL_SUBJ_DIR_ATTR */
  17646. #ifdef WOLFSSL_SUBJ_INFO_ACC
  17647. /* Decode subject infomation access extension in a certificate.
  17648. *
  17649. * X.509: RFC 5280, 4.2.2.2 - Subject Information Access.
  17650. *
  17651. * @param [in] input Buffer holding data.
  17652. * @param [in] sz Size of data in buffer.
  17653. * @param [in, out] cert Certificate object.
  17654. * @return 0 on success.
  17655. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  17656. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17657. * is invalid.
  17658. * @return MEMORY_E on dynamic memory allocation failure.
  17659. */
  17660. static int DecodeSubjInfoAcc(const byte* input, int sz, DecodedCert* cert)
  17661. {
  17662. word32 idx = 0;
  17663. int length = 0;
  17664. int ret = 0;
  17665. WOLFSSL_ENTER("DecodeSubjInfoAcc");
  17666. #ifdef OPENSSL_ALL
  17667. cert->extSubjAltNameSrc = input;
  17668. cert->extSubjAltNameSz = sz;
  17669. #endif /* OPENSSL_ALL */
  17670. /* Unwrap SubjectInfoAccessSyntax, the list of AccessDescriptions */
  17671. if (GetSequence(input, &idx, &length, sz) < 0)
  17672. return ASN_PARSE_E;
  17673. if (length == 0) {
  17674. /* RFC 5280 4.2.2.2. Subject Information Access
  17675. If the subjectInformationAccess extension is present, the
  17676. sequence MUST contain at least one entry. */
  17677. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17678. return ASN_PARSE_E;
  17679. }
  17680. /* Per fpkx-x509-cert-profile-common... section 5.3.
  17681. * [The] subjectInfoAccess extension must contain at least one
  17682. * instance of the id-ad-caRepository access method containing a
  17683. * publicly accessible HTTP URI which returns as certs-only
  17684. * CMS.
  17685. */
  17686. while (idx < (word32)sz) {
  17687. word32 oid = 0;
  17688. byte b;
  17689. /* Unwrap an AccessDescription */
  17690. if (GetSequence(input, &idx, &length, sz) < 0)
  17691. return ASN_PARSE_E;
  17692. /* Get the accessMethod */
  17693. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0)
  17694. return ASN_PARSE_E;
  17695. /* Only supporting URIs right now. */
  17696. if (GetASNTag(input, &idx, &b, sz) < 0)
  17697. return ASN_PARSE_E;
  17698. if (GetLength(input, &idx, &length, sz) < 0)
  17699. return ASN_PARSE_E;
  17700. /* Set caRepo entry */
  17701. if (b == GENERALNAME_URI && oid == AIA_CA_REPO_OID) {
  17702. cert->extSubjInfoAccCaRepoSz = length;
  17703. cert->extSubjInfoAccCaRepo = input + idx;
  17704. break;
  17705. }
  17706. idx += length;
  17707. }
  17708. if (cert->extSubjInfoAccCaRepo == NULL ||
  17709. cert->extSubjInfoAccCaRepoSz == 0) {
  17710. WOLFSSL_MSG("SubjectInfoAccess missing an URL.");
  17711. ret = ASN_PARSE_E;
  17712. }
  17713. WOLFSSL_LEAVE("DecodeSubjInfoAcc", ret);
  17714. return ret;
  17715. }
  17716. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  17717. /* Macro to check if bit is set, if not sets and return success.
  17718. Otherwise returns failure */
  17719. /* Macro required here because bit-field operation */
  17720. #ifndef WOLFSSL_NO_ASN_STRICT
  17721. #define VERIFY_AND_SET_OID(bit) \
  17722. if ((bit) == 0) \
  17723. (bit) = 1; \
  17724. else \
  17725. return ASN_OBJECT_ID_E;
  17726. #else
  17727. /* With no strict defined, the verify is skipped */
  17728. #define VERIFY_AND_SET_OID(bit) bit = 1;
  17729. #endif
  17730. /* Parse extension type specific data based on OID sum.
  17731. *
  17732. * Supported extensions:
  17733. * Basic Constraints - BASIC_CA_OID
  17734. * CRL Distribution Points - CRL_DIST_OID
  17735. * Authority Information Access - AUTH_INFO_OID
  17736. * Subject Alternative Name - ALT_NAMES_OID
  17737. * Authority Key Identifier - AUTH_KEY_OID
  17738. * Subject Key Identifier - SUBJ_KEY_OID
  17739. * Certificate Policies - CERT_POLICY_OID (conditional parsing)
  17740. * Key Usage - KEY_USAGE_OID
  17741. * Extended Key Usage - EXT_KEY_USAGE_OID
  17742. * Name Constraints - NAME_CONS_OID
  17743. * Inhibit anyPolicy - INHIBIT_ANY_OID
  17744. * Netscape Certificate Type - NETSCAPE_CT_OID (able to be excluded)
  17745. * OCSP no check - OCSP_NOCHECK_OID (when compiling OCSP)
  17746. * Subject Directory Attributes - SUBJ_DIR_ATTR_OID
  17747. * Subject Information Access - SUBJ_INFO_ACC_OID
  17748. * Unsupported extensions from RFC 5280:
  17749. * 4.2.1.5 - Policy mappings
  17750. * 4.2.1.7 - Issuer Alternative Name
  17751. * 4.2.1.11 - Policy Constraints
  17752. * 4.2.1.15 - Freshest CRL
  17753. *
  17754. * @param [in] input Buffer containing extension type specific data.
  17755. * @param [in] length Length of data.
  17756. * @param [in] oid OID sum for extension.
  17757. * @param [in] critical Whether extension is critical.
  17758. * @param [in, out] cert Certificate object.
  17759. * @return 0 on success.
  17760. * @return ASN_PARSE_E when BER encoding is invalid.
  17761. * @return MEMORY_E on dynamic memory allocation failure.
  17762. * @return Other negative values on error.
  17763. */
  17764. static int DecodeExtensionType(const byte* input, int length, word32 oid,
  17765. byte critical, DecodedCert* cert,
  17766. int *isUnknownExt)
  17767. {
  17768. int ret = 0;
  17769. word32 idx = 0;
  17770. if (isUnknownExt != NULL)
  17771. *isUnknownExt = 0;
  17772. switch (oid) {
  17773. /* Basic Constraints. */
  17774. case BASIC_CA_OID:
  17775. VERIFY_AND_SET_OID(cert->extBasicConstSet);
  17776. cert->extBasicConstCrit = critical;
  17777. if (DecodeBasicCaConstraint(input, length, cert) < 0) {
  17778. ret = ASN_PARSE_E;
  17779. }
  17780. break;
  17781. /* CRL Distribution point. */
  17782. case CRL_DIST_OID:
  17783. VERIFY_AND_SET_OID(cert->extCRLdistSet);
  17784. cert->extCRLdistCrit = critical;
  17785. if (DecodeCrlDist(input, length, cert) < 0) {
  17786. ret = ASN_PARSE_E;
  17787. }
  17788. break;
  17789. /* Authority information access. */
  17790. case AUTH_INFO_OID:
  17791. VERIFY_AND_SET_OID(cert->extAuthInfoSet);
  17792. cert->extAuthInfoCrit = critical;
  17793. if (DecodeAuthInfo(input, length, cert) < 0) {
  17794. ret = ASN_PARSE_E;
  17795. }
  17796. break;
  17797. /* Subject alternative name. */
  17798. case ALT_NAMES_OID:
  17799. VERIFY_AND_SET_OID(cert->extSubjAltNameSet);
  17800. cert->extSubjAltNameCrit = critical;
  17801. ret = DecodeAltNames(input, length, cert);
  17802. break;
  17803. /* Authority Key Identifier. */
  17804. case AUTH_KEY_OID:
  17805. VERIFY_AND_SET_OID(cert->extAuthKeyIdSet);
  17806. cert->extAuthKeyIdCrit = critical;
  17807. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  17808. /* This check is added due to RFC 5280 section 4.2.1.1
  17809. * stating that conforming CA's must mark this extension
  17810. * as non-critical. When parsing extensions check that
  17811. * certificate was made in compliance with this. */
  17812. if (critical) {
  17813. WOLFSSL_MSG("Critical Auth Key ID is not allowed");
  17814. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  17815. ret = ASN_CRIT_EXT_E;
  17816. }
  17817. #endif
  17818. if ((ret == 0) && (DecodeAuthKeyId(input, length, cert) < 0)) {
  17819. ret = ASN_PARSE_E;
  17820. }
  17821. break;
  17822. /* Subject Key Identifier. */
  17823. case SUBJ_KEY_OID:
  17824. VERIFY_AND_SET_OID(cert->extSubjKeyIdSet);
  17825. cert->extSubjKeyIdCrit = critical;
  17826. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  17827. /* This check is added due to RFC 5280 section 4.2.1.2
  17828. * stating that conforming CA's must mark this extension
  17829. * as non-critical. When parsing extensions check that
  17830. * certificate was made in compliance with this. */
  17831. if (critical) {
  17832. WOLFSSL_MSG("Critical Subject Key ID is not allowed");
  17833. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  17834. ret = ASN_CRIT_EXT_E;
  17835. }
  17836. #endif
  17837. if ((ret == 0) && (DecodeSubjKeyId(input, length, cert) < 0)) {
  17838. ret = ASN_PARSE_E;
  17839. }
  17840. break;
  17841. /* Certificate policies. */
  17842. case CERT_POLICY_OID:
  17843. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT)
  17844. VERIFY_AND_SET_OID(cert->extCertPolicySet);
  17845. #if defined(OPENSSL_EXTRA) || \
  17846. defined(OPENSSL_EXTRA_X509_SMALL)
  17847. cert->extCertPolicyCrit = critical;
  17848. #endif
  17849. #endif
  17850. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || \
  17851. defined(WOLFSSL_QT)
  17852. if (DecodeCertPolicy(input, length, cert) < 0) {
  17853. ret = ASN_PARSE_E;
  17854. }
  17855. #else
  17856. WOLFSSL_MSG("Certificate Policy extension not supported yet.");
  17857. #endif
  17858. break;
  17859. /* Key usage. */
  17860. case KEY_USAGE_OID:
  17861. VERIFY_AND_SET_OID(cert->extKeyUsageSet);
  17862. cert->extKeyUsageCrit = critical;
  17863. if (DecodeKeyUsage(input, length, cert) < 0) {
  17864. ret = ASN_PARSE_E;
  17865. }
  17866. break;
  17867. /* Extended key usage. */
  17868. case EXT_KEY_USAGE_OID:
  17869. VERIFY_AND_SET_OID(cert->extExtKeyUsageSet);
  17870. cert->extExtKeyUsageCrit = critical;
  17871. if (DecodeExtKeyUsage(input, length, cert) < 0) {
  17872. ret = ASN_PARSE_E;
  17873. }
  17874. break;
  17875. #ifndef IGNORE_NAME_CONSTRAINTS
  17876. /* Name constraints. */
  17877. case NAME_CONS_OID:
  17878. #ifndef WOLFSSL_NO_ASN_STRICT
  17879. /* Verify RFC 5280 Sec 4.2.1.10 rule:
  17880. "The name constraints extension,
  17881. which MUST be used only in a CA certificate" */
  17882. if (!cert->isCA) {
  17883. WOLFSSL_MSG("Name constraints allowed only for CA certs");
  17884. WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
  17885. ret = ASN_NAME_INVALID_E;
  17886. }
  17887. #endif
  17888. VERIFY_AND_SET_OID(cert->extNameConstraintSet);
  17889. cert->extNameConstraintCrit = critical;
  17890. if (DecodeNameConstraints(input, length, cert) < 0) {
  17891. ret = ASN_PARSE_E;
  17892. }
  17893. break;
  17894. #endif /* IGNORE_NAME_CONSTRAINTS */
  17895. /* Inhibit anyPolicy. */
  17896. case INHIBIT_ANY_OID:
  17897. VERIFY_AND_SET_OID(cert->inhibitAnyOidSet);
  17898. WOLFSSL_MSG("Inhibit anyPolicy extension not supported yet.");
  17899. break;
  17900. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  17901. /* Netscape's certificate type. */
  17902. case NETSCAPE_CT_OID:
  17903. if (DecodeNsCertType(input, length, cert) < 0)
  17904. ret = ASN_PARSE_E;
  17905. break;
  17906. #endif
  17907. #ifdef HAVE_OCSP
  17908. /* OCSP no check. */
  17909. case OCSP_NOCHECK_OID:
  17910. VERIFY_AND_SET_OID(cert->ocspNoCheckSet);
  17911. ret = GetASNNull(input, &idx, length);
  17912. if (ret != 0) {
  17913. ret = ASN_PARSE_E;
  17914. }
  17915. break;
  17916. #endif
  17917. case POLICY_CONST_OID:
  17918. VERIFY_AND_SET_OID(cert->extPolicyConstSet);
  17919. cert->extPolicyConstCrit = critical;
  17920. if (DecodePolicyConstraints(&input[idx], length, cert) < 0)
  17921. return ASN_PARSE_E;
  17922. break;
  17923. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  17924. case SUBJ_DIR_ATTR_OID:
  17925. VERIFY_AND_SET_OID(cert->extSubjDirAttrSet);
  17926. if (DecodeSubjDirAttr(&input[idx], length, cert) < 0)
  17927. return ASN_PARSE_E;
  17928. break;
  17929. #endif
  17930. #ifdef WOLFSSL_SUBJ_INFO_ACC
  17931. case SUBJ_INFO_ACC_OID:
  17932. VERIFY_AND_SET_OID(cert->extSubjInfoAccSet);
  17933. if (DecodeSubjInfoAcc(&input[idx], length, cert) < 0)
  17934. return ASN_PARSE_E;
  17935. break;
  17936. #endif
  17937. default:
  17938. if (isUnknownExt != NULL)
  17939. *isUnknownExt = 1;
  17940. #ifndef WOLFSSL_NO_ASN_STRICT
  17941. /* While it is a failure to not support critical extensions,
  17942. * still parse the certificate ignoring the unsupported
  17943. * extension to allow caller to accept it with the verify
  17944. * callback. */
  17945. if (critical) {
  17946. WOLFSSL_ERROR_VERBOSE(ASN_CRIT_EXT_E);
  17947. ret = ASN_CRIT_EXT_E;
  17948. }
  17949. #endif
  17950. break;
  17951. }
  17952. return ret;
  17953. }
  17954. #ifdef WOLFSSL_ASN_TEMPLATE
  17955. /* ASN.1 template for extensions.
  17956. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  17957. */
  17958. static const ASNItem certExtHdrASN[] = {
  17959. /* EXTTAG */ { 0, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 0 },
  17960. /* EXTSEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  17961. };
  17962. enum {
  17963. CERTEXTHDRASN_IDX_EXTTAG = 0,
  17964. CERTEXTHDRASN_IDX_EXTSEQ,
  17965. };
  17966. /* Number of itesm in ASN.1 template for extensions. */
  17967. #define certExtHdrASN_Length (sizeof(certExtHdrASN) / sizeof(ASNItem))
  17968. /* ASN.1 template for Extension.
  17969. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  17970. */
  17971. static const ASNItem certExtASN[] = {
  17972. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17973. /* Extension object id */
  17974. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  17975. /* critical - when true, must be parseable. */
  17976. /* CRIT */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  17977. /* Data for extension - leave index at start of data. */
  17978. /* VAL */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  17979. };
  17980. enum {
  17981. CERTEXTASN_IDX_SEQ = 0,
  17982. CERTEXTASN_IDX_OID,
  17983. CERTEXTASN_IDX_CRIT,
  17984. CERTEXTASN_IDX_VAL,
  17985. };
  17986. /* Number of items in ASN.1 template for Extension. */
  17987. #define certExtASN_Length (sizeof(certExtASN) / sizeof(ASNItem))
  17988. #endif
  17989. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \
  17990. && defined(HAVE_OID_DECODING)
  17991. int wc_SetUnknownExtCallback(DecodedCert* cert,
  17992. wc_UnknownExtCallback cb) {
  17993. if (cert == NULL) {
  17994. return BAD_FUNC_ARG;
  17995. }
  17996. cert->unknownExtCallback = cb;
  17997. return 0;
  17998. }
  17999. #endif
  18000. /*
  18001. * Processing the Certificate Extensions. This does not modify the current
  18002. * index. It is works starting with the recorded extensions pointer.
  18003. */
  18004. static int DecodeCertExtensions(DecodedCert* cert)
  18005. {
  18006. #ifndef WOLFSSL_ASN_TEMPLATE
  18007. int ret = 0;
  18008. word32 idx = 0;
  18009. int sz = cert->extensionsSz;
  18010. const byte* input = cert->extensions;
  18011. int length;
  18012. word32 oid;
  18013. byte critical = 0;
  18014. byte criticalFail = 0;
  18015. byte tag = 0;
  18016. WOLFSSL_ENTER("DecodeCertExtensions");
  18017. if (input == NULL || sz == 0)
  18018. return BAD_FUNC_ARG;
  18019. #ifdef WOLFSSL_CERT_REQ
  18020. if (!cert->isCSR)
  18021. #endif
  18022. { /* Not included in CSR */
  18023. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  18024. return ASN_PARSE_E;
  18025. }
  18026. if (tag != ASN_EXTENSIONS) {
  18027. WOLFSSL_MSG("\tfail: should be an EXTENSIONS");
  18028. return ASN_PARSE_E;
  18029. }
  18030. if (GetLength(input, &idx, &length, sz) < 0) {
  18031. WOLFSSL_MSG("\tfail: invalid length");
  18032. return ASN_PARSE_E;
  18033. }
  18034. }
  18035. if (GetSequence(input, &idx, &length, sz) < 0) {
  18036. WOLFSSL_MSG("\tfail: should be a SEQUENCE (1)");
  18037. return ASN_PARSE_E;
  18038. }
  18039. while (idx < (word32)sz) {
  18040. word32 localIdx;
  18041. if (GetSequence(input, &idx, &length, sz) < 0) {
  18042. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  18043. return ASN_PARSE_E;
  18044. }
  18045. oid = 0;
  18046. if ((ret = GetObjectId(input, &idx, &oid, oidCertExtType, sz)) < 0) {
  18047. WOLFSSL_MSG("\tfail: OBJECT ID");
  18048. return ret;
  18049. }
  18050. /* check for critical flag */
  18051. critical = 0;
  18052. if ((idx + 1) > (word32)sz) {
  18053. WOLFSSL_MSG("\tfail: malformed buffer");
  18054. return BUFFER_E;
  18055. }
  18056. localIdx = idx;
  18057. if (GetASNTag(input, &localIdx, &tag, sz) == 0) {
  18058. if (tag == ASN_BOOLEAN) {
  18059. ret = GetBoolean(input, &idx, sz);
  18060. if (ret < 0) {
  18061. WOLFSSL_MSG("\tfail: critical boolean");
  18062. return ret;
  18063. }
  18064. critical = (byte)ret;
  18065. }
  18066. }
  18067. /* process the extension based on the OID */
  18068. ret = GetOctetString(input, &idx, &length, sz);
  18069. if (ret < 0) {
  18070. WOLFSSL_MSG("\tfail: bad OCTET STRING");
  18071. return ret;
  18072. }
  18073. ret = DecodeExtensionType(input + idx, length, oid, critical, cert,
  18074. NULL);
  18075. if (ret == ASN_CRIT_EXT_E) {
  18076. ret = 0;
  18077. criticalFail = 1;
  18078. }
  18079. if (ret < 0)
  18080. goto end;
  18081. idx += length;
  18082. }
  18083. ret = criticalFail ? ASN_CRIT_EXT_E : 0;
  18084. end:
  18085. return ret;
  18086. #else
  18087. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  18088. ASNGetData dataExtsASN[certExtHdrASN_Length];
  18089. int ret = 0;
  18090. const byte* input = cert->extensions;
  18091. int sz = cert->extensionsSz;
  18092. word32 idx = 0;
  18093. int criticalRet = 0;
  18094. int offset = 0;
  18095. WOLFSSL_ENTER("DecodeCertExtensions");
  18096. if (input == NULL || sz == 0)
  18097. ret = BAD_FUNC_ARG;
  18098. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, cert->heap);
  18099. #ifdef WOLFSSL_CERT_REQ
  18100. if (cert->isCSR) {
  18101. offset = CERTEXTHDRASN_IDX_EXTSEQ;
  18102. }
  18103. #endif
  18104. if (ret == 0) {
  18105. /* Clear dynamic data. */
  18106. XMEMSET(dataExtsASN, 0, sizeof(dataExtsASN));
  18107. /* Parse extensions header. */
  18108. ret = GetASN_Items(certExtHdrASN + offset, dataExtsASN + offset,
  18109. certExtHdrASN_Length - offset, 0, input, &idx, sz);
  18110. }
  18111. /* Parse each extension. */
  18112. while ((ret == 0) && (idx < (word32)sz)) {
  18113. byte critical = 0;
  18114. int isUnknownExt = 0;
  18115. /* Clear dynamic data. */
  18116. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  18117. /* Ensure OID is an extention type. */
  18118. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  18119. /* Set criticality variable. */
  18120. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  18121. /* Parse extension wrapper. */
  18122. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  18123. &idx, sz);
  18124. if (ret == 0) {
  18125. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  18126. int length = dataASN[CERTEXTASN_IDX_VAL].length;
  18127. /* Decode the extension by type. */
  18128. ret = DecodeExtensionType(input + idx, length, oid, critical, cert,
  18129. &isUnknownExt);
  18130. #if defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_DECODING)
  18131. if (isUnknownExt && (cert->unknownExtCallback != NULL)) {
  18132. word16 decOid[MAX_OID_SZ];
  18133. word32 decOidSz = sizeof(decOid);
  18134. ret = DecodeObjectId(
  18135. dataASN[CERTEXTASN_IDX_OID].data.oid.data,
  18136. dataASN[CERTEXTASN_IDX_OID].data.oid.length,
  18137. decOid, &decOidSz);
  18138. if (ret != 0) {
  18139. /* Should never get here as the extension was successfully
  18140. * decoded earlier. Something might be corrupted. */
  18141. WOLFSSL_MSG("DecodeObjectId() failed. Corruption?");
  18142. WOLFSSL_ERROR(ret);
  18143. }
  18144. ret = cert->unknownExtCallback(decOid, decOidSz, critical,
  18145. dataASN[CERTEXTASN_IDX_VAL].data.buffer.data,
  18146. dataASN[CERTEXTASN_IDX_VAL].length);
  18147. }
  18148. #endif
  18149. (void)isUnknownExt;
  18150. /* Move index on to next extension. */
  18151. idx += length;
  18152. }
  18153. /* Don't fail criticality until all other extensions have been checked.
  18154. */
  18155. if (ret == ASN_CRIT_EXT_E) {
  18156. criticalRet = ASN_CRIT_EXT_E;
  18157. ret = 0;
  18158. }
  18159. }
  18160. if (ret == 0) {
  18161. /* Use criticality return. */
  18162. ret = criticalRet;
  18163. }
  18164. FREE_ASNGETDATA(dataASN, cert->heap);
  18165. return ret;
  18166. #endif
  18167. }
  18168. #ifdef WOLFSSL_ASN_TEMPLATE
  18169. /* ASN template for an X509 certificate.
  18170. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  18171. */
  18172. static const ASNItem x509CertASN[] = {
  18173. /* Certificate ::= SEQUENCE */
  18174. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18175. /* tbsCertificate TBSCertificate */
  18176. /* TBSCertificate ::= SEQUENCE */
  18177. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18178. /* version [0] EXPLICT Version DEFAULT v1 */
  18179. /* TBS_VER */ { 2, ASN_CONTEXT_SPECIFIC | ASN_X509_CERT_VERSION, 1, 1, 1 },
  18180. /* Version ::= INTEGER { v1(0), v2(1), v3(2) */
  18181. /* TBS_VER_INT */ { 3, ASN_INTEGER, 0, 0, 0 },
  18182. /* serialNumber CertificateSerialNumber */
  18183. /* CetificateSerialNumber ::= INTEGER */
  18184. /* TBS_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
  18185. /* signature AlgorithmIdentifier */
  18186. /* AlgorithmIdentifier ::= SEQUENCE */
  18187. /* TBS_ALGOID_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18188. /* Algorithm OBJECT IDENTIFIER */
  18189. /* TBS_ALGOID_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  18190. /* parameters ANY defined by algorithm OPTIONAL */
  18191. /* TBS_ALGOID_PARAMS_NULL */ { 3, ASN_TAG_NULL, 0, 0, 2 },
  18192. #ifdef WC_RSA_PSS
  18193. /* TBS_ALGOID_PARAMS */ { 3, ASN_SEQUENCE, 1, 0, 2 },
  18194. #endif
  18195. /* issuer Name */
  18196. /* TBS_ISSUER_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  18197. /* validity Validity */
  18198. /* Validity ::= SEQUENCE */
  18199. /* TBS_VALIDITY_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18200. /* notBefore Time */
  18201. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  18202. /* TBS_VALIDITY_NOTB_UTC */ { 3, ASN_UTC_TIME, 0, 0, 2 },
  18203. /* TBS_VALIDITY_NOTB_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 2 },
  18204. /* notAfter Time */
  18205. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  18206. /* TBS_VALIDITY_NOTA_UTC */ { 3, ASN_UTC_TIME, 0, 0, 3 },
  18207. /* TBS_VALIDITY_NOTA_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 3 },
  18208. /* subject Name */
  18209. /* TBS_SUBJECT_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  18210. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  18211. /* TBS_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18212. /* algorithm AlgorithmIdentifier */
  18213. /* AlgorithmIdentifier ::= SEQUENCE */
  18214. /* TBS_SPUBKEYINFO_ALGO_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  18215. /* Algorithm OBJECT IDENTIFIER */
  18216. /* TBS_SPUBKEYINFO_ALGO_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  18217. /* parameters ANY defined by algorithm OPTIONAL */
  18218. /* TBS_SPUBKEYINFO_ALGO_NULL */ { 4, ASN_TAG_NULL, 0, 0, 2 },
  18219. /* TBS_SPUBKEYINFO_ALGO_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 2 },
  18220. #ifdef WC_RSA_PSS
  18221. /* TBS_SPUBKEYINFO_ALGO_P_SEQ */ { 4, ASN_SEQUENCE, 1, 0, 2 },
  18222. #endif
  18223. /* subjectPublicKey BIT STRING */
  18224. /* TBS_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  18225. /* issuerUniqueID UniqueIdentfier OPTIONAL */
  18226. /* TBS_ISSUERUID */ { 2, ASN_CONTEXT_SPECIFIC | 1, 0, 0, 1 },
  18227. /* subjectUniqueID UniqueIdentfier OPTIONAL */
  18228. /* TBS_SUBJECTUID */ { 2, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 1 },
  18229. /* extensions Extensions OPTIONAL */
  18230. /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 1 },
  18231. /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
  18232. /* signatureAlgorithm AlgorithmIdentifier */
  18233. /* AlgorithmIdentifier ::= SEQUENCE */
  18234. /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18235. /* Algorithm OBJECT IDENTIFIER */
  18236. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  18237. /* parameters ANY defined by algorithm OPTIONAL */
  18238. /* SIGALGO_PARAMS_NULL */ { 2, ASN_TAG_NULL, 0, 0, 2 },
  18239. #ifdef WC_RSA_PSS
  18240. /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  18241. #endif
  18242. /* signature BIT STRING */
  18243. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  18244. };
  18245. enum {
  18246. X509CERTASN_IDX_SEQ = 0,
  18247. X509CERTASN_IDX_TBS_SEQ,
  18248. X509CERTASN_IDX_TBS_VER,
  18249. X509CERTASN_IDX_TBS_VER_INT,
  18250. X509CERTASN_IDX_TBS_SERIAL,
  18251. X509CERTASN_IDX_TBS_ALGOID_SEQ,
  18252. X509CERTASN_IDX_TBS_ALGOID_OID,
  18253. X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL,
  18254. #ifdef WC_RSA_PSS
  18255. X509CERTASN_IDX_TBS_ALGOID_PARAMS,
  18256. #endif
  18257. X509CERTASN_IDX_TBS_ISSUER_SEQ,
  18258. X509CERTASN_IDX_TBS_VALIDITY_SEQ,
  18259. X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC,
  18260. X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT,
  18261. X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC,
  18262. X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT,
  18263. X509CERTASN_IDX_TBS_SUBJECT_SEQ,
  18264. X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ,
  18265. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
  18266. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID,
  18267. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_NULL,
  18268. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID,
  18269. #ifdef WC_RSA_PSS
  18270. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_P_SEQ,
  18271. #endif
  18272. X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY,
  18273. X509CERTASN_IDX_TBS_ISSUERUID,
  18274. X509CERTASN_IDX_TBS_SUBJECTUID,
  18275. X509CERTASN_IDX_TBS_EXT,
  18276. X509CERTASN_IDX_TBS_EXT_SEQ,
  18277. X509CERTASN_IDX_SIGALGO_SEQ,
  18278. X509CERTASN_IDX_SIGALGO_OID,
  18279. X509CERTASN_IDX_SIGALGO_PARAMS_NULL,
  18280. #ifdef WC_RSA_PSS
  18281. X509CERTASN_IDX_SIGALGO_PARAMS,
  18282. #endif
  18283. X509CERTASN_IDX_SIGNATURE,
  18284. };
  18285. /* Number of items in ASN template for an X509 certificate. */
  18286. #define x509CertASN_Length (sizeof(x509CertASN) / sizeof(ASNItem))
  18287. /* Check the data data.
  18288. *
  18289. * @param [in] dataASN ASN template dynamic data item.
  18290. * @param [in] dataType BEFORE or AFTER date.
  18291. * @return 0 on success.
  18292. * @return ASN_TIME_E when BER tag is nor UTC or GENERALIZED time.
  18293. * @return ASN_DATE_SZ_E when time data is not supported.
  18294. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  18295. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  18296. */
  18297. static int CheckDate(ASNGetData *dataASN, int dateType)
  18298. {
  18299. int ret = 0;
  18300. /* Check BER tag is valid. */
  18301. if ((dataASN->tag != ASN_UTC_TIME) &&
  18302. (dataASN->tag != ASN_GENERALIZED_TIME)) {
  18303. ret = ASN_TIME_E;
  18304. }
  18305. /* Check date length is valid. */
  18306. if ((ret == 0) && ((dataASN->length > MAX_DATE_SIZE) ||
  18307. (dataASN->length < MIN_DATE_SIZE))) {
  18308. ret = ASN_DATE_SZ_E;
  18309. }
  18310. #ifndef NO_ASN_TIME
  18311. /* Check date is a valid string and BEFORE or AFTER now. */
  18312. if ((ret == 0) &&
  18313. (!XVALIDATE_DATE(dataASN->data.ref.data, dataASN->tag, dateType))) {
  18314. if (dateType == BEFORE) {
  18315. ret = ASN_BEFORE_DATE_E;
  18316. }
  18317. else {
  18318. ret = ASN_AFTER_DATE_E;
  18319. }
  18320. }
  18321. #endif
  18322. (void)dateType;
  18323. return ret;
  18324. }
  18325. /* Decode a certificate. Internal/non-public API.
  18326. *
  18327. * @param [in] cert Certificate object.
  18328. * @param [in] verify Whether to verify dates before and after now.
  18329. * @param [out] criticalExt Critical extension return code.
  18330. * @param [out] badDateRet Bad date return code.
  18331. * @param [in] stopAtPubKey Stop parsing before subkectPublicKeyInfo.
  18332. * @param [in] stopAfterPubKey Stop parsing after subkectPublicKeyInfo.
  18333. * @return 0 on success.
  18334. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  18335. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  18336. * @return ASN_DATE_SZ_E when time data is not supported.
  18337. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  18338. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  18339. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18340. * is invalid.
  18341. * @return BUFFER_E when data in buffer is too small.
  18342. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  18343. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  18344. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  18345. * non-zero length.
  18346. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  18347. */
  18348. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  18349. int* badDateRet, int stopAtPubKey,
  18350. int stopAfterPubKey)
  18351. {
  18352. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  18353. int ret = 0;
  18354. int badDate = 0;
  18355. int i;
  18356. byte version;
  18357. word32 idx;
  18358. word32 serialSz;
  18359. int done = 0;
  18360. CALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  18361. if (ret == 0) {
  18362. version = 0;
  18363. serialSz = EXTERNAL_SERIAL_SIZE;
  18364. /* Get the version and put the serial number into the buffer. */
  18365. GetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT], &version);
  18366. GetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
  18367. &serialSz);
  18368. /* Check OID types for signature, algorithm, ECC curve and sigAlg. */
  18369. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
  18370. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
  18371. oidKeyType);
  18372. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
  18373. oidCurveType);
  18374. GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
  18375. /* Parse the X509 certificate. */
  18376. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1,
  18377. cert->source, &cert->srcIdx, cert->maxIdx);
  18378. }
  18379. /* Check version is valid/supported - can't be negative. */
  18380. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  18381. WOLFSSL_MSG("Unexpected certificate version");
  18382. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18383. ret = ASN_PARSE_E;
  18384. }
  18385. if (ret == 0) {
  18386. /* Set fields extracted from data. */
  18387. cert->version = version;
  18388. cert->serialSz = serialSz;
  18389. cert->signatureOID = dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum;
  18390. cert->keyOID = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID].data.oid.sum;
  18391. cert->certBegin = dataASN[X509CERTASN_IDX_TBS_SEQ].offset;
  18392. /* No bad date error - don't always care. */
  18393. badDate = 0;
  18394. /* Find the item with the BEFORE date and check it. */
  18395. i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].tag != 0)
  18396. ? X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC
  18397. : X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT;
  18398. if ((CheckDate(&dataASN[i], BEFORE) < 0) && verify) {
  18399. badDate = ASN_BEFORE_DATE_E;
  18400. }
  18401. /* Store reference to BEFOREdate. */
  18402. cert->beforeDate = GetASNItem_Addr(dataASN[i], cert->source);
  18403. cert->beforeDateLen = GetASNItem_Length(dataASN[i], cert->source);
  18404. /* Find the item with the AFTER date and check it. */
  18405. i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].tag != 0)
  18406. ? X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC
  18407. : X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT;
  18408. if ((CheckDate(&dataASN[i], AFTER) < 0) && verify) {
  18409. badDate = ASN_AFTER_DATE_E;
  18410. }
  18411. /* Store reference to AFTER date. */
  18412. cert->afterDate = GetASNItem_Addr(dataASN[i], cert->source);
  18413. cert->afterDateLen = GetASNItem_Length(dataASN[i], cert->source);
  18414. /* Get the issuer name and calculate hash. */
  18415. idx = dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
  18416. ret = GetCertName(cert, cert->issuer, cert->issuerHash, ISSUER,
  18417. cert->source, &idx,
  18418. dataASN[X509CERTASN_IDX_TBS_VALIDITY_SEQ].offset);
  18419. }
  18420. if (ret == 0) {
  18421. /* Get the subject name and calculate hash. */
  18422. idx = dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
  18423. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  18424. cert->source, &idx,
  18425. dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset);
  18426. }
  18427. if (ret == 0) {
  18428. /* Determine if self signed by comparing issuer and subject hashes. */
  18429. #ifdef WOLFSSL_CERT_REQ
  18430. if (cert->isCSR)
  18431. cert->selfSigned = 1;
  18432. else
  18433. #endif
  18434. {
  18435. cert->selfSigned = XMEMCMP(cert->issuerHash, cert->subjectHash,
  18436. KEYID_SIZE) == 0 ? 1 : 0;
  18437. }
  18438. if (stopAtPubKey) {
  18439. /* Return any bad date error through badDateRet and return offset of
  18440. * subjectPublicKeyInfo.
  18441. */
  18442. if (badDateRet != NULL) {
  18443. *badDateRet = badDate;
  18444. }
  18445. ret = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset;
  18446. done = 1;
  18447. }
  18448. }
  18449. if ((ret == 0) && (!done)) {
  18450. /* Store the signature information. */
  18451. cert->sigIndex = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
  18452. GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE],
  18453. &cert->signature, &cert->sigLength);
  18454. /* Make sure 'signature' and 'signatureAlgorithm' are the same. */
  18455. if (dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum
  18456. != cert->signatureOID) {
  18457. WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
  18458. ret = ASN_SIG_OID_E;
  18459. }
  18460. /* Parameters not allowed after ECDSA or EdDSA algorithm OID. */
  18461. else if (IsSigAlgoECC(cert->signatureOID)) {
  18462. if ((dataASN[X509CERTASN_IDX_SIGALGO_PARAMS_NULL].tag != 0)
  18463. #ifdef WC_RSA_PSS
  18464. || (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0)
  18465. #endif
  18466. ) {
  18467. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18468. ret = ASN_PARSE_E;
  18469. }
  18470. }
  18471. #ifdef WC_RSA_PSS
  18472. /* Check parameters starting with a SEQUENCE. */
  18473. else if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
  18474. word32 oid = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
  18475. word32 sigAlgParamsSz;
  18476. /* Parameters only with RSA PSS. */
  18477. if (oid != CTC_RSASSAPSS) {
  18478. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18479. ret = ASN_PARSE_E;
  18480. }
  18481. if (ret == 0) {
  18482. const byte* tbsParams;
  18483. word32 tbsParamsSz;
  18484. const byte* sigAlgParams;
  18485. /* Check RSA PSS parameters are the same. */
  18486. tbsParams =
  18487. GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  18488. cert->source);
  18489. tbsParamsSz =
  18490. GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  18491. cert->source);
  18492. sigAlgParams =
  18493. GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  18494. cert->source);
  18495. sigAlgParamsSz =
  18496. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  18497. cert->source);
  18498. if ((tbsParamsSz != sigAlgParamsSz) ||
  18499. (XMEMCMP(tbsParams, sigAlgParams, tbsParamsSz) != 0)) {
  18500. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18501. ret = ASN_PARSE_E;
  18502. }
  18503. }
  18504. if (ret == 0) {
  18505. /* Store parameters for use in signature verification. */
  18506. cert->sigParamsIndex =
  18507. dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].offset;
  18508. cert->sigParamsLength = sigAlgParamsSz;
  18509. }
  18510. }
  18511. #endif
  18512. }
  18513. if ((ret == 0) && (!done)) {
  18514. /* Parse the public key. */
  18515. idx = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset;
  18516. ret = GetCertKey(cert, cert->source, &idx,
  18517. dataASN[X509CERTASN_IDX_TBS_ISSUERUID].offset);
  18518. if ((ret == 0) && stopAfterPubKey) {
  18519. /* Return any bad date error through badDateRed and return offset
  18520. * after subjectPublicKeyInfo.
  18521. */
  18522. if (badDateRet != NULL) {
  18523. *badDateRet = badDate;
  18524. }
  18525. done = 1;
  18526. }
  18527. }
  18528. if ((ret == 0) && (!done) &&
  18529. (dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data != NULL)) {
  18530. #ifndef ALLOW_V1_EXTENSIONS
  18531. /* Certificate extensions were only defined in version 2. */
  18532. if (cert->version < 2) {
  18533. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  18534. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  18535. ret = ASN_VERSION_E;
  18536. }
  18537. #endif
  18538. if (ret == 0) {
  18539. /* Save references to extension data. */
  18540. cert->extensions = GetASNItem_Addr(
  18541. dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
  18542. cert->extensionsSz = GetASNItem_Length(
  18543. dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
  18544. cert->extensionsIdx = dataASN[X509CERTASN_IDX_TBS_EXT].offset;
  18545. /* Decode the extension data starting at [3]. */
  18546. ret = DecodeCertExtensions(cert);
  18547. if (criticalExt != NULL) {
  18548. if (ret == ASN_CRIT_EXT_E) {
  18549. /* Return critical extension not recognized. */
  18550. *criticalExt = ret;
  18551. ret = 0;
  18552. }
  18553. else {
  18554. /* No critical extension error. */
  18555. *criticalExt = 0;
  18556. }
  18557. }
  18558. }
  18559. if (ret == 0) {
  18560. /* Advance past extensions. */
  18561. cert->srcIdx = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
  18562. }
  18563. }
  18564. if ((ret == 0) && (!done) && (badDate != 0)) {
  18565. /* Parsed whole certificate fine but return any date errors. */
  18566. ret = badDate;
  18567. }
  18568. FREE_ASNGETDATA(dataASN, cert->heap);
  18569. return ret;
  18570. }
  18571. /* Decode BER/DER data into certificate object.
  18572. *
  18573. * BER/DER data information held in source, srcIdx and maxIdx fields of
  18574. * certificate object.
  18575. *
  18576. * @param [in] cert Decoded certificate object.
  18577. * @param [in] verify Whether to find CA and verify certificate.
  18578. * @param [in] criticalExt Any error for critical extensions not recognized.
  18579. * @return 0 on success.
  18580. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  18581. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  18582. * @return ASN_DATE_SZ_E when time data is not supported.
  18583. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  18584. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  18585. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18586. * is invalid.
  18587. * @return BUFFER_E when data in buffer is too small.
  18588. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  18589. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  18590. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  18591. * non-zero length.
  18592. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  18593. */
  18594. int DecodeCert(DecodedCert* cert, int verify, int* criticalExt)
  18595. {
  18596. return DecodeCertInternal(cert, verify, criticalExt, NULL, 0, 0);
  18597. }
  18598. #ifdef WOLFSSL_CERT_REQ
  18599. /* ASN.1 template for certificate request Attribute.
  18600. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  18601. */
  18602. static const ASNItem reqAttrASN[] = {
  18603. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18604. /* type */
  18605. /* TYPE */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  18606. /* values */
  18607. /* VALS */ { 1, ASN_SET, 1, 0, 0 },
  18608. };
  18609. enum {
  18610. REQATTRASN_IDX_SEQ = 0,
  18611. REQATTRASN_IDX_TYPE,
  18612. REQATTRASN_IDX_VALS,
  18613. };
  18614. /* Number of items in ASN.1 template for certificate request Attribute. */
  18615. #define reqAttrASN_Length (sizeof(reqAttrASN) / sizeof(ASNItem))
  18616. /* ASN.1 template for a string choice. */
  18617. static const ASNItem strAttrASN[] = {
  18618. { 0, 0, 0, 0, 0 },
  18619. };
  18620. enum {
  18621. STRATTRASN_IDX_STR = 0,
  18622. };
  18623. /* Number of items in ASN.1 template for a string choice. */
  18624. #define strAttrASN_Length (sizeof(strAttrASN) / sizeof(ASNItem))
  18625. /* ASN.1 choices for types for a string in an attribute. */
  18626. static const byte strAttrChoice[] = {
  18627. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, 0
  18628. };
  18629. /* Decode a certificate request attribute's value.
  18630. *
  18631. * @param [in] cert Certificate request object.
  18632. * @param [out] criticalExt Critical extension return code.
  18633. * @param [in] oid OID decribing which attribute was found.
  18634. * @param [in] aIdx Index into certificate source to start parsing.
  18635. * @param [in] input Attribute value data.
  18636. * @param [in] maxIdx Maximum index to parse to.
  18637. * @return 0 on success.
  18638. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18639. * is invalid.
  18640. */
  18641. static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt,
  18642. word32 oid, word32 aIdx, const byte* input, word32 maxIdx)
  18643. {
  18644. int ret = 0;
  18645. word32 idx = 0;
  18646. ASNGetData strDataASN[strAttrASN_Length];
  18647. switch (oid) {
  18648. case PKCS9_CONTENT_TYPE_OID:
  18649. /* Clear dynamic data and specify choices acceptable. */
  18650. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  18651. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  18652. /* Parse a string. */
  18653. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  18654. 1, input, &idx, maxIdx);
  18655. if (ret == 0) {
  18656. /* Store references to password data. */
  18657. cert->contentType =
  18658. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  18659. cert->contentTypeLen =
  18660. strDataASN[STRATTRASN_IDX_STR].data.ref.length;
  18661. }
  18662. break;
  18663. /* A password by which the entity may request certificate revocation.
  18664. * PKCS#9: RFC 2985, 5.4.1 - Challenge password
  18665. */
  18666. case CHALLENGE_PASSWORD_OID:
  18667. /* Clear dynamic data and specify choices acceptable. */
  18668. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  18669. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  18670. /* Parse a string. */
  18671. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  18672. 1, input, &idx, maxIdx);
  18673. if (ret == 0) {
  18674. /* Store references to password data. */
  18675. cert->cPwd =
  18676. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  18677. cert->cPwdLen = strDataASN[STRATTRASN_IDX_STR].data.ref.length;
  18678. }
  18679. break;
  18680. /* Requested serial number to issue with.
  18681. * PKCS#9: RFC 2985, 5.2.10 - Serial Number
  18682. * (References: ISO/IEC 9594-6:1997)
  18683. */
  18684. case SERIAL_NUMBER_OID:
  18685. /* Clear dynamic data and specify choices acceptable. */
  18686. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  18687. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  18688. /* Parse a string. */
  18689. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  18690. 1, input, &idx, maxIdx);
  18691. if (ret == 0) {
  18692. /* Store references to serial number. */
  18693. cert->sNum =
  18694. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  18695. cert->sNumLen = strDataASN[STRATTRASN_IDX_STR].data.ref.length;
  18696. /* Store serial number if small enough. */
  18697. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  18698. XMEMCPY(cert->serial, cert->sNum, cert->sNumLen);
  18699. cert->serialSz = cert->sNumLen;
  18700. }
  18701. }
  18702. break;
  18703. /* Certificate extensions to be included in generated certificate.
  18704. * PKCS#9: RFC 2985, 5.4.2 - Extension request
  18705. */
  18706. case EXTENSION_REQUEST_OID:
  18707. /* Store references to all extensions. */
  18708. cert->extensions = input;
  18709. cert->extensionsSz = maxIdx;
  18710. cert->extensionsIdx = aIdx;
  18711. /* Decode and validate extensions. */
  18712. ret = DecodeCertExtensions(cert);
  18713. if (ret == ASN_CRIT_EXT_E) {
  18714. /* Return critical extension not recognized. */
  18715. *criticalExt = ret;
  18716. ret = 0;
  18717. }
  18718. else {
  18719. /* No critical extension error. */
  18720. *criticalExt = 0;
  18721. }
  18722. break;
  18723. default:
  18724. ret = ASN_PARSE_E;
  18725. break;
  18726. }
  18727. return ret;
  18728. }
  18729. /* Decode attributes of a BER encoded certificate request.
  18730. *
  18731. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  18732. *
  18733. * Outer sequence has been removed.
  18734. *
  18735. * @param [in] cert Certificate request object.
  18736. * @param [out] criticalExt Critical extension return code.
  18737. * @param [in] idx Index into certificate source to start parsing.
  18738. * @param [in] maxIdx Maximum index to parse to.
  18739. * @return 0 on success.
  18740. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  18741. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18742. * is invalid.
  18743. * @return BUFFER_E when data in buffer is too small.
  18744. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  18745. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  18746. * non-zero length.
  18747. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  18748. */
  18749. static int DecodeCertReqAttributes(DecodedCert* cert, int* criticalExt,
  18750. word32 idx, word32 maxIdx)
  18751. {
  18752. DECL_ASNGETDATA(dataASN, reqAttrASN_Length);
  18753. int ret = 0;
  18754. WOLFSSL_ENTER("DecodeCertReqAttributes");
  18755. ALLOC_ASNGETDATA(dataASN, reqAttrASN_Length, ret, cert->heap);
  18756. /* Parse each attribute until all data used up. */
  18757. while ((ret == 0) && (idx < maxIdx)) {
  18758. /* Clear dynamic data. */
  18759. XMEMSET(dataASN, 0, sizeof(ASNGetData) * reqAttrASN_Length);
  18760. GetASN_OID(&dataASN[REQATTRASN_IDX_TYPE], oidIgnoreType);
  18761. /* Parse an attribute. */
  18762. ret = GetASN_Items(reqAttrASN, dataASN, reqAttrASN_Length, 0,
  18763. cert->source, &idx, maxIdx);
  18764. /* idx is now at end of attribute data. */
  18765. if (ret == 0) {
  18766. ret = DecodeCertReqAttrValue(cert, criticalExt,
  18767. dataASN[REQATTRASN_IDX_TYPE].data.oid.sum,
  18768. GetASNItem_DataIdx(dataASN[REQATTRASN_IDX_VALS], cert->source),
  18769. dataASN[REQATTRASN_IDX_VALS].data.ref.data,
  18770. dataASN[REQATTRASN_IDX_VALS].data.ref.length);
  18771. }
  18772. }
  18773. FREE_ASNGETDATA(dataASN, cert->heap);
  18774. return ret;
  18775. }
  18776. /* ASN.1 template for a certificate request.
  18777. * PKCS#10: RFC 2986, 4.1 - CertificationRequestInfo
  18778. * PKCS#10: RFC 2986, 4.2 - CertificationRequest
  18779. */
  18780. static const ASNItem certReqASN[] = {
  18781. /* CertificationRequest */
  18782. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18783. /* CertificationRequestInfo */
  18784. /* INFO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18785. /* version INTEGER { v1(0), v2(1), v3(2) */
  18786. /* INFO_VER */ { 2, ASN_INTEGER, 0, 0, 0 },
  18787. /* subject Name */
  18788. /* INFO_SUBJ_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  18789. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  18790. /* INFO_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18791. /* algorithm AlgorithmIdentifier */
  18792. /* INFO_SPUBKEYINFO_ALGOID_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  18793. /* Algorithm OBJECT IDENTIFIER */
  18794. /* INFO_SPUBKEYINFO_ALGOID_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  18795. /* parameters ANY defined by algorithm OPTIONAL */
  18796. /* INFO_SPUBKEYINFO_ALGOID_NULL */ { 4, ASN_TAG_NULL, 0, 0, 1 },
  18797. /* INFO_SPUBKEYINFO_ALGOID_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 1 },
  18798. /* INFO_SPUBKEYINFO_ALGOID_PARAMS */ { 4, ASN_SEQUENCE, 1, 0, 1 },
  18799. /* subjectPublicKey BIT STRING */
  18800. /* INFO_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  18801. /* attributes [0] Attributes */
  18802. /* INFO_ATTRS */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  18803. /* signatureAlgorithm AlgorithmIdentifier */
  18804. /* INFO_SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18805. /* Algorithm OBJECT IDENTIFIER */
  18806. /* INFO_SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  18807. /* parameters ANY defined by algorithm OPTIONAL */
  18808. /* INFO_SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  18809. /* signature BIT STRING */
  18810. /* INFO_SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  18811. };
  18812. enum {
  18813. CERTREQASN_IDX_SEQ = 0,
  18814. CERTREQASN_IDX_INFO_SEQ,
  18815. CERTREQASN_IDX_INFO_VER,
  18816. CERTREQASN_IDX_INFO_SUBJ_SEQ,
  18817. CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ,
  18818. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_SEQ,
  18819. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID,
  18820. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_NULL,
  18821. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID,
  18822. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_PARAMS,
  18823. CERTREQASN_IDX_INFO_SPUBKEYINFO_PUBKEY,
  18824. CERTREQASN_IDX_INFO_ATTRS,
  18825. CERTREQASN_IDX_INFO_SIGALGO_SEQ,
  18826. CERTREQASN_IDX_INFO_SIGALGO_OID,
  18827. CERTREQASN_IDX_INFO_SIGALGO_NULL,
  18828. CERTREQASN_IDX_INFO_SIGNATURE,
  18829. };
  18830. /* Number of items in ASN.1 template for a certificate request. */
  18831. #define certReqASN_Length (sizeof(certReqASN) / sizeof(ASNItem))
  18832. /* Parse BER encoded certificate request.
  18833. *
  18834. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  18835. *
  18836. * @param [in] cert Certificate request object.
  18837. * @param [out] criticalExt Critical extension return code.
  18838. * @return 0 on success.
  18839. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  18840. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18841. * is invalid.
  18842. * @return BUFFER_E when data in buffer is too small.
  18843. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  18844. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  18845. * non-zero length.
  18846. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  18847. * @return MEMORY_E on dynamic memory allocation failure.
  18848. */
  18849. static int DecodeCertReq(DecodedCert* cert, int* criticalExt)
  18850. {
  18851. DECL_ASNGETDATA(dataASN, certReqASN_Length);
  18852. int ret = 0;
  18853. byte version;
  18854. word32 idx;
  18855. CALLOC_ASNGETDATA(dataASN, certReqASN_Length, ret, cert->heap);
  18856. if (ret == 0) {
  18857. /* Default version is 0. */
  18858. version = 0;
  18859. /* Set version var and OID types to expect. */
  18860. GetASN_Int8Bit(&dataASN[CERTREQASN_IDX_INFO_VER], &version);
  18861. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
  18862. oidKeyType);
  18863. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
  18864. oidCurveType);
  18865. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
  18866. /* Parse a certificate request. */
  18867. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1,
  18868. cert->source, &cert->srcIdx, cert->maxIdx);
  18869. }
  18870. /* Check version is valid/supported - can't be negative. */
  18871. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  18872. WOLFSSL_MSG("Unexpected certificate request version");
  18873. ret = ASN_PARSE_E;
  18874. }
  18875. if (ret == 0) {
  18876. /* Set fields of certificate request. */
  18877. cert->version = version;
  18878. cert->signatureOID =
  18879. dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
  18880. cert->keyOID =
  18881. dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID].data.oid.sum;
  18882. cert->certBegin = dataASN[CERTREQASN_IDX_INFO_SEQ].offset;
  18883. /* Parse the subject name. */
  18884. idx = dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ].offset;
  18885. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  18886. cert->source, &idx,
  18887. dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset);
  18888. }
  18889. if (ret == 0) {
  18890. /* Parse the certificate request Attributes. */
  18891. ret = DecodeCertReqAttributes(cert, criticalExt,
  18892. GetASNItem_DataIdx(dataASN[CERTREQASN_IDX_INFO_ATTRS],
  18893. cert->source),
  18894. dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset);
  18895. }
  18896. if (ret == 0) {
  18897. /* Parse the certificate request's key. */
  18898. idx = dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset;
  18899. ret = GetCertKey(cert, cert->source, &idx,
  18900. dataASN[CERTREQASN_IDX_INFO_ATTRS].offset);
  18901. }
  18902. if (ret == 0) {
  18903. /* Store references to signature. */
  18904. cert->sigIndex = dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset;
  18905. GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE],
  18906. &cert->signature, &cert->sigLength);
  18907. }
  18908. FREE_ASNGETDATA(dataASN, cert->heap);
  18909. return ret;
  18910. }
  18911. #endif /* WOLFSSL_CERT_REQ */
  18912. #endif
  18913. int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  18914. {
  18915. int ret;
  18916. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  18917. defined(WOLFSSL_DYN_CERT)
  18918. char* ptr;
  18919. #endif
  18920. ret = ParseCertRelative(cert, type, verify, cm);
  18921. if (ret < 0)
  18922. return ret;
  18923. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  18924. defined(WOLFSSL_DYN_CERT)
  18925. /* cert->subjectCN not stored as copy of WOLFSSL_NO_MALLOC defind */
  18926. if (cert->subjectCNLen > 0) {
  18927. ptr = (char*) XMALLOC(cert->subjectCNLen + 1, cert->heap,
  18928. DYNAMIC_TYPE_SUBJECT_CN);
  18929. if (ptr == NULL)
  18930. return MEMORY_E;
  18931. XMEMCPY(ptr, cert->subjectCN, cert->subjectCNLen);
  18932. ptr[cert->subjectCNLen] = '\0';
  18933. cert->subjectCN = ptr;
  18934. cert->subjectCNStored = 1;
  18935. }
  18936. #endif
  18937. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  18938. defined(WOLFSSL_DYN_CERT)
  18939. /* cert->publicKey not stored as copy if WOLFSSL_NO_MALLOC defined */
  18940. if ((cert->keyOID == RSAk
  18941. #ifdef WC_RSA_PSS
  18942. || cert->keyOID == RSAPSSk
  18943. #endif
  18944. ) && cert->publicKey != NULL && cert->pubKeySize > 0) {
  18945. ptr = (char*) XMALLOC(cert->pubKeySize, cert->heap,
  18946. DYNAMIC_TYPE_PUBLIC_KEY);
  18947. if (ptr == NULL)
  18948. return MEMORY_E;
  18949. XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
  18950. cert->publicKey = (byte *)ptr;
  18951. cert->pubKeyStored = 1;
  18952. }
  18953. #endif
  18954. return ret;
  18955. }
  18956. int wc_ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  18957. {
  18958. return ParseCert(cert, type, verify, cm);
  18959. }
  18960. #if !defined(OPENSSL_EXTRA) && !defined(OPENSSL_EXTRA_X509_SMALL) && \
  18961. !defined(GetCA)
  18962. /* from SSL proper, for locking can't do find here anymore.
  18963. * brought in from internal.h if built with compat layer.
  18964. * if defined(GetCA), it's a predefined macro and these prototypes
  18965. * would conflict.
  18966. */
  18967. #ifdef __cplusplus
  18968. extern "C" {
  18969. #endif
  18970. Signer* GetCA(void* signers, byte* hash);
  18971. #ifndef NO_SKID
  18972. Signer* GetCAByName(void* signers, byte* hash);
  18973. #endif
  18974. #ifdef __cplusplus
  18975. }
  18976. #endif
  18977. #endif /* !OPENSSL_EXTRA && !OPENSSL_EXTRA_X509_SMALL && !GetCA */
  18978. #if defined(WOLFCRYPT_ONLY)
  18979. /* dummy functions, not using wolfSSL so don't need actual ones */
  18980. Signer* GetCA(void* signers, byte* hash)
  18981. {
  18982. (void)hash;
  18983. return (Signer*)signers;
  18984. }
  18985. #ifndef NO_SKID
  18986. Signer* GetCAByName(void* signers, byte* hash)
  18987. {
  18988. (void)hash;
  18989. return (Signer*)signers;
  18990. }
  18991. #endif /* NO_SKID */
  18992. #endif /* WOLFCRYPT_ONLY */
  18993. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  18994. static Signer* GetCABySubjectAndPubKey(DecodedCert* cert, void* cm)
  18995. {
  18996. Signer* ca = NULL;
  18997. if (cert->extSubjKeyIdSet)
  18998. ca = GetCA(cm, cert->extSubjKeyId);
  18999. if (ca == NULL)
  19000. ca = GetCAByName(cm, cert->subjectHash);
  19001. if (ca) {
  19002. if ((ca->pubKeySize == cert->pubKeySize) &&
  19003. (XMEMCMP(ca->publicKey, cert->publicKey, ca->pubKeySize) == 0)) {
  19004. return ca;
  19005. }
  19006. }
  19007. return NULL;
  19008. }
  19009. #endif
  19010. #if defined(WOLFSSL_SMALL_CERT_VERIFY) || defined(OPENSSL_EXTRA)
  19011. #ifdef WOLFSSL_ASN_TEMPLATE
  19012. /* Get the Hash of the Authority Key Identifier from the list of extensions.
  19013. *
  19014. * @param [in] input Input data.
  19015. * @param [in] maxIdx Maximum index for data.
  19016. * @param [out] hash Hash of AKI.
  19017. * @param [out] set Whether the hash buffer was set.
  19018. * @param [in] heap Dynamic memory allocation hint.
  19019. * @return 0 on success.
  19020. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19021. * is invalid.
  19022. * @return MEMORY_E on dynamic memory allocation failure.
  19023. */
  19024. static int GetAKIHash(const byte* input, word32 maxIdx, byte* hash, int* set,
  19025. void* heap)
  19026. {
  19027. /* AKI and Certificate Extenion ASN.1 templates are the same length. */
  19028. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  19029. int ret = 0;
  19030. word32 idx = 0;
  19031. word32 extEndIdx;
  19032. byte* extData;
  19033. word32 extDataSz;
  19034. byte critical;
  19035. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, heap);
  19036. (void)heap;
  19037. extEndIdx = idx + maxIdx;
  19038. /* Step through each extension looking for AKI. */
  19039. while ((ret == 0) && (idx < extEndIdx)) {
  19040. /* Clear dynamic data and check for certificate extension type OIDs. */
  19041. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  19042. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  19043. /* Set criticality variable. */
  19044. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  19045. /* Parse an extension. */
  19046. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  19047. &idx, extEndIdx);
  19048. if (ret == 0) {
  19049. /* Get reference to extension data and move index on past this
  19050. * extension. */
  19051. GetASN_GetRef(&dataASN[CERTEXTASN_IDX_VAL], &extData, &extDataSz);
  19052. idx += extDataSz;
  19053. /* Check whether we have the AKI extension. */
  19054. if (dataASN[CERTEXTASN_IDX_OID].data.oid.sum == AUTH_KEY_OID) {
  19055. /* Clear dynamic data. */
  19056. XMEMSET(dataASN, 0, sizeof(*dataASN) * authKeyIdASN_Length);
  19057. /* Start parsing extension data from the start. */
  19058. idx = 0;
  19059. /* Parse AKI extension data. */
  19060. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length,
  19061. 1, extData, &idx, extDataSz);
  19062. if ((ret == 0) &&
  19063. (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data
  19064. != NULL)) {
  19065. /* We parsed successfully and have data. */
  19066. *set = 1;
  19067. /* Get the hash or hash of the hash if wrong size. */
  19068. ret = GetHashId(
  19069. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  19070. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  19071. hash);
  19072. }
  19073. break;
  19074. }
  19075. }
  19076. }
  19077. FREE_ASNGETDATA(dataASN, heap);
  19078. return ret;
  19079. }
  19080. #endif
  19081. /* Only quick step through the certificate to find fields that are then used
  19082. * in certificate signature verification.
  19083. * Must use the signature OID from the signed part of the certificate.
  19084. * Works also on certificate signing requests.
  19085. *
  19086. * This is only for minimizing dynamic memory usage during TLS certificate
  19087. * chain processing.
  19088. * Doesn't support:
  19089. * OCSP Only: alt lookup using subject and pub key w/o sig check
  19090. */
  19091. static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap,
  19092. void* cm, const byte* pubKey, word32 pubKeySz, int pubKeyOID, int req)
  19093. {
  19094. #ifndef WOLFSSL_ASN_TEMPLATE
  19095. #ifndef WOLFSSL_SMALL_STACK
  19096. SignatureCtx sigCtx[1];
  19097. #else
  19098. SignatureCtx* sigCtx;
  19099. #endif
  19100. byte hash[KEYID_SIZE];
  19101. Signer* ca = NULL;
  19102. word32 idx = 0;
  19103. int len;
  19104. word32 tbsCertIdx = 0;
  19105. word32 sigIndex = 0;
  19106. word32 signatureOID = 0;
  19107. word32 oid = 0;
  19108. word32 issuerIdx = 0;
  19109. word32 issuerSz = 0;
  19110. #ifndef NO_SKID
  19111. int extLen = 0;
  19112. word32 extIdx = 0;
  19113. word32 extEndIdx = 0;
  19114. int extAuthKeyIdSet = 0;
  19115. #endif
  19116. int ret = 0;
  19117. word32 localIdx;
  19118. byte tag;
  19119. const byte* sigParams = NULL;
  19120. word32 sigParamsSz = 0;
  19121. if (cert == NULL) {
  19122. return BAD_FUNC_ARG;
  19123. }
  19124. #ifdef WOLFSSL_SMALL_STACK
  19125. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, DYNAMIC_TYPE_SIGNATURE);
  19126. if (sigCtx == NULL)
  19127. return MEMORY_E;
  19128. #endif
  19129. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  19130. /* Certificate SEQUENCE */
  19131. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19132. ret = ASN_PARSE_E;
  19133. if (ret == 0) {
  19134. tbsCertIdx = idx;
  19135. /* TBSCertificate SEQUENCE */
  19136. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19137. ret = ASN_PARSE_E;
  19138. }
  19139. if (ret == 0) {
  19140. sigIndex = len + idx;
  19141. if ((idx + 1) > certSz)
  19142. ret = BUFFER_E;
  19143. }
  19144. if (ret == 0) {
  19145. /* version - optional */
  19146. localIdx = idx;
  19147. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19148. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  19149. idx++;
  19150. if (GetLength(cert, &idx, &len, certSz) < 0)
  19151. ret = ASN_PARSE_E;
  19152. idx += len;
  19153. }
  19154. }
  19155. }
  19156. if (ret == 0) {
  19157. /* serialNumber */
  19158. if (GetASNHeader(cert, ASN_INTEGER, &idx, &len, certSz) < 0)
  19159. ret = ASN_PARSE_E;
  19160. }
  19161. if (ret == 0) {
  19162. idx += len;
  19163. /* signature */
  19164. if (!req) {
  19165. if (GetAlgoId(cert, &idx, &signatureOID, oidSigType, certSz) < 0)
  19166. ret = ASN_PARSE_E;
  19167. #ifdef WC_RSA_PSS
  19168. else if (signatureOID == CTC_RSASSAPSS) {
  19169. int start = idx;
  19170. sigParams = cert + idx;
  19171. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19172. ret = ASN_PARSE_E;
  19173. if (ret == 0) {
  19174. idx += len;
  19175. sigParamsSz = idx - start;
  19176. }
  19177. }
  19178. #endif
  19179. }
  19180. }
  19181. if (ret == 0) {
  19182. issuerIdx = idx;
  19183. /* issuer for cert or subject for csr */
  19184. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19185. ret = ASN_PARSE_E;
  19186. }
  19187. if (ret == 0) {
  19188. issuerSz = len + idx - issuerIdx;
  19189. }
  19190. #ifndef NO_SKID
  19191. if (!req && ret == 0) {
  19192. idx += len;
  19193. /* validity */
  19194. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19195. ret = ASN_PARSE_E;
  19196. }
  19197. if (!req && ret == 0) {
  19198. idx += len;
  19199. /* subject */
  19200. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19201. ret = ASN_PARSE_E;
  19202. }
  19203. if (ret == 0) {
  19204. idx += len;
  19205. /* subjectPublicKeyInfo */
  19206. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19207. ret = ASN_PARSE_E;
  19208. }
  19209. if (req && ret == 0) {
  19210. idx += len;
  19211. /* attributes */
  19212. if (GetASNHeader_ex(cert,
  19213. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &idx,
  19214. &len, certSz, 1) < 0)
  19215. ret = ASN_PARSE_E;
  19216. }
  19217. if (!req) {
  19218. if (ret == 0) {
  19219. idx += len;
  19220. if ((idx + 1) > certSz)
  19221. ret = BUFFER_E;
  19222. }
  19223. if (ret == 0) {
  19224. /* issuerUniqueID - optional */
  19225. localIdx = idx;
  19226. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19227. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) {
  19228. idx++;
  19229. if (GetLength(cert, &idx, &len, certSz) < 0)
  19230. ret = ASN_PARSE_E;
  19231. idx += len;
  19232. }
  19233. }
  19234. }
  19235. if (ret == 0) {
  19236. if ((idx + 1) > certSz)
  19237. ret = BUFFER_E;
  19238. }
  19239. if (ret == 0) {
  19240. /* subjectUniqueID - optional */
  19241. localIdx = idx;
  19242. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19243. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)) {
  19244. idx++;
  19245. if (GetLength(cert, &idx, &len, certSz) < 0)
  19246. ret = ASN_PARSE_E;
  19247. idx += len;
  19248. }
  19249. }
  19250. }
  19251. if (ret == 0) {
  19252. if ((idx + 1) > certSz)
  19253. ret = BUFFER_E;
  19254. }
  19255. /* extensions - optional */
  19256. localIdx = idx;
  19257. if (ret == 0 && GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  19258. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)) {
  19259. idx++;
  19260. if (GetLength(cert, &idx, &extLen, certSz) < 0)
  19261. ret = ASN_PARSE_E;
  19262. if (ret == 0) {
  19263. if (GetSequence(cert, &idx, &extLen, certSz) < 0)
  19264. ret = ASN_PARSE_E;
  19265. }
  19266. if (ret == 0) {
  19267. extEndIdx = idx + extLen;
  19268. /* Check each extension for the ones we want. */
  19269. while (ret == 0 && idx < extEndIdx) {
  19270. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19271. ret = ASN_PARSE_E;
  19272. if (ret == 0) {
  19273. extIdx = idx;
  19274. if (GetObjectId(cert, &extIdx, &oid, oidCertExtType,
  19275. certSz) < 0) {
  19276. ret = ASN_PARSE_E;
  19277. }
  19278. if (ret == 0) {
  19279. if ((extIdx + 1) > certSz)
  19280. ret = BUFFER_E;
  19281. }
  19282. }
  19283. if (ret == 0) {
  19284. localIdx = extIdx;
  19285. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  19286. tag == ASN_BOOLEAN) {
  19287. if (GetBoolean(cert, &extIdx, certSz) < 0)
  19288. ret = ASN_PARSE_E;
  19289. }
  19290. }
  19291. if (ret == 0) {
  19292. if (GetOctetString(cert, &extIdx, &extLen, certSz) < 0)
  19293. ret = ASN_PARSE_E;
  19294. }
  19295. if (ret == 0) {
  19296. switch (oid) {
  19297. case AUTH_KEY_OID:
  19298. if (GetSequence(cert, &extIdx, &extLen, certSz) < 0)
  19299. ret = ASN_PARSE_E;
  19300. if (ret == 0 && (extIdx + 1) >= certSz)
  19301. ret = BUFFER_E;
  19302. if (ret == 0 &&
  19303. GetASNTag(cert, &extIdx, &tag, certSz) == 0 &&
  19304. tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  19305. if (GetLength(cert, &extIdx, &extLen, certSz) <= 0)
  19306. ret = ASN_PARSE_E;
  19307. if (ret == 0) {
  19308. extAuthKeyIdSet = 1;
  19309. /* Get the hash or hash of the hash if wrong
  19310. * size. */
  19311. ret = GetHashId(cert + extIdx, extLen,
  19312. hash);
  19313. }
  19314. }
  19315. break;
  19316. default:
  19317. break;
  19318. }
  19319. }
  19320. idx += len;
  19321. }
  19322. }
  19323. }
  19324. }
  19325. else if (ret == 0) {
  19326. idx += len;
  19327. }
  19328. if (ret == 0 && pubKey == NULL) {
  19329. if (extAuthKeyIdSet)
  19330. ca = GetCA(cm, hash);
  19331. if (ca == NULL) {
  19332. ret = CalcHashId(cert + issuerIdx, issuerSz, hash);
  19333. if (ret == 0)
  19334. ca = GetCAByName(cm, hash);
  19335. }
  19336. }
  19337. #else
  19338. if (ret == 0 && pubKey == NULL) {
  19339. ret = CalcHashId(cert + issuerIdx, issuerSz, hash);
  19340. if (ret == 0)
  19341. ca = GetCA(cm, hash);
  19342. }
  19343. #endif /* !NO_SKID */
  19344. if (ca == NULL && pubKey == NULL)
  19345. ret = ASN_NO_SIGNER_E;
  19346. if (ret == 0) {
  19347. idx = sigIndex;
  19348. /* signatureAlgorithm */
  19349. if (GetAlgoId(cert, &idx, &oid, oidSigType, certSz) < 0)
  19350. ret = ASN_PARSE_E;
  19351. #ifdef WC_RSA_PSS
  19352. else if (signatureOID == CTC_RSASSAPSS) {
  19353. word32 sz = idx;
  19354. const byte* params = cert + idx;
  19355. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19356. ret = ASN_PARSE_E;
  19357. if (ret == 0) {
  19358. idx += len;
  19359. sz = idx - sz;
  19360. if (req) {
  19361. if ((sz != sigParamsSz) ||
  19362. (XMEMCMP(sigParams, params, sz) != 0)) {
  19363. ret = ASN_PARSE_E;
  19364. }
  19365. }
  19366. else {
  19367. sigParams = params;
  19368. sigParamsSz = sz;
  19369. }
  19370. }
  19371. }
  19372. #endif
  19373. /* In CSR signature data is not present in body */
  19374. if (req)
  19375. signatureOID = oid;
  19376. }
  19377. if (ret == 0) {
  19378. if (oid != signatureOID)
  19379. ret = ASN_SIG_OID_E;
  19380. }
  19381. if (ret == 0) {
  19382. /* signatureValue */
  19383. if (CheckBitString(cert, &idx, &len, certSz, 1, NULL) < 0)
  19384. ret = ASN_PARSE_E;
  19385. }
  19386. if (ret == 0) {
  19387. if (pubKey != NULL) {
  19388. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  19389. sigIndex - tbsCertIdx, pubKey, pubKeySz, pubKeyOID,
  19390. cert + idx, len, signatureOID, sigParams, sigParamsSz, NULL);
  19391. }
  19392. else {
  19393. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  19394. sigIndex - tbsCertIdx, ca->publicKey, ca->pubKeySize,
  19395. ca->keyOID, cert + idx, len, signatureOID, sigParams,
  19396. sigParamsSz, NULL);
  19397. }
  19398. if (ret != 0) {
  19399. WOLFSSL_ERROR_VERBOSE(ret);
  19400. WOLFSSL_MSG("Confirm signature failed");
  19401. }
  19402. }
  19403. FreeSignatureCtx(sigCtx);
  19404. #ifdef WOLFSSL_SMALL_STACK
  19405. if (sigCtx != NULL)
  19406. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  19407. #endif
  19408. return ret;
  19409. #else /* WOLFSSL_ASN_TEMPLATE */
  19410. /* X509 ASN.1 template longer than Certificate Request template. */
  19411. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  19412. #ifndef WOLFSSL_SMALL_STACK
  19413. SignatureCtx sigCtx[1];
  19414. #else
  19415. SignatureCtx* sigCtx = NULL;
  19416. #endif
  19417. byte hash[KEYID_SIZE];
  19418. Signer* ca = NULL;
  19419. int ret = 0;
  19420. word32 idx = 0;
  19421. #ifndef NO_SKID
  19422. int extAuthKeyIdSet = 0;
  19423. #endif
  19424. const byte* tbs = NULL;
  19425. word32 tbsSz = 0;
  19426. #ifdef WC_RSA_PSS
  19427. const byte* tbsParams = NULL;
  19428. word32 tbsParamsSz = 0;
  19429. #endif
  19430. const byte* sig = NULL;
  19431. word32 sigSz = 0;
  19432. word32 sigOID = 0;
  19433. const byte* sigParams = NULL;
  19434. word32 sigParamsSz = 0;
  19435. const byte* caName = NULL;
  19436. word32 caNameLen = 0;
  19437. (void)req;
  19438. (void)heap;
  19439. if (cert == NULL) {
  19440. ret = BAD_FUNC_ARG;
  19441. }
  19442. ALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, heap);
  19443. #ifdef WOLFSSL_SMALL_STACK
  19444. if (ret == 0) {
  19445. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap,
  19446. DYNAMIC_TYPE_SIGNATURE);
  19447. if (sigCtx == NULL) {
  19448. ret = MEMORY_E;
  19449. }
  19450. }
  19451. #endif
  19452. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  19453. if ((ret == 0) && (!req)) {
  19454. /* Clear dynamic data for certificate items. */
  19455. XMEMSET(dataASN, 0, sizeof(ASNGetData) * x509CertASN_Length);
  19456. /* Set OID types expected for signature and public key. */
  19457. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
  19458. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
  19459. oidKeyType);
  19460. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
  19461. oidCurveType);
  19462. GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
  19463. /* Parse certificate. */
  19464. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1, cert,
  19465. &idx, certSz);
  19466. /* Check signature OIDs match. */
  19467. if ((ret == 0) && dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum
  19468. != dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum) {
  19469. ret = ASN_SIG_OID_E;
  19470. }
  19471. /* Store the data for verification in the certificate. */
  19472. if (ret == 0) {
  19473. tbs = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
  19474. tbsSz = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
  19475. caName = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  19476. cert);
  19477. caNameLen = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  19478. cert);
  19479. sigOID = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
  19480. #ifdef WC_RSA_PSS
  19481. if (dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].tag != 0) {
  19482. tbsParams =
  19483. GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  19484. cert);
  19485. tbsParamsSz =
  19486. GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  19487. cert);
  19488. }
  19489. if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
  19490. sigParams =
  19491. GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19492. cert);
  19493. sigParamsSz =
  19494. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19495. cert);
  19496. }
  19497. #endif
  19498. GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE], &sig, &sigSz);
  19499. #ifdef WC_RSA_PSS
  19500. if (tbsParamsSz != sigParamsSz) {
  19501. ret = ASN_PARSE_E;
  19502. }
  19503. else if ((tbsParamsSz > 0) && (sigOID != CTC_RSASSAPSS)) {
  19504. ret = ASN_PARSE_E;
  19505. }
  19506. else if ((tbsParamsSz > 0) &&
  19507. (XMEMCMP(tbsParams, sigParams, tbsParamsSz) != 0)) {
  19508. ret = ASN_PARSE_E;
  19509. }
  19510. #endif
  19511. }
  19512. }
  19513. else if (ret == 0) {
  19514. #ifndef WOLFSSL_CERT_REQ
  19515. ret = NOT_COMPILED_IN;
  19516. #else
  19517. /* Clear dynamic data for certificate request items. */
  19518. XMEMSET(dataASN, 0, sizeof(ASNGetData) * certReqASN_Length);
  19519. /* Set OID types expected for signature and public key. */
  19520. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
  19521. oidKeyType);
  19522. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
  19523. oidCurveType);
  19524. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
  19525. /* Parse certificate request. */
  19526. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1, cert,
  19527. &idx, certSz);
  19528. if (ret == 0) {
  19529. /* Store the data for verification in the certificate. */
  19530. tbs = GetASNItem_Addr(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
  19531. tbsSz = GetASNItem_Length(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
  19532. caName = GetASNItem_Addr(
  19533. dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
  19534. caNameLen = GetASNItem_Length(
  19535. dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
  19536. sigOID = dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
  19537. #ifdef WC_RSA_PSS
  19538. sigParams = GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19539. cert);
  19540. sigParamsSz =
  19541. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19542. cert);
  19543. #endif
  19544. GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE], &sig,
  19545. &sigSz);
  19546. }
  19547. #endif
  19548. }
  19549. /* If no public passed, then find the CA. */
  19550. if ((ret == 0) && (pubKey == NULL)) {
  19551. #ifndef NO_SKID
  19552. /* Find the AKI extension in list of extensions and get hash. */
  19553. if ((!req) &&
  19554. (dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data != NULL)) {
  19555. /* TODO: test case */
  19556. ret = GetAKIHash(dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data,
  19557. dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.length,
  19558. hash, &extAuthKeyIdSet, heap);
  19559. }
  19560. /* Get the CA by hash one was found. */
  19561. if (extAuthKeyIdSet) {
  19562. ca = GetCA(cm, hash);
  19563. }
  19564. if (ca == NULL)
  19565. #endif
  19566. {
  19567. /* Try hash of issuer name. */
  19568. ret = CalcHashId(caName, caNameLen, hash);
  19569. if (ret == 0) {
  19570. ca = GetCAByName(cm, hash);
  19571. }
  19572. }
  19573. if (ca != NULL) {
  19574. /* Extract public key information. */
  19575. pubKey = ca->publicKey;
  19576. pubKeySz = ca->pubKeySize;
  19577. pubKeyOID = ca->keyOID;
  19578. }
  19579. else {
  19580. /* No public key to verify with. */
  19581. ret = ASN_NO_SIGNER_E;
  19582. }
  19583. }
  19584. if (ret == 0) {
  19585. /* Check signature. */
  19586. ret = ConfirmSignature(sigCtx, tbs, tbsSz, pubKey, pubKeySz, pubKeyOID,
  19587. sig, sigSz, sigOID, sigParams, sigParamsSz, NULL);
  19588. if (ret != 0) {
  19589. WOLFSSL_MSG("Confirm signature failed");
  19590. }
  19591. }
  19592. FreeSignatureCtx(sigCtx);
  19593. #ifdef WOLFSSL_SMALL_STACK
  19594. if (sigCtx != NULL)
  19595. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  19596. #endif
  19597. FREE_ASNGETDATA(dataASN, heap);
  19598. return ret;
  19599. #endif /* WOLFSSL_ASN_TEMPLATE */
  19600. }
  19601. #ifdef OPENSSL_EXTRA
  19602. /* Call CheckCertSignature_ex using a public key buffer for verification
  19603. */
  19604. int CheckCertSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  19605. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  19606. {
  19607. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  19608. pubKey, pubKeySz, pubKeyOID, 0);
  19609. }
  19610. int wc_CheckCertSigPubKey(const byte* cert, word32 certSz, void* heap,
  19611. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  19612. {
  19613. return CheckCertSignaturePubKey(cert, certSz, heap, pubKey, pubKeySz,
  19614. pubKeyOID);
  19615. }
  19616. #ifdef WOLFSSL_CERT_REQ
  19617. int CheckCSRSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  19618. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  19619. {
  19620. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  19621. pubKey, pubKeySz, pubKeyOID, 1);
  19622. }
  19623. #endif /* WOLFSSL_CERT_REQ */
  19624. #endif /* OPENSSL_EXTRA */
  19625. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  19626. /* Call CheckCertSignature_ex using a certificate manager (cm)
  19627. */
  19628. int CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm)
  19629. {
  19630. return CheckCertSignature_ex(cert, certSz, heap, cm, NULL, 0, 0, 0);
  19631. }
  19632. #endif /* WOLFSSL_SMALL_CERT_VERIFY */
  19633. #endif /* WOLFSSL_SMALL_CERT_VERIFY || OPENSSL_EXTRA */
  19634. int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
  19635. {
  19636. int ret = 0;
  19637. int checkPathLen = 0;
  19638. int decrementMaxPathLen = 0;
  19639. #ifndef WOLFSSL_ASN_TEMPLATE
  19640. word32 confirmOID = 0;
  19641. #ifdef WOLFSSL_CERT_REQ
  19642. int len = 0;
  19643. #endif
  19644. #endif
  19645. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  19646. int idx = 0;
  19647. #endif
  19648. byte* sce_tsip_encRsaKeyIdx;
  19649. if (cert == NULL) {
  19650. return BAD_FUNC_ARG;
  19651. }
  19652. #ifdef WOLFSSL_CERT_REQ
  19653. if (type == CERTREQ_TYPE)
  19654. cert->isCSR = 1;
  19655. #endif
  19656. if (cert->sigCtx.state == SIG_STATE_BEGIN) {
  19657. #ifndef WOLFSSL_ASN_TEMPLATE
  19658. cert->badDate = 0;
  19659. cert->criticalExt = 0;
  19660. if ((ret = DecodeToKey(cert, verify)) < 0) {
  19661. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E)
  19662. cert->badDate = ret;
  19663. else
  19664. return ret;
  19665. }
  19666. WOLFSSL_MSG("Parsed Past Key");
  19667. #ifdef WOLFSSL_CERT_REQ
  19668. /* Read attributes */
  19669. if (cert->isCSR) {
  19670. if (GetASNHeader_ex(cert->source,
  19671. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &cert->srcIdx,
  19672. &len, cert->maxIdx, 1) < 0) {
  19673. WOLFSSL_MSG("GetASNHeader_ex error");
  19674. return ASN_PARSE_E;
  19675. }
  19676. if (len) {
  19677. word32 attrMaxIdx = cert->srcIdx + len;
  19678. word32 oid;
  19679. byte tag;
  19680. if (attrMaxIdx > cert->maxIdx) {
  19681. WOLFSSL_MSG("Attribute length greater than CSR length");
  19682. return ASN_PARSE_E;
  19683. }
  19684. while (cert->srcIdx < attrMaxIdx) {
  19685. /* Attributes have the structure:
  19686. * SEQ -> OID -> SET -> ATTRIBUTE */
  19687. if (GetSequence(cert->source, &cert->srcIdx, &len,
  19688. attrMaxIdx) < 0) {
  19689. WOLFSSL_MSG("attr GetSequence error");
  19690. return ASN_PARSE_E;
  19691. }
  19692. if (GetObjectId(cert->source, &cert->srcIdx, &oid,
  19693. oidCsrAttrType, attrMaxIdx) < 0) {
  19694. WOLFSSL_MSG("attr GetObjectId error");
  19695. return ASN_PARSE_E;
  19696. }
  19697. if (GetSet(cert->source, &cert->srcIdx, &len,
  19698. attrMaxIdx) < 0) {
  19699. WOLFSSL_MSG("attr GetSet error");
  19700. return ASN_PARSE_E;
  19701. }
  19702. switch (oid) {
  19703. case PKCS9_CONTENT_TYPE_OID:
  19704. if (GetHeader(cert->source, &tag,
  19705. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19706. WOLFSSL_MSG("attr GetHeader error");
  19707. return ASN_PARSE_E;
  19708. }
  19709. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  19710. tag != ASN_IA5_STRING) {
  19711. WOLFSSL_MSG("Unsupported attribute value format");
  19712. return ASN_PARSE_E;
  19713. }
  19714. cert->contentType = (char*)cert->source + cert->srcIdx;
  19715. cert->contentTypeLen = len;
  19716. cert->srcIdx += len;
  19717. break;
  19718. case CHALLENGE_PASSWORD_OID:
  19719. if (GetHeader(cert->source, &tag,
  19720. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19721. WOLFSSL_MSG("attr GetHeader error");
  19722. return ASN_PARSE_E;
  19723. }
  19724. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  19725. tag != ASN_IA5_STRING) {
  19726. WOLFSSL_MSG("Unsupported attribute value format");
  19727. return ASN_PARSE_E;
  19728. }
  19729. cert->cPwd = (char*)cert->source + cert->srcIdx;
  19730. cert->cPwdLen = len;
  19731. cert->srcIdx += len;
  19732. break;
  19733. case SERIAL_NUMBER_OID:
  19734. if (GetHeader(cert->source, &tag,
  19735. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19736. WOLFSSL_MSG("attr GetHeader error");
  19737. return ASN_PARSE_E;
  19738. }
  19739. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  19740. tag != ASN_IA5_STRING) {
  19741. WOLFSSL_MSG("Unsupported attribute value format");
  19742. return ASN_PARSE_E;
  19743. }
  19744. cert->sNum = (char*)cert->source + cert->srcIdx;
  19745. cert->sNumLen = len;
  19746. cert->srcIdx += len;
  19747. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  19748. XMEMCPY(cert->serial, cert->sNum, cert->sNumLen);
  19749. cert->serialSz = cert->sNumLen;
  19750. }
  19751. break;
  19752. case DNQUALIFIER_OID:
  19753. if (GetHeader(cert->source, &tag,
  19754. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19755. WOLFSSL_MSG("attr GetHeader error");
  19756. return ASN_PARSE_E;
  19757. }
  19758. cert->dnQualifier = (char*)cert->source + cert->srcIdx;
  19759. cert->dnQualifierLen = len;
  19760. cert->srcIdx += len;
  19761. break;
  19762. case INITIALS_OID:
  19763. if (GetHeader(cert->source, &tag,
  19764. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19765. WOLFSSL_MSG("attr GetHeader error");
  19766. return ASN_PARSE_E;
  19767. }
  19768. cert->initials = (char*)cert->source + cert->srcIdx;
  19769. cert->initialsLen = len;
  19770. cert->srcIdx += len;
  19771. break;
  19772. case SURNAME_OID:
  19773. if (GetHeader(cert->source, &tag,
  19774. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19775. WOLFSSL_MSG("attr GetHeader error");
  19776. return ASN_PARSE_E;
  19777. }
  19778. cert->surname = (char*)cert->source + cert->srcIdx;
  19779. cert->surnameLen = len;
  19780. cert->srcIdx += len;
  19781. break;
  19782. case GIVEN_NAME_OID:
  19783. if (GetHeader(cert->source, &tag,
  19784. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19785. WOLFSSL_MSG("attr GetHeader error");
  19786. return ASN_PARSE_E;
  19787. }
  19788. cert->givenName = (char*)cert->source + cert->srcIdx;
  19789. cert->givenNameLen = len;
  19790. cert->srcIdx += len;
  19791. break;
  19792. case UNSTRUCTURED_NAME_OID:
  19793. if (GetHeader(cert->source, &tag,
  19794. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19795. WOLFSSL_MSG("attr GetHeader error");
  19796. return ASN_PARSE_E;
  19797. }
  19798. cert->unstructuredName =
  19799. (char*)cert->source + cert->srcIdx;
  19800. cert->unstructuredNameLen = len;
  19801. cert->srcIdx += len;
  19802. break;
  19803. case EXTENSION_REQUEST_OID:
  19804. /* save extensions */
  19805. cert->extensions = &cert->source[cert->srcIdx];
  19806. cert->extensionsSz = len;
  19807. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  19808. if ((ret = DecodeCertExtensions(cert)) < 0) {
  19809. if (ret == ASN_CRIT_EXT_E) {
  19810. cert->criticalExt = ret;
  19811. }
  19812. else {
  19813. return ret;
  19814. }
  19815. }
  19816. cert->srcIdx += len;
  19817. break;
  19818. default:
  19819. WOLFSSL_MSG("Unsupported attribute type");
  19820. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  19821. return ASN_PARSE_E;
  19822. }
  19823. }
  19824. }
  19825. }
  19826. #endif
  19827. if (cert->srcIdx < cert->sigIndex) {
  19828. #ifndef ALLOW_V1_EXTENSIONS
  19829. if (cert->version < 2) {
  19830. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  19831. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  19832. return ASN_VERSION_E;
  19833. }
  19834. #endif
  19835. /* save extensions */
  19836. cert->extensions = &cert->source[cert->srcIdx];
  19837. cert->extensionsSz = cert->sigIndex - cert->srcIdx;
  19838. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  19839. if ((ret = DecodeCertExtensions(cert)) < 0) {
  19840. if (ret == ASN_CRIT_EXT_E)
  19841. cert->criticalExt = ret;
  19842. else
  19843. return ret;
  19844. }
  19845. #ifdef HAVE_OCSP
  19846. if (verify == VERIFY_OCSP_CERT) {
  19847. /* trust for the lifetime of the responder's cert*/
  19848. if (cert->ocspNoCheckSet)
  19849. verify = VERIFY;
  19850. else
  19851. verify = VERIFY_OCSP;
  19852. }
  19853. #endif
  19854. /* advance past extensions */
  19855. cert->srcIdx = cert->sigIndex;
  19856. }
  19857. if ((ret = GetSigAlg(cert,
  19858. #ifdef WOLFSSL_CERT_REQ
  19859. !cert->isCSR ? &confirmOID : &cert->signatureOID,
  19860. #else
  19861. &confirmOID,
  19862. #endif
  19863. cert->maxIdx)) < 0) {
  19864. return ret;
  19865. }
  19866. if ((ret = GetSignature(cert)) < 0) {
  19867. return ret;
  19868. }
  19869. if (confirmOID != cert->signatureOID
  19870. #ifdef WOLFSSL_CERT_REQ
  19871. && !cert->isCSR
  19872. #endif
  19873. ) {
  19874. WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
  19875. return ASN_SIG_OID_E;
  19876. }
  19877. #else
  19878. #ifdef WOLFSSL_CERT_REQ
  19879. if (cert->isCSR) {
  19880. ret = DecodeCertReq(cert, &cert->criticalExt);
  19881. if (ret < 0) {
  19882. return ret;
  19883. }
  19884. }
  19885. else
  19886. #endif
  19887. {
  19888. ret = DecodeCert(cert, verify, &cert->criticalExt);
  19889. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
  19890. cert->badDate = ret;
  19891. }
  19892. else if (ret < 0) {
  19893. WOLFSSL_ERROR_VERBOSE(ret);
  19894. return ret;
  19895. }
  19896. }
  19897. #endif
  19898. #ifndef NO_SKID
  19899. if (cert->extSubjKeyIdSet == 0 && cert->publicKey != NULL &&
  19900. cert->pubKeySize > 0) {
  19901. ret = CalcHashId(cert->publicKey, cert->pubKeySize,
  19902. cert->extSubjKeyId);
  19903. if (ret != 0) {
  19904. WOLFSSL_ERROR_VERBOSE(ret);
  19905. return ret;
  19906. }
  19907. }
  19908. #endif /* !NO_SKID */
  19909. if (!cert->selfSigned || (verify != NO_VERIFY && type != CA_TYPE &&
  19910. type != TRUSTED_PEER_TYPE)) {
  19911. cert->ca = NULL;
  19912. #ifndef NO_SKID
  19913. if (cert->extAuthKeyIdSet) {
  19914. cert->ca = GetCA(cm, cert->extAuthKeyId);
  19915. }
  19916. if (cert->ca == NULL && cert->extSubjKeyIdSet
  19917. && verify != VERIFY_OCSP) {
  19918. cert->ca = GetCA(cm, cert->extSubjKeyId);
  19919. }
  19920. if (cert->ca != NULL && XMEMCMP(cert->issuerHash,
  19921. cert->ca->subjectNameHash, KEYID_SIZE) != 0) {
  19922. cert->ca = NULL;
  19923. }
  19924. if (cert->ca == NULL) {
  19925. cert->ca = GetCAByName(cm, cert->issuerHash);
  19926. /* If AKID is available then this CA doesn't have the public
  19927. * key required */
  19928. if (cert->ca && cert->extAuthKeyIdSet) {
  19929. WOLFSSL_MSG("CA SKID doesn't match AKID");
  19930. cert->ca = NULL;
  19931. }
  19932. }
  19933. /* OCSP Only: alt lookup using subject and pub key w/o sig check */
  19934. #ifdef WOLFSSL_NO_TRUSTED_CERTS_VERIFY
  19935. if (cert->ca == NULL && verify == VERIFY_OCSP) {
  19936. cert->ca = GetCABySubjectAndPubKey(cert, cm);
  19937. if (cert->ca) {
  19938. ret = 0; /* success */
  19939. goto exit_pcr;
  19940. }
  19941. }
  19942. #endif /* WOLFSSL_NO_TRUSTED_CERTS_VERIFY */
  19943. #else
  19944. cert->ca = GetCA(cm, cert->issuerHash);
  19945. #endif /* !NO_SKID */
  19946. if (cert->ca) {
  19947. WOLFSSL_MSG("CA found");
  19948. }
  19949. }
  19950. if (cert->selfSigned) {
  19951. cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
  19952. } else {
  19953. /* RFC 5280 Section 4.2.1.9:
  19954. *
  19955. * load/receive check
  19956. *
  19957. * 1) Is CA boolean set?
  19958. * No - SKIP CHECK
  19959. * Yes - Check key usage
  19960. * 2) Is Key usage extension present?
  19961. * No - goto 3
  19962. * Yes - check keyCertSign assertion
  19963. * 2.a) Is keyCertSign asserted?
  19964. * No - goto 4
  19965. * Yes - goto 3
  19966. * 3) Is pathLen set?
  19967. * No - goto 4
  19968. * Yes - check pathLen against maxPathLen.
  19969. * 3.a) Is pathLen less than maxPathLen?
  19970. * No - goto 4
  19971. * Yes - set maxPathLen to pathLen and EXIT
  19972. * 4) Is maxPathLen > 0?
  19973. * Yes - Reduce by 1
  19974. * No - ERROR
  19975. */
  19976. if (cert->ca && cert->pathLengthSet) {
  19977. cert->maxPathLen = cert->pathLength;
  19978. if (cert->isCA) {
  19979. WOLFSSL_MSG("\tCA boolean set");
  19980. if (cert->extKeyUsageSet) {
  19981. WOLFSSL_MSG("\tExtension Key Usage Set");
  19982. if ((cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) != 0) {
  19983. checkPathLen = 1;
  19984. }
  19985. else {
  19986. decrementMaxPathLen = 1;
  19987. }
  19988. }
  19989. else {
  19990. checkPathLen = 1;
  19991. } /* !cert->ca check */
  19992. } /* cert is not a CA (assuming entity cert) */
  19993. if (checkPathLen && cert->pathLengthSet) {
  19994. if (cert->pathLength < cert->ca->maxPathLen) {
  19995. WOLFSSL_MSG("\tmaxPathLen status: set to pathLength");
  19996. cert->maxPathLen = cert->pathLength;
  19997. }
  19998. else {
  19999. decrementMaxPathLen = 1;
  20000. }
  20001. }
  20002. if (decrementMaxPathLen && cert->ca->maxPathLen > 0) {
  20003. WOLFSSL_MSG("\tmaxPathLen status: reduce by 1");
  20004. cert->maxPathLen = cert->ca->maxPathLen - 1;
  20005. if (verify != NO_VERIFY && type != CA_TYPE &&
  20006. type != TRUSTED_PEER_TYPE) {
  20007. WOLFSSL_MSG("\tmaxPathLen status: OK");
  20008. }
  20009. } else if (decrementMaxPathLen && cert->ca->maxPathLen == 0) {
  20010. cert->maxPathLen = 0;
  20011. if (verify != NO_VERIFY && type != CA_TYPE &&
  20012. type != TRUSTED_PEER_TYPE) {
  20013. WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
  20014. WOLFSSL_MSG("\tmaxPathLen status: ERROR");
  20015. WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_INV_E);
  20016. return ASN_PATHLEN_INV_E;
  20017. }
  20018. }
  20019. } else if (cert->ca && cert->isCA) {
  20020. /* case where cert->pathLength extension is not set */
  20021. if (cert->ca->maxPathLen > 0) {
  20022. cert->maxPathLen = cert->ca->maxPathLen - 1;
  20023. } else {
  20024. cert->maxPathLen = 0;
  20025. if (verify != NO_VERIFY && type != CA_TYPE &&
  20026. type != TRUSTED_PEER_TYPE) {
  20027. WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
  20028. WOLFSSL_MSG("\tmaxPathLen status: ERROR");
  20029. WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_INV_E);
  20030. return ASN_PATHLEN_INV_E;
  20031. }
  20032. }
  20033. }
  20034. }
  20035. #ifdef HAVE_OCSP
  20036. if (verify != NO_VERIFY && type != CA_TYPE &&
  20037. type != TRUSTED_PEER_TYPE) {
  20038. if (cert->ca) {
  20039. /* Need the CA's public key hash for OCSP */
  20040. XMEMCPY(cert->issuerKeyHash, cert->ca->subjectKeyHash,
  20041. KEYID_SIZE);
  20042. }
  20043. }
  20044. #endif /* HAVE_OCSP */
  20045. }
  20046. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  20047. /* prepare for TSIP TLS cert verification API use */
  20048. if (cert->keyOID == RSAk) {
  20049. /* to call TSIP API, it needs keys position info in bytes */
  20050. if ((ret = RsaPublicKeyDecodeRawIndex(cert->publicKey, (word32*)&idx,
  20051. cert->pubKeySize,
  20052. &cert->sigCtx.CertAtt.pubkey_n_start,
  20053. &cert->sigCtx.CertAtt.pubkey_n_len,
  20054. &cert->sigCtx.CertAtt.pubkey_e_start,
  20055. &cert->sigCtx.CertAtt.pubkey_e_len)) != 0) {
  20056. WOLFSSL_MSG("Decoding index from cert failed.");
  20057. return ret;
  20058. }
  20059. cert->sigCtx.CertAtt.certBegin = cert->certBegin;
  20060. } else if (cert->keyOID == ECDSAk) {
  20061. cert->sigCtx.CertAtt.certBegin = cert->certBegin;
  20062. }
  20063. /* check if we can use TSIP for cert verification */
  20064. /* if the ca is verified as tsip root ca. */
  20065. /* TSIP can only handle 2048 bits(256 byte) key. */
  20066. if (cert->ca && Renesas_cmn_checkCA(cert->ca->cm_idx) != 0 &&
  20067. (cert->sigCtx.CertAtt.pubkey_n_len == 256 ||
  20068. cert->sigCtx.CertAtt.curve_id == ECC_SECP256R1)) {
  20069. /* assign memory to encrypted tsip Rsa key index */
  20070. if (!cert->sce_tsip_encRsaKeyIdx)
  20071. cert->sce_tsip_encRsaKeyIdx =
  20072. (byte*)XMALLOC(TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY,
  20073. cert->heap, DYNAMIC_TYPE_RSA);
  20074. if (cert->sce_tsip_encRsaKeyIdx == NULL)
  20075. return MEMORY_E;
  20076. }
  20077. else {
  20078. if (cert->ca) {
  20079. /* TSIP isn't usable */
  20080. if (Renesas_cmn_checkCA(cert->ca->cm_idx) == 0)
  20081. WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't verified "
  20082. "by TSIP.");
  20083. else if (cert->sigCtx.CertAtt.pubkey_n_len != 256)
  20084. WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't signed by "
  20085. "RSA 2048.");
  20086. else
  20087. WOLFSSL_MSG("SCE-TSIP isn't usable");
  20088. }
  20089. cert->sce_tsip_encRsaKeyIdx = NULL;
  20090. }
  20091. sce_tsip_encRsaKeyIdx = cert->sce_tsip_encRsaKeyIdx;
  20092. #else
  20093. sce_tsip_encRsaKeyIdx = NULL;
  20094. #endif
  20095. if (verify != NO_VERIFY && type != CA_TYPE && type != TRUSTED_PEER_TYPE) {
  20096. if (cert->ca) {
  20097. if (verify == VERIFY || verify == VERIFY_OCSP ||
  20098. verify == VERIFY_SKIP_DATE) {
  20099. /* try to confirm/verify signature */
  20100. if ((ret = ConfirmSignature(&cert->sigCtx,
  20101. cert->source + cert->certBegin,
  20102. cert->sigIndex - cert->certBegin,
  20103. cert->ca->publicKey, cert->ca->pubKeySize,
  20104. cert->ca->keyOID, cert->signature,
  20105. cert->sigLength, cert->signatureOID,
  20106. #ifdef WC_RSA_PSS
  20107. cert->source + cert->sigParamsIndex,
  20108. cert->sigParamsLength,
  20109. #else
  20110. NULL, 0,
  20111. #endif
  20112. sce_tsip_encRsaKeyIdx)) != 0) {
  20113. if (ret != WC_PENDING_E) {
  20114. WOLFSSL_MSG("Confirm signature failed");
  20115. }
  20116. WOLFSSL_ERROR_VERBOSE(ret);
  20117. return ret;
  20118. }
  20119. }
  20120. #ifndef IGNORE_NAME_CONSTRAINTS
  20121. if (verify == VERIFY || verify == VERIFY_OCSP ||
  20122. verify == VERIFY_NAME || verify == VERIFY_SKIP_DATE) {
  20123. /* check that this cert's name is permitted by the signer's
  20124. * name constraints */
  20125. if (!ConfirmNameConstraints(cert->ca, cert)) {
  20126. WOLFSSL_MSG("Confirm name constraint failed");
  20127. WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
  20128. return ASN_NAME_INVALID_E;
  20129. }
  20130. }
  20131. #endif /* IGNORE_NAME_CONSTRAINTS */
  20132. }
  20133. #ifdef WOLFSSL_CERT_REQ
  20134. else if (type == CERTREQ_TYPE) {
  20135. if ((ret = ConfirmSignature(&cert->sigCtx,
  20136. cert->source + cert->certBegin,
  20137. cert->sigIndex - cert->certBegin,
  20138. cert->publicKey, cert->pubKeySize,
  20139. cert->keyOID, cert->signature,
  20140. cert->sigLength, cert->signatureOID,
  20141. #ifdef WC_RSA_PSS
  20142. cert->source + cert->sigParamsIndex, cert->sigParamsLength,
  20143. #else
  20144. NULL, 0,
  20145. #endif
  20146. sce_tsip_encRsaKeyIdx)) != 0) {
  20147. if (ret != WC_PENDING_E) {
  20148. WOLFSSL_MSG("Confirm signature failed");
  20149. }
  20150. WOLFSSL_ERROR_VERBOSE(ret);
  20151. return ret;
  20152. }
  20153. }
  20154. #endif
  20155. else {
  20156. /* no signer */
  20157. WOLFSSL_MSG("No CA signer to verify with");
  20158. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  20159. /* ret needs to be self-signer error for Qt compat */
  20160. if (cert->selfSigned) {
  20161. WOLFSSL_ERROR_VERBOSE(ASN_SELF_SIGNED_E);
  20162. return ASN_SELF_SIGNED_E;
  20163. }
  20164. else
  20165. #endif
  20166. {
  20167. WOLFSSL_ERROR_VERBOSE(ASN_NO_SIGNER_E);
  20168. return ASN_NO_SIGNER_E;
  20169. }
  20170. }
  20171. }
  20172. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  20173. exit_pcr:
  20174. #endif
  20175. if (cert->badDate != 0) {
  20176. if (verify != VERIFY_SKIP_DATE) {
  20177. return cert->badDate;
  20178. }
  20179. WOLFSSL_MSG("Date error: Verify option is skipping");
  20180. }
  20181. if (cert->criticalExt != 0)
  20182. return cert->criticalExt;
  20183. return ret;
  20184. }
  20185. /* Create and init an new signer */
  20186. Signer* MakeSigner(void* heap)
  20187. {
  20188. Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
  20189. DYNAMIC_TYPE_SIGNER);
  20190. if (signer) {
  20191. XMEMSET(signer, 0, sizeof(Signer));
  20192. }
  20193. (void)heap;
  20194. return signer;
  20195. }
  20196. /* Free an individual signer.
  20197. *
  20198. * Used by Certificate Manager.
  20199. *
  20200. * @param [in, out] signer On in, signer object.
  20201. * On out, pointer is no longer valid.
  20202. * @param [in] heap Dynamic memory hint.
  20203. */
  20204. void FreeSigner(Signer* signer, void* heap)
  20205. {
  20206. XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  20207. XFREE((void*)signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  20208. #ifndef IGNORE_NAME_CONSTRAINTS
  20209. if (signer->permittedNames)
  20210. FreeNameSubtrees(signer->permittedNames, heap);
  20211. if (signer->excludedNames)
  20212. FreeNameSubtrees(signer->excludedNames, heap);
  20213. #endif
  20214. #ifdef WOLFSSL_SIGNER_DER_CERT
  20215. FreeDer(&signer->derCert);
  20216. #endif
  20217. XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
  20218. (void)signer;
  20219. (void)heap;
  20220. }
  20221. /* Free the whole singer table with number of rows.
  20222. *
  20223. * Each table entry is a linked list of signers.
  20224. * Used by Certificate Manager.
  20225. *
  20226. * @param [in, out] table Array of signer objects.
  20227. * @param [in] rows Number of entries in table.
  20228. * @param [in] heap Dynamic memory hint.
  20229. */
  20230. void FreeSignerTable(Signer** table, int rows, void* heap)
  20231. {
  20232. int i;
  20233. for (i = 0; i < rows; i++) {
  20234. Signer* signer = table[i];
  20235. while (signer) {
  20236. Signer* next = signer->next;
  20237. FreeSigner(signer, heap);
  20238. signer = next;
  20239. }
  20240. table[i] = NULL;
  20241. }
  20242. }
  20243. #ifdef WOLFSSL_TRUST_PEER_CERT
  20244. /* Free an individual trusted peer cert.
  20245. *
  20246. * @param [in, out] tp Trusted peer certificate object.
  20247. * @param [in] heap Dynamic memory hint.
  20248. */
  20249. void FreeTrustedPeer(TrustedPeerCert* tp, void* heap)
  20250. {
  20251. if (tp == NULL) {
  20252. return;
  20253. }
  20254. if (tp->name) {
  20255. XFREE(tp->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  20256. }
  20257. if (tp->sig) {
  20258. XFREE(tp->sig, heap, DYNAMIC_TYPE_SIGNATURE);
  20259. }
  20260. #ifndef IGNORE_NAME_CONSTRAINTS
  20261. if (tp->permittedNames)
  20262. FreeNameSubtrees(tp->permittedNames, heap);
  20263. if (tp->excludedNames)
  20264. FreeNameSubtrees(tp->excludedNames, heap);
  20265. #endif
  20266. XFREE(tp, heap, DYNAMIC_TYPE_CERT);
  20267. (void)heap;
  20268. }
  20269. /* Free the whole Trusted Peer linked list.
  20270. *
  20271. * Each table entry is a linked list of trusted peer certificates.
  20272. * Used by Certificate Manager.
  20273. *
  20274. * @param [in, out] table Array of trusted peer certificate objects.
  20275. * @param [in] rows Number of entries in table.
  20276. * @param [in] heap Dynamic memory hint.
  20277. */
  20278. void FreeTrustedPeerTable(TrustedPeerCert** table, int rows, void* heap)
  20279. {
  20280. int i;
  20281. for (i = 0; i < rows; i++) {
  20282. TrustedPeerCert* tp = table[i];
  20283. while (tp) {
  20284. TrustedPeerCert* next = tp->next;
  20285. FreeTrustedPeer(tp, heap);
  20286. tp = next;
  20287. }
  20288. table[i] = NULL;
  20289. }
  20290. }
  20291. #endif /* WOLFSSL_TRUST_PEER_CERT */
  20292. int SetMyVersion(word32 version, byte* output, int header)
  20293. {
  20294. int i = 0;
  20295. if (output == NULL)
  20296. return BAD_FUNC_ARG;
  20297. if (header) {
  20298. output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  20299. output[i++] = 3;
  20300. }
  20301. output[i++] = ASN_INTEGER;
  20302. output[i++] = 0x01;
  20303. output[i++] = (byte)version;
  20304. return i;
  20305. }
  20306. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7)
  20307. int SetSerialNumber(const byte* sn, word32 snSz, byte* output,
  20308. word32 outputSz, int maxSnSz)
  20309. {
  20310. int i;
  20311. int snSzInt = (int)snSz;
  20312. if (sn == NULL || output == NULL || snSzInt < 0)
  20313. return BAD_FUNC_ARG;
  20314. /* remove leading zeros */
  20315. while (snSzInt > 0 && sn[0] == 0) {
  20316. snSzInt--;
  20317. sn++;
  20318. }
  20319. /* RFC 5280 - 4.1.2.2:
  20320. * Serial numbers must be a positive value (and not zero) */
  20321. if (snSzInt == 0) {
  20322. WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
  20323. return BAD_FUNC_ARG;
  20324. }
  20325. if (sn[0] & 0x80)
  20326. maxSnSz--;
  20327. /* truncate if input is too long */
  20328. if (snSzInt > maxSnSz)
  20329. snSzInt = maxSnSz;
  20330. i = SetASNInt(snSzInt, sn[0], NULL);
  20331. /* truncate if input is too long */
  20332. if (snSzInt > (int)outputSz - i)
  20333. snSzInt = (int)outputSz - i;
  20334. /* sanity check number of bytes to copy */
  20335. if (snSzInt <= 0) {
  20336. return BUFFER_E;
  20337. }
  20338. /* write out ASN.1 Integer */
  20339. (void)SetASNInt(snSzInt, sn[0], output);
  20340. XMEMCPY(output + i, sn, snSzInt);
  20341. /* compute final length */
  20342. i += snSzInt;
  20343. return i;
  20344. }
  20345. #endif /* !WOLFSSL_ASN_TEMPLATE */
  20346. #endif /* !NO_CERTS */
  20347. #ifndef WOLFSSL_ASN_TEMPLATE
  20348. int wc_GetSerialNumber(const byte* input, word32* inOutIdx,
  20349. byte* serial, int* serialSz, word32 maxIdx)
  20350. {
  20351. int result = 0;
  20352. int ret;
  20353. WOLFSSL_ENTER("wc_GetSerialNumber");
  20354. if (serial == NULL || input == NULL || serialSz == NULL) {
  20355. return BAD_FUNC_ARG;
  20356. }
  20357. /* First byte is ASN type */
  20358. if ((*inOutIdx+1) > maxIdx) {
  20359. WOLFSSL_MSG("Bad idx first");
  20360. return BUFFER_E;
  20361. }
  20362. ret = GetASNInt(input, inOutIdx, serialSz, maxIdx);
  20363. if (ret != 0)
  20364. return ret;
  20365. if (*serialSz > EXTERNAL_SERIAL_SIZE || *serialSz <= 0) {
  20366. WOLFSSL_MSG("Serial size bad");
  20367. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  20368. return ASN_PARSE_E;
  20369. }
  20370. /* return serial */
  20371. XMEMCPY(serial, &input[*inOutIdx], (size_t)*serialSz);
  20372. *inOutIdx += *serialSz;
  20373. return result;
  20374. }
  20375. #endif
  20376. #ifndef NO_CERTS
  20377. /* TODO: consider moving PEM code out to a different file. */
  20378. int AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  20379. {
  20380. int ret = BAD_FUNC_ARG;
  20381. if (pDer) {
  20382. int dynType = 0;
  20383. DerBuffer* der;
  20384. /* Determine dynamic type */
  20385. switch (type) {
  20386. case CA_TYPE: dynType = DYNAMIC_TYPE_CA; break;
  20387. case CERT_TYPE: dynType = DYNAMIC_TYPE_CERT; break;
  20388. case CRL_TYPE: dynType = DYNAMIC_TYPE_CRL; break;
  20389. case DSA_TYPE: dynType = DYNAMIC_TYPE_DSA; break;
  20390. case ECC_TYPE: dynType = DYNAMIC_TYPE_ECC; break;
  20391. case RSA_TYPE: dynType = DYNAMIC_TYPE_RSA; break;
  20392. default: dynType = DYNAMIC_TYPE_KEY; break;
  20393. }
  20394. /* Setup new buffer */
  20395. *pDer = (DerBuffer*)XMALLOC(sizeof(DerBuffer) + length, heap, dynType);
  20396. if (*pDer == NULL) {
  20397. return MEMORY_E;
  20398. }
  20399. XMEMSET(*pDer, 0, sizeof(DerBuffer) + length);
  20400. der = *pDer;
  20401. der->type = type;
  20402. der->dynType = dynType; /* Cache this for FreeDer */
  20403. der->heap = heap;
  20404. der->buffer = (byte*)der + sizeof(DerBuffer);
  20405. der->length = length;
  20406. ret = 0; /* Success */
  20407. }
  20408. return ret;
  20409. }
  20410. void FreeDer(DerBuffer** pDer)
  20411. {
  20412. if (pDer && *pDer)
  20413. {
  20414. DerBuffer* der = (DerBuffer*)*pDer;
  20415. /* ForceZero private keys */
  20416. if (der->type == PRIVATEKEY_TYPE && der->buffer != NULL) {
  20417. ForceZero(der->buffer, der->length);
  20418. }
  20419. der->buffer = NULL;
  20420. der->length = 0;
  20421. XFREE(der, der->heap, der->dynType);
  20422. *pDer = NULL;
  20423. }
  20424. }
  20425. int wc_AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  20426. {
  20427. return AllocDer(pDer, length, type, heap);
  20428. }
  20429. void wc_FreeDer(DerBuffer** pDer)
  20430. {
  20431. FreeDer(pDer);
  20432. }
  20433. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  20434. /* Note: If items added make sure MAX_X509_HEADER_SZ is
  20435. updated to reflect maximum length and pem_struct_min_sz
  20436. to reflect minimum size */
  20437. wcchar BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
  20438. wcchar END_CERT = "-----END CERTIFICATE-----";
  20439. #ifdef WOLFSSL_CERT_REQ
  20440. wcchar BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----";
  20441. wcchar END_CERT_REQ = "-----END CERTIFICATE REQUEST-----";
  20442. #endif
  20443. #ifndef NO_DH
  20444. wcchar BEGIN_DH_PARAM = "-----BEGIN DH PARAMETERS-----";
  20445. wcchar END_DH_PARAM = "-----END DH PARAMETERS-----";
  20446. wcchar BEGIN_X942_PARAM = "-----BEGIN X9.42 DH PARAMETERS-----";
  20447. wcchar END_X942_PARAM = "-----END X9.42 DH PARAMETERS-----";
  20448. #endif
  20449. #ifndef NO_DSA
  20450. wcchar BEGIN_DSA_PARAM = "-----BEGIN DSA PARAMETERS-----";
  20451. wcchar END_DSA_PARAM = "-----END DSA PARAMETERS-----";
  20452. #endif
  20453. wcchar BEGIN_X509_CRL = "-----BEGIN X509 CRL-----";
  20454. wcchar END_X509_CRL = "-----END X509 CRL-----";
  20455. wcchar BEGIN_RSA_PRIV = "-----BEGIN RSA PRIVATE KEY-----";
  20456. wcchar END_RSA_PRIV = "-----END RSA PRIVATE KEY-----";
  20457. wcchar BEGIN_RSA_PUB = "-----BEGIN RSA PUBLIC KEY-----";
  20458. wcchar END_RSA_PUB = "-----END RSA PUBLIC KEY-----";
  20459. wcchar BEGIN_PRIV_KEY = "-----BEGIN PRIVATE KEY-----";
  20460. wcchar END_PRIV_KEY = "-----END PRIVATE KEY-----";
  20461. wcchar BEGIN_ENC_PRIV_KEY = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
  20462. wcchar END_ENC_PRIV_KEY = "-----END ENCRYPTED PRIVATE KEY-----";
  20463. #ifdef HAVE_ECC
  20464. wcchar BEGIN_EC_PRIV = "-----BEGIN EC PRIVATE KEY-----";
  20465. wcchar END_EC_PRIV = "-----END EC PRIVATE KEY-----";
  20466. #endif
  20467. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  20468. !defined(NO_DSA)
  20469. wcchar BEGIN_DSA_PRIV = "-----BEGIN DSA PRIVATE KEY-----";
  20470. wcchar END_DSA_PRIV = "-----END DSA PRIVATE KEY-----";
  20471. #endif
  20472. #ifdef OPENSSL_EXTRA
  20473. const char BEGIN_PRIV_KEY_PREFIX[] = "-----BEGIN";
  20474. const char PRIV_KEY_SUFFIX[] = "PRIVATE KEY-----";
  20475. const char END_PRIV_KEY_PREFIX[] = "-----END";
  20476. #endif
  20477. wcchar BEGIN_PUB_KEY = "-----BEGIN PUBLIC KEY-----";
  20478. wcchar END_PUB_KEY = "-----END PUBLIC KEY-----";
  20479. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  20480. wcchar BEGIN_EDDSA_PRIV = "-----BEGIN EDDSA PRIVATE KEY-----";
  20481. wcchar END_EDDSA_PRIV = "-----END EDDSA PRIVATE KEY-----";
  20482. #endif
  20483. #if defined(HAVE_PQC)
  20484. #if defined(HAVE_FALCON)
  20485. wcchar BEGIN_FALCON_LEVEL1_PRIV = "-----BEGIN FALCON_LEVEL1 PRIVATE KEY-----";
  20486. wcchar END_FALCON_LEVEL1_PRIV = "-----END FALCON_LEVEL1 PRIVATE KEY-----";
  20487. wcchar BEGIN_FALCON_LEVEL5_PRIV = "-----BEGIN FALCON_LEVEL5 PRIVATE KEY-----";
  20488. wcchar END_FALCON_LEVEL5_PRIV = "-----END FALCON_LEVEL5 PRIVATE KEY-----";
  20489. #endif /* HAVE_FALCON */
  20490. #if defined(HAVE_DILITHIUM)
  20491. wcchar BEGIN_DILITHIUM_LEVEL2_PRIV = "-----BEGIN DILITHIUM_LEVEL2 PRIVATE KEY-----";
  20492. wcchar END_DILITHIUM_LEVEL2_PRIV = "-----END DILITHIUM_LEVEL2 PRIVATE KEY-----";
  20493. wcchar BEGIN_DILITHIUM_LEVEL3_PRIV = "-----BEGIN DILITHIUM_LEVEL3 PRIVATE KEY-----";
  20494. wcchar END_DILITHIUM_LEVEL3_PRIV = "-----END DILITHIUM_LEVEL3 PRIVATE KEY-----";
  20495. wcchar BEGIN_DILITHIUM_LEVEL5_PRIV = "-----BEGIN DILITHIUM_LEVEL5 PRIVATE KEY-----";
  20496. wcchar END_DILITHIUM_LEVEL5_PRIV = "-----END DILITHIUM_LEVEL5 PRIVATE KEY-----";
  20497. wcchar BEGIN_DILITHIUM_AES_LEVEL2_PRIV = "-----BEGIN DILITHIUM_AES_LEVEL2 PRIVATE KEY-----";
  20498. wcchar END_DILITHIUM_AES_LEVEL2_PRIV = "-----END DILITHIUM_AES_LEVEL2 PRIVATE KEY-----";
  20499. wcchar BEGIN_DILITHIUM_AES_LEVEL3_PRIV = "-----BEGIN DILITHIUM_AES_LEVEL3 PRIVATE KEY-----";
  20500. wcchar END_DILITHIUM_AES_LEVEL3_PRIV = "-----END DILITHIUM_AES_LEVEL3 PRIVATE KEY-----";
  20501. wcchar BEGIN_DILITHIUM_AES_LEVEL5_PRIV = "-----BEGIN DILITHIUM_AES_LEVEL5 PRIVATE KEY-----";
  20502. wcchar END_DILITHIUM_AES_LEVEL5_PRIV = "-----END DILITHIUM_AES_LEVEL5 PRIVATE KEY-----";
  20503. #endif /* HAVE_DILITHIUM */
  20504. #if defined(HAVE_SPHINCS)
  20505. wcchar BEGIN_SPHINCS_FAST_LEVEL1_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
  20506. wcchar END_SPHINCS_FAST_LEVEL1_PRIV = "-----END SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
  20507. wcchar BEGIN_SPHINCS_FAST_LEVEL3_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
  20508. wcchar END_SPHINCS_FAST_LEVEL3_PRIV = "-----END SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
  20509. wcchar BEGIN_SPHINCS_FAST_LEVEL5_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
  20510. wcchar END_SPHINCS_FAST_LEVEL5_PRIV = "-----END SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
  20511. wcchar BEGIN_SPHINCS_SMALL_LEVEL1_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
  20512. wcchar END_SPHINCS_SMALL_LEVEL1_PRIV = "-----END SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
  20513. wcchar BEGIN_SPHINCS_SMALL_LEVEL3_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
  20514. wcchar END_SPHINCS_SMALL_LEVEL3_PRIV = "-----END SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
  20515. wcchar BEGIN_SPHINCS_SMALL_LEVEL5_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
  20516. wcchar END_SPHINCS_SMALL_LEVEL5_PRIV = "-----END SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
  20517. #endif /* HAVE_SPHINCS */
  20518. #endif /* HAVE_PQC */
  20519. const int pem_struct_min_sz = XSTR_SIZEOF("-----BEGIN X509 CRL-----"
  20520. "-----END X509 CRL-----");
  20521. static WC_INLINE const char* SkipEndOfLineChars(const char* line,
  20522. const char* endOfLine)
  20523. {
  20524. /* eat end of line characters */
  20525. while (line < endOfLine &&
  20526. (line[0] == '\r' || line[0] == '\n')) {
  20527. line++;
  20528. }
  20529. return line;
  20530. }
  20531. int wc_PemGetHeaderFooter(int type, const char** header, const char** footer)
  20532. {
  20533. int ret = BAD_FUNC_ARG;
  20534. switch (type) {
  20535. case CA_TYPE: /* same as below */
  20536. case TRUSTED_PEER_TYPE:
  20537. case CERT_TYPE:
  20538. if (header) *header = BEGIN_CERT;
  20539. if (footer) *footer = END_CERT;
  20540. ret = 0;
  20541. break;
  20542. case CRL_TYPE:
  20543. if (header) *header = BEGIN_X509_CRL;
  20544. if (footer) *footer = END_X509_CRL;
  20545. ret = 0;
  20546. break;
  20547. #ifndef NO_DH
  20548. case DH_PARAM_TYPE:
  20549. if (header) *header = BEGIN_DH_PARAM;
  20550. if (footer) *footer = END_DH_PARAM;
  20551. ret = 0;
  20552. break;
  20553. case X942_PARAM_TYPE:
  20554. if (header) *header = BEGIN_X942_PARAM;
  20555. if (footer) *footer = END_X942_PARAM;
  20556. ret = 0;
  20557. break;
  20558. #endif
  20559. #ifndef NO_DSA
  20560. case DSA_PARAM_TYPE:
  20561. if (header) *header = BEGIN_DSA_PARAM;
  20562. if (footer) *footer = END_DSA_PARAM;
  20563. ret = 0;
  20564. break;
  20565. #endif
  20566. #ifdef WOLFSSL_CERT_REQ
  20567. case CERTREQ_TYPE:
  20568. if (header) *header = BEGIN_CERT_REQ;
  20569. if (footer) *footer = END_CERT_REQ;
  20570. ret = 0;
  20571. break;
  20572. #endif
  20573. #ifndef NO_DSA
  20574. case DSA_TYPE:
  20575. case DSA_PRIVATEKEY_TYPE:
  20576. if (header) *header = BEGIN_DSA_PRIV;
  20577. if (footer) *footer = END_DSA_PRIV;
  20578. ret = 0;
  20579. break;
  20580. #endif
  20581. #ifdef HAVE_ECC
  20582. case ECC_TYPE:
  20583. case ECC_PRIVATEKEY_TYPE:
  20584. if (header) *header = BEGIN_EC_PRIV;
  20585. if (footer) *footer = END_EC_PRIV;
  20586. ret = 0;
  20587. break;
  20588. #endif
  20589. case RSA_TYPE:
  20590. case PRIVATEKEY_TYPE:
  20591. if (header) *header = BEGIN_RSA_PRIV;
  20592. if (footer) *footer = END_RSA_PRIV;
  20593. ret = 0;
  20594. break;
  20595. #ifdef HAVE_ED25519
  20596. case ED25519_TYPE:
  20597. #endif
  20598. #ifdef HAVE_ED448
  20599. case ED448_TYPE:
  20600. #endif
  20601. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  20602. case EDDSA_PRIVATEKEY_TYPE:
  20603. if (header) *header = BEGIN_EDDSA_PRIV;
  20604. if (footer) *footer = END_EDDSA_PRIV;
  20605. ret = 0;
  20606. break;
  20607. #endif
  20608. #ifdef HAVE_PQC
  20609. #ifdef HAVE_FALCON
  20610. case FALCON_LEVEL1_TYPE:
  20611. if (header) *header = BEGIN_FALCON_LEVEL1_PRIV;
  20612. if (footer) *footer = END_FALCON_LEVEL1_PRIV;
  20613. ret = 0;
  20614. break;
  20615. case FALCON_LEVEL5_TYPE:
  20616. if (header) *header = BEGIN_FALCON_LEVEL5_PRIV;
  20617. if (footer) *footer = END_FALCON_LEVEL5_PRIV;
  20618. ret = 0;
  20619. break;
  20620. #endif /* HAVE_FALCON */
  20621. #ifdef HAVE_DILITHIUM
  20622. case DILITHIUM_LEVEL2_TYPE:
  20623. if (header) *header = BEGIN_DILITHIUM_LEVEL2_PRIV;
  20624. if (footer) *footer = END_DILITHIUM_LEVEL2_PRIV;
  20625. ret = 0;
  20626. break;
  20627. case DILITHIUM_LEVEL3_TYPE:
  20628. if (header) *header = BEGIN_DILITHIUM_LEVEL3_PRIV;
  20629. if (footer) *footer = END_DILITHIUM_LEVEL3_PRIV;
  20630. ret = 0;
  20631. break;
  20632. case DILITHIUM_LEVEL5_TYPE:
  20633. if (header) *header = BEGIN_DILITHIUM_LEVEL5_PRIV;
  20634. if (footer) *footer = END_DILITHIUM_LEVEL5_PRIV;
  20635. ret = 0;
  20636. break;
  20637. case DILITHIUM_AES_LEVEL2_TYPE:
  20638. if (header) *header = BEGIN_DILITHIUM_AES_LEVEL2_PRIV;
  20639. if (footer) *footer = END_DILITHIUM_AES_LEVEL2_PRIV;
  20640. ret = 0;
  20641. break;
  20642. case DILITHIUM_AES_LEVEL3_TYPE:
  20643. if (header) *header = BEGIN_DILITHIUM_AES_LEVEL3_PRIV;
  20644. if (footer) *footer = END_DILITHIUM_AES_LEVEL3_PRIV;
  20645. ret = 0;
  20646. break;
  20647. case DILITHIUM_AES_LEVEL5_TYPE:
  20648. if (header) *header = BEGIN_DILITHIUM_AES_LEVEL5_PRIV;
  20649. if (footer) *footer = END_DILITHIUM_AES_LEVEL5_PRIV;
  20650. ret = 0;
  20651. break;
  20652. #endif /* HAVE_DILITHIUM */
  20653. #ifdef HAVE_SPHINCS
  20654. case SPHINCS_FAST_LEVEL1_TYPE:
  20655. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL1_PRIV;
  20656. if (footer) *footer = END_SPHINCS_FAST_LEVEL1_PRIV;
  20657. ret = 0;
  20658. break;
  20659. case SPHINCS_FAST_LEVEL3_TYPE:
  20660. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL3_PRIV;
  20661. if (footer) *footer = END_SPHINCS_FAST_LEVEL3_PRIV;
  20662. ret = 0;
  20663. break;
  20664. case SPHINCS_FAST_LEVEL5_TYPE:
  20665. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL5_PRIV;
  20666. if (footer) *footer = END_SPHINCS_FAST_LEVEL5_PRIV;
  20667. ret = 0;
  20668. break;
  20669. case SPHINCS_SMALL_LEVEL1_TYPE:
  20670. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL1_PRIV;
  20671. if (footer) *footer = END_SPHINCS_SMALL_LEVEL1_PRIV;
  20672. ret = 0;
  20673. break;
  20674. case SPHINCS_SMALL_LEVEL3_TYPE:
  20675. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL3_PRIV;
  20676. if (footer) *footer = END_SPHINCS_SMALL_LEVEL3_PRIV;
  20677. ret = 0;
  20678. break;
  20679. case SPHINCS_SMALL_LEVEL5_TYPE:
  20680. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL5_PRIV;
  20681. if (footer) *footer = END_SPHINCS_SMALL_LEVEL5_PRIV;
  20682. ret = 0;
  20683. break;
  20684. #endif /* HAVE_SPHINCS */
  20685. #endif /* HAVE_PQC */
  20686. case PUBLICKEY_TYPE:
  20687. case ECC_PUBLICKEY_TYPE:
  20688. if (header) *header = BEGIN_PUB_KEY;
  20689. if (footer) *footer = END_PUB_KEY;
  20690. ret = 0;
  20691. break;
  20692. case RSA_PUBLICKEY_TYPE:
  20693. if (header) *header = BEGIN_RSA_PUB;
  20694. if (footer) *footer = END_RSA_PUB;
  20695. ret = 0;
  20696. break;
  20697. #ifndef NO_DH
  20698. case DH_PRIVATEKEY_TYPE:
  20699. #endif
  20700. case PKCS8_PRIVATEKEY_TYPE:
  20701. if (header) *header = BEGIN_PRIV_KEY;
  20702. if (footer) *footer = END_PRIV_KEY;
  20703. ret = 0;
  20704. break;
  20705. case PKCS8_ENC_PRIVATEKEY_TYPE:
  20706. if (header) *header = BEGIN_ENC_PRIV_KEY;
  20707. if (footer) *footer = END_ENC_PRIV_KEY;
  20708. ret = 0;
  20709. break;
  20710. default:
  20711. break;
  20712. }
  20713. return ret;
  20714. }
  20715. #ifdef WOLFSSL_ENCRYPTED_KEYS
  20716. static wcchar kProcTypeHeader = "Proc-Type";
  20717. static wcchar kDecInfoHeader = "DEK-Info";
  20718. #ifdef WOLFSSL_PEM_TO_DER
  20719. #ifndef NO_DES3
  20720. static wcchar kEncTypeDes = "DES-CBC";
  20721. static wcchar kEncTypeDes3 = "DES-EDE3-CBC";
  20722. #endif
  20723. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  20724. static wcchar kEncTypeAesCbc128 = "AES-128-CBC";
  20725. #endif
  20726. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  20727. static wcchar kEncTypeAesCbc192 = "AES-192-CBC";
  20728. #endif
  20729. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  20730. static wcchar kEncTypeAesCbc256 = "AES-256-CBC";
  20731. #endif
  20732. int wc_EncryptedInfoGet(EncryptedInfo* info, const char* cipherInfo)
  20733. {
  20734. int ret = 0;
  20735. if (info == NULL || cipherInfo == NULL)
  20736. return BAD_FUNC_ARG;
  20737. /* determine cipher information */
  20738. #ifndef NO_DES3
  20739. if (XSTRCMP(cipherInfo, kEncTypeDes) == 0) {
  20740. info->cipherType = WC_CIPHER_DES;
  20741. info->keySz = DES_KEY_SIZE;
  20742. /* DES_IV_SIZE is incorrectly 16 in FIPS v2. It should be 8, same as the
  20743. * block size. */
  20744. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  20745. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  20746. #else
  20747. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  20748. #endif
  20749. }
  20750. else if (XSTRCMP(cipherInfo, kEncTypeDes3) == 0) {
  20751. info->cipherType = WC_CIPHER_DES3;
  20752. info->keySz = DES3_KEY_SIZE;
  20753. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  20754. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  20755. #else
  20756. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  20757. #endif
  20758. }
  20759. else
  20760. #endif /* !NO_DES3 */
  20761. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  20762. if (XSTRCMP(cipherInfo, kEncTypeAesCbc128) == 0) {
  20763. info->cipherType = WC_CIPHER_AES_CBC;
  20764. info->keySz = AES_128_KEY_SIZE;
  20765. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  20766. }
  20767. else
  20768. #endif
  20769. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  20770. if (XSTRCMP(cipherInfo, kEncTypeAesCbc192) == 0) {
  20771. info->cipherType = WC_CIPHER_AES_CBC;
  20772. info->keySz = AES_192_KEY_SIZE;
  20773. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  20774. }
  20775. else
  20776. #endif
  20777. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  20778. if (XSTRCMP(cipherInfo, kEncTypeAesCbc256) == 0) {
  20779. info->cipherType = WC_CIPHER_AES_CBC;
  20780. info->keySz = AES_256_KEY_SIZE;
  20781. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  20782. }
  20783. else
  20784. #endif
  20785. {
  20786. ret = NOT_COMPILED_IN;
  20787. }
  20788. return ret;
  20789. }
  20790. int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer,
  20791. size_t bufSz)
  20792. {
  20793. int err = 0;
  20794. const char* bufferStart;
  20795. const char* bufferEnd;
  20796. char* line;
  20797. word32 lineSz;
  20798. char* finish;
  20799. word32 finishSz;
  20800. char* start = NULL;
  20801. word32 startSz;
  20802. const char* newline = NULL;
  20803. if (info == NULL || pBuffer == NULL || bufSz == 0)
  20804. return BAD_FUNC_ARG;
  20805. bufferStart = *pBuffer;
  20806. bufferEnd = bufferStart + bufSz;
  20807. /* find encrypted info marker */
  20808. line = XSTRNSTR(bufferStart, kProcTypeHeader,
  20809. min((word32)bufSz, PEM_LINE_LEN));
  20810. if (line != NULL) {
  20811. if (line >= bufferEnd) {
  20812. return BUFFER_E;
  20813. }
  20814. lineSz = (word32)(bufferEnd - line);
  20815. /* find DEC-Info marker */
  20816. start = XSTRNSTR(line, kDecInfoHeader, min(lineSz, PEM_LINE_LEN));
  20817. if (start == NULL)
  20818. return BUFFER_E;
  20819. /* skip dec-info and ": " */
  20820. start += XSTRLEN(kDecInfoHeader);
  20821. if (start >= bufferEnd)
  20822. return BUFFER_E;
  20823. if (start[0] == ':') {
  20824. start++;
  20825. if (start >= bufferEnd)
  20826. return BUFFER_E;
  20827. }
  20828. if (start[0] == ' ')
  20829. start++;
  20830. startSz = (word32)(bufferEnd - start);
  20831. finish = XSTRNSTR(start, ",", min(startSz, PEM_LINE_LEN));
  20832. if ((start != NULL) && (finish != NULL) && (start < finish)) {
  20833. if (finish >= bufferEnd) {
  20834. return BUFFER_E;
  20835. }
  20836. finishSz = (word32)(bufferEnd - finish);
  20837. newline = XSTRNSTR(finish, "\r", min(finishSz, PEM_LINE_LEN));
  20838. /* get cipher name */
  20839. if (NAME_SZ < (finish - start)) /* buffer size of info->name */
  20840. return BUFFER_E;
  20841. if (XMEMCPY(info->name, start, finish - start) == NULL)
  20842. return BUFFER_E;
  20843. info->name[finish - start] = '\0'; /* null term */
  20844. /* populate info */
  20845. err = wc_EncryptedInfoGet(info, info->name);
  20846. if (err != 0)
  20847. return err;
  20848. /* get IV */
  20849. if (finishSz < info->ivSz + 1)
  20850. return BUFFER_E;
  20851. if (newline == NULL) {
  20852. newline = XSTRNSTR(finish, "\n", min(finishSz,
  20853. PEM_LINE_LEN));
  20854. }
  20855. if ((newline != NULL) && (newline > finish)) {
  20856. finish++;
  20857. info->ivSz = (word32)(newline - finish);
  20858. if (info->ivSz > IV_SZ)
  20859. return BUFFER_E;
  20860. if (XMEMCPY(info->iv, finish, info->ivSz) == NULL)
  20861. return BUFFER_E;
  20862. info->set = 1;
  20863. }
  20864. else
  20865. return BUFFER_E;
  20866. }
  20867. else
  20868. return BUFFER_E;
  20869. /* eat end of line characters */
  20870. newline = SkipEndOfLineChars(newline, bufferEnd);
  20871. /* return new headerEnd */
  20872. *pBuffer = newline;
  20873. }
  20874. return err;
  20875. }
  20876. #endif /* WOLFSSL_PEM_TO_DER */
  20877. #ifdef WOLFSSL_DER_TO_PEM
  20878. static int wc_EncryptedInfoAppend(char* dest, int destSz, char* cipherInfo)
  20879. {
  20880. if (cipherInfo != NULL) {
  20881. int cipherInfoStrLen = (int)XSTRLEN((char*)cipherInfo);
  20882. if (cipherInfoStrLen > HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3))
  20883. cipherInfoStrLen = HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3);
  20884. if (destSz - (int)XSTRLEN(dest) >= cipherInfoStrLen + (9+14+8+2+2+1)) {
  20885. /* strncat's src length needs to include the NULL */
  20886. XSTRNCAT(dest, kProcTypeHeader, 10);
  20887. XSTRNCAT(dest, ": 4,ENCRYPTED\n", 15);
  20888. XSTRNCAT(dest, kDecInfoHeader, 9);
  20889. XSTRNCAT(dest, ": ", 3);
  20890. XSTRNCAT(dest, cipherInfo, destSz - (int)XSTRLEN(dest) - 1);
  20891. XSTRNCAT(dest, "\n\n", 4);
  20892. }
  20893. }
  20894. return 0;
  20895. }
  20896. #endif /* WOLFSSL_DER_TO_PEM */
  20897. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  20898. #ifdef WOLFSSL_DER_TO_PEM
  20899. /* Used for compatibility API */
  20900. WOLFSSL_ABI
  20901. int wc_DerToPem(const byte* der, word32 derSz,
  20902. byte* output, word32 outSz, int type)
  20903. {
  20904. return wc_DerToPemEx(der, derSz, output, outSz, NULL, type);
  20905. }
  20906. /* convert der buffer to pem into output, can't do inplace, der and output
  20907. need to be different */
  20908. int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz,
  20909. byte *cipher_info, int type)
  20910. {
  20911. const char* headerStr = NULL;
  20912. const char* footerStr = NULL;
  20913. #ifdef WOLFSSL_SMALL_STACK
  20914. char* header = NULL;
  20915. char* footer = NULL;
  20916. #else
  20917. char header[MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE];
  20918. char footer[MAX_X509_HEADER_SZ];
  20919. #endif
  20920. int headerLen = MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE;
  20921. int footerLen = MAX_X509_HEADER_SZ;
  20922. int i;
  20923. int err;
  20924. int outLen; /* return length or error */
  20925. (void)cipher_info;
  20926. if (der == output) /* no in place conversion */
  20927. return BAD_FUNC_ARG;
  20928. err = wc_PemGetHeaderFooter(type, &headerStr, &footerStr);
  20929. if (err != 0)
  20930. return err;
  20931. #ifdef WOLFSSL_SMALL_STACK
  20932. header = (char*)XMALLOC(headerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20933. if (header == NULL)
  20934. return MEMORY_E;
  20935. footer = (char*)XMALLOC(footerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20936. if (footer == NULL) {
  20937. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20938. return MEMORY_E;
  20939. }
  20940. #endif
  20941. /* build header and footer based on type */
  20942. XSTRNCPY(header, headerStr, headerLen - 1);
  20943. header[headerLen - 2] = 0;
  20944. XSTRNCPY(footer, footerStr, footerLen - 1);
  20945. footer[footerLen - 2] = 0;
  20946. /* add new line to end */
  20947. XSTRNCAT(header, "\n", 2);
  20948. XSTRNCAT(footer, "\n", 2);
  20949. #ifdef WOLFSSL_ENCRYPTED_KEYS
  20950. err = wc_EncryptedInfoAppend(header, headerLen, (char*)cipher_info);
  20951. if (err != 0) {
  20952. #ifdef WOLFSSL_SMALL_STACK
  20953. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20954. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20955. #endif
  20956. return err;
  20957. }
  20958. #endif
  20959. headerLen = (int)XSTRLEN(header);
  20960. footerLen = (int)XSTRLEN(footer);
  20961. /* if null output and 0 size passed in then return size needed */
  20962. if (!output && outSz == 0) {
  20963. #ifdef WOLFSSL_SMALL_STACK
  20964. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20965. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20966. #endif
  20967. outLen = 0;
  20968. if ((err = Base64_Encode(der, derSz, NULL, (word32*)&outLen))
  20969. != LENGTH_ONLY_E) {
  20970. WOLFSSL_ERROR_VERBOSE(err);
  20971. return err;
  20972. }
  20973. return headerLen + footerLen + outLen;
  20974. }
  20975. if (!der || !output) {
  20976. #ifdef WOLFSSL_SMALL_STACK
  20977. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20978. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20979. #endif
  20980. return BAD_FUNC_ARG;
  20981. }
  20982. /* don't even try if outSz too short */
  20983. if (outSz < headerLen + footerLen + derSz) {
  20984. #ifdef WOLFSSL_SMALL_STACK
  20985. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20986. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20987. #endif
  20988. return BAD_FUNC_ARG;
  20989. }
  20990. /* header */
  20991. XMEMCPY(output, header, headerLen);
  20992. i = headerLen;
  20993. #ifdef WOLFSSL_SMALL_STACK
  20994. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20995. #endif
  20996. /* body */
  20997. outLen = outSz - (headerLen + footerLen); /* input to Base64_Encode */
  20998. if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0) {
  20999. #ifdef WOLFSSL_SMALL_STACK
  21000. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21001. #endif
  21002. WOLFSSL_ERROR_VERBOSE(err);
  21003. return err;
  21004. }
  21005. i += outLen;
  21006. /* footer */
  21007. if ( (i + footerLen) > (int)outSz) {
  21008. #ifdef WOLFSSL_SMALL_STACK
  21009. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21010. #endif
  21011. return BAD_FUNC_ARG;
  21012. }
  21013. XMEMCPY(output + i, footer, footerLen);
  21014. #ifdef WOLFSSL_SMALL_STACK
  21015. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21016. #endif
  21017. return outLen + headerLen + footerLen;
  21018. }
  21019. #endif /* WOLFSSL_DER_TO_PEM */
  21020. #ifdef WOLFSSL_PEM_TO_DER
  21021. /* Remove PEM header/footer, convert to ASN1, store any encrypted data
  21022. info->consumed tracks of PEM bytes consumed in case multiple parts */
  21023. int PemToDer(const unsigned char* buff, long longSz, int type,
  21024. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  21025. {
  21026. const char* header = NULL;
  21027. const char* footer = NULL;
  21028. const char* headerEnd;
  21029. const char* footerEnd;
  21030. const char* consumedEnd;
  21031. const char* bufferEnd = (const char*)(buff + longSz);
  21032. long neededSz;
  21033. int ret = 0;
  21034. int sz = (int)longSz;
  21035. int encrypted_key = 0;
  21036. DerBuffer* der;
  21037. word32 algId = 0;
  21038. word32 idx;
  21039. #if defined(WOLFSSL_ENCRYPTED_KEYS)
  21040. #if ((defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_DES3)) || \
  21041. (!defined(NO_AES) && defined(HAVE_AES_CBC) && \
  21042. defined(HAVE_AES_DECRYPT))) && \
  21043. !defined(NO_WOLFSSL_SKIP_TRAILING_PAD)
  21044. int padVal = 0;
  21045. #endif
  21046. #endif
  21047. #ifdef OPENSSL_EXTRA
  21048. char beginBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  21049. char endBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  21050. #endif
  21051. WOLFSSL_ENTER("PemToDer");
  21052. /* get PEM header and footer based on type */
  21053. ret = wc_PemGetHeaderFooter(type, &header, &footer);
  21054. if (ret != 0)
  21055. return ret;
  21056. /* map header if not found for type */
  21057. for (;;) {
  21058. headerEnd = XSTRNSTR((char*)buff, header, sz);
  21059. if (headerEnd) {
  21060. break;
  21061. }
  21062. if (type == PRIVATEKEY_TYPE) {
  21063. if (header == BEGIN_RSA_PRIV) {
  21064. header = BEGIN_PRIV_KEY;
  21065. footer = END_PRIV_KEY;
  21066. }
  21067. else if (header == BEGIN_PRIV_KEY) {
  21068. header = BEGIN_ENC_PRIV_KEY;
  21069. footer = END_ENC_PRIV_KEY;
  21070. }
  21071. #ifdef HAVE_ECC
  21072. else if (header == BEGIN_ENC_PRIV_KEY) {
  21073. header = BEGIN_EC_PRIV;
  21074. footer = END_EC_PRIV;
  21075. }
  21076. else if (header == BEGIN_EC_PRIV) {
  21077. header = BEGIN_DSA_PRIV;
  21078. footer = END_DSA_PRIV;
  21079. }
  21080. #endif
  21081. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  21082. #ifdef HAVE_ECC
  21083. else if (header == BEGIN_DSA_PRIV) {
  21084. #else
  21085. else if (header == BEGIN_ENC_PRIV_KEY) {
  21086. #endif
  21087. header = BEGIN_EDDSA_PRIV;
  21088. footer = END_EDDSA_PRIV;
  21089. }
  21090. #endif
  21091. else {
  21092. #ifdef WOLF_PRIVATE_KEY_ID
  21093. /* allow loading a public key for use with crypto or PK callbacks */
  21094. type = PUBLICKEY_TYPE;
  21095. header = BEGIN_PUB_KEY;
  21096. footer = END_PUB_KEY;
  21097. #else
  21098. break;
  21099. #endif
  21100. }
  21101. }
  21102. else if (type == PUBLICKEY_TYPE) {
  21103. if (header == BEGIN_PUB_KEY) {
  21104. header = BEGIN_RSA_PUB;
  21105. footer = END_RSA_PUB;
  21106. }
  21107. else {
  21108. break;
  21109. }
  21110. }
  21111. #ifdef HAVE_CRL
  21112. else if ((type == CRL_TYPE) && (header != BEGIN_X509_CRL)) {
  21113. header = BEGIN_X509_CRL;
  21114. footer = END_X509_CRL;
  21115. }
  21116. #endif
  21117. else {
  21118. break;
  21119. }
  21120. }
  21121. if (!headerEnd) {
  21122. #ifdef OPENSSL_EXTRA
  21123. if (type == PRIVATEKEY_TYPE) {
  21124. const char* beginEnd;
  21125. int endLen;
  21126. /* see if there is a -----BEGIN * PRIVATE KEY----- header */
  21127. headerEnd = XSTRNSTR((char*)buff, PRIV_KEY_SUFFIX, sz);
  21128. if (headerEnd) {
  21129. beginEnd = headerEnd + XSTR_SIZEOF(PRIV_KEY_SUFFIX);
  21130. if (beginEnd >= (char*)buff + sz) {
  21131. return BUFFER_E;
  21132. }
  21133. /* back up to BEGIN_PRIV_KEY_PREFIX */
  21134. while (headerEnd > (char*)buff &&
  21135. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  21136. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 &&
  21137. *headerEnd != '\n') {
  21138. headerEnd--;
  21139. }
  21140. if (headerEnd <= (char*)buff ||
  21141. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  21142. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 ||
  21143. beginEnd - headerEnd > PEM_LINE_LEN) {
  21144. WOLFSSL_MSG("Couldn't find PEM header");
  21145. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21146. return ASN_NO_PEM_HEADER;
  21147. }
  21148. /* headerEnd now points to beginning of header */
  21149. XMEMCPY(beginBuf, headerEnd, beginEnd - headerEnd);
  21150. beginBuf[beginEnd - headerEnd] = '\0';
  21151. /* look for matching footer */
  21152. footer = XSTRNSTR(beginEnd,
  21153. beginBuf + XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX),
  21154. (unsigned int)((char*)buff + sz - beginEnd));
  21155. if (!footer) {
  21156. WOLFSSL_MSG("Couldn't find PEM footer");
  21157. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21158. return ASN_NO_PEM_HEADER;
  21159. }
  21160. footer -= XSTR_SIZEOF(END_PRIV_KEY_PREFIX);
  21161. if (footer > (char*)buff + sz - XSTR_SIZEOF(END_PRIV_KEY_PREFIX)
  21162. || XSTRNCMP(footer, END_PRIV_KEY_PREFIX,
  21163. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)) != 0) {
  21164. WOLFSSL_MSG("Unexpected footer for PEM");
  21165. return BUFFER_E;
  21166. }
  21167. endLen = (unsigned int)(beginEnd - headerEnd -
  21168. (XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX) -
  21169. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)));
  21170. XMEMCPY(endBuf, footer, endLen);
  21171. endBuf[endLen] = '\0';
  21172. header = beginBuf;
  21173. footer = endBuf;
  21174. headerEnd = beginEnd;
  21175. }
  21176. }
  21177. if (!headerEnd) {
  21178. WOLFSSL_MSG("Couldn't find PEM header");
  21179. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21180. return ASN_NO_PEM_HEADER;
  21181. }
  21182. #else
  21183. WOLFSSL_MSG("Couldn't find PEM header");
  21184. return ASN_NO_PEM_HEADER;
  21185. #endif
  21186. } else {
  21187. headerEnd += XSTRLEN(header);
  21188. }
  21189. /* eat end of line characters */
  21190. headerEnd = SkipEndOfLineChars(headerEnd, bufferEnd);
  21191. if (keyFormat) {
  21192. /* keyFormat is Key_Sum enum */
  21193. if (type == PRIVATEKEY_TYPE) {
  21194. #ifndef NO_RSA
  21195. if (header == BEGIN_RSA_PRIV)
  21196. *keyFormat = RSAk;
  21197. #endif
  21198. #ifdef HAVE_ECC
  21199. if (header == BEGIN_EC_PRIV)
  21200. *keyFormat = ECDSAk;
  21201. #endif
  21202. #ifndef NO_DSA
  21203. if (header == BEGIN_DSA_PRIV)
  21204. *keyFormat = DSAk;
  21205. #endif
  21206. }
  21207. #ifdef WOLF_PRIVATE_KEY_ID
  21208. else if (type == PUBLICKEY_TYPE) {
  21209. #ifndef NO_RSA
  21210. if (header == BEGIN_RSA_PUB)
  21211. *keyFormat = RSAk;
  21212. #endif
  21213. }
  21214. #endif
  21215. }
  21216. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21217. if (info) {
  21218. ret = wc_EncryptedInfoParse(info, &headerEnd, bufferEnd - headerEnd);
  21219. if (ret < 0)
  21220. return ret;
  21221. if (info->set)
  21222. encrypted_key = 1;
  21223. }
  21224. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  21225. /* find footer */
  21226. footerEnd = XSTRNSTR(headerEnd, footer, (unsigned int)((char*)buff +
  21227. sz - headerEnd));
  21228. if (!footerEnd) {
  21229. if (info)
  21230. info->consumed = longSz; /* No more certs if no footer */
  21231. return BUFFER_E;
  21232. }
  21233. consumedEnd = footerEnd + XSTRLEN(footer);
  21234. if (consumedEnd < bufferEnd) { /* handle no end of line on last line */
  21235. /* eat end of line characters */
  21236. consumedEnd = SkipEndOfLineChars(consumedEnd, bufferEnd);
  21237. /* skip possible null term */
  21238. if (consumedEnd < bufferEnd && consumedEnd[0] == '\0')
  21239. consumedEnd++;
  21240. }
  21241. if (info)
  21242. info->consumed = (long)(consumedEnd - (const char*)buff);
  21243. /* set up der buffer */
  21244. neededSz = (long)(footerEnd - headerEnd);
  21245. if (neededSz > sz || neededSz <= 0)
  21246. return BUFFER_E;
  21247. ret = AllocDer(pDer, (word32)neededSz, type, heap);
  21248. if (ret < 0) {
  21249. return ret;
  21250. }
  21251. der = *pDer;
  21252. if (Base64_Decode((byte*)headerEnd, (word32)neededSz,
  21253. der->buffer, &der->length) < 0) {
  21254. WOLFSSL_ERROR(BUFFER_E);
  21255. return BUFFER_E;
  21256. }
  21257. if ((header == BEGIN_PRIV_KEY
  21258. #ifdef OPENSSL_EXTRA
  21259. || header == beginBuf
  21260. #endif
  21261. #ifdef HAVE_ECC
  21262. || header == BEGIN_EC_PRIV
  21263. #endif
  21264. ) && !encrypted_key)
  21265. {
  21266. /* detect pkcs8 key and get alg type */
  21267. /* keep PKCS8 header */
  21268. idx = 0;
  21269. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length, &algId);
  21270. if (ret > 0) {
  21271. if (keyFormat)
  21272. *keyFormat = algId;
  21273. }
  21274. else {
  21275. /* ignore failure here and assume key is not pkcs8 wrapped */
  21276. }
  21277. return 0;
  21278. }
  21279. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21280. if (encrypted_key || header == BEGIN_ENC_PRIV_KEY) {
  21281. int passwordSz = NAME_SZ;
  21282. #ifdef WOLFSSL_SMALL_STACK
  21283. char* password = NULL;
  21284. #else
  21285. char password[NAME_SZ];
  21286. #endif
  21287. if (!info || !info->passwd_cb) {
  21288. WOLFSSL_MSG("No password callback set");
  21289. WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
  21290. return NO_PASSWORD;
  21291. }
  21292. #ifdef WOLFSSL_SMALL_STACK
  21293. password = (char*)XMALLOC(passwordSz, heap, DYNAMIC_TYPE_STRING);
  21294. if (password == NULL) {
  21295. return MEMORY_E;
  21296. }
  21297. #endif
  21298. /* get password */
  21299. ret = info->passwd_cb(password, passwordSz, PEM_PASS_READ,
  21300. info->passwd_userdata);
  21301. if (ret >= 0) {
  21302. passwordSz = ret;
  21303. #ifdef WOLFSSL_CHECK_MEM_ZERO
  21304. wc_MemZero_Add("PEM password", password, passwordSz);
  21305. #endif
  21306. /* convert and adjust length */
  21307. if (header == BEGIN_ENC_PRIV_KEY) {
  21308. #ifndef NO_PWDBASED
  21309. ret = wc_DecryptPKCS8Key(der->buffer, der->length,
  21310. password, passwordSz);
  21311. if (ret > 0) {
  21312. /* update length by decrypted content */
  21313. der->length = ret;
  21314. idx = 0;
  21315. /* detect pkcs8 key and get alg type */
  21316. /* keep PKCS8 header */
  21317. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length,
  21318. &algId);
  21319. if (ret >= 0) {
  21320. if (keyFormat)
  21321. *keyFormat = algId;
  21322. ret = 0;
  21323. }
  21324. }
  21325. #else
  21326. WOLFSSL_ERROR_VERBOSE(NOT_COMPILED_IN);
  21327. ret = NOT_COMPILED_IN;
  21328. #endif
  21329. }
  21330. /* decrypt the key */
  21331. else {
  21332. if (passwordSz == 0) {
  21333. /* The key is encrypted but does not have a password */
  21334. WOLFSSL_MSG("No password for encrypted key");
  21335. WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
  21336. ret = NO_PASSWORD;
  21337. }
  21338. else {
  21339. ret = wc_BufferKeyDecrypt(info, der->buffer, der->length,
  21340. (byte*)password, passwordSz, WC_MD5);
  21341. #ifndef NO_WOLFSSL_SKIP_TRAILING_PAD
  21342. #ifndef NO_DES3
  21343. if (info->cipherType == WC_CIPHER_DES3) {
  21344. /* Assuming there is padding:
  21345. * (der->length > 0 && der->length > DES_BLOCK_SIZE &&
  21346. * (der->length % DES_BLOCK_SIZE) != 0)
  21347. * and assuming the last value signifies the number of
  21348. * padded bytes IE if last value is 0x08 then there are
  21349. * 8 bytes of padding:
  21350. * padVal = der->buffer[der->length-1];
  21351. * then strip this padding before proceeding:
  21352. * der->length -= padVal;
  21353. */
  21354. if (der->length > DES_BLOCK_SIZE &&
  21355. (der->length % DES_BLOCK_SIZE) != 0) {
  21356. padVal = der->buffer[der->length-1];
  21357. if (padVal < DES_BLOCK_SIZE) {
  21358. der->length -= padVal;
  21359. }
  21360. }
  21361. }
  21362. #endif /* !NO_DES3 */
  21363. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && \
  21364. defined(HAVE_AES_DECRYPT)
  21365. if (info->cipherType == WC_CIPHER_AES_CBC) {
  21366. if (der->length > AES_BLOCK_SIZE) {
  21367. padVal = der->buffer[der->length-1];
  21368. if (padVal <= AES_BLOCK_SIZE) {
  21369. der->length -= padVal;
  21370. }
  21371. }
  21372. }
  21373. #endif
  21374. #endif /* !NO_WOLFSSL_SKIP_TRAILING_PAD */
  21375. }
  21376. }
  21377. #ifdef OPENSSL_EXTRA
  21378. if (ret) {
  21379. PEMerr(0, PEM_R_BAD_DECRYPT);
  21380. }
  21381. #endif
  21382. ForceZero(password, passwordSz);
  21383. }
  21384. #ifdef OPENSSL_EXTRA
  21385. else {
  21386. PEMerr(0, PEM_R_BAD_PASSWORD_READ);
  21387. }
  21388. #endif
  21389. #ifdef WOLFSSL_SMALL_STACK
  21390. XFREE(password, heap, DYNAMIC_TYPE_STRING);
  21391. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  21392. wc_MemZero_Check(password, NAME_SZ);
  21393. #endif
  21394. }
  21395. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  21396. return ret;
  21397. }
  21398. int wc_PemToDer(const unsigned char* buff, long longSz, int type,
  21399. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  21400. {
  21401. int ret = PemToDer(buff, longSz, type, pDer, heap, info, keyFormat);
  21402. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  21403. if (ret == 0 && type == PRIVATEKEY_TYPE) {
  21404. DerBuffer* der = *pDer;
  21405. /* if a PKCS8 key header exists remove it */
  21406. ret = ToTraditional(der->buffer, der->length);
  21407. if (ret > 0) {
  21408. der->length = ret;
  21409. }
  21410. ret = 0; /* ignore error removing PKCS8 header */
  21411. }
  21412. #endif
  21413. return ret;
  21414. }
  21415. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21416. /* our KeyPemToDer password callback, password in userData */
  21417. static int KeyPemToDerPassCb(char* passwd, int sz, int rw, void* userdata)
  21418. {
  21419. (void)rw;
  21420. if (userdata == NULL)
  21421. return 0;
  21422. XSTRNCPY(passwd, (char*)userdata, sz);
  21423. return min((word32)sz, (word32)XSTRLEN((char*)userdata));
  21424. }
  21425. #endif
  21426. /* Return bytes written to buff or < 0 for error */
  21427. int wc_KeyPemToDer(const unsigned char* pem, int pemSz,
  21428. unsigned char* buff, int buffSz, const char* pass)
  21429. {
  21430. int ret;
  21431. DerBuffer* der = NULL;
  21432. #ifdef WOLFSSL_SMALL_STACK
  21433. EncryptedInfo* info = NULL;
  21434. #else
  21435. EncryptedInfo info[1];
  21436. #endif
  21437. WOLFSSL_ENTER("wc_KeyPemToDer");
  21438. if (pem == NULL || buff == NULL || buffSz <= 0) {
  21439. WOLFSSL_MSG("Bad pem der args");
  21440. return BAD_FUNC_ARG;
  21441. }
  21442. #ifdef WOLFSSL_SMALL_STACK
  21443. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  21444. DYNAMIC_TYPE_ENCRYPTEDINFO);
  21445. if (info == NULL)
  21446. return MEMORY_E;
  21447. #endif
  21448. XMEMSET(info, 0, sizeof(EncryptedInfo));
  21449. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21450. info->passwd_cb = KeyPemToDerPassCb;
  21451. info->passwd_userdata = (void*)pass;
  21452. #else
  21453. (void)pass;
  21454. #endif
  21455. ret = PemToDer(pem, pemSz, PRIVATEKEY_TYPE, &der, NULL, info, NULL);
  21456. #ifdef WOLFSSL_SMALL_STACK
  21457. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  21458. #endif
  21459. if (ret < 0 || der == NULL) {
  21460. WOLFSSL_MSG("Bad Pem To Der");
  21461. }
  21462. else {
  21463. if (der->length <= (word32)buffSz) {
  21464. XMEMCPY(buff, der->buffer, der->length);
  21465. ret = der->length;
  21466. }
  21467. else {
  21468. WOLFSSL_MSG("Bad der length");
  21469. ret = BAD_FUNC_ARG;
  21470. }
  21471. }
  21472. FreeDer(&der);
  21473. return ret;
  21474. }
  21475. /* Return bytes written to buff or < 0 for error */
  21476. int wc_CertPemToDer(const unsigned char* pem, int pemSz,
  21477. unsigned char* buff, int buffSz, int type)
  21478. {
  21479. int ret;
  21480. DerBuffer* der = NULL;
  21481. WOLFSSL_ENTER("wc_CertPemToDer");
  21482. if (pem == NULL || buff == NULL || buffSz <= 0) {
  21483. WOLFSSL_MSG("Bad pem der args");
  21484. return BAD_FUNC_ARG;
  21485. }
  21486. if (type != CERT_TYPE && type != CA_TYPE && type != CERTREQ_TYPE) {
  21487. WOLFSSL_MSG("Bad cert type");
  21488. return BAD_FUNC_ARG;
  21489. }
  21490. ret = PemToDer(pem, pemSz, type, &der, NULL, NULL, NULL);
  21491. if (ret < 0 || der == NULL) {
  21492. WOLFSSL_MSG("Bad Pem To Der");
  21493. }
  21494. else {
  21495. if (der->length <= (word32)buffSz) {
  21496. XMEMCPY(buff, der->buffer, der->length);
  21497. ret = der->length;
  21498. }
  21499. else {
  21500. WOLFSSL_MSG("Bad der length");
  21501. ret = BAD_FUNC_ARG;
  21502. }
  21503. }
  21504. FreeDer(&der);
  21505. return ret;
  21506. }
  21507. #endif /* WOLFSSL_PEM_TO_DER */
  21508. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  21509. #ifdef WOLFSSL_PEM_TO_DER
  21510. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  21511. /* Return bytes written to buff or < 0 for error */
  21512. int wc_PubKeyPemToDer(const unsigned char* pem, int pemSz,
  21513. unsigned char* buff, int buffSz)
  21514. {
  21515. int ret;
  21516. DerBuffer* der = NULL;
  21517. WOLFSSL_ENTER("wc_PubKeyPemToDer");
  21518. if (pem == NULL || buff == NULL || buffSz <= 0) {
  21519. WOLFSSL_MSG("Bad pem der args");
  21520. return BAD_FUNC_ARG;
  21521. }
  21522. ret = PemToDer(pem, pemSz, PUBLICKEY_TYPE, &der, NULL, NULL, NULL);
  21523. if (ret < 0 || der == NULL) {
  21524. WOLFSSL_MSG("Bad Pem To Der");
  21525. }
  21526. else {
  21527. if (der->length <= (word32)buffSz) {
  21528. XMEMCPY(buff, der->buffer, der->length);
  21529. ret = der->length;
  21530. }
  21531. else {
  21532. WOLFSSL_MSG("Bad der length");
  21533. ret = BAD_FUNC_ARG;
  21534. }
  21535. }
  21536. FreeDer(&der);
  21537. return ret;
  21538. }
  21539. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  21540. #endif /* WOLFSSL_PEM_TO_DER */
  21541. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_PEM_TO_DER)
  21542. #ifdef WOLFSSL_CERT_GEN
  21543. int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der)
  21544. {
  21545. #ifdef WOLFSSL_SMALL_STACK
  21546. byte staticBuffer[1]; /* force XMALLOC */
  21547. #else
  21548. byte staticBuffer[FILE_BUFFER_SIZE];
  21549. #endif
  21550. byte* fileBuf = staticBuffer;
  21551. int dynamic = 0;
  21552. int ret = 0;
  21553. long sz = 0;
  21554. XFILE file = NULL;
  21555. WOLFSSL_ENTER("wc_PemCertToDer");
  21556. if (fileName == NULL) {
  21557. ret = BAD_FUNC_ARG;
  21558. }
  21559. else {
  21560. file = XFOPEN(fileName, "rb");
  21561. if (file == XBADFILE) {
  21562. ret = BUFFER_E;
  21563. }
  21564. }
  21565. if (ret == 0) {
  21566. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  21567. ret = BUFFER_E;
  21568. }
  21569. sz = XFTELL(file);
  21570. XREWIND(file);
  21571. if (sz <= 0) {
  21572. ret = BUFFER_E;
  21573. }
  21574. else if (sz > (long)sizeof(staticBuffer)) {
  21575. fileBuf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE);
  21576. if (fileBuf == NULL)
  21577. ret = MEMORY_E;
  21578. else
  21579. dynamic = 1;
  21580. }
  21581. if (ret == 0) {
  21582. if ((size_t)XFREAD(fileBuf, 1, sz, file) != (size_t)sz) {
  21583. ret = BUFFER_E;
  21584. }
  21585. else {
  21586. ret = PemToDer(fileBuf, sz, CA_TYPE, der, 0, NULL,NULL);
  21587. }
  21588. }
  21589. XFCLOSE(file);
  21590. if (dynamic)
  21591. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  21592. }
  21593. return ret;
  21594. }
  21595. /* load pem cert from file into der buffer, return der size or error */
  21596. int wc_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz)
  21597. {
  21598. int ret;
  21599. DerBuffer* converted = NULL;
  21600. ret = wc_PemCertToDer_ex(fileName, &converted);
  21601. if (ret == 0) {
  21602. if (converted->length < (word32)derSz) {
  21603. XMEMCPY(derBuf, converted->buffer, converted->length);
  21604. ret = converted->length;
  21605. }
  21606. else
  21607. ret = BUFFER_E;
  21608. FreeDer(&converted);
  21609. }
  21610. return ret;
  21611. }
  21612. #endif /* WOLFSSL_CERT_GEN */
  21613. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  21614. /* load pem public key from file into der buffer, return der size or error */
  21615. int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der)
  21616. {
  21617. #ifdef WOLFSSL_SMALL_STACK
  21618. byte staticBuffer[1]; /* force XMALLOC */
  21619. #else
  21620. byte staticBuffer[FILE_BUFFER_SIZE];
  21621. #endif
  21622. byte* fileBuf = staticBuffer;
  21623. int dynamic = 0;
  21624. int ret = 0;
  21625. long sz = 0;
  21626. XFILE file = NULL;
  21627. WOLFSSL_ENTER("wc_PemPubKeyToDer");
  21628. if (fileName == NULL) {
  21629. ret = BAD_FUNC_ARG;
  21630. }
  21631. else {
  21632. file = XFOPEN(fileName, "rb");
  21633. if (file == XBADFILE) {
  21634. ret = BUFFER_E;
  21635. }
  21636. }
  21637. if (ret == 0) {
  21638. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  21639. ret = BUFFER_E;
  21640. }
  21641. sz = XFTELL(file);
  21642. XREWIND(file);
  21643. if (sz <= 0) {
  21644. ret = BUFFER_E;
  21645. }
  21646. else if (sz > (long)sizeof(staticBuffer)) {
  21647. fileBuf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE);
  21648. if (fileBuf == NULL)
  21649. ret = MEMORY_E;
  21650. else
  21651. dynamic = 1;
  21652. }
  21653. if (ret == 0) {
  21654. if ((size_t)XFREAD(fileBuf, 1, sz, file) != (size_t)sz) {
  21655. ret = BUFFER_E;
  21656. }
  21657. else {
  21658. ret = PemToDer(fileBuf, sz, PUBLICKEY_TYPE, der,
  21659. 0, NULL, NULL);
  21660. }
  21661. }
  21662. XFCLOSE(file);
  21663. if (dynamic) {
  21664. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  21665. }
  21666. }
  21667. return ret;
  21668. }
  21669. /* load pem public key from file into der buffer, return der size or error */
  21670. int wc_PemPubKeyToDer(const char* fileName,
  21671. unsigned char* derBuf, int derSz)
  21672. {
  21673. int ret;
  21674. DerBuffer* converted = NULL;
  21675. ret = wc_PemPubKeyToDer_ex(fileName, &converted);
  21676. if (ret == 0) {
  21677. if (converted->length < (word32)derSz) {
  21678. XMEMCPY(derBuf, converted->buffer, converted->length);
  21679. ret = converted->length;
  21680. }
  21681. else
  21682. ret = BUFFER_E;
  21683. FreeDer(&converted);
  21684. }
  21685. return ret;
  21686. }
  21687. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  21688. #endif /* !NO_FILESYSTEM && WOLFSSL_PEM_TO_DER */
  21689. /* Get public key in DER format from a populated DecodedCert struct.
  21690. *
  21691. * Users must call wc_InitDecodedCert() and wc_ParseCert() before calling
  21692. * this API. wc_InitDecodedCert() accepts a DER/ASN.1 encoded certificate.
  21693. * To convert a PEM cert to DER first use wc_CertPemToDer() before calling
  21694. * wc_InitDecodedCert().
  21695. *
  21696. * cert - populated DecodedCert struct holding X.509 certificate
  21697. * derKey - output buffer to place DER/ASN.1 encoded public key
  21698. * derKeySz [IN/OUT] - size of derKey buffer on input, size of public key
  21699. * on return. If derKey is passed in as NULL, derKeySz
  21700. * will be set to required buffer size for public key
  21701. * and LENGTH_ONLY_E will be returned from function.
  21702. * Returns 0 on success, or negative error code on failure. LENGTH_ONLY_E
  21703. * if derKey is NULL and returning length only.
  21704. */
  21705. int wc_GetPubKeyDerFromCert(struct DecodedCert* cert,
  21706. byte* derKey, word32* derKeySz)
  21707. {
  21708. int ret = 0;
  21709. /* derKey may be NULL to return length only */
  21710. if (cert == NULL || derKeySz == NULL ||
  21711. (derKey != NULL && *derKeySz == 0)) {
  21712. return BAD_FUNC_ARG;
  21713. }
  21714. if (cert->publicKey == NULL) {
  21715. WOLFSSL_MSG("DecodedCert does not contain public key\n");
  21716. return BAD_FUNC_ARG;
  21717. }
  21718. /* if derKey is NULL, return required output buffer size in derKeySz */
  21719. if (derKey == NULL) {
  21720. *derKeySz = cert->pubKeySize;
  21721. ret = LENGTH_ONLY_E;
  21722. }
  21723. if (ret == 0) {
  21724. if (cert->pubKeySize > *derKeySz) {
  21725. WOLFSSL_MSG("Output buffer not large enough for public key DER");
  21726. ret = BAD_FUNC_ARG;
  21727. }
  21728. else {
  21729. XMEMCPY(derKey, cert->publicKey, cert->pubKeySize);
  21730. *derKeySz = cert->pubKeySize;
  21731. }
  21732. }
  21733. return ret;
  21734. }
  21735. #ifdef WOLFSSL_FPKI
  21736. /* Search through list for first matching alt name of the same type
  21737. * If 'current' is null then the search starts at the head of the list
  21738. * otherwise the search starts from the node after 'current' alt name.
  21739. * Returns 0 on success
  21740. */
  21741. static DNS_entry* FindAltName(struct DecodedCert* cert, int nameType,
  21742. DNS_entry* current)
  21743. {
  21744. DNS_entry* entry;
  21745. if (current == NULL) {
  21746. entry = cert->altNames;
  21747. }
  21748. else {
  21749. entry = current->next;
  21750. }
  21751. /* cycle through alt names to check for needed types */
  21752. while (entry != NULL) {
  21753. if (entry->type == nameType) {
  21754. break;
  21755. }
  21756. entry = entry->next;
  21757. }
  21758. return entry;
  21759. }
  21760. /* returns 0 on success */
  21761. int wc_GetUUIDFromCert(struct DecodedCert* cert, byte* uuid, word32* uuidSz)
  21762. {
  21763. int ret = ALT_NAME_E;
  21764. DNS_entry* id = NULL;
  21765. do {
  21766. id = FindAltName(cert, ASN_URI_TYPE, id);
  21767. if (id != NULL) {
  21768. /* check if URI string matches expected format for UUID */
  21769. if (id->len != DEFAULT_UUID_SZ) {
  21770. continue; /* size not right not a UUID URI */
  21771. }
  21772. if (XMEMCMP(id->name, "urn:uuid:", 9) != 0) {
  21773. continue; /* beginning text not right for a UUID URI */
  21774. }
  21775. if (uuid == NULL) {
  21776. *uuidSz = id->len;
  21777. return LENGTH_ONLY_E;
  21778. }
  21779. if ((int)*uuidSz < id->len) {
  21780. return BUFFER_E;
  21781. }
  21782. XMEMCPY(uuid, id->name, id->len);
  21783. ret = 0; /* success */
  21784. break;
  21785. }
  21786. } while (id != NULL);
  21787. return ret;
  21788. }
  21789. /* reutrns 0 on success */
  21790. int wc_GetFASCNFromCert(struct DecodedCert* cert, byte* fascn, word32* fascnSz)
  21791. {
  21792. int ret = ALT_NAME_E;
  21793. DNS_entry* id = NULL;
  21794. do {
  21795. id = FindAltName(cert, ASN_OTHER_TYPE, id);
  21796. if (id != NULL && id->oidSum == FASCN_OID) {
  21797. if (fascn == NULL) {
  21798. *fascnSz = id->len;
  21799. return LENGTH_ONLY_E;
  21800. }
  21801. if ((int)*fascnSz < id->len) {
  21802. return BUFFER_E;
  21803. }
  21804. XMEMCPY(fascn, id->name, id->len);
  21805. ret = 0; /* success */
  21806. }
  21807. } while (id != NULL);
  21808. return ret;
  21809. }
  21810. #endif /* WOLFSSL_FPKI */
  21811. #if !defined(NO_RSA) && (defined(WOLFSSL_CERT_GEN) || \
  21812. defined(WOLFSSL_KCAPI_RSA) || \
  21813. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA)))
  21814. /* USER RSA ifdef portions used instead of refactor in consideration for
  21815. possible fips build */
  21816. /* Encode a public RSA key to output.
  21817. *
  21818. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  21819. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  21820. *
  21821. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  21822. * (RSAPublicKey).
  21823. *
  21824. * @param [out] output Buffer to put encoded data in.
  21825. * @param [in] key RSA key object.
  21826. * @param [in] outLen Size of the output buffer in bytes.
  21827. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  21828. * @return Size of encoded data in bytes on success.
  21829. * @return BAD_FUNC_ARG when output or key is NULL, or outLen is less than
  21830. * minimum length (5 bytes).
  21831. * @return MEMORY_E when dynamic memory allocation failed.
  21832. */
  21833. static int SetRsaPublicKey(byte* output, RsaKey* key, int outLen,
  21834. int with_header)
  21835. {
  21836. #ifndef WOLFSSL_ASN_TEMPLATE
  21837. int idx, nSz, eSz, seqSz, headSz = 0, bitStringSz = 0, algoSz = 0;
  21838. byte seq[MAX_SEQ_SZ];
  21839. byte headSeq[MAX_SEQ_SZ];
  21840. byte bitString[1 + MAX_LENGTH_SZ + 1];
  21841. byte algo[MAX_ALGO_SZ]; /* 20 bytes */
  21842. if (key == NULL) {
  21843. return BAD_FUNC_ARG;
  21844. }
  21845. #ifdef HAVE_USER_RSA
  21846. nSz = SetASNIntRSA(key->n, NULL);
  21847. #else
  21848. nSz = SetASNIntMP(&key->n, MAX_RSA_INT_SZ, NULL);
  21849. #endif
  21850. if (nSz < 0)
  21851. return nSz;
  21852. #ifdef HAVE_USER_RSA
  21853. eSz = SetASNIntRSA(key->e, NULL);
  21854. #else
  21855. eSz = SetASNIntMP(&key->e, MAX_RSA_INT_SZ, NULL);
  21856. #endif
  21857. if (eSz < 0)
  21858. return eSz;
  21859. seqSz = SetSequence(nSz + eSz, seq);
  21860. /* headers */
  21861. if (with_header) {
  21862. algoSz = SetAlgoID(RSAk, algo, oidKeyType, 0);
  21863. bitStringSz = SetBitString(seqSz + nSz + eSz, 0, bitString);
  21864. headSz = SetSequence(nSz + eSz + seqSz + bitStringSz + algoSz, headSeq);
  21865. }
  21866. /* if getting length only */
  21867. if (output == NULL) {
  21868. return headSz + algoSz + bitStringSz + seqSz + nSz + eSz;
  21869. }
  21870. /* check output size */
  21871. if ((headSz + algoSz + bitStringSz + seqSz + nSz + eSz) > outLen) {
  21872. return BUFFER_E;
  21873. }
  21874. /* write output */
  21875. idx = 0;
  21876. if (with_header) {
  21877. /* header size */
  21878. XMEMCPY(output + idx, headSeq, headSz);
  21879. idx += headSz;
  21880. /* algo */
  21881. XMEMCPY(output + idx, algo, algoSz);
  21882. idx += algoSz;
  21883. /* bit string */
  21884. XMEMCPY(output + idx, bitString, bitStringSz);
  21885. idx += bitStringSz;
  21886. }
  21887. /* seq */
  21888. XMEMCPY(output + idx, seq, seqSz);
  21889. idx += seqSz;
  21890. /* n */
  21891. #ifdef HAVE_USER_RSA
  21892. nSz = SetASNIntRSA(key->n, output + idx);
  21893. #else
  21894. nSz = SetASNIntMP(&key->n, nSz, output + idx);
  21895. #endif
  21896. idx += nSz;
  21897. /* e */
  21898. #ifdef HAVE_USER_RSA
  21899. eSz = SetASNIntRSA(key->e, output + idx);
  21900. #else
  21901. eSz = SetASNIntMP(&key->e, eSz, output + idx);
  21902. #endif
  21903. idx += eSz;
  21904. return idx;
  21905. #else
  21906. DECL_ASNSETDATA(dataASN, rsaPublicKeyASN_Length);
  21907. int sz = 0;
  21908. int ret = 0;
  21909. int o = 0;
  21910. /* Check parameter validity. */
  21911. if ((key == NULL) || ((output != NULL) && (outLen < MAX_SEQ_SZ))) {
  21912. ret = BAD_FUNC_ARG;
  21913. }
  21914. CALLOC_ASNSETDATA(dataASN, rsaPublicKeyASN_Length, ret, key->heap);
  21915. if (ret == 0) {
  21916. if (!with_header) {
  21917. /* Start encoding with items after header. */
  21918. o = RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ;
  21919. }
  21920. /* Set OID for RSA key. */
  21921. SetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], RSAk, oidKeyType);
  21922. #ifdef WC_RSA_PSS
  21923. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].noOut = 1;
  21924. #endif
  21925. /* Set public key mp_ints. */
  21926. #ifdef HAVE_USER_RSA
  21927. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], key->n);
  21928. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], key->e);
  21929. #else
  21930. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], &key->n);
  21931. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], &key->e);
  21932. #endif
  21933. /* Calculate size of RSA public key. */
  21934. ret = SizeASN_Items(rsaPublicKeyASN + o, dataASN + o,
  21935. rsaPublicKeyASN_Length - o, &sz);
  21936. }
  21937. /* Check output buffer is big enough for encoding. */
  21938. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  21939. ret = BUFFER_E;
  21940. }
  21941. if ((ret == 0) && (output != NULL)) {
  21942. /* Encode RSA public key. */
  21943. SetASN_Items(rsaPublicKeyASN + o, dataASN + o,
  21944. rsaPublicKeyASN_Length - o, output);
  21945. }
  21946. if (ret == 0) {
  21947. /* Return size of encoding. */
  21948. ret = sz;
  21949. }
  21950. FREE_ASNSETDATA(dataASN, key->heap);
  21951. return ret;
  21952. #endif /* WOLFSSL_ASN_TEMPLATE */
  21953. }
  21954. /* Calculate size of encoded public RSA key in bytes.
  21955. *
  21956. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  21957. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  21958. *
  21959. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  21960. * (RSAPublicKey).
  21961. *
  21962. * @param [in] key RSA key object.
  21963. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  21964. * @return Size of encoded data in bytes on success.
  21965. * @return BAD_FUNC_ARG when key is NULL.
  21966. * @return MEMORY_E when dynamic memory allocation failed.
  21967. */
  21968. int wc_RsaPublicKeyDerSize(RsaKey* key, int with_header)
  21969. {
  21970. return SetRsaPublicKey(NULL, key, 0, with_header);
  21971. }
  21972. /* Encode public RSA key in DER format.
  21973. *
  21974. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  21975. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  21976. *
  21977. * @param [in] key RSA key object.
  21978. * @param [out] output Buffer to put encoded data in.
  21979. * @param [in] inLen Size of buffer in bytes.
  21980. * @return Size of encoded data in bytes on success.
  21981. * @return BAD_FUNC_ARG when key or output is NULL.
  21982. * @return MEMORY_E when dynamic memory allocation failed.
  21983. */
  21984. int wc_RsaKeyToPublicDer(RsaKey* key, byte* output, word32 inLen)
  21985. {
  21986. return SetRsaPublicKey(output, key, inLen, 1);
  21987. }
  21988. /* Returns public DER version of the RSA key. If with_header is 0 then only a
  21989. * seq + n + e is returned in ASN.1 DER format */
  21990. int wc_RsaKeyToPublicDer_ex(RsaKey* key, byte* output, word32 inLen,
  21991. int with_header)
  21992. {
  21993. return SetRsaPublicKey(output, key, inLen, with_header);
  21994. }
  21995. #endif /* !NO_RSA && (WOLFSSL_CERT_GEN || WOLFSSL_KCAPI_RSA ||
  21996. ((OPENSSL_EXTRA || WOLFSSL_KEY_GEN) && !HAVE_USER_RSA))) */
  21997. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  21998. defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)) && \
  21999. !defined(NO_RSA) && !defined(HAVE_USER_RSA)
  22000. /* Encode private RSA key in DER format.
  22001. *
  22002. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  22003. *
  22004. * @param [in] key RSA key object.
  22005. * @param [out] output Buffer to put encoded data in.
  22006. * @param [in] inLen Size of buffer in bytes.
  22007. * @return Size of encoded data in bytes on success.
  22008. * @return BAD_FUNC_ARG when key is NULL or not a private key.
  22009. * @return MEMORY_E when dynamic memory allocation failed.
  22010. */
  22011. int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
  22012. {
  22013. #ifndef WOLFSSL_ASN_TEMPLATE
  22014. int ret = 0, i, j, outLen = 0, mpSz;
  22015. word32 seqSz = 0, verSz = 0, rawLen, intTotalLen = 0;
  22016. word32 sizes[RSA_INTS];
  22017. byte seq[MAX_SEQ_SZ];
  22018. byte ver[MAX_VERSION_SZ];
  22019. byte* tmps[RSA_INTS];
  22020. if (key == NULL)
  22021. return BAD_FUNC_ARG;
  22022. if (key->type != RSA_PRIVATE)
  22023. return BAD_FUNC_ARG;
  22024. for (i = 0; i < RSA_INTS; i++)
  22025. tmps[i] = NULL;
  22026. /* write all big ints from key to DER tmps */
  22027. for (i = 0; i < RSA_INTS; i++) {
  22028. mp_int* keyInt = GetRsaInt(key, (byte)i);
  22029. rawLen = mp_unsigned_bin_size(keyInt) + 1;
  22030. if (output != NULL) {
  22031. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  22032. DYNAMIC_TYPE_RSA);
  22033. if (tmps[i] == NULL) {
  22034. ret = MEMORY_E;
  22035. break;
  22036. }
  22037. }
  22038. mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, tmps[i]);
  22039. if (mpSz < 0) {
  22040. ret = mpSz;
  22041. break;
  22042. }
  22043. intTotalLen += (sizes[i] = mpSz);
  22044. }
  22045. if (ret == 0) {
  22046. /* make headers */
  22047. verSz = SetMyVersion(0, ver, FALSE);
  22048. seqSz = SetSequence(verSz + intTotalLen, seq);
  22049. outLen = seqSz + verSz + intTotalLen;
  22050. if (output != NULL && outLen > (int)inLen)
  22051. ret = BUFFER_E;
  22052. }
  22053. if (ret == 0 && output != NULL) {
  22054. /* write to output */
  22055. XMEMCPY(output, seq, seqSz);
  22056. j = seqSz;
  22057. XMEMCPY(output + j, ver, verSz);
  22058. j += verSz;
  22059. for (i = 0; i < RSA_INTS; i++) {
  22060. XMEMCPY(output + j, tmps[i], sizes[i]);
  22061. j += sizes[i];
  22062. }
  22063. }
  22064. for (i = 0; i < RSA_INTS; i++) {
  22065. if (tmps[i])
  22066. XFREE(tmps[i], key->heap, DYNAMIC_TYPE_RSA);
  22067. }
  22068. if (ret == 0)
  22069. ret = outLen;
  22070. return ret;
  22071. #else
  22072. DECL_ASNSETDATA(dataASN, rsaKeyASN_Length);
  22073. int i;
  22074. int sz = 0;
  22075. int ret = 0;
  22076. if ((key == NULL) || (key->type != RSA_PRIVATE)) {
  22077. ret = BAD_FUNC_ARG;
  22078. }
  22079. CALLOC_ASNSETDATA(dataASN, rsaKeyASN_Length, ret, key->heap);
  22080. if (ret == 0) {
  22081. /* Set the version. */
  22082. SetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], 0);
  22083. /* Set all the mp_ints in private key. */
  22084. for (i = 0; i < RSA_INTS; i++) {
  22085. SetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i], GetRsaInt(key, i));
  22086. }
  22087. /* Calculate size of RSA private key encoding. */
  22088. ret = SizeASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, &sz);
  22089. }
  22090. /* Check output buffer has enough space for encoding. */
  22091. if ((ret == 0) && (output != NULL) && (sz > (int)inLen)) {
  22092. ret = BAD_FUNC_ARG;
  22093. }
  22094. if ((ret == 0) && (output != NULL)) {
  22095. /* Encode RSA private key. */
  22096. SetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, output);
  22097. }
  22098. if (ret == 0) {
  22099. /* Return size of encoding. */
  22100. ret = sz;
  22101. }
  22102. FREE_ASNSETDATA(dataASN, key->heap);
  22103. return ret;
  22104. #endif
  22105. }
  22106. #endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA && !HAVE_USER_RSA */
  22107. #ifdef WOLFSSL_CERT_GEN
  22108. /* Initialize and Set Certificate defaults:
  22109. version = 3 (0x2)
  22110. serial = 0
  22111. sigType = SHA_WITH_RSA
  22112. issuer = blank
  22113. daysValid = 500
  22114. selfSigned = 1 (true) use subject as issuer
  22115. subject = blank
  22116. */
  22117. int wc_InitCert_ex(Cert* cert, void* heap, int devId)
  22118. {
  22119. #ifdef WOLFSSL_MULTI_ATTRIB
  22120. int i = 0;
  22121. #endif
  22122. if (cert == NULL) {
  22123. return BAD_FUNC_ARG;
  22124. }
  22125. XMEMSET(cert, 0, sizeof(Cert));
  22126. cert->version = 2; /* version 3 is hex 2 */
  22127. #ifndef NO_SHA
  22128. cert->sigType = CTC_SHAwRSA;
  22129. #elif !defined(NO_SHA256)
  22130. cert->sigType = CTC_SHA256wRSA;
  22131. #else
  22132. cert->sigType = 0;
  22133. #endif
  22134. cert->daysValid = 500;
  22135. cert->selfSigned = 1;
  22136. cert->keyType = RSA_KEY;
  22137. cert->issuer.countryEnc = CTC_PRINTABLE;
  22138. cert->issuer.stateEnc = CTC_UTF8;
  22139. cert->issuer.streetEnc = CTC_UTF8;
  22140. cert->issuer.localityEnc = CTC_UTF8;
  22141. cert->issuer.surEnc = CTC_UTF8;
  22142. #ifdef WOLFSSL_CERT_NAME_ALL
  22143. cert->issuer.givenNameEnc = CTC_UTF8;
  22144. cert->issuer.initialsEnc = CTC_UTF8;
  22145. cert->issuer.dnQualifierEnc = CTC_UTF8;
  22146. cert->issuer.dnNameEnc = CTC_UTF8;
  22147. #endif
  22148. cert->issuer.orgEnc = CTC_UTF8;
  22149. cert->issuer.unitEnc = CTC_UTF8;
  22150. cert->issuer.commonNameEnc = CTC_UTF8;
  22151. cert->issuer.serialDevEnc = CTC_PRINTABLE;
  22152. cert->issuer.userIdEnc = CTC_UTF8;
  22153. cert->issuer.postalCodeEnc = CTC_UTF8;
  22154. #ifdef WOLFSSL_CERT_EXT
  22155. cert->issuer.busCatEnc = CTC_UTF8;
  22156. cert->issuer.joiCEnc = CTC_UTF8;
  22157. cert->issuer.joiStEnc = CTC_UTF8;
  22158. #endif
  22159. cert->subject.countryEnc = CTC_PRINTABLE;
  22160. cert->subject.stateEnc = CTC_UTF8;
  22161. cert->subject.streetEnc = CTC_UTF8;
  22162. cert->subject.localityEnc = CTC_UTF8;
  22163. cert->subject.surEnc = CTC_UTF8;
  22164. #ifdef WOLFSSL_CERT_NAME_ALL
  22165. cert->subject.givenNameEnc = CTC_UTF8;
  22166. cert->subject.initialsEnc = CTC_UTF8;
  22167. cert->subject.dnQualifierEnc = CTC_UTF8;
  22168. cert->subject.dnNameEnc = CTC_UTF8;
  22169. #endif
  22170. cert->subject.orgEnc = CTC_UTF8;
  22171. cert->subject.unitEnc = CTC_UTF8;
  22172. cert->subject.commonNameEnc = CTC_UTF8;
  22173. cert->subject.serialDevEnc = CTC_PRINTABLE;
  22174. cert->subject.userIdEnc = CTC_UTF8;
  22175. cert->subject.postalCodeEnc = CTC_UTF8;
  22176. #ifdef WOLFSSL_CERT_EXT
  22177. cert->subject.busCatEnc = CTC_UTF8;
  22178. cert->subject.joiCEnc = CTC_UTF8;
  22179. cert->subject.joiStEnc = CTC_UTF8;
  22180. #endif
  22181. #ifdef WOLFSSL_MULTI_ATTRIB
  22182. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  22183. cert->issuer.name[i].type = CTC_UTF8;
  22184. cert->subject.name[i].type = CTC_UTF8;
  22185. }
  22186. #endif /* WOLFSSL_MULTI_ATTRIB */
  22187. cert->heap = heap;
  22188. (void)devId; /* future */
  22189. return 0;
  22190. }
  22191. WOLFSSL_ABI
  22192. int wc_InitCert(Cert* cert)
  22193. {
  22194. return wc_InitCert_ex(cert, NULL, INVALID_DEVID);
  22195. }
  22196. WOLFSSL_ABI
  22197. Cert* wc_CertNew(void* heap)
  22198. {
  22199. Cert* certNew;
  22200. certNew = (Cert*)XMALLOC(sizeof(Cert), heap, DYNAMIC_TYPE_CERT);
  22201. if (certNew) {
  22202. if (wc_InitCert_ex(certNew, heap, INVALID_DEVID) != 0) {
  22203. XFREE(certNew, heap, DYNAMIC_TYPE_CERT);
  22204. certNew = NULL;
  22205. }
  22206. }
  22207. return certNew;
  22208. }
  22209. WOLFSSL_ABI
  22210. void wc_CertFree(Cert* cert)
  22211. {
  22212. if (cert) {
  22213. void* heap = cert->heap;
  22214. ForceZero(cert, sizeof(Cert));
  22215. XFREE(cert, heap, DYNAMIC_TYPE_CERT);
  22216. (void)heap;
  22217. }
  22218. }
  22219. /* DER encoded x509 Certificate */
  22220. typedef struct DerCert {
  22221. byte size[MAX_LENGTH_SZ]; /* length encoded */
  22222. byte version[MAX_VERSION_SZ]; /* version encoded */
  22223. byte serial[(int)CTC_SERIAL_SIZE + (int)MAX_LENGTH_SZ]; /* serial number encoded */
  22224. byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
  22225. byte issuer[WC_ASN_NAME_MAX]; /* issuer encoded */
  22226. byte subject[WC_ASN_NAME_MAX]; /* subject encoded */
  22227. byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
  22228. byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa public key encoded */
  22229. byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
  22230. byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
  22231. #ifdef WOLFSSL_CERT_EXT
  22232. byte skid[MAX_KID_SZ]; /* Subject Key Identifier extension */
  22233. byte akid[MAX_KID_SZ
  22234. #ifdef WOLFSSL_AKID_NAME
  22235. + sizeof(CertName) + CTC_SERIAL_SIZE
  22236. #endif
  22237. ]; /* Authority Key Identifier extension */
  22238. byte keyUsage[MAX_KEYUSAGE_SZ]; /* Key Usage extension */
  22239. byte extKeyUsage[MAX_EXTKEYUSAGE_SZ]; /* Extended Key Usage extension */
  22240. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  22241. byte nsCertType[MAX_NSCERTTYPE_SZ]; /* Extended Key Usage extension */
  22242. #endif
  22243. byte certPolicies[MAX_CERTPOL_NB*MAX_CERTPOL_SZ]; /* Certificate Policies */
  22244. byte crlInfo[CTC_MAX_CRLINFO_SZ]; /* CRL Distribution Points */
  22245. #endif
  22246. #ifdef WOLFSSL_CERT_REQ
  22247. byte attrib[MAX_ATTRIB_SZ]; /* Cert req attributes encoded */
  22248. #ifdef WOLFSSL_CUSTOM_OID
  22249. byte extCustom[MAX_ATTRIB_SZ]; /* Encoded user oid and value */
  22250. #endif
  22251. #endif
  22252. #ifdef WOLFSSL_ALT_NAMES
  22253. byte altNames[CTC_MAX_ALT_SIZE]; /* Alternative Names encoded */
  22254. #endif
  22255. int sizeSz; /* encoded size length */
  22256. int versionSz; /* encoded version length */
  22257. int serialSz; /* encoded serial length */
  22258. int sigAlgoSz; /* encoded sig algo length */
  22259. int issuerSz; /* encoded issuer length */
  22260. int subjectSz; /* encoded subject length */
  22261. int validitySz; /* encoded validity length */
  22262. int publicKeySz; /* encoded public key length */
  22263. int caSz; /* encoded CA extension length */
  22264. #ifdef WOLFSSL_CERT_EXT
  22265. int skidSz; /* encoded SKID extension length */
  22266. int akidSz; /* encoded SKID extension length */
  22267. int keyUsageSz; /* encoded KeyUsage extension length */
  22268. int extKeyUsageSz; /* encoded ExtendedKeyUsage extension length */
  22269. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  22270. int nsCertTypeSz; /* encoded Netscape Certifcate Type
  22271. * extension length */
  22272. #endif
  22273. int certPoliciesSz; /* encoded CertPolicies extension length*/
  22274. int crlInfoSz; /* encoded CRL Dist Points length */
  22275. #endif
  22276. #ifdef WOLFSSL_ALT_NAMES
  22277. int altNamesSz; /* encoded AltNames extension length */
  22278. #endif
  22279. int extensionsSz; /* encoded extensions total length */
  22280. int total; /* total encoded lengths */
  22281. #ifdef WOLFSSL_CERT_REQ
  22282. int attribSz;
  22283. #ifdef WOLFSSL_CUSTOM_OID
  22284. int extCustomSz;
  22285. #endif
  22286. #endif
  22287. } DerCert;
  22288. #ifdef WOLFSSL_CERT_REQ
  22289. #ifndef WOLFSSL_ASN_TEMPLATE
  22290. /* Write a set header to output */
  22291. static word32 SetPrintableString(word32 len, byte* output)
  22292. {
  22293. output[0] = ASN_PRINTABLE_STRING;
  22294. return SetLength(len, output + 1) + 1;
  22295. }
  22296. static word32 SetUTF8String(word32 len, byte* output)
  22297. {
  22298. output[0] = ASN_UTF8STRING;
  22299. return SetLength(len, output + 1) + 1;
  22300. }
  22301. #endif
  22302. #endif /* WOLFSSL_CERT_REQ */
  22303. #ifndef WOLFSSL_CERT_GEN_CACHE
  22304. /* wc_SetCert_Free is only public when WOLFSSL_CERT_GEN_CACHE is not defined */
  22305. static
  22306. #endif
  22307. WOLFSSL_ABI
  22308. void wc_SetCert_Free(Cert* cert)
  22309. {
  22310. if (cert != NULL) {
  22311. cert->der = NULL;
  22312. if (cert->decodedCert) {
  22313. FreeDecodedCert((DecodedCert*)cert->decodedCert);
  22314. XFREE(cert->decodedCert, cert->heap, DYNAMIC_TYPE_DCERT);
  22315. cert->decodedCert = NULL;
  22316. }
  22317. }
  22318. }
  22319. static int wc_SetCert_LoadDer(Cert* cert, const byte* der, word32 derSz)
  22320. {
  22321. int ret;
  22322. if (cert == NULL) {
  22323. ret = BAD_FUNC_ARG;
  22324. }
  22325. else {
  22326. /* Allocate DecodedCert struct and Zero */
  22327. cert->decodedCert = (void*)XMALLOC(sizeof(DecodedCert), cert->heap,
  22328. DYNAMIC_TYPE_DCERT);
  22329. if (cert->decodedCert == NULL) {
  22330. ret = MEMORY_E;
  22331. }
  22332. else {
  22333. XMEMSET(cert->decodedCert, 0, sizeof(DecodedCert));
  22334. InitDecodedCert((DecodedCert*)cert->decodedCert, der, derSz,
  22335. cert->heap);
  22336. ret = ParseCertRelative((DecodedCert*)cert->decodedCert,
  22337. CERT_TYPE, 0, NULL);
  22338. if (ret >= 0) {
  22339. cert->der = (byte*)der;
  22340. }
  22341. else {
  22342. wc_SetCert_Free(cert);
  22343. }
  22344. }
  22345. }
  22346. return ret;
  22347. }
  22348. #endif /* WOLFSSL_CERT_GEN */
  22349. #ifdef HAVE_ECC
  22350. #ifdef WOLFSSL_ASN_TEMPLATE
  22351. /* ASN.1 template for ECC public key (SubjectPublicKeyInfo).
  22352. * RFC 5480, 2 - Subject Public Key Information Fields
  22353. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  22354. * X9.62 ECC point format.
  22355. * See ASN.1 template 'eccSpecifiedASN' for specifiedCurve.
  22356. */
  22357. static const ASNItem eccPublicKeyASN[] = {
  22358. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  22359. /* AlgorithmIdentifier */
  22360. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  22361. /* algorithm */
  22362. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  22363. /* namedCurve */
  22364. /* ALGOID_CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  22365. /* specifiedCurve - explicit parameters */
  22366. /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  22367. /* Public Key */
  22368. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  22369. };
  22370. enum {
  22371. ECCPUBLICKEYASN_IDX_SEQ = 0,
  22372. ECCPUBLICKEYASN_IDX_ALGOID_SEQ,
  22373. ECCPUBLICKEYASN_IDX_ALGOID_OID,
  22374. ECCPUBLICKEYASN_IDX_ALGOID_CURVEID,
  22375. ECCPUBLICKEYASN_IDX_ALGOID_PARAMS,
  22376. ECCPUBLICKEYASN_IDX_PUBKEY,
  22377. };
  22378. /* Number of items in ASN.1 template for ECC public key. */
  22379. #define eccPublicKeyASN_Length (sizeof(eccPublicKeyASN) / sizeof(ASNItem))
  22380. #endif /* WOLFSSL_ASN_TEMPLATE */
  22381. #endif /* HAVE_ECC */
  22382. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  22383. /* Encode public ECC key in DER format.
  22384. *
  22385. * RFC 5480, 2 - Subject Public Key Information Fields
  22386. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  22387. * X9.62 ECC point format.
  22388. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  22389. *
  22390. * @param [out] output Buffer to put encoded data in.
  22391. * @param [in] key ECC key object.
  22392. * @param [in] outLen Size of buffer in bytes.
  22393. * @param [in] with_header Whether to use SubjectPublicKeyInfo format.
  22394. * @return Size of encoded data in bytes on success.
  22395. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  22396. * @return MEMORY_E when dynamic memory allocation failed.
  22397. */
  22398. static int SetEccPublicKey(byte* output, ecc_key* key, int outLen,
  22399. int with_header, int comp)
  22400. {
  22401. #ifndef WOLFSSL_ASN_TEMPLATE
  22402. int ret, idx = 0, algoSz, curveSz, bitStringSz;
  22403. word32 pubSz;
  22404. byte bitString[1 + MAX_LENGTH_SZ + 1]; /* 6 */
  22405. byte algo[MAX_ALGO_SZ]; /* 20 */
  22406. /* public size */
  22407. pubSz = key->dp ? key->dp->size : MAX_ECC_BYTES;
  22408. if (comp)
  22409. pubSz = 1 + pubSz;
  22410. else
  22411. pubSz = 1 + 2 * pubSz;
  22412. /* check for buffer overflow */
  22413. if (output != NULL && pubSz > (word32)outLen) {
  22414. return BUFFER_E;
  22415. }
  22416. /* headers */
  22417. if (with_header) {
  22418. curveSz = SetCurve(key, NULL, 0);
  22419. if (curveSz <= 0) {
  22420. return curveSz;
  22421. }
  22422. /* calculate size */
  22423. algoSz = SetAlgoID(ECDSAk, algo, oidKeyType, curveSz);
  22424. bitStringSz = SetBitString(pubSz, 0, bitString);
  22425. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz, NULL);
  22426. /* check for buffer overflow */
  22427. if (output != NULL &&
  22428. curveSz + algoSz + bitStringSz + idx + pubSz > (word32)outLen) {
  22429. return BUFFER_E;
  22430. }
  22431. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz, output);
  22432. /* algo */
  22433. if (output)
  22434. XMEMCPY(output + idx, algo, algoSz);
  22435. idx += algoSz;
  22436. /* curve */
  22437. if (output)
  22438. (void)SetCurve(key, output + idx, curveSz);
  22439. idx += curveSz;
  22440. /* bit string */
  22441. if (output)
  22442. XMEMCPY(output + idx, bitString, bitStringSz);
  22443. idx += bitStringSz;
  22444. }
  22445. /* pub */
  22446. if (output) {
  22447. PRIVATE_KEY_UNLOCK();
  22448. ret = wc_ecc_export_x963_ex(key, output + idx, &pubSz, comp);
  22449. PRIVATE_KEY_LOCK();
  22450. if (ret != 0) {
  22451. return ret;
  22452. }
  22453. }
  22454. idx += pubSz;
  22455. return idx;
  22456. #else
  22457. word32 pubSz = 0;
  22458. int sz = 0;
  22459. int ret = 0;
  22460. int curveIdSz = 0;
  22461. byte* curveOid = NULL;
  22462. /* Check key validity. */
  22463. if ((key == NULL) || (key->dp == NULL)) {
  22464. ret = BAD_FUNC_ARG;
  22465. }
  22466. if (ret == 0) {
  22467. /* Calculate the size of the encoded public point. */
  22468. PRIVATE_KEY_UNLOCK();
  22469. ret = wc_ecc_export_x963_ex(key, NULL, &pubSz, comp);
  22470. PRIVATE_KEY_LOCK();
  22471. /* LENGTH_ONLY_E on success. */
  22472. if (ret == LENGTH_ONLY_E) {
  22473. ret = 0;
  22474. }
  22475. }
  22476. if ((ret == 0) && with_header) {
  22477. /* Including SubjectPublicKeyInfo header. */
  22478. DECL_ASNSETDATA(dataASN, eccPublicKeyASN_Length);
  22479. CALLOC_ASNSETDATA(dataASN, eccPublicKeyASN_Length, ret, key->heap);
  22480. /* Get the length of the named curve OID to put into the encoding. */
  22481. curveIdSz = SetCurve(key, NULL, 0);
  22482. if (curveIdSz < 0) {
  22483. ret = curveIdSz;
  22484. }
  22485. if (ret == 0) {
  22486. /* Set the key type OID. */
  22487. SetASN_OID(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], ECDSAk,
  22488. oidKeyType);
  22489. /* Set the curve OID. */
  22490. SetASN_ReplaceBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID],
  22491. NULL, curveIdSz);
  22492. /* Don't try to write out explicit parameters. */
  22493. dataASN[ECCPUBLICKEYASN_IDX_ALGOID_PARAMS].noOut = 1;
  22494. /* Set size of public point to ensure space is made for it. */
  22495. SetASN_Buffer(&dataASN[ECCPUBLICKEYASN_IDX_PUBKEY], NULL, pubSz);
  22496. /* Calculate size of ECC public key. */
  22497. ret = SizeASN_Items(eccPublicKeyASN, dataASN,
  22498. eccPublicKeyASN_Length, &sz);
  22499. }
  22500. /* Check buffer, if passed in, is big enough for encoded data. */
  22501. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  22502. ret = BUFFER_E;
  22503. }
  22504. if ((ret == 0) && (output != NULL)) {
  22505. /* Encode ECC public key. */
  22506. SetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length,
  22507. output);
  22508. /* Skip to where public point is to be encoded. */
  22509. output += sz - pubSz;
  22510. /* Cache the location to place the name curve OID. */
  22511. curveOid = (byte*)
  22512. dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID].data.buffer.data;
  22513. }
  22514. FREE_ASNSETDATA(dataASN, key->heap);
  22515. }
  22516. else if ((ret == 0) && (output != NULL) && (pubSz > (word32)outLen)) {
  22517. ret = BUFFER_E;
  22518. }
  22519. else {
  22520. /* Total size is the public point size. */
  22521. sz = pubSz;
  22522. }
  22523. if ((ret == 0) && (output != NULL)) {
  22524. /* Put named curve OID data into encoding. */
  22525. curveIdSz = SetCurve(key, curveOid, curveIdSz);
  22526. if (curveIdSz < 0) {
  22527. ret = curveIdSz;
  22528. }
  22529. }
  22530. if ((ret == 0) && (output != NULL)) {
  22531. /* Encode public point. */
  22532. PRIVATE_KEY_UNLOCK();
  22533. ret = wc_ecc_export_x963_ex(key, output, &pubSz, comp);
  22534. PRIVATE_KEY_LOCK();
  22535. }
  22536. if (ret == 0) {
  22537. /* Return the size of the encoding. */
  22538. ret = sz;
  22539. }
  22540. return ret;
  22541. #endif
  22542. }
  22543. /* Encode the public part of an ECC key in a DER.
  22544. *
  22545. * Pass NULL for output to get the size of the encoding.
  22546. *
  22547. * @param [in] key ECC key object.
  22548. * @param [out] output Buffer to hold DER encoding.
  22549. * @param [in] inLen Size of buffer in bytes.
  22550. * @param [in] with_AlgCurve Whether to use SubjectPublicKeyInfo format.
  22551. * @return Size of encoded data in bytes on success.
  22552. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  22553. * @return MEMORY_E when dynamic memory allocation failed.
  22554. */
  22555. WOLFSSL_ABI
  22556. int wc_EccPublicKeyToDer(ecc_key* key, byte* output, word32 inLen,
  22557. int with_AlgCurve)
  22558. {
  22559. return SetEccPublicKey(output, key, inLen, with_AlgCurve, 0);
  22560. }
  22561. int wc_EccPublicKeyToDer_ex(ecc_key* key, byte* output, word32 inLen,
  22562. int with_AlgCurve, int comp)
  22563. {
  22564. return SetEccPublicKey(output, key, inLen, with_AlgCurve, comp);
  22565. }
  22566. int wc_EccPublicKeyDerSize(ecc_key* key, int with_AlgCurve)
  22567. {
  22568. return SetEccPublicKey(NULL, key, 0, with_AlgCurve, 0);
  22569. }
  22570. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  22571. #ifdef WOLFSSL_ASN_TEMPLATE
  22572. #if defined(WC_ENABLE_ASYM_KEY_EXPORT) || defined(WC_ENABLE_ASYM_KEY_IMPORT)
  22573. /* ASN.1 template for Ed25519 and Ed448 public key (SubkectPublicKeyInfo).
  22574. * RFC 8410, 4 - Subject Public Key Fields
  22575. */
  22576. static const ASNItem edPubKeyASN[] = {
  22577. /* SubjectPublicKeyInfo */
  22578. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  22579. /* AlgorithmIdentifier */
  22580. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  22581. /* Ed25519/Ed448 OID */
  22582. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  22583. /* Public key stream */
  22584. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  22585. };
  22586. enum {
  22587. EDPUBKEYASN_IDX_SEQ = 0,
  22588. EDPUBKEYASN_IDX_ALGOID_SEQ,
  22589. EDPUBKEYASN_IDX_ALGOID_OID,
  22590. EDPUBKEYASN_IDX_PUBKEY,
  22591. };
  22592. /* Number of items in ASN.1 template for Ed25519 and Ed448 public key. */
  22593. #define edPubKeyASN_Length (sizeof(edPubKeyASN) / sizeof(ASNItem))
  22594. #endif /* WC_ENABLE_ASYM_KEY_EXPORT || WC_ENABLE_ASYM_KEY_IMPORT */
  22595. #endif /* WOLFSSL_ASN_TEMPLATE */
  22596. #ifdef WC_ENABLE_ASYM_KEY_EXPORT
  22597. /* Build ASN.1 formatted public key based on RFC 8410
  22598. *
  22599. * Pass NULL for output to get the size of the encoding.
  22600. *
  22601. * @param [in] pubKey public key buffer
  22602. * @param [in] pubKeyLen public ket buffer length
  22603. * @param [out] output Buffer to put encoded data in (optional)
  22604. * @param [in] outLen Size of buffer in bytes
  22605. * @param [in] keyType is "enum Key_Sum" like ED25519k
  22606. * @param [in] withHeader Whether to include SubjectPublicKeyInfo around key.
  22607. * @return Size of encoded data in bytes on success
  22608. * @return BAD_FUNC_ARG when key is NULL.
  22609. * @return MEMORY_E when dynamic memory allocation failed.
  22610. */
  22611. int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen,
  22612. byte* output, word32 outLen, int keyType, int withHeader)
  22613. {
  22614. int ret = 0;
  22615. #ifndef WOLFSSL_ASN_TEMPLATE
  22616. word32 idx = 0;
  22617. word32 seqDataSz = 0;
  22618. word32 sz;
  22619. #else
  22620. int sz = 0;
  22621. DECL_ASNSETDATA(dataASN, edPubKeyASN_Length);
  22622. #endif
  22623. if (pubKey == NULL) {
  22624. return BAD_FUNC_ARG;
  22625. }
  22626. #ifndef WOLFSSL_ASN_TEMPLATE
  22627. /* calculate size */
  22628. if (withHeader) {
  22629. word32 algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
  22630. word32 bitStringSz = SetBitString(pubKeyLen, 0, NULL);
  22631. seqDataSz = algoSz + bitStringSz + pubKeyLen;
  22632. sz = SetSequence(seqDataSz, NULL) + seqDataSz;
  22633. }
  22634. else {
  22635. sz = pubKeyLen;
  22636. }
  22637. /* checkout output size */
  22638. if (output != NULL && sz > outLen) {
  22639. ret = BUFFER_E;
  22640. }
  22641. /* headers */
  22642. if (ret == 0 && output != NULL && withHeader) {
  22643. /* sequence */
  22644. idx = SetSequence(seqDataSz, output);
  22645. /* algo */
  22646. idx += SetAlgoID(keyType, output + idx, oidKeyType, 0);
  22647. /* bit string */
  22648. idx += SetBitString(pubKeyLen, 0, output + idx);
  22649. }
  22650. if (ret == 0 && output != NULL) {
  22651. /* pub */
  22652. XMEMCPY(output + idx, pubKey, pubKeyLen);
  22653. idx += pubKeyLen;
  22654. sz = idx;
  22655. }
  22656. if (ret == 0) {
  22657. ret = sz;
  22658. }
  22659. #else
  22660. if (withHeader) {
  22661. CALLOC_ASNSETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
  22662. if (ret == 0) {
  22663. /* Set the OID. */
  22664. SetASN_OID(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], keyType,
  22665. oidKeyType);
  22666. /* Leave space for public point. */
  22667. SetASN_Buffer(&dataASN[EDPUBKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
  22668. /* Calculate size of public key encoding. */
  22669. ret = SizeASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, &sz);
  22670. }
  22671. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  22672. ret = BUFFER_E;
  22673. }
  22674. if ((ret == 0) && (output != NULL)) {
  22675. /* Encode public key. */
  22676. SetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, output);
  22677. /* Set location to encode public point. */
  22678. output = (byte*)dataASN[EDPUBKEYASN_IDX_PUBKEY].data.buffer.data;
  22679. }
  22680. FREE_ASNSETDATA(dataASN, NULL);
  22681. }
  22682. else if ((output != NULL) && (pubKeyLen > outLen)) {
  22683. ret = BUFFER_E;
  22684. }
  22685. else if (ret == 0) {
  22686. sz = pubKeyLen;
  22687. }
  22688. if ((ret == 0) && (output != NULL)) {
  22689. /* Put public key into space provided. */
  22690. XMEMCPY(output, pubKey, pubKeyLen);
  22691. }
  22692. if (ret == 0) {
  22693. ret = sz;
  22694. }
  22695. #endif /* WOLFSSL_ASN_TEMPLATE */
  22696. return ret;
  22697. }
  22698. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  22699. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  22700. /* Encode the public part of an Ed25519 key in DER.
  22701. *
  22702. * Pass NULL for output to get the size of the encoding.
  22703. *
  22704. * @param [in] key Ed25519 key object.
  22705. * @param [out] output Buffer to put encoded data in.
  22706. * @param [in] outLen Size of buffer in bytes.
  22707. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  22708. * @return Size of encoded data in bytes on success.
  22709. * @return BAD_FUNC_ARG when key is NULL.
  22710. * @return MEMORY_E when dynamic memory allocation failed.
  22711. */
  22712. int wc_Ed25519PublicKeyToDer(ed25519_key* key, byte* output, word32 inLen,
  22713. int withAlg)
  22714. {
  22715. int ret;
  22716. byte pubKey[ED25519_PUB_KEY_SIZE];
  22717. word32 pubKeyLen = (word32)sizeof(pubKey);
  22718. if (key == NULL) {
  22719. return BAD_FUNC_ARG;
  22720. }
  22721. ret = wc_ed25519_export_public(key, pubKey, &pubKeyLen);
  22722. if (ret == 0) {
  22723. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  22724. ED25519k, withAlg);
  22725. }
  22726. return ret;
  22727. }
  22728. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  22729. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  22730. /* Encode the public part of an Ed448 key in DER.
  22731. *
  22732. * Pass NULL for output to get the size of the encoding.
  22733. *
  22734. * @param [in] key Ed448 key object.
  22735. * @param [out] output Buffer to put encoded data in.
  22736. * @param [in] outLen Size of buffer in bytes.
  22737. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  22738. * @return Size of encoded data in bytes on success.
  22739. * @return BAD_FUNC_ARG when key is NULL.
  22740. * @return MEMORY_E when dynamic memory allocation failed.
  22741. */
  22742. int wc_Ed448PublicKeyToDer(ed448_key* key, byte* output, word32 inLen,
  22743. int withAlg)
  22744. {
  22745. int ret;
  22746. byte pubKey[ED448_PUB_KEY_SIZE];
  22747. word32 pubKeyLen = (word32)sizeof(pubKey);
  22748. if (key == NULL) {
  22749. return BAD_FUNC_ARG;
  22750. }
  22751. ret = wc_ed448_export_public(key, pubKey, &pubKeyLen);
  22752. if (ret == 0) {
  22753. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  22754. ED448k, withAlg);
  22755. }
  22756. return ret;
  22757. }
  22758. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  22759. #ifdef WOLFSSL_CERT_GEN
  22760. #ifndef NO_ASN_TIME
  22761. static WC_INLINE byte itob(int number)
  22762. {
  22763. return (byte)number + 0x30;
  22764. }
  22765. /* write time to output, format */
  22766. static void SetTime(struct tm* date, byte* output)
  22767. {
  22768. int i = 0;
  22769. output[i++] = itob((date->tm_year % 10000) / 1000);
  22770. output[i++] = itob((date->tm_year % 1000) / 100);
  22771. output[i++] = itob((date->tm_year % 100) / 10);
  22772. output[i++] = itob( date->tm_year % 10);
  22773. output[i++] = itob(date->tm_mon / 10);
  22774. output[i++] = itob(date->tm_mon % 10);
  22775. output[i++] = itob(date->tm_mday / 10);
  22776. output[i++] = itob(date->tm_mday % 10);
  22777. output[i++] = itob(date->tm_hour / 10);
  22778. output[i++] = itob(date->tm_hour % 10);
  22779. output[i++] = itob(date->tm_min / 10);
  22780. output[i++] = itob(date->tm_min % 10);
  22781. output[i++] = itob(date->tm_sec / 10);
  22782. output[i++] = itob(date->tm_sec % 10);
  22783. output[i] = 'Z'; /* Zulu profile */
  22784. }
  22785. #endif
  22786. #ifndef WOLFSSL_ASN_TEMPLATE
  22787. /* Copy Dates from cert, return bytes written */
  22788. static int CopyValidity(byte* output, Cert* cert)
  22789. {
  22790. int seqSz;
  22791. WOLFSSL_ENTER("CopyValidity");
  22792. /* headers and output */
  22793. seqSz = SetSequence(cert->beforeDateSz + cert->afterDateSz, output);
  22794. if (output) {
  22795. XMEMCPY(output + seqSz, cert->beforeDate, cert->beforeDateSz);
  22796. XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
  22797. cert->afterDateSz);
  22798. }
  22799. return seqSz + cert->beforeDateSz + cert->afterDateSz;
  22800. }
  22801. #endif /* !WOLFSSL_ASN_TEMPLATE */
  22802. /* Simple name OID size. */
  22803. #define NAME_OID_SZ 3
  22804. /* Domain name OIDs. */
  22805. static const byte nameOid[][NAME_OID_SZ] = {
  22806. { 0x55, 0x04, ASN_COUNTRY_NAME },
  22807. { 0x55, 0x04, ASN_STATE_NAME },
  22808. { 0x55, 0x04, ASN_STREET_ADDR },
  22809. { 0x55, 0x04, ASN_LOCALITY_NAME },
  22810. #ifdef WOLFSSL_CERT_NAME_ALL
  22811. { 0x55, 0x04, ASN_NAME },
  22812. { 0x55, 0x04, ASN_GIVEN_NAME },
  22813. { 0x55, 0x04, ASN_INITIALS },
  22814. { 0x55, 0x04, ASN_DNQUALIFIER },
  22815. #endif
  22816. { 0x55, 0x04, ASN_SUR_NAME },
  22817. { 0x55, 0x04, ASN_ORG_NAME },
  22818. { 0x00, 0x00, ASN_DOMAIN_COMPONENT}, /* not actual OID - see dcOid */
  22819. /* list all DC values before OUs */
  22820. { 0x55, 0x04, ASN_ORGUNIT_NAME },
  22821. { 0x55, 0x04, ASN_COMMON_NAME },
  22822. { 0x55, 0x04, ASN_SERIAL_NUMBER },
  22823. #ifdef WOLFSSL_CERT_EXT
  22824. { 0x55, 0x04, ASN_BUS_CAT },
  22825. #endif
  22826. { 0x55, 0x04, ASN_POSTAL_CODE },
  22827. { 0x00, 0x00, ASN_EMAIL_NAME}, /* not actual OID - see attrEmailOid */
  22828. { 0x00, 0x00, ASN_USER_ID}, /* not actual OID - see uidOid */
  22829. #ifdef WOLFSSL_CUSTOM_OID
  22830. { 0x00, 0x00, ASN_CUSTOM_NAME} /* OID comes from CertOidField */
  22831. #endif
  22832. };
  22833. #define NAME_ENTRIES (int)(sizeof(nameOid)/NAME_OID_SZ)
  22834. /* Get ASN Name from index */
  22835. byte GetCertNameId(int idx)
  22836. {
  22837. if (idx < NAME_ENTRIES)
  22838. return nameOid[idx][2];
  22839. return 0;
  22840. }
  22841. /* Get Which Name from index */
  22842. const char* GetOneCertName(CertName* name, int idx)
  22843. {
  22844. byte type = GetCertNameId(idx);
  22845. switch (type) {
  22846. case ASN_COUNTRY_NAME:
  22847. return name->country;
  22848. case ASN_STATE_NAME:
  22849. return name->state;
  22850. case ASN_STREET_ADDR:
  22851. return name->street;
  22852. case ASN_LOCALITY_NAME:
  22853. return name->locality;
  22854. #ifdef WOLFSSL_CERT_NAME_ALL
  22855. case ASN_NAME:
  22856. return name->dnName;
  22857. case ASN_GIVEN_NAME:
  22858. return name->givenName;
  22859. case ASN_INITIALS:
  22860. return name->initials;
  22861. case ASN_DNQUALIFIER:
  22862. return name->dnQualifier;
  22863. #endif /* WOLFSSL_CERT_NAME_ALL */
  22864. case ASN_SUR_NAME:
  22865. return name->sur;
  22866. case ASN_ORG_NAME:
  22867. return name->org;
  22868. case ASN_ORGUNIT_NAME:
  22869. return name->unit;
  22870. case ASN_COMMON_NAME:
  22871. return name->commonName;
  22872. case ASN_SERIAL_NUMBER:
  22873. return name->serialDev;
  22874. case ASN_USER_ID:
  22875. return name->userId;
  22876. case ASN_POSTAL_CODE:
  22877. return name->postalCode;
  22878. case ASN_EMAIL_NAME:
  22879. return name->email;
  22880. #ifdef WOLFSSL_CERT_EXT
  22881. case ASN_BUS_CAT:
  22882. return name->busCat;
  22883. #endif
  22884. #ifdef WOLFSSL_CUSTOM_OID
  22885. case ASN_CUSTOM_NAME:
  22886. return (const char*)name->custom.val;
  22887. #endif
  22888. default:
  22889. return NULL;
  22890. }
  22891. }
  22892. /* Get Which Name Encoding from index */
  22893. static char GetNameType(CertName* name, int idx)
  22894. {
  22895. byte type = GetCertNameId(idx);
  22896. switch (type) {
  22897. case ASN_COUNTRY_NAME:
  22898. return name->countryEnc;
  22899. case ASN_STATE_NAME:
  22900. return name->stateEnc;
  22901. case ASN_STREET_ADDR:
  22902. return name->streetEnc;
  22903. case ASN_LOCALITY_NAME:
  22904. return name->localityEnc;
  22905. #ifdef WOLFSSL_CERT_NAME_ALL
  22906. case ASN_NAME:
  22907. return name->dnNameEnc;
  22908. case ASN_GIVEN_NAME:
  22909. return name->givenNameEnc;
  22910. case ASN_INITIALS:
  22911. return name->initialsEnc;
  22912. case ASN_DNQUALIFIER:
  22913. return name->dnQualifierEnc;
  22914. #endif /* WOLFSSL_CERT_NAME_ALL */
  22915. case ASN_SUR_NAME:
  22916. return name->surEnc;
  22917. case ASN_ORG_NAME:
  22918. return name->orgEnc;
  22919. case ASN_ORGUNIT_NAME:
  22920. return name->unitEnc;
  22921. case ASN_COMMON_NAME:
  22922. return name->commonNameEnc;
  22923. case ASN_SERIAL_NUMBER:
  22924. return name->serialDevEnc;
  22925. case ASN_USER_ID:
  22926. return name->userIdEnc;
  22927. case ASN_POSTAL_CODE:
  22928. return name->postalCodeEnc;
  22929. case ASN_EMAIL_NAME:
  22930. return 0; /* special */
  22931. #ifdef WOLFSSL_CERT_EXT
  22932. case ASN_BUS_CAT:
  22933. return name->busCatEnc;
  22934. #endif
  22935. #ifdef WOLFSSL_CUSTOM_OID
  22936. case ASN_CUSTOM_NAME:
  22937. return name->custom.enc;
  22938. #endif
  22939. default:
  22940. return 0;
  22941. }
  22942. }
  22943. #ifndef WOLFSSL_ASN_TEMPLATE
  22944. /*
  22945. Extensions ::= SEQUENCE OF Extension
  22946. Extension ::= SEQUENCE {
  22947. extnId OBJECT IDENTIFIER,
  22948. critical BOOLEAN DEFAULT FALSE,
  22949. extnValue OCTET STRING }
  22950. */
  22951. /* encode all extensions, return total bytes written */
  22952. static int SetExtensions(byte* out, word32 outSz, int *IdxInOut,
  22953. const byte* ext, int extSz)
  22954. {
  22955. if (out == NULL || IdxInOut == NULL || ext == NULL)
  22956. return BAD_FUNC_ARG;
  22957. if (outSz < (word32)(*IdxInOut+extSz))
  22958. return BUFFER_E;
  22959. XMEMCPY(&out[*IdxInOut], ext, extSz); /* extensions */
  22960. *IdxInOut += extSz;
  22961. return *IdxInOut;
  22962. }
  22963. /* encode extensions header, return total bytes written */
  22964. static int SetExtensionsHeader(byte* out, word32 outSz, int extSz)
  22965. {
  22966. byte sequence[MAX_SEQ_SZ];
  22967. byte len[MAX_LENGTH_SZ];
  22968. int seqSz, lenSz, idx = 0;
  22969. if (out == NULL)
  22970. return BAD_FUNC_ARG;
  22971. if (outSz < 3)
  22972. return BUFFER_E;
  22973. seqSz = SetSequence(extSz, sequence);
  22974. /* encode extensions length provided */
  22975. lenSz = SetLength(extSz+seqSz, len);
  22976. if (outSz < (word32)(lenSz+seqSz+1))
  22977. return BUFFER_E;
  22978. out[idx++] = ASN_EXTENSIONS; /* extensions id */
  22979. XMEMCPY(&out[idx], len, lenSz); /* length */
  22980. idx += lenSz;
  22981. XMEMCPY(&out[idx], sequence, seqSz); /* sequence */
  22982. idx += seqSz;
  22983. return idx;
  22984. }
  22985. /* encode CA basic constraints true with path length
  22986. * return total bytes written */
  22987. static int SetCaWithPathLen(byte* out, word32 outSz, byte pathLen)
  22988. {
  22989. /* ASN1->DER sequence for Basic Constraints True and path length */
  22990. const byte caPathLenBasicConstASN1[] = {
  22991. 0x30, 0x0F, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04,
  22992. 0x08, 0x30, 0x06, 0x01, 0x01, 0xFF, 0x02, 0x01,
  22993. 0x00
  22994. };
  22995. if (out == NULL)
  22996. return BAD_FUNC_ARG;
  22997. if (outSz < sizeof(caPathLenBasicConstASN1))
  22998. return BUFFER_E;
  22999. XMEMCPY(out, caPathLenBasicConstASN1, sizeof(caPathLenBasicConstASN1));
  23000. out[sizeof(caPathLenBasicConstASN1)-1] = pathLen;
  23001. return (int)sizeof(caPathLenBasicConstASN1);
  23002. }
  23003. /* encode CA basic constraints true
  23004. * return total bytes written */
  23005. static int SetCa(byte* out, word32 outSz)
  23006. {
  23007. /* ASN1->DER sequence for Basic Constraints True */
  23008. const byte caBasicConstASN1[] = {
  23009. 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  23010. 0x05, 0x30, 0x03, 0x01, 0x01, 0xff
  23011. };
  23012. if (out == NULL)
  23013. return BAD_FUNC_ARG;
  23014. if (outSz < sizeof(caBasicConstASN1))
  23015. return BUFFER_E;
  23016. XMEMCPY(out, caBasicConstASN1, sizeof(caBasicConstASN1));
  23017. return (int)sizeof(caBasicConstASN1);
  23018. }
  23019. /* encode basic constraints without CA Boolean
  23020. * return total bytes written */
  23021. static int SetBC(byte* out, word32 outSz)
  23022. {
  23023. /* ASN1->DER sequence for Basic Constraint without CA Boolean */
  23024. const byte BasicConstASN1[] = {
  23025. 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  23026. 0x02, 0x30, 0x00
  23027. };
  23028. if (out == NULL)
  23029. return BAD_FUNC_ARG;
  23030. if (outSz < sizeof(BasicConstASN1))
  23031. return BUFFER_E;
  23032. XMEMCPY(out, BasicConstASN1, sizeof(BasicConstASN1));
  23033. return (int)sizeof(BasicConstASN1);
  23034. }
  23035. #endif
  23036. #ifdef WOLFSSL_CERT_EXT
  23037. #ifndef WOLFSSL_ASN_TEMPLATE
  23038. /* encode OID and associated value, return total bytes written */
  23039. static int SetOidValue(byte* out, word32 outSz, const byte *oid, word32 oidSz,
  23040. byte *in, word32 inSz)
  23041. {
  23042. int idx = 0;
  23043. if (out == NULL || oid == NULL || in == NULL)
  23044. return BAD_FUNC_ARG;
  23045. if (outSz < 3)
  23046. return BUFFER_E;
  23047. /* sequence, + 1 => byte to put value size */
  23048. idx = SetSequence(inSz + oidSz + 1, out);
  23049. if ((idx + inSz + oidSz + 1) > outSz)
  23050. return BUFFER_E;
  23051. XMEMCPY(out+idx, oid, oidSz);
  23052. idx += oidSz;
  23053. out[idx++] = (byte)inSz;
  23054. XMEMCPY(out+idx, in, inSz);
  23055. return (idx+inSz);
  23056. }
  23057. /* encode Subject Key Identifier, return total bytes written
  23058. * RFC5280 : non-critical */
  23059. static int SetSKID(byte* output, word32 outSz, const byte *input, word32 length)
  23060. {
  23061. byte skid_len[1 + MAX_LENGTH_SZ];
  23062. byte skid_enc_len[MAX_LENGTH_SZ];
  23063. int idx = 0, skid_lenSz, skid_enc_lenSz;
  23064. const byte skid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04 };
  23065. if (output == NULL || input == NULL)
  23066. return BAD_FUNC_ARG;
  23067. /* Octet String header */
  23068. skid_lenSz = SetOctetString(length, skid_len);
  23069. /* length of encoded value */
  23070. skid_enc_lenSz = SetLength(length + skid_lenSz, skid_enc_len);
  23071. if (outSz < 3)
  23072. return BUFFER_E;
  23073. idx = SetSequence(length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz,
  23074. output);
  23075. if ((length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz) > outSz)
  23076. return BUFFER_E;
  23077. /* put oid */
  23078. XMEMCPY(output+idx, skid_oid, sizeof(skid_oid));
  23079. idx += sizeof(skid_oid);
  23080. /* put encoded len */
  23081. XMEMCPY(output+idx, skid_enc_len, skid_enc_lenSz);
  23082. idx += skid_enc_lenSz;
  23083. /* put octet header */
  23084. XMEMCPY(output+idx, skid_len, skid_lenSz);
  23085. idx += skid_lenSz;
  23086. /* put value */
  23087. XMEMCPY(output+idx, input, length);
  23088. idx += length;
  23089. return idx;
  23090. }
  23091. /* encode Authority Key Identifier, return total bytes written
  23092. * RFC5280 : non-critical */
  23093. static int SetAKID(byte* output, word32 outSz, byte *input, word32 length,
  23094. byte rawAkid)
  23095. {
  23096. int enc_valSz, inSeqSz;
  23097. byte enc_val_buf[MAX_KID_SZ];
  23098. byte* enc_val;
  23099. const byte akid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x23 };
  23100. const byte akid_cs[] = { 0x80 };
  23101. word32 idx;
  23102. (void)rawAkid;
  23103. if (output == NULL || input == NULL)
  23104. return BAD_FUNC_ARG;
  23105. #ifdef WOLFSSL_AKID_NAME
  23106. if (rawAkid) {
  23107. enc_val = input;
  23108. enc_valSz = length;
  23109. }
  23110. else
  23111. #endif
  23112. {
  23113. enc_val = enc_val_buf;
  23114. enc_valSz = length + 3 + sizeof(akid_cs);
  23115. if (enc_valSz > (int)sizeof(enc_val_buf))
  23116. return BAD_FUNC_ARG;
  23117. /* sequence for ContentSpec & value */
  23118. enc_valSz = SetOidValue(enc_val, enc_valSz, akid_cs, sizeof(akid_cs),
  23119. input, length);
  23120. if (enc_valSz <= 0)
  23121. return enc_valSz;
  23122. }
  23123. /* The size of the extension sequence contents */
  23124. inSeqSz = sizeof(akid_oid) + SetOctetString(enc_valSz, NULL) +
  23125. enc_valSz;
  23126. if (SetSequence(inSeqSz, NULL) + inSeqSz > outSz)
  23127. return BAD_FUNC_ARG;
  23128. /* Write out the sequence header */
  23129. idx = SetSequence(inSeqSz, output);
  23130. /* Write out OID */
  23131. XMEMCPY(output + idx, akid_oid, sizeof(akid_oid));
  23132. idx += sizeof(akid_oid);
  23133. /* Write out AKID */
  23134. idx += SetOctetString(enc_valSz, output + idx);
  23135. XMEMCPY(output + idx, enc_val, enc_valSz);
  23136. return idx + enc_valSz;
  23137. }
  23138. /* encode Key Usage, return total bytes written
  23139. * RFC5280 : critical */
  23140. static int SetKeyUsage(byte* output, word32 outSz, word16 input)
  23141. {
  23142. byte ku[5];
  23143. int idx;
  23144. const byte keyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0f,
  23145. 0x01, 0x01, 0xff, 0x04};
  23146. if (output == NULL)
  23147. return BAD_FUNC_ARG;
  23148. idx = SetBitString16Bit(input, ku);
  23149. return SetOidValue(output, outSz, keyusage_oid, sizeof(keyusage_oid),
  23150. ku, idx);
  23151. }
  23152. static int SetOjectIdValue(byte* output, word32 outSz, int* idx,
  23153. const byte* oid, word32 oidSz)
  23154. {
  23155. /* verify room */
  23156. if (*idx + 2 + oidSz >= outSz)
  23157. return ASN_PARSE_E;
  23158. *idx += SetObjectId(oidSz, &output[*idx]);
  23159. XMEMCPY(&output[*idx], oid, oidSz);
  23160. *idx += oidSz;
  23161. return 0;
  23162. }
  23163. #endif
  23164. #ifdef WOLFSSL_ASN_TEMPLATE
  23165. /* ASN.1 template for extended key usage.
  23166. * X.509: RFC 5280, 4.2.12 - Extended Key Usage
  23167. * Dynamic creation of template for encoding.
  23168. */
  23169. static const ASNItem ekuASN[] = {
  23170. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  23171. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  23172. };
  23173. enum {
  23174. EKUASN_IDX_SEQ = 0,
  23175. EKUASN_IDX_OID,
  23176. };
  23177. /* OIDs corresponding to extended key usage. */
  23178. struct {
  23179. const byte* oid;
  23180. word32 oidSz;
  23181. } ekuOid[] = {
  23182. { extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid) },
  23183. { extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid) },
  23184. { extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid) },
  23185. { extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid) },
  23186. { extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid) },
  23187. { extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid) },
  23188. };
  23189. #define EKU_OID_LO 1
  23190. #define EKU_OID_HI 6
  23191. #endif /* WOLFSSL_ASN_TEMPLATE */
  23192. /* encode Extended Key Usage (RFC 5280 4.2.1.12), return total bytes written */
  23193. static int SetExtKeyUsage(Cert* cert, byte* output, word32 outSz, byte input)
  23194. {
  23195. #ifndef WOLFSSL_ASN_TEMPLATE
  23196. int idx = 0, oidListSz = 0, totalSz, ret = 0;
  23197. const byte extkeyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x25 };
  23198. if (output == NULL)
  23199. return BAD_FUNC_ARG;
  23200. /* Skip to OID List */
  23201. totalSz = 2 + sizeof(extkeyusage_oid) + 4;
  23202. idx = totalSz;
  23203. /* Build OID List */
  23204. /* If any set, then just use it */
  23205. if (input & EXTKEYUSE_ANY) {
  23206. ret |= SetOjectIdValue(output, outSz, &idx,
  23207. extExtKeyUsageAnyOid, sizeof(extExtKeyUsageAnyOid));
  23208. }
  23209. else {
  23210. if (input & EXTKEYUSE_SERVER_AUTH)
  23211. ret |= SetOjectIdValue(output, outSz, &idx,
  23212. extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid));
  23213. if (input & EXTKEYUSE_CLIENT_AUTH)
  23214. ret |= SetOjectIdValue(output, outSz, &idx,
  23215. extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid));
  23216. if (input & EXTKEYUSE_CODESIGN)
  23217. ret |= SetOjectIdValue(output, outSz, &idx,
  23218. extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid));
  23219. if (input & EXTKEYUSE_EMAILPROT)
  23220. ret |= SetOjectIdValue(output, outSz, &idx,
  23221. extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid));
  23222. if (input & EXTKEYUSE_TIMESTAMP)
  23223. ret |= SetOjectIdValue(output, outSz, &idx,
  23224. extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid));
  23225. if (input & EXTKEYUSE_OCSP_SIGN)
  23226. ret |= SetOjectIdValue(output, outSz, &idx,
  23227. extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid));
  23228. #ifdef WOLFSSL_EKU_OID
  23229. /* iterate through OID values */
  23230. if (input & EXTKEYUSE_USER) {
  23231. int i, sz;
  23232. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  23233. sz = cert->extKeyUsageOIDSz[i];
  23234. if (sz > 0) {
  23235. ret |= SetOjectIdValue(output, outSz, &idx,
  23236. cert->extKeyUsageOID[i], sz);
  23237. }
  23238. }
  23239. }
  23240. #endif /* WOLFSSL_EKU_OID */
  23241. }
  23242. if (ret != 0)
  23243. return ASN_PARSE_E;
  23244. /* Calculate Sizes */
  23245. oidListSz = idx - totalSz;
  23246. totalSz = idx - 2; /* exclude first seq/len (2) */
  23247. /* 1. Seq + Total Len (2) */
  23248. idx = SetSequence(totalSz, output);
  23249. /* 2. Object ID (2) */
  23250. XMEMCPY(&output[idx], extkeyusage_oid, sizeof(extkeyusage_oid));
  23251. idx += sizeof(extkeyusage_oid);
  23252. /* 3. Octet String (2) */
  23253. idx += SetOctetString(totalSz - idx, &output[idx]);
  23254. /* 4. Seq + OidListLen (2) */
  23255. idx += SetSequence(oidListSz, &output[idx]);
  23256. /* 5. Oid List (already set in-place above) */
  23257. idx += oidListSz;
  23258. (void)cert;
  23259. return idx;
  23260. #else
  23261. /* TODO: consider calculating size of OBJECT_IDs, setting length into
  23262. * SEQUENCE, encode SEQUENCE, encode OBJECT_IDs into buffer. */
  23263. ASNSetData* dataASN;
  23264. ASNItem* extKuASN = NULL;
  23265. int asnIdx = 1;
  23266. int cnt = 1 + EKU_OID_HI;
  23267. int i;
  23268. int ret = 0;
  23269. int sz = 0;
  23270. #ifdef WOLFSSL_EKU_OID
  23271. cnt += CTC_MAX_EKU_NB;
  23272. #endif
  23273. /* Allocate memory for dynamic data items. */
  23274. dataASN = (ASNSetData*)XMALLOC(cnt * sizeof(ASNSetData), cert->heap,
  23275. DYNAMIC_TYPE_TMP_BUFFER);
  23276. if (dataASN == NULL) {
  23277. ret = MEMORY_E;
  23278. }
  23279. if (ret == 0) {
  23280. /* Allocate memory for dynamic ASN.1 template. */
  23281. extKuASN = (ASNItem*)XMALLOC(cnt * sizeof(ASNItem), cert->heap,
  23282. DYNAMIC_TYPE_TMP_BUFFER);
  23283. if (extKuASN == NULL) {
  23284. ret = MEMORY_E;
  23285. }
  23286. }
  23287. if (ret == 0) {
  23288. /* Copy Sequence into dynamic ASN.1 template. */
  23289. XMEMCPY(&extKuASN[EKUASN_IDX_SEQ], ekuASN, sizeof(ASNItem));
  23290. /* Clear dynamic data. */
  23291. XMEMSET(dataASN, 0, cnt * sizeof(ASNSetData));
  23292. /* Build up the template and data. */
  23293. /* If 'any' set, then just use it. */
  23294. if ((input & EXTKEYUSE_ANY) == EXTKEYUSE_ANY) {
  23295. /* Set template item. */
  23296. XMEMCPY(&extKuASN[EKUASN_IDX_OID], &ekuASN[EKUASN_IDX_OID],
  23297. sizeof(ASNItem));
  23298. /* Set data item. */
  23299. SetASN_Buffer(&dataASN[asnIdx], extExtKeyUsageAnyOid,
  23300. sizeof(extExtKeyUsageAnyOid));
  23301. asnIdx++;
  23302. }
  23303. else {
  23304. /* Step through the flagged purposes. */
  23305. for (i = EKU_OID_LO; i <= EKU_OID_HI; i++) {
  23306. if ((input & (1 << i)) != 0) {
  23307. /* Set template item. */
  23308. XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
  23309. sizeof(ASNItem));
  23310. /* Set data item. */
  23311. SetASN_Buffer(&dataASN[asnIdx], ekuOid[i - 1].oid,
  23312. ekuOid[i - 1].oidSz);
  23313. asnIdx++;
  23314. }
  23315. }
  23316. #ifdef WOLFSSL_EKU_OID
  23317. if (input & EXTKEYUSE_USER) {
  23318. /* Iterate through OID values */
  23319. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  23320. sz = cert->extKeyUsageOIDSz[i];
  23321. if (sz > 0) {
  23322. /* Set template item. */
  23323. XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
  23324. sizeof(ASNItem));
  23325. /* Set data item. */
  23326. SetASN_Buffer(&dataASN[asnIdx], cert->extKeyUsageOID[i],
  23327. sz);
  23328. asnIdx++;
  23329. }
  23330. }
  23331. }
  23332. #endif /* WOLFSSL_EKU_OID */
  23333. (void)cert;
  23334. }
  23335. /* Calculate size of encoding. */
  23336. sz = 0;
  23337. ret = SizeASN_Items(extKuASN, dataASN, asnIdx, &sz);
  23338. }
  23339. /* When buffer to write to, ensure it's big enough. */
  23340. if ((ret == 0) && (output != NULL) && (sz > (int)outSz)) {
  23341. ret = BUFFER_E;
  23342. }
  23343. if ((ret == 0) && (output != NULL)) {
  23344. /* Encode extended key usage. */
  23345. SetASN_Items(extKuASN, dataASN, asnIdx, output);
  23346. }
  23347. if (ret == 0) {
  23348. /* Return the encoding size. */
  23349. ret = sz;
  23350. }
  23351. /* Dispose of allocated data. */
  23352. if (extKuASN != NULL) {
  23353. XFREE(extKuASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23354. }
  23355. if (dataASN != NULL) {
  23356. XFREE(dataASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23357. }
  23358. return ret;
  23359. #endif
  23360. }
  23361. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  23362. #ifndef WOLFSSL_ASN_TEMPLATE
  23363. static int SetNsCertType(Cert* cert, byte* output, word32 outSz, byte input)
  23364. {
  23365. word32 idx;
  23366. byte unusedBits = 0;
  23367. byte nsCertType = input;
  23368. word32 totalSz;
  23369. word32 bitStrSz;
  23370. const byte nscerttype_oid[] = { 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
  23371. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  23372. if (cert == NULL || output == NULL ||
  23373. input == 0)
  23374. return BAD_FUNC_ARG;
  23375. totalSz = sizeof(nscerttype_oid);
  23376. /* Get amount of lsb zero's */
  23377. for (;(input & 1) == 0; input >>= 1)
  23378. unusedBits++;
  23379. /* 1 byte of NS Cert Type extension */
  23380. bitStrSz = SetBitString(1, unusedBits, NULL) + 1;
  23381. totalSz += SetOctetString(bitStrSz, NULL) + bitStrSz;
  23382. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  23383. return BAD_FUNC_ARG;
  23384. /* 1. Seq + Total Len */
  23385. idx = SetSequence(totalSz, output);
  23386. /* 2. Object ID */
  23387. XMEMCPY(&output[idx], nscerttype_oid, sizeof(nscerttype_oid));
  23388. idx += sizeof(nscerttype_oid);
  23389. /* 3. Octet String */
  23390. idx += SetOctetString(bitStrSz, &output[idx]);
  23391. /* 4. Bit String */
  23392. idx += SetBitString(1, unusedBits, &output[idx]);
  23393. output[idx++] = nsCertType;
  23394. return idx;
  23395. }
  23396. #endif
  23397. #endif
  23398. #ifndef WOLFSSL_ASN_TEMPLATE
  23399. static int SetCRLInfo(Cert* cert, byte* output, word32 outSz, byte* input,
  23400. int inSz)
  23401. {
  23402. word32 idx;
  23403. word32 totalSz;
  23404. const byte crlinfo_oid[] = { 0x06, 0x03, 0x55, 0x1D, 0x1F };
  23405. if (cert == NULL || output == NULL ||
  23406. input == 0 || inSz <= 0)
  23407. return BAD_FUNC_ARG;
  23408. totalSz = sizeof(crlinfo_oid) + SetOctetString(inSz, NULL) + inSz;
  23409. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  23410. return BAD_FUNC_ARG;
  23411. /* 1. Seq + Total Len */
  23412. idx = SetSequence(totalSz, output);
  23413. /* 2. Object ID */
  23414. XMEMCPY(&output[idx], crlinfo_oid, sizeof(crlinfo_oid));
  23415. idx += sizeof(crlinfo_oid);
  23416. /* 3. Octet String */
  23417. idx += SetOctetString(inSz, &output[idx]);
  23418. /* 4. CRL Info */
  23419. XMEMCPY(&output[idx], input, inSz);
  23420. idx += inSz;
  23421. return idx;
  23422. }
  23423. #endif
  23424. /* encode Certificate Policies, return total bytes written
  23425. * each input value must be ITU-T X.690 formatted : a.b.c...
  23426. * input must be an array of values with a NULL terminated for the latest
  23427. * RFC5280 : non-critical */
  23428. static int SetCertificatePolicies(byte *output,
  23429. word32 outputSz,
  23430. char input[MAX_CERTPOL_NB][MAX_CERTPOL_SZ],
  23431. word16 nb_certpol,
  23432. void* heap)
  23433. {
  23434. #ifndef WOLFSSL_ASN_TEMPLATE
  23435. byte oid[MAX_OID_SZ];
  23436. byte der_oid[MAX_CERTPOL_NB][MAX_OID_SZ];
  23437. byte out[MAX_CERTPOL_SZ];
  23438. word32 oidSz;
  23439. word32 outSz;
  23440. word32 i = 0;
  23441. word32 der_oidSz[MAX_CERTPOL_NB];
  23442. int ret;
  23443. const byte certpol_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x20, 0x04 };
  23444. const byte oid_oid[] = { 0x06 };
  23445. if (output == NULL || input == NULL || nb_certpol > MAX_CERTPOL_NB)
  23446. return BAD_FUNC_ARG;
  23447. for (i = 0; i < nb_certpol; i++) {
  23448. oidSz = sizeof(oid);
  23449. XMEMSET(oid, 0, oidSz);
  23450. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  23451. if (ret != 0)
  23452. return ret;
  23453. /* compute sequence value for the oid */
  23454. ret = SetOidValue(der_oid[i], MAX_OID_SZ, oid_oid,
  23455. sizeof(oid_oid), oid, oidSz);
  23456. if (ret <= 0)
  23457. return ret;
  23458. else
  23459. der_oidSz[i] = (word32)ret;
  23460. }
  23461. /* concatenate oid, keep two byte for sequence/size of the created value */
  23462. for (i = 0, outSz = 2; i < nb_certpol; i++) {
  23463. XMEMCPY(out+outSz, der_oid[i], der_oidSz[i]);
  23464. outSz += der_oidSz[i];
  23465. }
  23466. /* add sequence */
  23467. ret = SetSequence(outSz-2, out);
  23468. if (ret <= 0)
  23469. return ret;
  23470. /* add Policy OID to compute final value */
  23471. return SetOidValue(output, outputSz, certpol_oid, sizeof(certpol_oid),
  23472. out, outSz);
  23473. #else
  23474. int i;
  23475. int ret = 0;
  23476. byte oid[MAX_OID_SZ];
  23477. word32 oidSz;
  23478. word32 sz = 0;
  23479. int piSz;
  23480. if ((input == NULL) || (nb_certpol > MAX_CERTPOL_NB)) {
  23481. ret = BAD_FUNC_ARG;
  23482. }
  23483. /* Put in policyIdentifier but not policyQualifiers. */
  23484. for (i = 0; (ret == 0) && (i < nb_certpol); i++) {
  23485. ASNSetData dataASN[policyInfoASN_Length];
  23486. oidSz = sizeof(oid);
  23487. XMEMSET(oid, 0, oidSz);
  23488. dataASN[POLICYINFOASN_IDX_QUALI].noOut = 1;
  23489. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  23490. if (ret == 0) {
  23491. XMEMSET(dataASN, 0, sizeof(dataASN));
  23492. SetASN_Buffer(&dataASN[POLICYINFOASN_IDX_ID], oid, oidSz);
  23493. ret = SizeASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  23494. &piSz);
  23495. }
  23496. if ((ret == 0) && (output != NULL) && (sz + piSz > outputSz)) {
  23497. ret = BUFFER_E;
  23498. }
  23499. if (ret == 0) {
  23500. if (output != NULL) {
  23501. SetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  23502. output);
  23503. output += piSz;
  23504. }
  23505. sz += piSz;
  23506. }
  23507. }
  23508. if (ret == 0) {
  23509. ret = sz;
  23510. }
  23511. return ret;
  23512. #endif
  23513. }
  23514. #endif /* WOLFSSL_CERT_EXT */
  23515. #ifdef WOLFSSL_ALT_NAMES
  23516. #ifndef WOLFSSL_ASN_TEMPLATE
  23517. /* encode Alternative Names, return total bytes written */
  23518. static int SetAltNames(byte *output, word32 outSz,
  23519. const byte *input, word32 length, int critical)
  23520. {
  23521. byte san_len[1 + MAX_LENGTH_SZ];
  23522. int idx = 0, san_lenSz;
  23523. const byte san_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x11 };
  23524. const byte san_crit[] = { 0x01, 0x01, 0xff };
  23525. word32 seqSz;
  23526. if (output == NULL || input == NULL)
  23527. return BAD_FUNC_ARG;
  23528. if (outSz < length)
  23529. return BUFFER_E;
  23530. /* Octet String header */
  23531. san_lenSz = SetOctetString(length, san_len);
  23532. if (outSz < MAX_SEQ_SZ)
  23533. return BUFFER_E;
  23534. seqSz = length + sizeof(san_oid) + san_lenSz;
  23535. if (critical)
  23536. seqSz += sizeof(san_crit);
  23537. idx = SetSequence(seqSz, output);
  23538. if (seqSz > outSz)
  23539. return BUFFER_E;
  23540. /* put oid */
  23541. XMEMCPY(output+idx, san_oid, sizeof(san_oid));
  23542. idx += sizeof(san_oid);
  23543. if (critical) {
  23544. XMEMCPY(output+idx, san_crit, sizeof(san_crit));
  23545. idx += sizeof(san_crit);
  23546. }
  23547. /* put octet header */
  23548. XMEMCPY(output+idx, san_len, san_lenSz);
  23549. idx += san_lenSz;
  23550. /* put value */
  23551. XMEMCPY(output+idx, input, length);
  23552. idx += length;
  23553. return idx;
  23554. }
  23555. #endif /* WOLFSSL_ASN_TEMPLATE */
  23556. int FlattenAltNames(byte* output, word32 outputSz, const DNS_entry* names)
  23557. {
  23558. word32 idx;
  23559. const DNS_entry* curName;
  23560. word32 namesSz = 0;
  23561. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23562. word32 i;
  23563. #endif
  23564. if (output == NULL)
  23565. return BAD_FUNC_ARG;
  23566. if (names == NULL)
  23567. return 0;
  23568. curName = names;
  23569. do {
  23570. namesSz += curName->len + 2 +
  23571. ((curName->len < ASN_LONG_LENGTH) ? 0
  23572. : BytePrecision(curName->len));
  23573. curName = curName->next;
  23574. } while (curName != NULL);
  23575. if (outputSz < MAX_SEQ_SZ + namesSz)
  23576. return BUFFER_E;
  23577. idx = SetSequence(namesSz, output);
  23578. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23579. namesSz += idx;
  23580. i = namesSz;
  23581. #endif
  23582. curName = names;
  23583. do {
  23584. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23585. word32 len = SetLength(curName->len, NULL);
  23586. idx = i - curName->len - len - 1;
  23587. i = idx;
  23588. #endif
  23589. output[idx] = (byte) (ASN_CONTEXT_SPECIFIC | curName->type);
  23590. if (curName->type == ASN_DIR_TYPE) {
  23591. output[idx] |= ASN_CONSTRUCTED;
  23592. }
  23593. idx++;
  23594. idx += SetLength(curName->len, output + idx);
  23595. XMEMCPY(output + idx, curName->name, curName->len);
  23596. #ifndef WOLFSSL_ALT_NAMES_NO_REV
  23597. idx += curName->len;
  23598. #endif
  23599. curName = curName->next;
  23600. } while (curName != NULL);
  23601. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23602. idx = namesSz;
  23603. #endif
  23604. return idx;
  23605. }
  23606. #endif /* WOLFSSL_ALT_NAMES */
  23607. #endif /* WOLFSSL_CERT_GEN */
  23608. #if defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  23609. /* Simple domain name OID size. */
  23610. #define DN_OID_SZ 3
  23611. /* Encodes one attribute of the name (issuer/subject)
  23612. *
  23613. * name structure to hold result of encoding
  23614. * nameStr value to be encoded
  23615. * nameTag tag of encoding i.e CTC_UTF8
  23616. * type id of attribute i.e ASN_COMMON_NAME
  23617. * emailTag tag of email i.e CTC_UTF8
  23618. * returns length on success
  23619. */
  23620. static int EncodeName(EncodedName* name, const char* nameStr,
  23621. byte nameTag, byte type, byte emailTag, CertName* cname)
  23622. {
  23623. #if !defined(WOLFSSL_ASN_TEMPLATE)
  23624. word32 idx = 0;
  23625. /* bottom up */
  23626. byte firstLen[1 + MAX_LENGTH_SZ];
  23627. byte secondLen[MAX_LENGTH_SZ];
  23628. byte sequence[MAX_SEQ_SZ];
  23629. byte set[MAX_SET_SZ];
  23630. int strLen;
  23631. int thisLen;
  23632. int firstSz, secondSz, seqSz, setSz;
  23633. if (nameStr == NULL) {
  23634. name->used = 0;
  23635. return 0;
  23636. }
  23637. thisLen = strLen = (int)XSTRLEN(nameStr);
  23638. #ifdef WOLFSSL_CUSTOM_OID
  23639. if (type == ASN_CUSTOM_NAME) {
  23640. if (cname == NULL || cname->custom.oidSz == 0) {
  23641. name->used = 0;
  23642. return 0;
  23643. }
  23644. thisLen = strLen = cname->custom.valSz;
  23645. }
  23646. #else
  23647. (void)cname;
  23648. #endif
  23649. if (strLen == 0) { /* no user data for this item */
  23650. name->used = 0;
  23651. return 0;
  23652. }
  23653. /* Restrict country code size */
  23654. if (type == ASN_COUNTRY_NAME && strLen != CTC_COUNTRY_SIZE) {
  23655. WOLFSSL_MSG("Country code size error");
  23656. WOLFSSL_ERROR_VERBOSE(ASN_COUNTRY_SIZE_E);
  23657. return ASN_COUNTRY_SIZE_E;
  23658. }
  23659. secondSz = SetLength(strLen, secondLen);
  23660. thisLen += secondSz;
  23661. switch (type) {
  23662. case ASN_EMAIL_NAME: /* email */
  23663. thisLen += (int)sizeof(attrEmailOid);
  23664. firstSz = (int)sizeof(attrEmailOid);
  23665. break;
  23666. case ASN_DOMAIN_COMPONENT:
  23667. thisLen += (int)sizeof(dcOid);
  23668. firstSz = (int)sizeof(dcOid);
  23669. break;
  23670. case ASN_USER_ID:
  23671. thisLen += (int)sizeof(uidOid);
  23672. firstSz = (int)sizeof(uidOid);
  23673. break;
  23674. #ifdef WOLFSSL_CUSTOM_OID
  23675. case ASN_CUSTOM_NAME:
  23676. thisLen += cname->custom.oidSz;
  23677. firstSz = cname->custom.oidSz;
  23678. break;
  23679. #endif
  23680. default:
  23681. thisLen += DN_OID_SZ;
  23682. firstSz = DN_OID_SZ;
  23683. }
  23684. thisLen++; /* id type */
  23685. firstSz = SetObjectId(firstSz, firstLen);
  23686. thisLen += firstSz;
  23687. seqSz = SetSequence(thisLen, sequence);
  23688. thisLen += seqSz;
  23689. setSz = SetSet(thisLen, set);
  23690. thisLen += setSz;
  23691. if (thisLen > (int)sizeof(name->encoded)) {
  23692. return BUFFER_E;
  23693. }
  23694. /* store it */
  23695. idx = 0;
  23696. /* set */
  23697. XMEMCPY(name->encoded, set, setSz);
  23698. idx += setSz;
  23699. /* seq */
  23700. XMEMCPY(name->encoded + idx, sequence, seqSz);
  23701. idx += seqSz;
  23702. /* asn object id */
  23703. XMEMCPY(name->encoded + idx, firstLen, firstSz);
  23704. idx += firstSz;
  23705. switch (type) {
  23706. case ASN_EMAIL_NAME:
  23707. /* email joint id */
  23708. XMEMCPY(name->encoded + idx, attrEmailOid, sizeof(attrEmailOid));
  23709. idx += (int)sizeof(attrEmailOid);
  23710. name->encoded[idx++] = emailTag;
  23711. break;
  23712. case ASN_DOMAIN_COMPONENT:
  23713. XMEMCPY(name->encoded + idx, dcOid, sizeof(dcOid)-1);
  23714. idx += (int)sizeof(dcOid)-1;
  23715. /* id type */
  23716. name->encoded[idx++] = type;
  23717. /* str type */
  23718. name->encoded[idx++] = nameTag;
  23719. break;
  23720. case ASN_USER_ID:
  23721. XMEMCPY(name->encoded + idx, uidOid, sizeof(uidOid));
  23722. idx += (int)sizeof(uidOid);
  23723. /* str type */
  23724. name->encoded[idx++] = nameTag;
  23725. break;
  23726. #ifdef WOLFSSL_CUSTOM_OID
  23727. case ASN_CUSTOM_NAME:
  23728. XMEMCPY(name->encoded + idx, cname->custom.oid,
  23729. cname->custom.oidSz);
  23730. idx += cname->custom.oidSz;
  23731. /* str type */
  23732. name->encoded[idx++] = nameTag;
  23733. break;
  23734. #endif
  23735. default:
  23736. name->encoded[idx++] = 0x55;
  23737. name->encoded[idx++] = 0x04;
  23738. /* id type */
  23739. name->encoded[idx++] = type;
  23740. /* str type */
  23741. name->encoded[idx++] = nameTag;
  23742. }
  23743. /* second length */
  23744. XMEMCPY(name->encoded + idx, secondLen, secondSz);
  23745. idx += secondSz;
  23746. /* str value */
  23747. XMEMCPY(name->encoded + idx, nameStr, strLen);
  23748. idx += strLen;
  23749. name->type = type;
  23750. name->totalLen = idx;
  23751. name->used = 1;
  23752. return idx;
  23753. #else
  23754. DECL_ASNSETDATA(dataASN, rdnASN_Length);
  23755. ASNItem namesASN[rdnASN_Length];
  23756. byte dnOid[DN_OID_SZ] = { 0x55, 0x04, 0x00 };
  23757. int ret = 0;
  23758. int sz = 0;
  23759. const byte* oid;
  23760. int oidSz;
  23761. word32 nameSz;
  23762. /* Validate input parameters. */
  23763. if ((name == NULL) || (nameStr == NULL)) {
  23764. ret = BAD_FUNC_ARG;
  23765. }
  23766. CALLOC_ASNSETDATA(dataASN, rdnASN_Length, ret, NULL);
  23767. if (ret == 0) {
  23768. nameSz = (word32)XSTRLEN(nameStr);
  23769. /* Copy the RDN encoding template. ASN.1 tag for the name string is set
  23770. * based on type. */
  23771. XMEMCPY(namesASN, rdnASN, sizeof(namesASN));
  23772. /* Set OID and ASN.1 tag for name depending on type. */
  23773. switch (type) {
  23774. case ASN_EMAIL_NAME:
  23775. /* email OID different to standard types. */
  23776. oid = attrEmailOid;
  23777. oidSz = sizeof(attrEmailOid);
  23778. /* Use email specific type/tag. */
  23779. nameTag = emailTag;
  23780. break;
  23781. case ASN_DOMAIN_COMPONENT:
  23782. /* Domain component OID different to standard types. */
  23783. oid = dcOid;
  23784. oidSz = sizeof(dcOid);
  23785. break;
  23786. case ASN_USER_ID:
  23787. /* Domain component OID different to standard types. */
  23788. oid = uidOid;
  23789. oidSz = sizeof(uidOid);
  23790. break;
  23791. #ifdef WOLFSSL_CUSTOM_OID
  23792. case ASN_CUSTOM_NAME:
  23793. nameSz = cname->custom.valSz;
  23794. oid = cname->custom.oid;
  23795. oidSz = cname->custom.oidSz;
  23796. break;
  23797. #endif
  23798. default:
  23799. /* Construct OID using type. */
  23800. dnOid[2] = type;
  23801. oid = dnOid;
  23802. oidSz = DN_OID_SZ;
  23803. break;
  23804. }
  23805. /* Set OID corresponding to the name type. */
  23806. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
  23807. /* Set name string. */
  23808. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], (const byte *)nameStr, nameSz);
  23809. /* Set the ASN.1 tag for the name string. */
  23810. namesASN[RDNASN_IDX_ATTR_VAL].tag = nameTag;
  23811. /* Calculate size of encoded name and indexes of components. */
  23812. ret = SizeASN_Items(namesASN, dataASN, rdnASN_Length, &sz);
  23813. }
  23814. /* Check if name's buffer is big enough. */
  23815. if ((ret == 0) && (sz > (int)sizeof(name->encoded))) {
  23816. ret = BUFFER_E;
  23817. }
  23818. if (ret == 0) {
  23819. /* Encode name into the buffer. */
  23820. SetASN_Items(namesASN, dataASN, rdnASN_Length, name->encoded);
  23821. /* Cache the type and size, and set that it is used. */
  23822. name->type = type;
  23823. name->totalLen = sz;
  23824. name->used = 1;
  23825. /* Return size of encoding. */
  23826. ret = sz;
  23827. }
  23828. (void)cname;
  23829. FREE_ASNSETDATA(dataASN, NULL);
  23830. return ret;
  23831. #endif /* WOLFSSL_ASN_TEMPLATE */
  23832. }
  23833. /* canonical encoding one attribute of the name (issuer/subject)
  23834. * call EncodeName with CTC_UTF8 for email type
  23835. *
  23836. * name structure to hold result of encoding
  23837. * nameStr value to be encoded
  23838. * nameType type of encoding i.e CTC_UTF8
  23839. * type id of attribute i.e ASN_COMMON_NAME
  23840. *
  23841. * returns length on success
  23842. */
  23843. int wc_EncodeNameCanonical(EncodedName* name, const char* nameStr,
  23844. char nameType, byte type)
  23845. {
  23846. return EncodeName(name, nameStr, (byte)nameType, type,
  23847. ASN_UTF8STRING, NULL);
  23848. }
  23849. #endif /* WOLFSSL_CERT_GEN || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  23850. #ifdef WOLFSSL_CERT_GEN
  23851. /* Encodes one attribute of the name (issuer/subject)
  23852. * call we_EncodeName_ex with 0x16, IA5String for email type
  23853. * name structure to hold result of encoding
  23854. * nameStr value to be encoded
  23855. * nameType type of encoding i.e CTC_UTF8
  23856. * type id of attribute i.e ASN_COMMON_NAME
  23857. *
  23858. * returns length on success
  23859. */
  23860. int wc_EncodeName(EncodedName* name, const char* nameStr, char nameType,
  23861. byte type)
  23862. {
  23863. return EncodeName(name, nameStr, (byte)nameType, type,
  23864. ASN_IA5_STRING, NULL);
  23865. }
  23866. #ifdef WOLFSSL_ASN_TEMPLATE
  23867. static void SetRdnItems(ASNItem* namesASN, ASNSetData* dataASN, const byte* oid,
  23868. int oidSz, byte tag, const byte* data, int sz)
  23869. {
  23870. XMEMCPY(namesASN, rdnASN, sizeof(rdnASN));
  23871. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
  23872. namesASN[RDNASN_IDX_ATTR_VAL].tag = tag;
  23873. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], data, sz);
  23874. }
  23875. #ifdef WOLFSSL_MULTI_ATTRIB
  23876. static int FindMultiAttrib(CertName* name, int id, int* idx)
  23877. {
  23878. int i;
  23879. for (i = *idx + 1; i < CTC_MAX_ATTRIB; i++) {
  23880. if (name->name[i].sz > 0 && name->name[i].id == id) {
  23881. break;
  23882. }
  23883. }
  23884. if (i == CTC_MAX_ATTRIB) {
  23885. i = -1;
  23886. }
  23887. *idx = i;
  23888. return i >= 0;
  23889. }
  23890. #endif
  23891. /* ASN.1 template for the SEQUENCE around the RDNs.
  23892. * X.509: RFC 5280, 4.1.2.4 - RDNSequence
  23893. */
  23894. static const ASNItem nameASN[] = {
  23895. { 0, ASN_SEQUENCE, 1, 1, 0 },
  23896. };
  23897. enum {
  23898. NAMEASN_IDX_SEQ = 0,
  23899. };
  23900. /* Number of items in ASN.1 template for the SEQUENCE around the RDNs. */
  23901. #define nameASN_Length (sizeof(nameASN) / sizeof(ASNItem))
  23902. static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN,
  23903. int maxIdx, CertName* name)
  23904. {
  23905. int i;
  23906. int idx;
  23907. int ret = 0;
  23908. int nameLen[NAME_ENTRIES];
  23909. #ifdef WOLFSSL_MULTI_ATTRIB
  23910. int j;
  23911. #endif
  23912. for (i = 0; i < NAME_ENTRIES; i++) {
  23913. /* Keep name length to identify component is to be encoded. */
  23914. const char* nameStr = GetOneCertName(name, i);
  23915. nameLen[i] = nameStr ? (int)XSTRLEN(nameStr) : 0;
  23916. }
  23917. idx = nameASN_Length;
  23918. for (i = 0; i < NAME_ENTRIES; i++) {
  23919. int type = GetCertNameId(i);
  23920. #ifdef WOLFSSL_MULTI_ATTRIB
  23921. j = -1;
  23922. /* Put DomainComponents before OrgUnitName. */
  23923. while (FindMultiAttrib(name, type, &j)) {
  23924. if (dataASN != NULL && namesASN != NULL) {
  23925. if (idx > maxIdx - (int)rdnASN_Length) {
  23926. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  23927. ret = BUFFER_E;
  23928. break;
  23929. }
  23930. /* Copy data into dynamic vars. */
  23931. SetRdnItems(namesASN + idx, dataASN + idx, dcOid,
  23932. sizeof(dcOid), name->name[j].type,
  23933. (byte*)name->name[j].value, name->name[j].sz);
  23934. }
  23935. idx += rdnASN_Length;
  23936. }
  23937. if (ret != 0)
  23938. break;
  23939. #endif
  23940. if (nameLen[i] > 0) {
  23941. if (dataASN != NULL) {
  23942. if (idx > maxIdx - (int)rdnASN_Length) {
  23943. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  23944. ret = BUFFER_E;
  23945. break;
  23946. }
  23947. /* Write out first instance of attribute type. */
  23948. if (type == ASN_EMAIL_NAME) {
  23949. /* Copy email data into dynamic vars. */
  23950. SetRdnItems(namesASN + idx, dataASN + idx, attrEmailOid,
  23951. sizeof(attrEmailOid), ASN_IA5_STRING,
  23952. (const byte*)GetOneCertName(name, i), nameLen[i]);
  23953. }
  23954. else if (type == ASN_USER_ID) {
  23955. /* Copy userID data into dynamic vars. */
  23956. SetRdnItems(namesASN + idx, dataASN + idx, uidOid,
  23957. sizeof(uidOid), GetNameType(name, i),
  23958. (const byte*)GetOneCertName(name, i), nameLen[i]);
  23959. }
  23960. else if (type == ASN_CUSTOM_NAME) {
  23961. #ifdef WOLFSSL_CUSTOM_OID
  23962. SetRdnItems(namesASN + idx, dataASN + idx, name->custom.oid,
  23963. name->custom.oidSz, name->custom.enc,
  23964. name->custom.val, name->custom.valSz);
  23965. #endif
  23966. }
  23967. else {
  23968. /* Copy name data into dynamic vars. */
  23969. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
  23970. NAME_OID_SZ, GetNameType(name, i),
  23971. (const byte*)GetOneCertName(name, i), nameLen[i]);
  23972. }
  23973. }
  23974. idx += rdnASN_Length;
  23975. }
  23976. #ifdef WOLFSSL_MULTI_ATTRIB
  23977. j = -1;
  23978. /* Write all other attributes of this type. */
  23979. while (FindMultiAttrib(name, type, &j)) {
  23980. if (dataASN != NULL && namesASN != NULL) {
  23981. if (idx > maxIdx - (int)rdnASN_Length) {
  23982. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  23983. ret = BUFFER_E;
  23984. break;
  23985. }
  23986. /* Copy data into dynamic vars. */
  23987. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
  23988. NAME_OID_SZ, name->name[j].type,
  23989. (byte*)name->name[j].value, name->name[j].sz);
  23990. }
  23991. idx += rdnASN_Length;
  23992. }
  23993. if (ret != 0)
  23994. break;
  23995. #endif
  23996. }
  23997. if (ret == 0)
  23998. ret = idx;
  23999. return ret;
  24000. }
  24001. #endif
  24002. /* encode CertName into output, return total bytes written */
  24003. int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap)
  24004. {
  24005. #ifndef WOLFSSL_ASN_TEMPLATE
  24006. int ret;
  24007. int totalBytes = 0, i, idx;
  24008. #ifdef WOLFSSL_SMALL_STACK
  24009. EncodedName* names = NULL;
  24010. #else
  24011. EncodedName names[NAME_ENTRIES];
  24012. #endif
  24013. #ifdef WOLFSSL_MULTI_ATTRIB
  24014. EncodedName addNames[CTC_MAX_ATTRIB];
  24015. int j, type;
  24016. #endif
  24017. if (output == NULL || name == NULL)
  24018. return BAD_FUNC_ARG;
  24019. if (outputSz < 3)
  24020. return BUFFER_E;
  24021. #ifdef WOLFSSL_SMALL_STACK
  24022. names = (EncodedName*)XMALLOC(sizeof(EncodedName) * NAME_ENTRIES, NULL,
  24023. DYNAMIC_TYPE_TMP_BUFFER);
  24024. if (names == NULL)
  24025. return MEMORY_E;
  24026. #endif
  24027. for (i = 0; i < NAME_ENTRIES; i++) {
  24028. const char* nameStr = GetOneCertName(name, i);
  24029. ret = EncodeName(&names[i], nameStr, GetNameType(name, i),
  24030. GetCertNameId(i), ASN_IA5_STRING, name);
  24031. if (ret < 0) {
  24032. #ifdef WOLFSSL_SMALL_STACK
  24033. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24034. #endif
  24035. WOLFSSL_MSG("EncodeName failed");
  24036. return BUFFER_E;
  24037. }
  24038. totalBytes += ret;
  24039. }
  24040. #ifdef WOLFSSL_MULTI_ATTRIB
  24041. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  24042. if (name->name[i].sz > 0) {
  24043. ret = EncodeName(&addNames[i], name->name[i].value,
  24044. (byte)name->name[i].type, name->name[i].id,
  24045. ASN_IA5_STRING, NULL);
  24046. if (ret < 0) {
  24047. #ifdef WOLFSSL_SMALL_STACK
  24048. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24049. #endif
  24050. WOLFSSL_MSG("EncodeName on multiple attributes failed");
  24051. return BUFFER_E;
  24052. }
  24053. totalBytes += ret;
  24054. }
  24055. else {
  24056. addNames[i].used = 0;
  24057. }
  24058. }
  24059. #endif /* WOLFSSL_MULTI_ATTRIB */
  24060. /* header */
  24061. idx = SetSequence(totalBytes, output);
  24062. totalBytes += idx;
  24063. if (totalBytes > WC_ASN_NAME_MAX) {
  24064. #ifdef WOLFSSL_SMALL_STACK
  24065. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24066. #endif
  24067. WOLFSSL_MSG("Total Bytes is greater than WC_ASN_NAME_MAX");
  24068. return BUFFER_E;
  24069. }
  24070. for (i = 0; i < NAME_ENTRIES; i++) {
  24071. #ifdef WOLFSSL_MULTI_ATTRIB
  24072. type = GetCertNameId(i);
  24073. for (j = 0; j < CTC_MAX_ATTRIB; j++) {
  24074. if (name->name[j].sz > 0 && type == name->name[j].id) {
  24075. if (outputSz < (word32)(idx+addNames[j].totalLen)) {
  24076. #ifdef WOLFSSL_SMALL_STACK
  24077. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24078. #endif
  24079. WOLFSSL_MSG("Not enough space left for DC value");
  24080. return BUFFER_E;
  24081. }
  24082. XMEMCPY(output + idx, addNames[j].encoded,
  24083. addNames[j].totalLen);
  24084. idx += addNames[j].totalLen;
  24085. }
  24086. }
  24087. #endif /* WOLFSSL_MULTI_ATTRIB */
  24088. if (names[i].used) {
  24089. if (outputSz < (word32)(idx+names[i].totalLen)) {
  24090. #ifdef WOLFSSL_SMALL_STACK
  24091. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24092. #endif
  24093. return BUFFER_E;
  24094. }
  24095. XMEMCPY(output + idx, names[i].encoded, names[i].totalLen);
  24096. idx += names[i].totalLen;
  24097. }
  24098. }
  24099. #ifdef WOLFSSL_SMALL_STACK
  24100. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24101. #endif
  24102. (void)heap;
  24103. return totalBytes;
  24104. #else
  24105. /* TODO: consider calculating size of entries, putting length into
  24106. * SEQUENCE, encode SEQUENCE, encode entries into buffer. */
  24107. ASNSetData* dataASN = NULL; /* Can't use DECL_ASNSETDATA. Always dynamic. */
  24108. ASNItem* namesASN = NULL;
  24109. int items = 0;
  24110. int ret = 0;
  24111. int sz = 0;
  24112. /* Calculate length of name entries and size for allocating. */
  24113. ret = SetNameRdnItems(NULL, NULL, 0, name);
  24114. if (ret > 0) {
  24115. items = ret;
  24116. ret = 0;
  24117. }
  24118. /* Allocate dynamic data items. */
  24119. dataASN = (ASNSetData*)XMALLOC(items * sizeof(ASNSetData), heap,
  24120. DYNAMIC_TYPE_TMP_BUFFER);
  24121. if (dataASN == NULL) {
  24122. ret = MEMORY_E;
  24123. }
  24124. else {
  24125. /* Allocate dynamic ASN.1 template items. */
  24126. namesASN = (ASNItem*)XMALLOC(items * sizeof(ASNItem), heap,
  24127. DYNAMIC_TYPE_TMP_BUFFER);
  24128. if (namesASN == NULL) {
  24129. ret = MEMORY_E;
  24130. }
  24131. }
  24132. if (ret == 0) {
  24133. /* Clear the dynamic data. */
  24134. XMEMSET(dataASN, 0, items * sizeof(ASNSetData));
  24135. /* Copy in the outer sequence. */
  24136. XMEMCPY(namesASN, nameASN, sizeof(nameASN));
  24137. ret = SetNameRdnItems(dataASN, namesASN, items, name);
  24138. if (ret == items)
  24139. ret = 0;
  24140. else if (ret > 0) {
  24141. WOLFSSL_MSG("SetNameRdnItems returned different length");
  24142. ret = BUFFER_E;
  24143. }
  24144. }
  24145. if (ret == 0) {
  24146. /* Calculate size of encoding. */
  24147. ret = SizeASN_Items(namesASN, dataASN, items, &sz);
  24148. }
  24149. /* Check buffer size if passed in. */
  24150. if (ret == 0 && output != NULL && sz > (int)outputSz) {
  24151. ret = BUFFER_E;
  24152. }
  24153. if (ret == 0) {
  24154. if (output != NULL) {
  24155. /* Encode Name. */
  24156. ret = SetASN_Items(namesASN, dataASN, items, output);
  24157. }
  24158. else {
  24159. /* Return the encoding size. */
  24160. ret = sz;
  24161. }
  24162. }
  24163. if (namesASN != NULL)
  24164. XFREE(namesASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24165. if (dataASN != NULL)
  24166. XFREE(dataASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24167. (void)heap;
  24168. return ret;
  24169. #endif
  24170. }
  24171. int SetName(byte* output, word32 outputSz, CertName* name)
  24172. {
  24173. return SetNameEx(output, outputSz, name, NULL);
  24174. }
  24175. #ifdef WOLFSSL_ASN_TEMPLATE
  24176. static int EncodePublicKey(int keyType, byte* output, int outLen,
  24177. RsaKey* rsaKey, ecc_key* eccKey,
  24178. ed25519_key* ed25519Key, ed448_key* ed448Key,
  24179. DsaKey* dsaKey)
  24180. {
  24181. int ret = 0;
  24182. (void)outLen;
  24183. (void)rsaKey;
  24184. (void)eccKey;
  24185. (void)ed25519Key;
  24186. (void)ed448Key;
  24187. (void)dsaKey;
  24188. switch (keyType) {
  24189. #ifndef NO_RSA
  24190. case RSA_KEY:
  24191. ret = SetRsaPublicKey(output, rsaKey, outLen, 1);
  24192. if (ret <= 0) {
  24193. ret = PUBLIC_KEY_E;
  24194. }
  24195. break;
  24196. #endif
  24197. #ifdef HAVE_ECC
  24198. case ECC_KEY:
  24199. ret = SetEccPublicKey(output, eccKey, outLen, 1, 0);
  24200. if (ret <= 0) {
  24201. ret = PUBLIC_KEY_E;
  24202. }
  24203. break;
  24204. #endif /* HAVE_ECC */
  24205. #ifdef HAVE_ED25519
  24206. case ED25519_KEY:
  24207. ret = wc_Ed25519PublicKeyToDer(ed25519Key, output, outLen, 1);
  24208. if (ret <= 0) {
  24209. ret = PUBLIC_KEY_E;
  24210. }
  24211. break;
  24212. #endif
  24213. #ifdef HAVE_ED448
  24214. case ED448_KEY:
  24215. ret = wc_Ed448PublicKeyToDer(ed448Key, output, outLen, 1);
  24216. if (ret <= 0) {
  24217. ret = PUBLIC_KEY_E;
  24218. }
  24219. break;
  24220. #endif
  24221. default:
  24222. ret = PUBLIC_KEY_E;
  24223. break;
  24224. }
  24225. return ret;
  24226. }
  24227. /* ASN.1 template for certificate extensions.
  24228. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  24229. * All extensions supported for encoding are described.
  24230. */
  24231. static const ASNItem static_certExtsASN[] = {
  24232. /* Basic Constraints Extension - 4.2.1.9 */
  24233. /* BC_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24234. /* BC_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24235. /* BC_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24236. /* BC_STR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  24237. /* cA */
  24238. /* BC_CA */ { 3, ASN_BOOLEAN, 0, 0, 0 },
  24239. /* pathLenConstraint */
  24240. /* BC_PATHLEN */ { 3, ASN_INTEGER, 0, 0, 1 },
  24241. /* Subject Alternative Name - 4.2.1.6 */
  24242. /* SAN_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24243. /* SAN_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24244. /* SAN_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24245. /* SAN_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24246. /* Subject Key Identifier - 4.2.1.2 */
  24247. /* SKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24248. /* SKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24249. /* SKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24250. /* SKID_KEYID */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  24251. /* Authority Key Identifier - 4.2.1.1 */
  24252. /* AKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24253. /* AKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24254. /* AKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24255. /* AKID_STR_SEQ, */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  24256. /* AKID_KEYID */ { 3, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  24257. /* Key Usage - 4.2.1.3 */
  24258. /* KU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24259. /* KU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24260. /* KU_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24261. /* KU_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24262. /* KU_USAGE */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  24263. /* Extended Key Usage - 4,2,1,12 */
  24264. /* EKU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24265. /* EKU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24266. /* EKU_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24267. /* Certificate Policies - 4.2.1.4 */
  24268. /* POLICIES_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24269. /* POLICIES_OID, */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24270. /* POLICIES_STR, */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24271. /* POLICIES_INFO */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  24272. /* Netscape Certificate Type */
  24273. /* NSTYPE_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24274. /* NSTYPE_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24275. /* NSTYPE_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24276. /* NSTYPE_USAGE, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  24277. /* CRLINFO_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24278. /* CRLINFO_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24279. /* CRLINFO_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24280. /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24281. /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24282. /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24283. };
  24284. enum {
  24285. CERTEXTSASN_IDX_BC_SEQ = 0,
  24286. CERTEXTSASN_IDX_BC_OID,
  24287. CERTEXTSASN_IDX_BC_STR,
  24288. CERTEXTSASN_IDX_BC_STR_SEQ,
  24289. CERTEXTSASN_IDX_BC_CA,
  24290. CERTEXTSASN_IDX_BC_PATHLEN,
  24291. CERTEXTSASN_IDX_SAN_SEQ,
  24292. CERTEXTSASN_IDX_SAN_OID,
  24293. CERTEXTSASN_IDX_SAN_CRIT,
  24294. CERTEXTSASN_IDX_SAN_STR,
  24295. CERTEXTSASN_IDX_SKID_SEQ,
  24296. CERTEXTSASN_IDX_SKID_OID,
  24297. CERTEXTSASN_IDX_SKID_STR,
  24298. CERTEXTSASN_IDX_SKID_KEYID,
  24299. CERTEXTSASN_IDX_AKID_SEQ,
  24300. CERTEXTSASN_IDX_AKID_OID,
  24301. CERTEXTSASN_IDX_AKID_STR,
  24302. CERTEXTSASN_IDX_AKID_STR_SEQ,
  24303. CERTEXTSASN_IDX_AKID_KEYID,
  24304. CERTEXTSASN_IDX_KU_SEQ,
  24305. CERTEXTSASN_IDX_KU_OID,
  24306. CERTEXTSASN_IDX_KU_CRIT,
  24307. CERTEXTSASN_IDX_KU_STR,
  24308. CERTEXTSASN_IDX_KU_USAGE,
  24309. CERTEXTSASN_IDX_EKU_SEQ,
  24310. CERTEXTSASN_IDX_EKU_OID,
  24311. CERTEXTSASN_IDX_EKU_STR,
  24312. CERTEXTSASN_IDX_POLICIES_SEQ,
  24313. CERTEXTSASN_IDX_POLICIES_OID,
  24314. CERTEXTSASN_IDX_POLICIES_STR,
  24315. CERTEXTSASN_IDX_POLICIES_INFO,
  24316. CERTEXTSASN_IDX_NSTYPE_SEQ,
  24317. CERTEXTSASN_IDX_NSTYPE_OID,
  24318. CERTEXTSASN_IDX_NSTYPE_STR,
  24319. CERTEXTSASN_IDX_NSTYPE_USAGE,
  24320. CERTEXTSASN_IDX_CRLINFO_SEQ,
  24321. CERTEXTSASN_IDX_CRLINFO_OID,
  24322. CERTEXTSASN_IDX_CRLINFO_STR,
  24323. CERTEXTSASN_IDX_CUSTOM_SEQ,
  24324. CERTEXTSASN_IDX_CUSTOM_OID,
  24325. CERTEXTSASN_IDX_CUSTOM_STR,
  24326. CERTEXTSASN_IDX_START_CUSTOM,
  24327. };
  24328. /* Number of items in ASN.1 template for certificate extensions. We multiply
  24329. * by 4 because there are 4 things (seq, OID, crit flag, octet string). */
  24330. #define certExtsASN_Length ((sizeof(static_certExtsASN) / sizeof(ASNItem)) \
  24331. + (NUM_CUSTOM_EXT * 4))
  24332. static const ASNItem customExtASN[] = {
  24333. /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24334. /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24335. /* CUSTOM_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24336. /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24337. };
  24338. static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz,
  24339. int forRequest)
  24340. {
  24341. DECL_ASNSETDATA(dataASN, certExtsASN_Length);
  24342. int sz;
  24343. int ret = 0;
  24344. int i = 0;
  24345. static const byte bcOID[] = { 0x55, 0x1d, 0x13 };
  24346. #ifdef WOLFSSL_ALT_NAMES
  24347. static const byte sanOID[] = { 0x55, 0x1d, 0x11 };
  24348. #endif
  24349. #ifdef WOLFSSL_CERT_EXT
  24350. static const byte skidOID[] = { 0x55, 0x1d, 0x0e };
  24351. static const byte akidOID[] = { 0x55, 0x1d, 0x23 };
  24352. static const byte kuOID[] = { 0x55, 0x1d, 0x0f };
  24353. static const byte ekuOID[] = { 0x55, 0x1d, 0x25 };
  24354. static const byte cpOID[] = { 0x55, 0x1d, 0x20 };
  24355. static const byte nsCertOID[] = { 0x60, 0x86, 0x48, 0x01,
  24356. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  24357. static const byte crlInfoOID[] = { 0x55, 0x1D, 0x1F };
  24358. #endif
  24359. #ifdef WOLFSSL_SMALL_STACK
  24360. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24361. byte *encodedOids;
  24362. #endif
  24363. ASNItem *certExtsASN = (ASNItem *)XMALLOC(certExtsASN_Length *
  24364. sizeof(ASNItem), cert->heap,
  24365. DYNAMIC_TYPE_TMP_BUFFER);
  24366. if (certExtsASN == NULL) {
  24367. return MEMORY_E;
  24368. }
  24369. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24370. encodedOids = (byte *)XMALLOC(NUM_CUSTOM_EXT * MAX_OID_SZ, cert->heap,
  24371. DYNAMIC_TYPE_TMP_BUFFER);
  24372. if (encodedOids == NULL) {
  24373. XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24374. return MEMORY_E;
  24375. }
  24376. #endif
  24377. #else
  24378. ASNItem certExtsASN[certExtsASN_Length];
  24379. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24380. byte encodedOids[NUM_CUSTOM_EXT * MAX_OID_SZ];
  24381. #endif
  24382. #endif
  24383. /* Clone static_certExtsASN into a certExtsASN and then fill the rest of it
  24384. * with (NUM_CUSTOM_EXT*4) more ASNItems specifying extensions. See comment
  24385. * above definition of certExtsASN_Length. */
  24386. XMEMCPY(certExtsASN, static_certExtsASN, sizeof(static_certExtsASN));
  24387. for (i = sizeof(static_certExtsASN) / sizeof(ASNItem);
  24388. i < (int)certExtsASN_Length; i += 4) {
  24389. XMEMCPY(&certExtsASN[i], customExtASN, sizeof(customExtASN));
  24390. }
  24391. (void)forRequest;
  24392. CALLOC_ASNSETDATA(dataASN, certExtsASN_Length, ret, cert->heap);
  24393. if (ret == 0) {
  24394. if (cert->isCA) {
  24395. /* Set Basic Constraints to be a Certificate Authority. */
  24396. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_BC_CA], 1);
  24397. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
  24398. if (cert->pathLenSet
  24399. #ifdef WOLFSSL_CERT_EXT
  24400. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  24401. #endif
  24402. ) {
  24403. SetASN_Int8Bit(&dataASN[CERTEXTSASN_IDX_BC_PATHLEN],
  24404. cert->pathLen);
  24405. }
  24406. else {
  24407. dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
  24408. }
  24409. }
  24410. else if (cert->basicConstSet) {
  24411. /* Set Basic Constraints to be a non Certificate Authority. */
  24412. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
  24413. dataASN[CERTEXTSASN_IDX_BC_CA].noOut = 1;
  24414. dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
  24415. }
  24416. else {
  24417. /* Don't write out Basic Constraints extension items. */
  24418. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_BC_SEQ,
  24419. CERTEXTSASN_IDX_BC_PATHLEN);
  24420. }
  24421. #ifdef WOLFSSL_ALT_NAMES
  24422. if (!forRequest && cert->altNamesSz > 0) {
  24423. /* Set Subject Alternative Name OID and data. */
  24424. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_OID],
  24425. sanOID, sizeof(sanOID));
  24426. if (cert->altNamesCrit) {
  24427. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_SAN_CRIT], 1);
  24428. }
  24429. else {
  24430. dataASN[CERTEXTSASN_IDX_SAN_CRIT].noOut = 1;
  24431. }
  24432. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_STR],
  24433. cert->altNames, cert->altNamesSz);
  24434. }
  24435. else
  24436. #endif
  24437. {
  24438. /* Don't write out Subject Alternative Name extension items. */
  24439. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SAN_SEQ,
  24440. CERTEXTSASN_IDX_SAN_STR);
  24441. }
  24442. #ifdef WOLFSSL_CERT_EXT
  24443. if (cert->skidSz > 0) {
  24444. /* Set Subject Key Identifier OID and data. */
  24445. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_OID],
  24446. skidOID, sizeof(skidOID));
  24447. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_KEYID],
  24448. cert->skid, cert->skidSz);
  24449. }
  24450. else
  24451. #endif
  24452. {
  24453. /* Don't write out Subject Key Identifier extension items. */
  24454. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SKID_SEQ,
  24455. CERTEXTSASN_IDX_SKID_KEYID);
  24456. }
  24457. #ifdef WOLFSSL_CERT_EXT
  24458. if (cert->akidSz > 0) {
  24459. /* Set Authority Key Identifier OID and data. */
  24460. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_OID],
  24461. akidOID, sizeof(akidOID));
  24462. #ifdef WOLFSSL_AKID_NAME
  24463. if (cert->rawAkid) {
  24464. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_STR],
  24465. cert->akid, cert->akidSz);
  24466. /* cert->akid contains the internal ext structure */
  24467. SetASNItem_NoOutBelow(dataASN, certExtsASN,
  24468. CERTEXTSASN_IDX_AKID_STR, certExtsASN_Length);
  24469. }
  24470. else
  24471. #endif
  24472. {
  24473. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_KEYID],
  24474. cert->akid, cert->akidSz);
  24475. }
  24476. }
  24477. else
  24478. #endif
  24479. {
  24480. /* Don't write out Authority Key Identifier extension items. */
  24481. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_AKID_SEQ,
  24482. CERTEXTSASN_IDX_AKID_KEYID);
  24483. }
  24484. #ifdef WOLFSSL_CERT_EXT
  24485. if (cert->keyUsage != 0) {
  24486. /* Set Key Usage OID, critical and value. */
  24487. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_KU_OID],
  24488. kuOID, sizeof(kuOID));
  24489. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_KU_CRIT], 1);
  24490. SetASN_Int16Bit(&dataASN[CERTEXTSASN_IDX_KU_USAGE],
  24491. cert->keyUsage);
  24492. }
  24493. else
  24494. #endif
  24495. {
  24496. /* Don't write out Key Usage extension items. */
  24497. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_KU_SEQ,
  24498. CERTEXTSASN_IDX_KU_USAGE);
  24499. }
  24500. #ifdef WOLFSSL_CERT_EXT
  24501. if (cert->extKeyUsage != 0) {
  24502. /* Calculate size of Extended Key Usage data. */
  24503. sz = SetExtKeyUsage(cert, NULL, 0, cert->extKeyUsage);
  24504. if (sz <= 0) {
  24505. ret = KEYUSAGE_E;
  24506. }
  24507. /* Set Extended Key Usage OID and data. */
  24508. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_OID],
  24509. ekuOID, sizeof(ekuOID));
  24510. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_STR],
  24511. NULL, sz);
  24512. }
  24513. else
  24514. #endif
  24515. {
  24516. /* Don't write out Extended Key Usage extension items. */
  24517. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_EKU_SEQ,
  24518. CERTEXTSASN_IDX_EKU_STR);
  24519. }
  24520. #ifdef WOLFSSL_CERT_EXT
  24521. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  24522. /* Calculate size of certificate policies. */
  24523. sz = SetCertificatePolicies(NULL, 0, cert->certPolicies,
  24524. cert->certPoliciesNb, cert->heap);
  24525. if (sz > 0) {
  24526. /* Set Certificate Policies OID. */
  24527. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_OID],
  24528. cpOID, sizeof(cpOID));
  24529. /* Make space for data. */
  24530. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_INFO],
  24531. NULL, sz);
  24532. }
  24533. else {
  24534. ret = CERTPOLICIES_E;
  24535. }
  24536. }
  24537. else
  24538. #endif
  24539. {
  24540. /* Don't write out Certificate Policies extension items. */
  24541. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_POLICIES_SEQ,
  24542. CERTEXTSASN_IDX_POLICIES_INFO);
  24543. }
  24544. #if defined(WOLFSSL_CERT_EXT) && !defined(IGNORE_NETSCAPE_CERT_TYPE)
  24545. /* Netscape Certificate Type */
  24546. if (cert->nsCertType != 0) {
  24547. /* Set Netscape Certificate Type OID and data. */
  24548. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_OID],
  24549. nsCertOID, sizeof(nsCertOID));
  24550. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_USAGE],
  24551. &cert->nsCertType, 1);
  24552. }
  24553. else
  24554. #endif
  24555. {
  24556. /* Don't write out Netscape Certificate Type. */
  24557. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_NSTYPE_SEQ,
  24558. CERTEXTSASN_IDX_NSTYPE_USAGE);
  24559. }
  24560. #ifdef WOLFSSL_CERT_EXT
  24561. if (cert->crlInfoSz > 0) {
  24562. /* Set CRL Distribution Points OID and data. */
  24563. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_OID],
  24564. crlInfoOID, sizeof(crlInfoOID));
  24565. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_STR],
  24566. cert->crlInfo, cert->crlInfoSz);
  24567. }
  24568. else
  24569. #endif
  24570. {
  24571. /* Don't write out CRL Distribution Points. */
  24572. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CRLINFO_SEQ,
  24573. CERTEXTSASN_IDX_CRLINFO_STR);
  24574. }
  24575. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
  24576. /* encode a custom oid and value */
  24577. if (cert->extCustom.oidSz > 0) {
  24578. /* Set CRL Distribution Points OID and data. */
  24579. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_OID],
  24580. cert->extCustom.oid, cert->extCustom.oidSz);
  24581. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_STR],
  24582. cert->extCustom.val, cert->extCustom.valSz);
  24583. }
  24584. else
  24585. #endif
  24586. {
  24587. /* Don't write out custom OID. */
  24588. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CUSTOM_SEQ,
  24589. CERTEXTSASN_IDX_CUSTOM_STR);
  24590. }
  24591. i = 0;
  24592. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
  24593. for (; i < cert->customCertExtCount; i++) {
  24594. int idx = CERTEXTSASN_IDX_START_CUSTOM + (i * 4);
  24595. word32 encodedOidSz = MAX_OID_SZ;
  24596. idx++; /* Skip one for for SEQ. */
  24597. /* EncodePolicyOID() will never return error since we parsed this
  24598. * OID when it was set. */
  24599. EncodePolicyOID(&encodedOids[i * MAX_OID_SZ], &encodedOidSz,
  24600. cert->customCertExt[i].oid, NULL);
  24601. SetASN_Buffer(&dataASN[idx], &encodedOids[i * MAX_OID_SZ],
  24602. encodedOidSz);
  24603. idx++;
  24604. if (cert->customCertExt[i].crit) {
  24605. SetASN_Boolean(&dataASN[idx], 1);
  24606. } else {
  24607. dataASN[idx].noOut = 1;
  24608. }
  24609. idx++;
  24610. SetASN_Buffer(&dataASN[idx], cert->customCertExt[i].val,
  24611. cert->customCertExt[i].valSz);
  24612. }
  24613. #endif
  24614. while (i < NUM_CUSTOM_EXT) {
  24615. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_START_CUSTOM + (i * 4),
  24616. CERTEXTSASN_IDX_START_CUSTOM + (i * 4) + 3);
  24617. i++;
  24618. }
  24619. }
  24620. if (ret == 0) {
  24621. /* Calculate size of encoded extensions. */
  24622. ret = SizeASN_Items(certExtsASN, dataASN, certExtsASN_Length, &sz);
  24623. }
  24624. if (ret == 0) {
  24625. /* Only SEQUENCE - don't encode extensions. */
  24626. if (sz == 2) {
  24627. sz = 0;
  24628. }
  24629. /* Check buffer is big enough. */
  24630. else if ((output != NULL) && (sz > (int)maxSz)) {
  24631. ret = BUFFER_E;
  24632. }
  24633. }
  24634. if ((ret == 0) && (output != NULL) && (sz > 0)) {
  24635. /* Encode certificate extensions into buffer. */
  24636. SetASN_Items(certExtsASN, dataASN, certExtsASN_Length, output);
  24637. #ifdef WOLFSSL_CERT_EXT
  24638. if (cert->extKeyUsage != 0){
  24639. /* Encode Extended Key Usage into space provided. */
  24640. if (SetExtKeyUsage(cert,
  24641. (byte*)dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.data,
  24642. dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.length,
  24643. cert->extKeyUsage) <= 0) {
  24644. ret = KEYUSAGE_E;
  24645. }
  24646. }
  24647. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  24648. /* Encode Certificate Policies into space provided. */
  24649. if (SetCertificatePolicies(
  24650. (byte*)dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.data,
  24651. dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.length,
  24652. cert->certPolicies, cert->certPoliciesNb, cert->heap) <= 0) {
  24653. ret = CERTPOLICIES_E;
  24654. }
  24655. }
  24656. #endif
  24657. }
  24658. if (ret == 0) {
  24659. /* Return the encoding size. */
  24660. ret = sz;
  24661. }
  24662. FREE_ASNSETDATA(dataASN, cert->heap);
  24663. #ifdef WOLFSSL_SMALL_STACK
  24664. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24665. XFREE(encodedOids, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24666. #endif
  24667. XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24668. #endif
  24669. return ret;
  24670. }
  24671. #endif /* WOLFSSL_ASN_TEMPLATE */
  24672. #ifndef WOLFSSL_ASN_TEMPLATE
  24673. /* Set Date validity from now until now + daysValid
  24674. * return size in bytes written to output, 0 on error */
  24675. /* TODO https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.5
  24676. * "MUST always encode certificate validity dates through the year 2049 as
  24677. * UTCTime; certificate validity dates in 2050 or later MUST be encoded as
  24678. * GeneralizedTime." */
  24679. static int SetValidity(byte* output, int daysValid)
  24680. {
  24681. #ifndef NO_ASN_TIME
  24682. byte before[MAX_DATE_SIZE];
  24683. byte after[MAX_DATE_SIZE];
  24684. int beforeSz;
  24685. int afterSz;
  24686. int seqSz;
  24687. time_t now;
  24688. time_t then;
  24689. struct tm* tmpTime;
  24690. struct tm* expandedTime;
  24691. struct tm localTime;
  24692. #if defined(NEED_TMP_TIME)
  24693. /* for use with gmtime_r */
  24694. struct tm tmpTimeStorage;
  24695. tmpTime = &tmpTimeStorage;
  24696. #else
  24697. tmpTime = NULL;
  24698. #endif
  24699. (void)tmpTime;
  24700. now = wc_Time(0);
  24701. /* before now */
  24702. before[0] = ASN_GENERALIZED_TIME;
  24703. beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
  24704. /* subtract 1 day of seconds for more compliance */
  24705. then = now - 86400;
  24706. expandedTime = XGMTIME(&then, tmpTime);
  24707. if (expandedTime == NULL) {
  24708. WOLFSSL_MSG("XGMTIME failed");
  24709. return 0; /* error */
  24710. }
  24711. localTime = *expandedTime;
  24712. /* adjust */
  24713. localTime.tm_year += 1900;
  24714. localTime.tm_mon += 1;
  24715. SetTime(&localTime, before + beforeSz);
  24716. beforeSz += ASN_GEN_TIME_SZ;
  24717. after[0] = ASN_GENERALIZED_TIME;
  24718. afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
  24719. /* add daysValid of seconds */
  24720. then = now + (daysValid * (time_t)86400);
  24721. expandedTime = XGMTIME(&then, tmpTime);
  24722. if (expandedTime == NULL) {
  24723. WOLFSSL_MSG("XGMTIME failed");
  24724. return 0; /* error */
  24725. }
  24726. localTime = *expandedTime;
  24727. /* adjust */
  24728. localTime.tm_year += 1900;
  24729. localTime.tm_mon += 1;
  24730. SetTime(&localTime, after + afterSz);
  24731. afterSz += ASN_GEN_TIME_SZ;
  24732. /* headers and output */
  24733. seqSz = SetSequence(beforeSz + afterSz, output);
  24734. XMEMCPY(output + seqSz, before, beforeSz);
  24735. XMEMCPY(output + seqSz + beforeSz, after, afterSz);
  24736. return seqSz + beforeSz + afterSz;
  24737. #else
  24738. (void)output;
  24739. (void)daysValid;
  24740. return NOT_COMPILED_IN;
  24741. #endif
  24742. }
  24743. #else
  24744. static int SetValidity(byte* before, byte* after, int daysValid)
  24745. {
  24746. int ret = 0;
  24747. time_t now;
  24748. time_t then;
  24749. struct tm* tmpTime;
  24750. struct tm* expandedTime;
  24751. struct tm localTime;
  24752. #if defined(NEED_TMP_TIME)
  24753. /* for use with gmtime_r */
  24754. struct tm tmpTimeStorage;
  24755. tmpTime = &tmpTimeStorage;
  24756. #else
  24757. tmpTime = NULL;
  24758. #endif
  24759. (void)tmpTime;
  24760. now = wc_Time(0);
  24761. /* subtract 1 day of seconds for more compliance */
  24762. then = now - 86400;
  24763. expandedTime = XGMTIME(&then, tmpTime);
  24764. if (expandedTime == NULL) {
  24765. WOLFSSL_MSG("XGMTIME failed");
  24766. ret = DATE_E;
  24767. }
  24768. if (ret == 0) {
  24769. localTime = *expandedTime;
  24770. /* adjust */
  24771. localTime.tm_year += 1900;
  24772. localTime.tm_mon += 1;
  24773. SetTime(&localTime, before);
  24774. /* add daysValid of seconds */
  24775. then = now + (daysValid * (time_t)86400);
  24776. expandedTime = XGMTIME(&then, tmpTime);
  24777. if (expandedTime == NULL) {
  24778. WOLFSSL_MSG("XGMTIME failed");
  24779. ret = DATE_E;
  24780. }
  24781. }
  24782. if (ret == 0) {
  24783. localTime = *expandedTime;
  24784. /* adjust */
  24785. localTime.tm_year += 1900;
  24786. localTime.tm_mon += 1;
  24787. SetTime(&localTime, after);
  24788. }
  24789. return ret;
  24790. }
  24791. #endif /* WOLFSSL_ASN_TEMPLATE */
  24792. #ifndef WOLFSSL_ASN_TEMPLATE
  24793. /* encode info from cert into DER encoded format */
  24794. static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey,
  24795. WC_RNG* rng, DsaKey* dsaKey, ed25519_key* ed25519Key,
  24796. ed448_key* ed448Key, falcon_key* falconKey,
  24797. dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
  24798. {
  24799. int ret;
  24800. if (cert == NULL || der == NULL || rng == NULL)
  24801. return BAD_FUNC_ARG;
  24802. /* make sure at least one key type is provided */
  24803. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  24804. dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
  24805. dilithiumKey == NULL && sphincsKey == NULL) {
  24806. return PUBLIC_KEY_E;
  24807. }
  24808. /* init */
  24809. XMEMSET(der, 0, sizeof(DerCert));
  24810. /* version */
  24811. der->versionSz = SetMyVersion(cert->version, der->version, TRUE);
  24812. /* serial number (must be positive) */
  24813. if (cert->serialSz == 0) {
  24814. /* generate random serial */
  24815. cert->serialSz = CTC_GEN_SERIAL_SZ;
  24816. ret = wc_RNG_GenerateBlock(rng, cert->serial, cert->serialSz);
  24817. if (ret != 0)
  24818. return ret;
  24819. /* Clear the top bit to avoid a negative value */
  24820. cert->serial[0] &= 0x7f;
  24821. }
  24822. der->serialSz = SetSerialNumber(cert->serial, cert->serialSz, der->serial,
  24823. sizeof(der->serial), CTC_SERIAL_SIZE);
  24824. if (der->serialSz < 0)
  24825. return der->serialSz;
  24826. /* signature algo */
  24827. der->sigAlgoSz = SetAlgoID(cert->sigType, der->sigAlgo, oidSigType, 0);
  24828. if (der->sigAlgoSz <= 0)
  24829. return ALGO_ID_E;
  24830. /* public key */
  24831. #ifndef NO_RSA
  24832. if (cert->keyType == RSA_KEY) {
  24833. if (rsaKey == NULL)
  24834. return PUBLIC_KEY_E;
  24835. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  24836. sizeof(der->publicKey), 1);
  24837. }
  24838. #endif
  24839. #ifdef HAVE_ECC
  24840. if (cert->keyType == ECC_KEY) {
  24841. if (eccKey == NULL)
  24842. return PUBLIC_KEY_E;
  24843. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  24844. sizeof(der->publicKey), 1, 0);
  24845. }
  24846. #endif
  24847. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  24848. if (cert->keyType == DSA_KEY) {
  24849. if (dsaKey == NULL)
  24850. return PUBLIC_KEY_E;
  24851. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  24852. sizeof(der->publicKey), 1);
  24853. }
  24854. #endif
  24855. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  24856. if (cert->keyType == ED25519_KEY) {
  24857. if (ed25519Key == NULL)
  24858. return PUBLIC_KEY_E;
  24859. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  24860. (word32)sizeof(der->publicKey), 1);
  24861. }
  24862. #endif
  24863. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  24864. if (cert->keyType == ED448_KEY) {
  24865. if (ed448Key == NULL)
  24866. return PUBLIC_KEY_E;
  24867. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  24868. (word32)sizeof(der->publicKey), 1);
  24869. }
  24870. #endif
  24871. #if defined(HAVE_PQC)
  24872. #if defined(HAVE_FALCON)
  24873. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  24874. (cert->keyType == FALCON_LEVEL5_KEY)) {
  24875. if (falconKey == NULL)
  24876. return PUBLIC_KEY_E;
  24877. der->publicKeySz =
  24878. wc_Falcon_PublicKeyToDer(falconKey, der->publicKey,
  24879. (word32)sizeof(der->publicKey), 1);
  24880. }
  24881. #endif /* HAVE_FALCON */
  24882. #if defined(HAVE_DILITHIUM)
  24883. if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
  24884. (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
  24885. (cert->keyType == DILITHIUM_LEVEL5_KEY) ||
  24886. (cert->keyType == DILITHIUM_AES_LEVEL2_KEY) ||
  24887. (cert->keyType == DILITHIUM_AES_LEVEL3_KEY) ||
  24888. (cert->keyType == DILITHIUM_AES_LEVEL5_KEY)) {
  24889. if (dilithiumKey == NULL)
  24890. return PUBLIC_KEY_E;
  24891. der->publicKeySz =
  24892. wc_Dilithium_PublicKeyToDer(dilithiumKey, der->publicKey,
  24893. (word32)sizeof(der->publicKey), 1);
  24894. }
  24895. #endif /* HAVE_DILITHIUM */
  24896. #if defined(HAVE_SPHINCS)
  24897. if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
  24898. (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
  24899. (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
  24900. (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
  24901. (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
  24902. (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
  24903. if (sphincsKey == NULL)
  24904. return PUBLIC_KEY_E;
  24905. der->publicKeySz =
  24906. wc_Sphincs_PublicKeyToDer(sphincsKey, der->publicKey,
  24907. (word32)sizeof(der->publicKey), 1);
  24908. }
  24909. #endif /* HAVE_SPHINCS */
  24910. #endif /* HAVE_PQC */
  24911. if (der->publicKeySz <= 0)
  24912. return PUBLIC_KEY_E;
  24913. der->validitySz = 0;
  24914. /* copy date validity if already set in cert struct */
  24915. if (cert->beforeDateSz && cert->afterDateSz) {
  24916. der->validitySz = CopyValidity(der->validity, cert);
  24917. if (der->validitySz <= 0)
  24918. return DATE_E;
  24919. }
  24920. /* set date validity using daysValid if not set already */
  24921. if (der->validitySz == 0) {
  24922. der->validitySz = SetValidity(der->validity, cert->daysValid);
  24923. if (der->validitySz <= 0)
  24924. return DATE_E;
  24925. }
  24926. /* subject name */
  24927. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  24928. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  24929. /* Use the raw subject */
  24930. int idx;
  24931. der->subjectSz = min(sizeof(der->subject),
  24932. (word32)XSTRLEN((const char*)cert->sbjRaw));
  24933. /* header */
  24934. idx = SetSequence(der->subjectSz, der->subject);
  24935. if (der->subjectSz + idx > (int)sizeof(der->subject)) {
  24936. return SUBJECT_E;
  24937. }
  24938. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  24939. der->subjectSz);
  24940. der->subjectSz += idx;
  24941. }
  24942. else
  24943. #endif
  24944. {
  24945. /* Use the name structure */
  24946. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  24947. &cert->subject, cert->heap);
  24948. }
  24949. if (der->subjectSz <= 0)
  24950. return SUBJECT_E;
  24951. /* issuer name */
  24952. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  24953. if (XSTRLEN((const char*)cert->issRaw) > 0) {
  24954. /* Use the raw issuer */
  24955. int idx;
  24956. der->issuerSz = min(sizeof(der->issuer),
  24957. (word32)XSTRLEN((const char*)cert->issRaw));
  24958. /* header */
  24959. idx = SetSequence(der->issuerSz, der->issuer);
  24960. if (der->issuerSz + idx > (int)sizeof(der->issuer)) {
  24961. return ISSUER_E;
  24962. }
  24963. XMEMCPY((char*)der->issuer + idx, (const char*)cert->issRaw,
  24964. der->issuerSz);
  24965. der->issuerSz += idx;
  24966. }
  24967. else
  24968. #endif
  24969. {
  24970. /* Use the name structure */
  24971. der->issuerSz = SetNameEx(der->issuer, sizeof(der->issuer),
  24972. cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
  24973. }
  24974. if (der->issuerSz <= 0)
  24975. return ISSUER_E;
  24976. /* set the extensions */
  24977. der->extensionsSz = 0;
  24978. /* RFC 5280 : 4.2.1.9. Basic Constraints
  24979. * The pathLenConstraint field is meaningful only if the CA boolean is
  24980. * asserted and the key usage extension, if present, asserts the
  24981. * keyCertSign bit */
  24982. /* Set CA and path length */
  24983. if ((cert->isCA) && (cert->pathLenSet)
  24984. #ifdef WOLFSSL_CERT_EXT
  24985. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  24986. #endif
  24987. ) {
  24988. der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
  24989. if (der->caSz <= 0)
  24990. return CA_TRUE_E;
  24991. der->extensionsSz += der->caSz;
  24992. }
  24993. /* Set CA */
  24994. else if (cert->isCA) {
  24995. der->caSz = SetCa(der->ca, sizeof(der->ca));
  24996. if (der->caSz <= 0)
  24997. return CA_TRUE_E;
  24998. der->extensionsSz += der->caSz;
  24999. }
  25000. /* Set Basic Constraint */
  25001. else if (cert->basicConstSet) {
  25002. der->caSz = SetBC(der->ca, sizeof(der->ca));
  25003. if (der->caSz <= 0)
  25004. return EXTENSIONS_E;
  25005. der->extensionsSz += der->caSz;
  25006. }
  25007. else
  25008. der->caSz = 0;
  25009. #ifdef WOLFSSL_ALT_NAMES
  25010. /* Alternative Name */
  25011. if (cert->altNamesSz) {
  25012. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  25013. cert->altNames, cert->altNamesSz,
  25014. cert->altNamesCrit);
  25015. if (der->altNamesSz <= 0)
  25016. return ALT_NAME_E;
  25017. der->extensionsSz += der->altNamesSz;
  25018. }
  25019. else
  25020. der->altNamesSz = 0;
  25021. #endif
  25022. #ifdef WOLFSSL_CERT_EXT
  25023. /* SKID */
  25024. if (cert->skidSz) {
  25025. /* check the provided SKID size */
  25026. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  25027. return SKID_E;
  25028. /* Note: different skid buffers sizes for der (MAX_KID_SZ) and
  25029. cert (CTC_MAX_SKID_SIZE). */
  25030. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  25031. cert->skid, cert->skidSz);
  25032. if (der->skidSz <= 0)
  25033. return SKID_E;
  25034. der->extensionsSz += der->skidSz;
  25035. }
  25036. else
  25037. der->skidSz = 0;
  25038. /* AKID */
  25039. if (cert->akidSz) {
  25040. /* check the provided AKID size */
  25041. if ((
  25042. #ifdef WOLFSSL_AKID_NAME
  25043. !cert->rawAkid &&
  25044. #endif
  25045. cert->akidSz > (int)min(CTC_MAX_AKID_SIZE, sizeof(der->akid)))
  25046. #ifdef WOLFSSL_AKID_NAME
  25047. || (cert->rawAkid && cert->akidSz > (int)sizeof(der->akid))
  25048. #endif
  25049. )
  25050. return AKID_E;
  25051. der->akidSz = SetAKID(der->akid, sizeof(der->akid), cert->akid,
  25052. cert->akidSz,
  25053. #ifdef WOLFSSL_AKID_NAME
  25054. cert->rawAkid
  25055. #else
  25056. 0
  25057. #endif
  25058. );
  25059. if (der->akidSz <= 0)
  25060. return AKID_E;
  25061. der->extensionsSz += der->akidSz;
  25062. }
  25063. else
  25064. der->akidSz = 0;
  25065. /* Key Usage */
  25066. if (cert->keyUsage != 0){
  25067. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  25068. cert->keyUsage);
  25069. if (der->keyUsageSz <= 0)
  25070. return KEYUSAGE_E;
  25071. der->extensionsSz += der->keyUsageSz;
  25072. }
  25073. else
  25074. der->keyUsageSz = 0;
  25075. /* Extended Key Usage */
  25076. if (cert->extKeyUsage != 0){
  25077. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  25078. sizeof(der->extKeyUsage), cert->extKeyUsage);
  25079. if (der->extKeyUsageSz <= 0)
  25080. return EXTKEYUSAGE_E;
  25081. der->extensionsSz += der->extKeyUsageSz;
  25082. }
  25083. else
  25084. der->extKeyUsageSz = 0;
  25085. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  25086. /* Netscape Certificate Type */
  25087. if (cert->nsCertType != 0) {
  25088. der->nsCertTypeSz = SetNsCertType(cert, der->nsCertType,
  25089. sizeof(der->nsCertType), cert->nsCertType);
  25090. if (der->nsCertTypeSz <= 0)
  25091. return EXTENSIONS_E;
  25092. der->extensionsSz += der->nsCertTypeSz;
  25093. }
  25094. else
  25095. der->nsCertTypeSz = 0;
  25096. #endif
  25097. if (cert->crlInfoSz > 0) {
  25098. der->crlInfoSz = SetCRLInfo(cert, der->crlInfo, sizeof(der->crlInfo),
  25099. cert->crlInfo, cert->crlInfoSz);
  25100. if (der->crlInfoSz <= 0)
  25101. return EXTENSIONS_E;
  25102. der->extensionsSz += der->crlInfoSz;
  25103. }
  25104. else
  25105. der->crlInfoSz = 0;
  25106. /* Certificate Policies */
  25107. if (cert->certPoliciesNb != 0) {
  25108. der->certPoliciesSz = SetCertificatePolicies(der->certPolicies,
  25109. sizeof(der->certPolicies),
  25110. cert->certPolicies,
  25111. cert->certPoliciesNb,
  25112. cert->heap);
  25113. if (der->certPoliciesSz <= 0)
  25114. return CERTPOLICIES_E;
  25115. der->extensionsSz += der->certPoliciesSz;
  25116. }
  25117. else
  25118. der->certPoliciesSz = 0;
  25119. #endif /* WOLFSSL_CERT_EXT */
  25120. /* put extensions */
  25121. if (der->extensionsSz > 0) {
  25122. /* put the start of extensions sequence (ID, Size) */
  25123. der->extensionsSz = SetExtensionsHeader(der->extensions,
  25124. sizeof(der->extensions),
  25125. der->extensionsSz);
  25126. if (der->extensionsSz <= 0)
  25127. return EXTENSIONS_E;
  25128. /* put CA */
  25129. if (der->caSz) {
  25130. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25131. &der->extensionsSz,
  25132. der->ca, der->caSz);
  25133. if (ret == 0)
  25134. return EXTENSIONS_E;
  25135. }
  25136. #ifdef WOLFSSL_ALT_NAMES
  25137. /* put Alternative Names */
  25138. if (der->altNamesSz) {
  25139. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25140. &der->extensionsSz,
  25141. der->altNames, der->altNamesSz);
  25142. if (ret <= 0)
  25143. return EXTENSIONS_E;
  25144. }
  25145. #endif
  25146. #ifdef WOLFSSL_CERT_EXT
  25147. /* put SKID */
  25148. if (der->skidSz) {
  25149. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25150. &der->extensionsSz,
  25151. der->skid, der->skidSz);
  25152. if (ret <= 0)
  25153. return EXTENSIONS_E;
  25154. }
  25155. /* put AKID */
  25156. if (der->akidSz) {
  25157. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25158. &der->extensionsSz,
  25159. der->akid, der->akidSz);
  25160. if (ret <= 0)
  25161. return EXTENSIONS_E;
  25162. }
  25163. /* put CRL Distribution Points */
  25164. if (der->crlInfoSz) {
  25165. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25166. &der->extensionsSz,
  25167. der->crlInfo, der->crlInfoSz);
  25168. if (ret <= 0)
  25169. return EXTENSIONS_E;
  25170. }
  25171. /* put KeyUsage */
  25172. if (der->keyUsageSz) {
  25173. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25174. &der->extensionsSz,
  25175. der->keyUsage, der->keyUsageSz);
  25176. if (ret <= 0)
  25177. return EXTENSIONS_E;
  25178. }
  25179. /* put ExtendedKeyUsage */
  25180. if (der->extKeyUsageSz) {
  25181. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25182. &der->extensionsSz,
  25183. der->extKeyUsage, der->extKeyUsageSz);
  25184. if (ret <= 0)
  25185. return EXTENSIONS_E;
  25186. }
  25187. /* put Netscape Cert Type */
  25188. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  25189. if (der->nsCertTypeSz) {
  25190. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25191. &der->extensionsSz,
  25192. der->nsCertType, der->nsCertTypeSz);
  25193. if (ret <= 0)
  25194. return EXTENSIONS_E;
  25195. }
  25196. #endif
  25197. /* put Certificate Policies */
  25198. if (der->certPoliciesSz) {
  25199. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25200. &der->extensionsSz,
  25201. der->certPolicies, der->certPoliciesSz);
  25202. if (ret <= 0)
  25203. return EXTENSIONS_E;
  25204. }
  25205. #endif /* WOLFSSL_CERT_EXT */
  25206. }
  25207. der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
  25208. der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
  25209. der->extensionsSz;
  25210. return 0;
  25211. }
  25212. /* write DER encoded cert to buffer, size already checked */
  25213. static int WriteCertBody(DerCert* der, byte* buf)
  25214. {
  25215. int idx;
  25216. /* signed part header */
  25217. idx = SetSequence(der->total, buf);
  25218. /* version */
  25219. XMEMCPY(buf + idx, der->version, der->versionSz);
  25220. idx += der->versionSz;
  25221. /* serial */
  25222. XMEMCPY(buf + idx, der->serial, der->serialSz);
  25223. idx += der->serialSz;
  25224. /* sig algo */
  25225. XMEMCPY(buf + idx, der->sigAlgo, der->sigAlgoSz);
  25226. idx += der->sigAlgoSz;
  25227. /* issuer */
  25228. XMEMCPY(buf + idx, der->issuer, der->issuerSz);
  25229. idx += der->issuerSz;
  25230. /* validity */
  25231. XMEMCPY(buf + idx, der->validity, der->validitySz);
  25232. idx += der->validitySz;
  25233. /* subject */
  25234. XMEMCPY(buf + idx, der->subject, der->subjectSz);
  25235. idx += der->subjectSz;
  25236. /* public key */
  25237. XMEMCPY(buf + idx, der->publicKey, der->publicKeySz);
  25238. idx += der->publicKeySz;
  25239. if (der->extensionsSz) {
  25240. /* extensions */
  25241. XMEMCPY(buf + idx, der->extensions, min(der->extensionsSz,
  25242. (int)sizeof(der->extensions)));
  25243. idx += der->extensionsSz;
  25244. }
  25245. return idx;
  25246. }
  25247. #endif /* !WOLFSSL_ASN_TEMPLATE */
  25248. /* Make signature from buffer (sz), write to sig (sigSz) */
  25249. static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, int sz,
  25250. byte* sig, int sigSz, RsaKey* rsaKey, ecc_key* eccKey,
  25251. ed25519_key* ed25519Key, ed448_key* ed448Key, falcon_key* falconKey,
  25252. dilithium_key* dilithiumKey, sphincs_key* sphincsKey, WC_RNG* rng,
  25253. int sigAlgoType, void* heap)
  25254. {
  25255. int digestSz = 0, typeH = 0, ret = 0;
  25256. (void)digestSz;
  25257. (void)typeH;
  25258. (void)buf;
  25259. (void)sz;
  25260. (void)sig;
  25261. (void)sigSz;
  25262. (void)rsaKey;
  25263. (void)eccKey;
  25264. (void)ed25519Key;
  25265. (void)ed448Key;
  25266. (void)falconKey;
  25267. (void)dilithiumKey;
  25268. (void)sphincsKey;
  25269. (void)rng;
  25270. (void)heap;
  25271. switch (certSignCtx->state) {
  25272. case CERTSIGN_STATE_BEGIN:
  25273. case CERTSIGN_STATE_DIGEST:
  25274. certSignCtx->state = CERTSIGN_STATE_DIGEST;
  25275. certSignCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, heap,
  25276. DYNAMIC_TYPE_TMP_BUFFER);
  25277. if (certSignCtx->digest == NULL) {
  25278. ret = MEMORY_E; goto exit_ms;
  25279. }
  25280. ret = HashForSignature(buf, sz, sigAlgoType, certSignCtx->digest,
  25281. &typeH, &digestSz, 0);
  25282. /* set next state, since WC_PENDING_E rentry for these are not "call again" */
  25283. certSignCtx->state = CERTSIGN_STATE_ENCODE;
  25284. if (ret != 0) {
  25285. goto exit_ms;
  25286. }
  25287. FALL_THROUGH;
  25288. case CERTSIGN_STATE_ENCODE:
  25289. #ifndef NO_RSA
  25290. if (rsaKey) {
  25291. certSignCtx->encSig = (byte*)XMALLOC(MAX_DER_DIGEST_SZ, heap,
  25292. DYNAMIC_TYPE_TMP_BUFFER);
  25293. if (certSignCtx->encSig == NULL) {
  25294. ret = MEMORY_E; goto exit_ms;
  25295. }
  25296. /* signature */
  25297. certSignCtx->encSigSz = wc_EncodeSignature(certSignCtx->encSig,
  25298. certSignCtx->digest, digestSz, typeH);
  25299. }
  25300. #endif /* !NO_RSA */
  25301. FALL_THROUGH;
  25302. case CERTSIGN_STATE_DO:
  25303. certSignCtx->state = CERTSIGN_STATE_DO;
  25304. ret = ALGO_ID_E; /* default to error */
  25305. #ifndef NO_RSA
  25306. if (rsaKey) {
  25307. /* signature */
  25308. ret = wc_RsaSSL_Sign(certSignCtx->encSig, certSignCtx->encSigSz,
  25309. sig, sigSz, rsaKey, rng);
  25310. }
  25311. #endif /* !NO_RSA */
  25312. #ifdef HAVE_ECC
  25313. if (!rsaKey && eccKey) {
  25314. word32 outSz = sigSz;
  25315. ret = wc_ecc_sign_hash(certSignCtx->digest, digestSz,
  25316. sig, &outSz, rng, eccKey);
  25317. if (ret == 0)
  25318. ret = outSz;
  25319. }
  25320. #endif /* HAVE_ECC */
  25321. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_SIGN)
  25322. if (!rsaKey && !eccKey && ed25519Key) {
  25323. word32 outSz = sigSz;
  25324. ret = wc_ed25519_sign_msg(buf, sz, sig, &outSz, ed25519Key);
  25325. if (ret == 0)
  25326. ret = outSz;
  25327. }
  25328. #endif /* HAVE_ED25519 && HAVE_ED25519_SIGN */
  25329. #if defined(HAVE_ED448) && defined(HAVE_ED448_SIGN)
  25330. if (!rsaKey && !eccKey && !ed25519Key && ed448Key) {
  25331. word32 outSz = sigSz;
  25332. ret = wc_ed448_sign_msg(buf, sz, sig, &outSz, ed448Key, NULL, 0);
  25333. if (ret == 0)
  25334. ret = outSz;
  25335. }
  25336. #endif /* HAVE_ED448 && HAVE_ED448_SIGN */
  25337. #if defined(HAVE_PQC)
  25338. #if defined(HAVE_FALCON)
  25339. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && falconKey) {
  25340. word32 outSz = sigSz;
  25341. ret = wc_falcon_sign_msg(buf, sz, sig, &outSz, falconKey);
  25342. if (ret == 0)
  25343. ret = outSz;
  25344. }
  25345. #endif /* HAVE_FALCON */
  25346. #if defined(HAVE_DILITHIUM)
  25347. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
  25348. dilithiumKey) {
  25349. word32 outSz = sigSz;
  25350. ret = wc_dilithium_sign_msg(buf, sz, sig, &outSz, dilithiumKey);
  25351. if (ret == 0)
  25352. ret = outSz;
  25353. }
  25354. #endif /* HAVE_DILITHIUM */
  25355. #if defined(HAVE_SPHINCS)
  25356. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
  25357. !dilithiumKey && sphincsKey) {
  25358. word32 outSz = sigSz;
  25359. ret = wc_sphincs_sign_msg(buf, sz, sig, &outSz, sphincsKey);
  25360. if (ret == 0)
  25361. ret = outSz;
  25362. }
  25363. #endif /* HAVE_SPHINCS */
  25364. #endif /* HAVE_PQC */
  25365. break;
  25366. }
  25367. exit_ms:
  25368. #ifdef WOLFSSL_ASYNC_CRYPT
  25369. if (ret == WC_PENDING_E) {
  25370. return ret;
  25371. }
  25372. #endif
  25373. #ifndef NO_RSA
  25374. if (rsaKey) {
  25375. XFREE(certSignCtx->encSig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25376. }
  25377. #endif /* !NO_RSA */
  25378. XFREE(certSignCtx->digest, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25379. certSignCtx->digest = NULL;
  25380. /* reset state */
  25381. certSignCtx->state = CERTSIGN_STATE_BEGIN;
  25382. if (ret < 0) {
  25383. WOLFSSL_ERROR_VERBOSE(ret);
  25384. }
  25385. return ret;
  25386. }
  25387. #ifdef WOLFSSL_ASN_TEMPLATE
  25388. /* Generate a random integer value of at most len bytes.
  25389. *
  25390. * Most-significant bit will not be set when maximum size.
  25391. * Random value may be smaller than maximum size in bytes.
  25392. *
  25393. * @param [in] rng Random number generator.
  25394. * @param [out] out Buffer to hold integer value.
  25395. * @param [in] len Maximum number of bytes of integer.
  25396. * @return 0 on success.
  25397. * @return -ve when random number generation failed.
  25398. */
  25399. static int GenerateInteger(WC_RNG* rng, byte* out, int len)
  25400. {
  25401. int ret;
  25402. /* Generate random number. */
  25403. ret = wc_RNG_GenerateBlock(rng, out, len);
  25404. if (ret == 0) {
  25405. int i;
  25406. /* Clear the top bit to make positive. */
  25407. out[0] &= 0x7f;
  25408. /* Find first non-zero byte. One zero byte is valid though. */
  25409. for (i = 0; i < len - 1; i++) {
  25410. if (out[i] != 0) {
  25411. break;
  25412. }
  25413. }
  25414. if (i != 0) {
  25415. /* Remove leading zeros. */
  25416. XMEMMOVE(out, out + i, len - i);
  25417. }
  25418. }
  25419. return ret;
  25420. }
  25421. /* ASN.1 template for a Certificate.
  25422. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  25423. */
  25424. static const ASNItem sigASN[] = {
  25425. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25426. /* tbsCertificate */
  25427. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  25428. /* signatureAlgorithm */
  25429. /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  25430. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  25431. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  25432. /* signatureValue */
  25433. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  25434. };
  25435. enum {
  25436. SIGASN_IDX_SEQ = 0,
  25437. SIGASN_IDX_TBS_SEQ,
  25438. SIGASN_IDX_SIGALGO_SEQ,
  25439. SIGASN_IDX_SIGALGO_OID,
  25440. SIGASN_IDX_SIGALGO_NULL,
  25441. SIGASN_IDX_SIGNATURE,
  25442. };
  25443. /* Number of items in ASN.1 template for a Certificate. */
  25444. #define sigASN_Length (sizeof(sigASN) / sizeof(ASNItem))
  25445. #endif
  25446. /* add signature to end of buffer, size of buffer assumed checked, return
  25447. new length */
  25448. int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz,
  25449. int sigAlgoType)
  25450. {
  25451. #ifndef WOLFSSL_ASN_TEMPLATE
  25452. byte seq[MAX_SEQ_SZ];
  25453. int idx = bodySz, seqSz;
  25454. /* algo */
  25455. idx += SetAlgoID(sigAlgoType, buf ? buf + idx : NULL, oidSigType, 0);
  25456. /* bit string */
  25457. idx += SetBitString(sigSz, 0, buf ? buf + idx : NULL);
  25458. /* signature */
  25459. if (buf)
  25460. XMEMCPY(buf + idx, sig, sigSz);
  25461. idx += sigSz;
  25462. /* make room for overall header */
  25463. seqSz = SetSequence(idx, seq);
  25464. if (buf) {
  25465. XMEMMOVE(buf + seqSz, buf, idx);
  25466. XMEMCPY(buf, seq, seqSz);
  25467. }
  25468. return idx + seqSz;
  25469. #else
  25470. DECL_ASNSETDATA(dataASN, sigASN_Length);
  25471. word32 seqSz;
  25472. int sz;
  25473. int ret = 0;
  25474. CALLOC_ASNSETDATA(dataASN, sigASN_Length, ret, NULL);
  25475. /* In place, put body between SEQUENCE and signature. */
  25476. if (ret == 0) {
  25477. /* Set sigature OID and signature data. */
  25478. SetASN_OID(&dataASN[SIGASN_IDX_SIGALGO_OID], sigAlgoType, oidSigType);
  25479. if (IsSigAlgoECC(sigAlgoType)) {
  25480. /* ECDSA and EdDSA doesn't have NULL tagged item. */
  25481. dataASN[SIGASN_IDX_SIGALGO_NULL].noOut = 1;
  25482. }
  25483. SetASN_Buffer(&dataASN[SIGASN_IDX_SIGNATURE], sig, sigSz);
  25484. /* Calculate size of signature data. */
  25485. ret = SizeASN_Items(&sigASN[SIGASN_IDX_SIGALGO_SEQ],
  25486. &dataASN[SIGASN_IDX_SIGALGO_SEQ], sigASN_Length - 2, &sz);
  25487. }
  25488. if (ret == 0) {
  25489. /* Calculate size of outer sequence by calculating size of the encoded
  25490. * length and adding 1 for tag. */
  25491. seqSz = SizeASNHeader(bodySz + sz);
  25492. if (buf != NULL) {
  25493. /* Move body to after sequence. */
  25494. XMEMMOVE(buf + seqSz, buf, bodySz);
  25495. }
  25496. /* Leave space for body in encoding. */
  25497. SetASN_ReplaceBuffer(&dataASN[SIGASN_IDX_TBS_SEQ], NULL, bodySz);
  25498. /* Calculate overall size and put in offsets and lengths. */
  25499. ret = SizeASN_Items(sigASN, dataASN, sigASN_Length, &sz);
  25500. }
  25501. if ((ret == 0) && (buf != NULL)) {
  25502. /* Write SEQUENCE and signature around body. */
  25503. SetASN_Items(sigASN, dataASN, sigASN_Length, buf);
  25504. }
  25505. if (ret == 0) {
  25506. /* Return the encoding size. */
  25507. ret = sz;
  25508. }
  25509. FREE_ASNSETDATA(dataASN, NULL);
  25510. return ret;
  25511. #endif /* WOLFSSL_ASN_TEMPLATE */
  25512. }
  25513. /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
  25514. static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
  25515. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng,
  25516. DsaKey* dsaKey, ed25519_key* ed25519Key,
  25517. ed448_key* ed448Key, falcon_key* falconKey,
  25518. dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
  25519. {
  25520. #ifndef WOLFSSL_ASN_TEMPLATE
  25521. int ret;
  25522. #ifdef WOLFSSL_SMALL_STACK
  25523. DerCert* der;
  25524. #else
  25525. DerCert der[1];
  25526. #endif
  25527. if (derBuffer == NULL)
  25528. return BAD_FUNC_ARG;
  25529. if (eccKey)
  25530. cert->keyType = ECC_KEY;
  25531. else if (rsaKey)
  25532. cert->keyType = RSA_KEY;
  25533. else if (dsaKey)
  25534. cert->keyType = DSA_KEY;
  25535. else if (ed25519Key)
  25536. cert->keyType = ED25519_KEY;
  25537. else if (ed448Key)
  25538. cert->keyType = ED448_KEY;
  25539. #ifdef HAVE_PQC
  25540. #ifdef HAVE_FALCON
  25541. else if ((falconKey != NULL) && (falconKey->level == 1))
  25542. cert->keyType = FALCON_LEVEL1_KEY;
  25543. else if ((falconKey != NULL) && (falconKey->level == 5))
  25544. cert->keyType = FALCON_LEVEL5_KEY;
  25545. #endif /* HAVE_FALCON */
  25546. #ifdef HAVE_DILITHIUM
  25547. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)
  25548. && (dilithiumKey->sym == SHAKE_VARIANT))
  25549. cert->keyType = DILITHIUM_LEVEL2_KEY;
  25550. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)
  25551. && (dilithiumKey->sym == SHAKE_VARIANT))
  25552. cert->keyType = DILITHIUM_LEVEL3_KEY;
  25553. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)
  25554. && (dilithiumKey->sym == SHAKE_VARIANT))
  25555. cert->keyType = DILITHIUM_LEVEL5_KEY;
  25556. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)
  25557. && (dilithiumKey->sym == AES_VARIANT))
  25558. cert->keyType = DILITHIUM_AES_LEVEL2_KEY;
  25559. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)
  25560. && (dilithiumKey->sym == AES_VARIANT))
  25561. cert->keyType = DILITHIUM_AES_LEVEL3_KEY;
  25562. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)
  25563. && (dilithiumKey->sym == AES_VARIANT))
  25564. cert->keyType = DILITHIUM_AES_LEVEL5_KEY;
  25565. #endif /* HAVE_DILITHIUM */
  25566. #ifdef HAVE_SPHINCS
  25567. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25568. && (sphincsKey->optim == FAST_VARIANT))
  25569. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  25570. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25571. && (sphincsKey->optim == FAST_VARIANT))
  25572. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  25573. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25574. && (sphincsKey->optim == FAST_VARIANT))
  25575. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  25576. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25577. && (sphincsKey->optim == SMALL_VARIANT))
  25578. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  25579. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25580. && (sphincsKey->optim == SMALL_VARIANT))
  25581. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  25582. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25583. && (sphincsKey->optim == SMALL_VARIANT))
  25584. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  25585. #endif /* HAVE_SPHINCS */
  25586. #endif /* HAVE_PQC */
  25587. else
  25588. return BAD_FUNC_ARG;
  25589. #ifdef WOLFSSL_SMALL_STACK
  25590. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25591. if (der == NULL)
  25592. return MEMORY_E;
  25593. #endif
  25594. ret = EncodeCert(cert, der, rsaKey, eccKey, rng, dsaKey, ed25519Key,
  25595. ed448Key, falconKey, dilithiumKey, sphincsKey);
  25596. if (ret == 0) {
  25597. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  25598. ret = BUFFER_E;
  25599. else
  25600. ret = cert->bodySz = WriteCertBody(der, derBuffer);
  25601. }
  25602. #ifdef WOLFSSL_SMALL_STACK
  25603. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25604. #endif
  25605. return ret;
  25606. #else
  25607. /* TODO: issRaw and sbjRaw should be NUL terminated. */
  25608. DECL_ASNSETDATA(dataASN, x509CertASN_Length);
  25609. word32 publicKeySz = 0;
  25610. word32 issuerSz = 0;
  25611. word32 subjectSz = 0;
  25612. word32 extSz = 0;
  25613. int sz = 0;
  25614. int ret = 0;
  25615. word32 issRawLen = 0;
  25616. word32 sbjRawLen = 0;
  25617. /* Unused without OQS */
  25618. (void)falconKey;
  25619. (void)dilithiumKey;
  25620. (void)sphincsKey;
  25621. CALLOC_ASNSETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  25622. if (ret == 0) {
  25623. /* Set key type into certificate object based on key passed in. */
  25624. if (rsaKey) {
  25625. cert->keyType = RSA_KEY;
  25626. }
  25627. else if (eccKey) {
  25628. cert->keyType = ECC_KEY;
  25629. }
  25630. else if (dsaKey) {
  25631. cert->keyType = DSA_KEY;
  25632. }
  25633. else if (ed25519Key) {
  25634. cert->keyType = ED25519_KEY;
  25635. }
  25636. else if (ed448Key) {
  25637. cert->keyType = ED448_KEY;
  25638. }
  25639. #ifdef HAVE_PQC
  25640. #ifdef HAVE_FALCON
  25641. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  25642. cert->keyType = FALCON_LEVEL1_KEY;
  25643. }
  25644. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  25645. cert->keyType = FALCON_LEVEL5_KEY;
  25646. }
  25647. #endif /* HAVE_FALCON */
  25648. #ifdef HAVE_DILITHIUM
  25649. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)
  25650. && (dilithiumKey->sym == SHAKE_VARIANT)) {
  25651. cert->keyType = DILITHIUM_LEVEL2_KEY;
  25652. }
  25653. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)
  25654. && (dilithiumKey->sym == SHAKE_VARIANT)) {
  25655. cert->keyType = DILITHIUM_LEVEL3_KEY;
  25656. }
  25657. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)
  25658. && (dilithiumKey->sym == SHAKE_VARIANT)) {
  25659. cert->keyType = DILITHIUM_LEVEL5_KEY;
  25660. }
  25661. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)
  25662. && (dilithiumKey->sym == AES_VARIANT)) {
  25663. cert->keyType = DILITHIUM_AES_LEVEL2_KEY;
  25664. }
  25665. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)
  25666. && (dilithiumKey->sym == AES_VARIANT)) {
  25667. cert->keyType = DILITHIUM_AES_LEVEL3_KEY;
  25668. }
  25669. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)
  25670. && (dilithiumKey->sym == AES_VARIANT)) {
  25671. cert->keyType = DILITHIUM_AES_LEVEL5_KEY;
  25672. }
  25673. #endif /* HAVE_DILITHIUM */
  25674. #ifdef HAVE_SPHINCS
  25675. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25676. && (sphincsKey->optim == FAST_VARIANT)) {
  25677. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  25678. }
  25679. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25680. && (sphincsKey->optim == FAST_VARIANT)) {
  25681. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  25682. }
  25683. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25684. && (sphincsKey->optim == FAST_VARIANT)) {
  25685. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  25686. }
  25687. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25688. && (sphincsKey->optim == SMALL_VARIANT)) {
  25689. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  25690. }
  25691. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25692. && (sphincsKey->optim == SMALL_VARIANT)) {
  25693. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  25694. }
  25695. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25696. && (sphincsKey->optim == SMALL_VARIANT)) {
  25697. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  25698. }
  25699. #endif /* HAVE_SPHINCS */
  25700. #endif /* HAVE_PQC */
  25701. else {
  25702. ret = BAD_FUNC_ARG;
  25703. }
  25704. }
  25705. if ((ret == 0) && (cert->serialSz == 0)) {
  25706. /* Generate random serial number. */
  25707. cert->serialSz = CTC_GEN_SERIAL_SZ;
  25708. ret = GenerateInteger(rng, cert->serial, CTC_GEN_SERIAL_SZ);
  25709. }
  25710. if (ret == 0) {
  25711. /* Determine issuer name size. */
  25712. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25713. defined(WOLFSSL_CERT_REQ)
  25714. issRawLen = (word32)XSTRLEN((const char*)cert->issRaw);
  25715. if (issRawLen > 0) {
  25716. issuerSz = min(sizeof(cert->issRaw), issRawLen);
  25717. }
  25718. else
  25719. #endif
  25720. {
  25721. /* Calculate issuer name encoding size. If the cert is self-signed
  25722. * use the subject instead of the issuer. */
  25723. issuerSz = SetNameEx(NULL, WC_ASN_NAME_MAX, cert->selfSigned ?
  25724. &cert->subject : &cert->issuer, cert->heap);
  25725. ret = issuerSz;
  25726. }
  25727. }
  25728. if (ret >= 0) {
  25729. /* Determine subject name size. */
  25730. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25731. defined(WOLFSSL_CERT_REQ)
  25732. sbjRawLen = (word32)XSTRLEN((const char*)cert->sbjRaw);
  25733. if (sbjRawLen > 0) {
  25734. subjectSz = min(sizeof(cert->sbjRaw), sbjRawLen);
  25735. }
  25736. else
  25737. #endif
  25738. {
  25739. /* Calculate subject name encoding size. */
  25740. subjectSz = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject,
  25741. cert->heap);
  25742. ret = subjectSz;
  25743. }
  25744. }
  25745. if (ret >= 0) {
  25746. /* Calculate public key encoding size. */
  25747. ret = publicKeySz = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  25748. eccKey, ed25519Key, ed448Key, dsaKey);
  25749. }
  25750. if (ret >= 0) {
  25751. /* Calculate extensions encoding size - may be 0. */
  25752. ret = extSz = EncodeExtensions(cert, NULL, 0, 0);
  25753. }
  25754. if (ret >= 0) {
  25755. /* Don't write out outer sequence - only doing body. */
  25756. dataASN[X509CERTASN_IDX_SEQ].noOut = 1;
  25757. /* Set version, serial number and signature OID */
  25758. SetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT], cert->version);
  25759. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
  25760. cert->serialSz);
  25761. SetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], cert->sigType,
  25762. oidSigType);
  25763. if (IsSigAlgoECC(cert->sigType)) {
  25764. /* No NULL tagged item with ECDSA and EdDSA signature OIDs. */
  25765. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL].noOut = 1;
  25766. }
  25767. #ifdef WC_RSA_PSS
  25768. /* TODO: Encode RSA PSS parameters. */
  25769. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].noOut = 1;
  25770. #endif
  25771. if (issRawLen > 0) {
  25772. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25773. defined(WOLFSSL_CERT_REQ)
  25774. /* Put in encoded issuer name. */
  25775. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  25776. cert->issRaw, issuerSz);
  25777. #endif
  25778. }
  25779. else {
  25780. /* Leave space for issuer name. */
  25781. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  25782. NULL, issuerSz);
  25783. }
  25784. if (cert->beforeDateSz && cert->afterDateSz) {
  25785. if (cert->beforeDate[0] == ASN_UTC_TIME) {
  25786. /* Make space for before date data. */
  25787. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC],
  25788. cert->beforeDate + 2, ASN_UTC_TIME_SIZE - 1);
  25789. /* Don't put out Generalized Time before data. */
  25790. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT].noOut = 1;
  25791. }
  25792. else {
  25793. /* Don't put out UTC before data. */
  25794. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
  25795. /* Make space for before date data. */
  25796. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
  25797. cert->beforeDate + 2, ASN_GEN_TIME_SZ);
  25798. }
  25799. if (cert->afterDate[0] == ASN_UTC_TIME) {
  25800. /* Make space for after date data. */
  25801. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC],
  25802. cert->afterDate + 2, ASN_UTC_TIME_SIZE - 1);
  25803. /* Don't put out UTC Generalized Time after data. */
  25804. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT].noOut = 1;
  25805. }
  25806. else {
  25807. /* Don't put out UTC after data. */
  25808. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
  25809. /* Make space for after date data. */
  25810. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
  25811. cert->afterDate + 2, ASN_GEN_TIME_SZ);
  25812. }
  25813. }
  25814. else
  25815. {
  25816. /* Don't put out UTC before data. */
  25817. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
  25818. /* Make space for before date data. */
  25819. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
  25820. NULL, ASN_GEN_TIME_SZ);
  25821. /* Don't put out UTC after data. */
  25822. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
  25823. /* Make space for after date data. */
  25824. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
  25825. NULL, ASN_GEN_TIME_SZ);
  25826. }
  25827. if (sbjRawLen > 0) {
  25828. /* Put in encoded subject name. */
  25829. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25830. defined(WOLFSSL_CERT_REQ)
  25831. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
  25832. cert->sbjRaw, subjectSz);
  25833. #endif
  25834. }
  25835. else {
  25836. /* Leave space for subject name. */
  25837. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
  25838. NULL, subjectSz);
  25839. }
  25840. /* Leave space for public key. */
  25841. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ],
  25842. NULL, publicKeySz);
  25843. /* Replacement buffer instead of algorithm identifier items. */
  25844. SetASNItem_NoOut(dataASN,
  25845. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
  25846. X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY);
  25847. /* issuerUniqueID and subjectUniqueID not supported. */
  25848. dataASN[X509CERTASN_IDX_TBS_ISSUERUID].noOut = 1;
  25849. dataASN[X509CERTASN_IDX_TBS_SUBJECTUID].noOut = 1;
  25850. /* Leave space for extensions if any set into certificate object. */
  25851. if (extSz > 0) {
  25852. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_EXT_SEQ], NULL, extSz);
  25853. }
  25854. else {
  25855. SetASNItem_NoOutNode(dataASN, x509CertASN,
  25856. X509CERTASN_IDX_TBS_EXT, x509CertASN_Length);
  25857. }
  25858. /* No signature - added later. */
  25859. SetASNItem_NoOut(dataASN, X509CERTASN_IDX_SIGALGO_SEQ,
  25860. X509CERTASN_IDX_SIGNATURE);
  25861. /* Calculate encoded certificate body size. */
  25862. ret = SizeASN_Items(x509CertASN, dataASN, x509CertASN_Length, &sz);
  25863. }
  25864. /* Check buffer is big enough for encoded data. */
  25865. if ((ret == 0) && (sz > (int)derSz)) {
  25866. ret = BUFFER_E;
  25867. }
  25868. if (ret == 0) {
  25869. /* Encode certificate body into buffer. */
  25870. SetASN_Items(x509CertASN, dataASN, x509CertASN_Length, derBuffer);
  25871. if (issRawLen == 0) {
  25872. /* Encode issuer name into buffer. Use the subject as the issuer
  25873. * if it is self-signed. Size will be correct because we did the
  25874. * same for size. */
  25875. ret = SetNameEx(
  25876. (byte*)dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.data,
  25877. dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.length,
  25878. cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
  25879. }
  25880. }
  25881. if ((ret >= 0) && (sbjRawLen == 0)) {
  25882. /* Encode subject name into buffer. */
  25883. ret = SetNameEx(
  25884. (byte*)dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.data,
  25885. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.length,
  25886. &cert->subject, cert->heap);
  25887. }
  25888. if (ret >= 0) {
  25889. if (cert->beforeDateSz == 0 || cert->afterDateSz == 0)
  25890. {
  25891. /* Encode validity into buffer. */
  25892. ret = SetValidity(
  25893. (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT]
  25894. .data.buffer.data,
  25895. (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT]
  25896. .data.buffer.data, cert->daysValid);
  25897. }
  25898. }
  25899. if (ret >= 0) {
  25900. /* Encode public key into buffer. */
  25901. ret = EncodePublicKey(cert->keyType,
  25902. (byte*)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
  25903. .data.buffer.data,
  25904. dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
  25905. .data.buffer.length,
  25906. rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
  25907. }
  25908. if ((ret >= 0) && (!dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].noOut)) {
  25909. /* Encode extensions into buffer. */
  25910. ret = EncodeExtensions(cert,
  25911. (byte*)dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.data,
  25912. dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.length, 0);
  25913. }
  25914. if (ret >= 0) {
  25915. /* Store encoded certifcate body size. */
  25916. cert->bodySz = sz;
  25917. /* Return the encoding size. */
  25918. ret = sz;
  25919. }
  25920. FREE_ASNSETDATA(dataASN, cert->heap);
  25921. return ret;
  25922. #endif
  25923. }
  25924. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  25925. int wc_MakeCert_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  25926. void* key, WC_RNG* rng)
  25927. {
  25928. RsaKey* rsaKey = NULL;
  25929. DsaKey* dsaKey = NULL;
  25930. ecc_key* eccKey = NULL;
  25931. ed25519_key* ed25519Key = NULL;
  25932. ed448_key* ed448Key = NULL;
  25933. falcon_key* falconKey = NULL;
  25934. dilithium_key* dilithiumKey = NULL;
  25935. sphincs_key* sphincsKey = NULL;
  25936. if (keyType == RSA_TYPE)
  25937. rsaKey = (RsaKey*)key;
  25938. else if (keyType == DSA_TYPE)
  25939. dsaKey = (DsaKey*)key;
  25940. else if (keyType == ECC_TYPE)
  25941. eccKey = (ecc_key*)key;
  25942. else if (keyType == ED25519_TYPE)
  25943. ed25519Key = (ed25519_key*)key;
  25944. else if (keyType == ED448_TYPE)
  25945. ed448Key = (ed448_key*)key;
  25946. else if (keyType == FALCON_LEVEL1_TYPE)
  25947. falconKey = (falcon_key*)key;
  25948. else if (keyType == FALCON_LEVEL5_TYPE)
  25949. falconKey = (falcon_key*)key;
  25950. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  25951. dilithiumKey = (dilithium_key*)key;
  25952. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  25953. dilithiumKey = (dilithium_key*)key;
  25954. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  25955. dilithiumKey = (dilithium_key*)key;
  25956. else if (keyType == DILITHIUM_AES_LEVEL2_TYPE)
  25957. dilithiumKey = (dilithium_key*)key;
  25958. else if (keyType == DILITHIUM_AES_LEVEL3_TYPE)
  25959. dilithiumKey = (dilithium_key*)key;
  25960. else if (keyType == DILITHIUM_AES_LEVEL5_TYPE)
  25961. dilithiumKey = (dilithium_key*)key;
  25962. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  25963. sphincsKey = (sphincs_key*)key;
  25964. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  25965. sphincsKey = (sphincs_key*)key;
  25966. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  25967. sphincsKey = (sphincs_key*)key;
  25968. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  25969. sphincsKey = (sphincs_key*)key;
  25970. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  25971. sphincsKey = (sphincs_key*)key;
  25972. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  25973. sphincsKey = (sphincs_key*)key;
  25974. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, dsaKey,
  25975. ed25519Key, ed448Key, falconKey, dilithiumKey,
  25976. sphincsKey);
  25977. }
  25978. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  25979. WOLFSSL_ABI
  25980. int wc_MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,
  25981. ecc_key* eccKey, WC_RNG* rng)
  25982. {
  25983. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, NULL,
  25984. NULL, NULL, NULL, NULL);
  25985. }
  25986. #ifdef WOLFSSL_CERT_REQ
  25987. #ifndef WOLFSSL_ASN_TEMPLATE
  25988. /* return size of data set on success
  25989. * if getting size only then attr and oid should be NULL
  25990. */
  25991. static int SetReqAttribSingle(byte* output, int* idx, char* attr, int attrSz,
  25992. const byte* oid, int oidSz, byte printable, int extSz)
  25993. {
  25994. int totalSz = 0;
  25995. int seqSz = 0;
  25996. int setSz = 0;
  25997. int strSz = 0;
  25998. byte seq[MAX_SEQ_SZ];
  25999. byte set[MAX_SET_SZ];
  26000. byte str[MAX_PRSTR_SZ];
  26001. totalSz = SetObjectId(oidSz, NULL);
  26002. totalSz += oidSz;
  26003. if (extSz > 0) {
  26004. totalSz += setSz = SetSet(extSz, set);
  26005. totalSz += seqSz = SetSequence(totalSz + extSz, seq);
  26006. totalSz += extSz;
  26007. }
  26008. else {
  26009. if (printable) {
  26010. totalSz += strSz = SetPrintableString(attrSz, str);
  26011. }
  26012. else {
  26013. totalSz += strSz = SetUTF8String(attrSz, str);
  26014. }
  26015. totalSz += setSz = SetSet(strSz + attrSz, set);
  26016. totalSz += seqSz = SetSequence(totalSz + attrSz, seq);
  26017. totalSz += attrSz;
  26018. }
  26019. if (oid) {
  26020. XMEMCPY(&output[*idx], seq, seqSz);
  26021. *idx += seqSz;
  26022. *idx += SetObjectId(oidSz, output + *idx);
  26023. XMEMCPY(&output[*idx], oid, oidSz);
  26024. *idx += oidSz;
  26025. XMEMCPY(&output[*idx], set, setSz);
  26026. *idx += setSz;
  26027. if (strSz > 0) {
  26028. XMEMCPY(&output[*idx], str, strSz);
  26029. *idx += strSz;
  26030. if (attrSz > 0) {
  26031. XMEMCPY(&output[*idx], attr, attrSz);
  26032. *idx += attrSz;
  26033. }
  26034. }
  26035. }
  26036. return totalSz;
  26037. }
  26038. static int SetReqAttrib(byte* output, Cert* cert, int extSz)
  26039. {
  26040. int sz = 0; /* overall size */
  26041. int setSz = 0;
  26042. output[0] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  26043. sz++;
  26044. if (cert->challengePw[0]) {
  26045. setSz += SetReqAttribSingle(output, &sz, NULL,
  26046. (int)XSTRLEN(cert->challengePw), NULL,
  26047. sizeof(attrChallengePasswordOid),
  26048. cert->challengePwPrintableString, 0);
  26049. }
  26050. if (cert->unstructuredName[0]) {
  26051. setSz += SetReqAttribSingle(output, &sz, NULL,
  26052. (int)XSTRLEN(cert->unstructuredName), NULL,
  26053. sizeof(attrUnstructuredNameOid), 1, 0);
  26054. }
  26055. if (extSz) {
  26056. setSz += SetReqAttribSingle(output, &sz, NULL, 0, NULL,
  26057. sizeof(attrExtensionRequestOid), 1, extSz);
  26058. }
  26059. /* Put the pieces together. */
  26060. sz += SetLength(setSz, &output[sz]);
  26061. if (sz + setSz - extSz > MAX_ATTRIB_SZ) {
  26062. WOLFSSL_MSG("Attribute Buffer is not big enough!");
  26063. return REQ_ATTRIBUTE_E;
  26064. }
  26065. if (cert->challengePw[0]) {
  26066. SetReqAttribSingle(output, &sz, cert->challengePw,
  26067. (int)XSTRLEN(cert->challengePw), &attrChallengePasswordOid[0],
  26068. sizeof(attrChallengePasswordOid),
  26069. cert->challengePwPrintableString, 0);
  26070. }
  26071. if (cert->unstructuredName[0]) {
  26072. SetReqAttribSingle(output, &sz, cert->unstructuredName,
  26073. (int)XSTRLEN(cert->unstructuredName),
  26074. &attrUnstructuredNameOid[0],
  26075. sizeof(attrUnstructuredNameOid), 1, 0);
  26076. }
  26077. if (extSz) {
  26078. SetReqAttribSingle(output, &sz, NULL, 0, &attrExtensionRequestOid[0],
  26079. sizeof(attrExtensionRequestOid), 1, extSz);
  26080. /* The actual extension data will be tacked onto the output later. */
  26081. }
  26082. return sz;
  26083. }
  26084. #ifdef WOLFSSL_CUSTOM_OID
  26085. /* encode a custom oid and value */
  26086. static int SetCustomObjectId(Cert* cert, byte* output, word32 outSz,
  26087. CertOidField* custom)
  26088. {
  26089. int idx = 0, cust_lenSz, cust_oidSz;
  26090. if (cert == NULL || output == NULL || custom == NULL) {
  26091. return BAD_FUNC_ARG;
  26092. }
  26093. if (custom->oid == NULL || custom->oidSz <= 0) {
  26094. return 0; /* none set */
  26095. }
  26096. /* Octet String header */
  26097. cust_lenSz = SetOctetString(custom->valSz, NULL);
  26098. cust_oidSz = SetObjectId(custom->oidSz, NULL);
  26099. /* check for output buffer room */
  26100. if ((word32)(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz) >
  26101. outSz) {
  26102. return BUFFER_E;
  26103. }
  26104. /* put sequence with total */
  26105. idx = SetSequence(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz,
  26106. output);
  26107. /* put oid header */
  26108. idx += SetObjectId(custom->oidSz, output+idx);
  26109. XMEMCPY(output+idx, custom->oid, custom->oidSz);
  26110. idx += custom->oidSz;
  26111. /* put value */
  26112. idx += SetOctetString(custom->valSz, output+idx);
  26113. XMEMCPY(output+idx, custom->val, custom->valSz);
  26114. idx += custom->valSz;
  26115. return idx;
  26116. }
  26117. #endif /* WOLFSSL_CUSTOM_OID */
  26118. /* encode info from cert into DER encoded format */
  26119. static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey,
  26120. DsaKey* dsaKey, ecc_key* eccKey,
  26121. ed25519_key* ed25519Key, ed448_key* ed448Key,
  26122. falcon_key* falconKey, dilithium_key* dilithiumKey,
  26123. sphincs_key* sphincsKey)
  26124. {
  26125. int ret;
  26126. (void)eccKey;
  26127. (void)ed25519Key;
  26128. (void)ed448Key;
  26129. (void)falconKey;
  26130. (void)dilithiumKey;
  26131. (void)sphincsKey;
  26132. if (cert == NULL || der == NULL)
  26133. return BAD_FUNC_ARG;
  26134. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  26135. dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
  26136. falconKey == NULL) {
  26137. return PUBLIC_KEY_E;
  26138. }
  26139. /* init */
  26140. XMEMSET(der, 0, sizeof(DerCert));
  26141. /* version */
  26142. der->versionSz = SetMyVersion(cert->version, der->version, FALSE);
  26143. /* subject name */
  26144. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26145. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  26146. /* Use the raw subject */
  26147. int idx;
  26148. der->subjectSz = min(sizeof(der->subject),
  26149. (word32)XSTRLEN((const char*)cert->sbjRaw));
  26150. /* header */
  26151. idx = SetSequence(der->subjectSz, der->subject);
  26152. if (der->subjectSz + idx > (int)sizeof(der->subject)) {
  26153. return SUBJECT_E;
  26154. }
  26155. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  26156. der->subjectSz);
  26157. der->subjectSz += idx;
  26158. }
  26159. else
  26160. #endif
  26161. {
  26162. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  26163. &cert->subject, cert->heap);
  26164. }
  26165. if (der->subjectSz <= 0)
  26166. return SUBJECT_E;
  26167. /* public key */
  26168. #ifndef NO_RSA
  26169. if (cert->keyType == RSA_KEY) {
  26170. if (rsaKey == NULL)
  26171. return PUBLIC_KEY_E;
  26172. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  26173. sizeof(der->publicKey), 1);
  26174. }
  26175. #endif
  26176. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  26177. if (cert->keyType == DSA_KEY) {
  26178. if (dsaKey == NULL)
  26179. return PUBLIC_KEY_E;
  26180. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  26181. sizeof(der->publicKey), 1);
  26182. }
  26183. #endif
  26184. #ifdef HAVE_ECC
  26185. if (cert->keyType == ECC_KEY) {
  26186. if (eccKey == NULL)
  26187. return PUBLIC_KEY_E;
  26188. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  26189. sizeof(der->publicKey), 1, 0);
  26190. }
  26191. #endif
  26192. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  26193. if (cert->keyType == ED25519_KEY) {
  26194. if (ed25519Key == NULL)
  26195. return PUBLIC_KEY_E;
  26196. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  26197. (word32)sizeof(der->publicKey), 1);
  26198. }
  26199. #endif
  26200. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  26201. if (cert->keyType == ED448_KEY) {
  26202. if (ed448Key == NULL)
  26203. return PUBLIC_KEY_E;
  26204. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  26205. (word32)sizeof(der->publicKey), 1);
  26206. }
  26207. #endif
  26208. #if defined(HAVE_PQC)
  26209. #if defined(HAVE_FALCON)
  26210. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  26211. (cert->keyType == FALCON_LEVEL5_KEY)) {
  26212. if (falconKey == NULL)
  26213. return PUBLIC_KEY_E;
  26214. der->publicKeySz = wc_Falcon_PublicKeyToDer(falconKey,
  26215. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26216. }
  26217. #endif
  26218. #if defined(HAVE_DILITHIUM)
  26219. if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
  26220. (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
  26221. (cert->keyType == DILITHIUM_LEVEL5_KEY) ||
  26222. (cert->keyType == DILITHIUM_AES_LEVEL2_KEY) ||
  26223. (cert->keyType == DILITHIUM_AES_LEVEL3_KEY) ||
  26224. (cert->keyType == DILITHIUM_AES_LEVEL5_KEY)) {
  26225. if (dilithiumKey == NULL)
  26226. return PUBLIC_KEY_E;
  26227. der->publicKeySz = wc_Dilithium_PublicKeyToDer(dilithiumKey,
  26228. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26229. }
  26230. #endif
  26231. #if defined(HAVE_SPHINCS)
  26232. if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
  26233. (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
  26234. (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
  26235. (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
  26236. (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
  26237. (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
  26238. if (sphincsKey == NULL)
  26239. return PUBLIC_KEY_E;
  26240. der->publicKeySz = wc_Sphincs_PublicKeyToDer(sphincsKey,
  26241. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26242. }
  26243. #endif
  26244. #endif /* HAVE_PQC */
  26245. if (der->publicKeySz <= 0)
  26246. return PUBLIC_KEY_E;
  26247. /* set the extensions */
  26248. der->extensionsSz = 0;
  26249. /* RFC 5280 : 4.2.1.9. Basic Constraints
  26250. * The pathLenConstraint field is meaningful only if the CA boolean is
  26251. * asserted and the key usage extension, if present, asserts the
  26252. * keyCertSign bit */
  26253. /* Set CA and path length */
  26254. if ((cert->isCA) && (cert->pathLenSet)
  26255. #ifdef WOLFSSL_CERT_EXT
  26256. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  26257. #endif
  26258. ) {
  26259. der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
  26260. if (der->caSz <= 0)
  26261. return CA_TRUE_E;
  26262. der->extensionsSz += der->caSz;
  26263. }
  26264. /* Set CA */
  26265. else if (cert->isCA) {
  26266. der->caSz = SetCa(der->ca, sizeof(der->ca));
  26267. if (der->caSz <= 0)
  26268. return CA_TRUE_E;
  26269. der->extensionsSz += der->caSz;
  26270. }
  26271. /* Set Basic Constraint */
  26272. else if (cert->basicConstSet) {
  26273. der->caSz = SetBC(der->ca, sizeof(der->ca));
  26274. if (der->caSz <= 0)
  26275. return EXTENSIONS_E;
  26276. der->extensionsSz += der->caSz;
  26277. }
  26278. else
  26279. der->caSz = 0;
  26280. #ifdef WOLFSSL_ALT_NAMES
  26281. /* Alternative Name */
  26282. if (cert->altNamesSz) {
  26283. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  26284. cert->altNames, cert->altNamesSz,
  26285. cert->altNamesCrit);
  26286. if (der->altNamesSz <= 0)
  26287. return ALT_NAME_E;
  26288. der->extensionsSz += der->altNamesSz;
  26289. }
  26290. else
  26291. der->altNamesSz = 0;
  26292. #endif
  26293. #ifdef WOLFSSL_CERT_EXT
  26294. /* SKID */
  26295. if (cert->skidSz) {
  26296. /* check the provided SKID size */
  26297. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  26298. return SKID_E;
  26299. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  26300. cert->skid, cert->skidSz);
  26301. if (der->skidSz <= 0)
  26302. return SKID_E;
  26303. der->extensionsSz += der->skidSz;
  26304. }
  26305. else
  26306. der->skidSz = 0;
  26307. /* Key Usage */
  26308. if (cert->keyUsage != 0) {
  26309. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  26310. cert->keyUsage);
  26311. if (der->keyUsageSz <= 0)
  26312. return KEYUSAGE_E;
  26313. der->extensionsSz += der->keyUsageSz;
  26314. }
  26315. else
  26316. der->keyUsageSz = 0;
  26317. /* Extended Key Usage */
  26318. if (cert->extKeyUsage != 0) {
  26319. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  26320. sizeof(der->extKeyUsage), cert->extKeyUsage);
  26321. if (der->extKeyUsageSz <= 0)
  26322. return EXTKEYUSAGE_E;
  26323. der->extensionsSz += der->extKeyUsageSz;
  26324. }
  26325. else
  26326. der->extKeyUsageSz = 0;
  26327. #endif /* WOLFSSL_CERT_EXT */
  26328. #ifdef WOLFSSL_CUSTOM_OID
  26329. /* encode a custom oid and value */
  26330. /* zero returns, means none set */
  26331. ret = SetCustomObjectId(cert, der->extCustom,
  26332. sizeof(der->extCustom), &cert->extCustom);
  26333. if (ret < 0)
  26334. return ret;
  26335. der->extCustomSz = ret;
  26336. der->extensionsSz += der->extCustomSz;
  26337. #endif
  26338. /* put extensions */
  26339. if (der->extensionsSz > 0) {
  26340. /* put the start of sequence (ID, Size) */
  26341. der->extensionsSz = SetSequence(der->extensionsSz, der->extensions);
  26342. if (der->extensionsSz <= 0)
  26343. return EXTENSIONS_E;
  26344. /* put CA */
  26345. if (der->caSz) {
  26346. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26347. &der->extensionsSz,
  26348. der->ca, der->caSz);
  26349. if (ret <= 0)
  26350. return EXTENSIONS_E;
  26351. }
  26352. #ifdef WOLFSSL_ALT_NAMES
  26353. /* put Alternative Names */
  26354. if (der->altNamesSz) {
  26355. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26356. &der->extensionsSz,
  26357. der->altNames, der->altNamesSz);
  26358. if (ret <= 0)
  26359. return EXTENSIONS_E;
  26360. }
  26361. #endif
  26362. #ifdef WOLFSSL_CERT_EXT
  26363. /* put SKID */
  26364. if (der->skidSz) {
  26365. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26366. &der->extensionsSz,
  26367. der->skid, der->skidSz);
  26368. if (ret <= 0)
  26369. return EXTENSIONS_E;
  26370. }
  26371. /* put AKID */
  26372. if (der->akidSz) {
  26373. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26374. &der->extensionsSz,
  26375. der->akid, der->akidSz);
  26376. if (ret <= 0)
  26377. return EXTENSIONS_E;
  26378. }
  26379. /* put KeyUsage */
  26380. if (der->keyUsageSz) {
  26381. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26382. &der->extensionsSz,
  26383. der->keyUsage, der->keyUsageSz);
  26384. if (ret <= 0)
  26385. return EXTENSIONS_E;
  26386. }
  26387. /* put ExtendedKeyUsage */
  26388. if (der->extKeyUsageSz) {
  26389. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26390. &der->extensionsSz,
  26391. der->extKeyUsage, der->extKeyUsageSz);
  26392. if (ret <= 0)
  26393. return EXTENSIONS_E;
  26394. }
  26395. #ifdef WOLFSSL_CUSTOM_OID
  26396. if (der->extCustomSz) {
  26397. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26398. &der->extensionsSz,
  26399. der->extCustom, der->extCustomSz);
  26400. if (ret <= 0)
  26401. return EXTENSIONS_E;
  26402. }
  26403. #endif
  26404. #endif /* WOLFSSL_CERT_EXT */
  26405. }
  26406. der->attribSz = SetReqAttrib(der->attrib, cert, der->extensionsSz);
  26407. if (der->attribSz <= 0)
  26408. return REQ_ATTRIBUTE_E;
  26409. der->total = der->versionSz + der->subjectSz + der->publicKeySz +
  26410. der->extensionsSz + der->attribSz;
  26411. return 0;
  26412. }
  26413. /* write DER encoded cert req to buffer, size already checked */
  26414. static int WriteCertReqBody(DerCert* der, byte* buf)
  26415. {
  26416. int idx;
  26417. /* signed part header */
  26418. idx = SetSequence(der->total, buf);
  26419. /* version */
  26420. if (buf)
  26421. XMEMCPY(buf + idx, der->version, der->versionSz);
  26422. idx += der->versionSz;
  26423. /* subject */
  26424. if (buf)
  26425. XMEMCPY(buf + idx, der->subject, der->subjectSz);
  26426. idx += der->subjectSz;
  26427. /* public key */
  26428. if (buf)
  26429. XMEMCPY(buf + idx, der->publicKey, der->publicKeySz);
  26430. idx += der->publicKeySz;
  26431. /* attributes */
  26432. if (buf)
  26433. XMEMCPY(buf + idx, der->attrib, der->attribSz);
  26434. idx += der->attribSz;
  26435. /* extensions */
  26436. if (der->extensionsSz) {
  26437. if (buf)
  26438. XMEMCPY(buf + idx, der->extensions, min(der->extensionsSz,
  26439. (int)sizeof(der->extensions)));
  26440. idx += der->extensionsSz;
  26441. }
  26442. return idx;
  26443. }
  26444. #endif
  26445. #ifdef WOLFSSL_ASN_TEMPLATE
  26446. /* ASN.1 template for Certificate Request body.
  26447. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  26448. */
  26449. static const ASNItem certReqBodyASN[] = {
  26450. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  26451. /* version */
  26452. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  26453. /* subject */
  26454. /* SUBJ_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  26455. /* subjectPKInfo */
  26456. /* SPUBKEYINFO_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  26457. /* attributes*/
  26458. /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  26459. /* Challenge Password Attribute */
  26460. /* ATTRS_CPW_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  26461. /* ATTRS_CPW_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  26462. /* ATTRS_CPW_SET */ { 3, ASN_SET, 1, 1, 0 },
  26463. /* ATTRS_CPW_PS */ { 4, ASN_PRINTABLE_STRING, 0, 0, 0 },
  26464. /* ATTRS_CPW_UTF */ { 4, ASN_UTF8STRING, 0, 0, 0 },
  26465. /* Extensions Attribute */
  26466. /* EXT_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  26467. /* EXT_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  26468. /* EXT_SET */ { 3, ASN_SET, 1, 1, 0 },
  26469. /* EXT_BODY */ { 4, ASN_SEQUENCE, 1, 0, 0 },
  26470. };
  26471. enum {
  26472. CERTREQBODYASN_IDX_SEQ = 0,
  26473. CERTREQBODYASN_IDX_VER,
  26474. CERTREQBODYASN_IDX_SUBJ_SEQ,
  26475. CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ,
  26476. CERTREQBODYASN_IDX_ATTRS,
  26477. CERTREQBODYASN_IDX_ATTRS_CPW_SEQ,
  26478. CERTREQBODYASN_IDX_ATTRS_CPW_OID,
  26479. CERTREQBODYASN_IDX_ATTRS_CPW_SET,
  26480. CERTREQBODYASN_IDX_ATTRS_CPW_PS,
  26481. CERTREQBODYASN_IDX_ATTRS_CPW_UTF,
  26482. CERTREQBODYASN_IDX_EXT_SEQ,
  26483. CERTREQBODYASN_IDX_EXT_OID,
  26484. CERTREQBODYASN_IDX_EXT_SET,
  26485. CERTREQBODYASN_IDX_EXT_BODY,
  26486. };
  26487. /* Number of items in ASN.1 template for Certificate Request body. */
  26488. #define certReqBodyASN_Length (sizeof(certReqBodyASN) / sizeof(ASNItem))
  26489. #endif
  26490. static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  26491. RsaKey* rsaKey, DsaKey* dsaKey, ecc_key* eccKey,
  26492. ed25519_key* ed25519Key, ed448_key* ed448Key,
  26493. falcon_key* falconKey, dilithium_key* dilithiumKey,
  26494. sphincs_key* sphincsKey)
  26495. {
  26496. #ifndef WOLFSSL_ASN_TEMPLATE
  26497. int ret;
  26498. #ifdef WOLFSSL_SMALL_STACK
  26499. DerCert* der;
  26500. #else
  26501. DerCert der[1];
  26502. #endif
  26503. if (eccKey)
  26504. cert->keyType = ECC_KEY;
  26505. else if (rsaKey)
  26506. cert->keyType = RSA_KEY;
  26507. else if (dsaKey)
  26508. cert->keyType = DSA_KEY;
  26509. else if (ed25519Key)
  26510. cert->keyType = ED25519_KEY;
  26511. else if (ed448Key)
  26512. cert->keyType = ED448_KEY;
  26513. #ifdef HAVE_PQC
  26514. #ifdef HAVE_FALCON
  26515. else if ((falconKey != NULL) && (falconKey->level == 1))
  26516. cert->keyType = FALCON_LEVEL1_KEY;
  26517. else if ((falconKey != NULL) && (falconKey->level == 5))
  26518. cert->keyType = FALCON_LEVEL5_KEY;
  26519. #endif /* HAVE_FALCON */
  26520. #ifdef HAVE_DILITHIUM
  26521. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)
  26522. && (dilithiumKey->sym == SHAKE_VARIANT))
  26523. cert->keyType = DILITHIUM_LEVEL2_KEY;
  26524. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)
  26525. && (dilithiumKey->sym == SHAKE_VARIANT))
  26526. cert->keyType = DILITHIUM_LEVEL3_KEY;
  26527. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)
  26528. && (dilithiumKey->sym == SHAKE_VARIANT))
  26529. cert->keyType = DILITHIUM_LEVEL5_KEY;
  26530. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)
  26531. && (dilithiumKey->sym == AES_VARIANT))
  26532. cert->keyType = DILITHIUM_AES_LEVEL2_KEY;
  26533. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)
  26534. && (dilithiumKey->sym == AES_VARIANT))
  26535. cert->keyType = DILITHIUM_AES_LEVEL3_KEY;
  26536. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)
  26537. && (dilithiumKey->sym == AES_VARIANT))
  26538. cert->keyType = DILITHIUM_AES_LEVEL5_KEY;
  26539. #endif /* HAVE_DILITHIUM */
  26540. #ifdef HAVE_SPHINCS
  26541. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26542. && (sphincsKey->optim == FAST_VARIANT))
  26543. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  26544. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26545. && (sphincsKey->optim == FAST_VARIANT))
  26546. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  26547. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26548. && (sphincsKey->optim == FAST_VARIANT))
  26549. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  26550. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26551. && (sphincsKey->optim == SMALL_VARIANT))
  26552. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  26553. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26554. && (sphincsKey->optim == SMALL_VARIANT))
  26555. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  26556. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26557. && (sphincsKey->optim == SMALL_VARIANT))
  26558. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  26559. #endif /* HAVE_SPHINCS */
  26560. #endif /* HAVE_PQC */
  26561. else
  26562. return BAD_FUNC_ARG;
  26563. #ifdef WOLFSSL_SMALL_STACK
  26564. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap,
  26565. DYNAMIC_TYPE_TMP_BUFFER);
  26566. if (der == NULL)
  26567. return MEMORY_E;
  26568. #endif
  26569. ret = EncodeCertReq(cert, der, rsaKey, dsaKey, eccKey, ed25519Key, ed448Key,
  26570. falconKey, dilithiumKey, sphincsKey);
  26571. if (ret == 0) {
  26572. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  26573. ret = BUFFER_E;
  26574. else
  26575. ret = cert->bodySz = WriteCertReqBody(der, derBuffer);
  26576. }
  26577. #ifdef WOLFSSL_SMALL_STACK
  26578. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  26579. #endif
  26580. return ret;
  26581. #else
  26582. DECL_ASNSETDATA(dataASN, certReqBodyASN_Length);
  26583. word32 publicKeySz;
  26584. word32 subjectSz = 0;
  26585. word32 extSz;
  26586. int sz = 0;
  26587. int ret = 0;
  26588. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26589. word32 sbjRawSz;
  26590. #endif
  26591. /* Unused without OQS */
  26592. (void)falconKey;
  26593. (void)dilithiumKey;
  26594. (void)sphincsKey;
  26595. CALLOC_ASNSETDATA(dataASN, certReqBodyASN_Length, ret, cert->heap);
  26596. if (ret == 0) {
  26597. /* Set key type into certificate object based on key passed in. */
  26598. if (rsaKey != NULL) {
  26599. cert->keyType = RSA_KEY;
  26600. }
  26601. else if (eccKey != NULL) {
  26602. cert->keyType = ECC_KEY;
  26603. }
  26604. else if (dsaKey != NULL) {
  26605. cert->keyType = DSA_KEY;
  26606. }
  26607. else if (ed25519Key != NULL) {
  26608. cert->keyType = ED25519_KEY;
  26609. }
  26610. else if (ed448Key != NULL) {
  26611. cert->keyType = ED448_KEY;
  26612. }
  26613. #ifdef HAVE_PQC
  26614. #ifdef HAVE_FALCON
  26615. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  26616. cert->keyType = FALCON_LEVEL1_KEY;
  26617. }
  26618. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  26619. cert->keyType = FALCON_LEVEL5_KEY;
  26620. }
  26621. #endif /* HAVE_FALCON */
  26622. #ifdef HAVE_DILITHIUM
  26623. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)
  26624. && (dilithiumKey->sym == SHAKE_VARIANT)) {
  26625. cert->keyType = DILITHIUM_LEVEL2_KEY;
  26626. }
  26627. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)
  26628. && (dilithiumKey->sym == SHAKE_VARIANT)) {
  26629. cert->keyType = DILITHIUM_LEVEL3_KEY;
  26630. }
  26631. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)
  26632. && (dilithiumKey->sym == SHAKE_VARIANT)) {
  26633. cert->keyType = DILITHIUM_LEVEL5_KEY;
  26634. }
  26635. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)
  26636. && (dilithiumKey->sym == AES_VARIANT)) {
  26637. cert->keyType = DILITHIUM_AES_LEVEL2_KEY;
  26638. }
  26639. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)
  26640. && (dilithiumKey->sym == AES_VARIANT)) {
  26641. cert->keyType = DILITHIUM_AES_LEVEL3_KEY;
  26642. }
  26643. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)
  26644. && (dilithiumKey->sym == AES_VARIANT)) {
  26645. cert->keyType = DILITHIUM_AES_LEVEL5_KEY;
  26646. }
  26647. #endif /* HAVE_DILITHIUM */
  26648. #ifdef HAVE_SPHINCS
  26649. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26650. && (sphincsKey->optim == FAST_VARIANT)) {
  26651. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  26652. }
  26653. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26654. && (sphincsKey->optim == FAST_VARIANT)) {
  26655. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  26656. }
  26657. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26658. && (sphincsKey->optim == FAST_VARIANT)) {
  26659. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  26660. }
  26661. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26662. && (sphincsKey->optim == SMALL_VARIANT)) {
  26663. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  26664. }
  26665. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26666. && (sphincsKey->optim == SMALL_VARIANT)) {
  26667. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  26668. }
  26669. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26670. && (sphincsKey->optim == SMALL_VARIANT)) {
  26671. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  26672. }
  26673. #endif /* HAVE_SPHINCS */
  26674. #endif /* HAVE_PQC */
  26675. else {
  26676. ret = BAD_FUNC_ARG;
  26677. }
  26678. }
  26679. if (ret == 0) {
  26680. /* Determine subject name size. */
  26681. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26682. sbjRawSz = (word32)XSTRLEN((const char*)cert->sbjRaw);
  26683. if (sbjRawSz > 0) {
  26684. subjectSz = min(sizeof(cert->sbjRaw), sbjRawSz);
  26685. }
  26686. else
  26687. #endif
  26688. {
  26689. subjectSz = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject, cert->heap);
  26690. ret = subjectSz;
  26691. }
  26692. }
  26693. if (ret >= 0) {
  26694. /* Determine encode public key size. */
  26695. ret = publicKeySz = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  26696. eccKey, ed25519Key, ed448Key, dsaKey);
  26697. }
  26698. if (ret >= 0) {
  26699. /* Determine encode extensions size. */
  26700. ret = extSz = EncodeExtensions(cert, NULL, 0, 1);
  26701. }
  26702. if (ret >= 0) {
  26703. /* Set version. */
  26704. SetASN_Int8Bit(&dataASN[CERTREQBODYASN_IDX_VER], cert->version);
  26705. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26706. if (sbjRawSz > 0) {
  26707. /* Put in encoded subject name. */
  26708. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], cert->sbjRaw,
  26709. subjectSz);
  26710. }
  26711. else
  26712. #endif
  26713. {
  26714. /* Leave space for subject name. */
  26715. SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], NULL,
  26716. subjectSz);
  26717. }
  26718. /* Leave space for public key. */
  26719. SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ],
  26720. NULL, publicKeySz);
  26721. if (cert->challengePw[0] != '\0') {
  26722. /* Add challenge password attribute. */
  26723. /* Set challenge password OID. */
  26724. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_OID],
  26725. attrChallengePasswordOid, sizeof(attrChallengePasswordOid));
  26726. /* Enable the ASN template item with the appropriate tag. */
  26727. if (cert->challengePwPrintableString) {
  26728. /* PRINTABLE_STRING - set buffer */
  26729. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS],
  26730. (byte*)cert->challengePw,
  26731. (word32)XSTRLEN(cert->challengePw));
  26732. /* UTF8STRING - don't encode */
  26733. dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF].noOut = 1;
  26734. }
  26735. else {
  26736. /* PRINTABLE_STRING - don't encode */
  26737. dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS].noOut = 1;
  26738. /* UTF8STRING - set buffer */
  26739. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF],
  26740. (byte*)cert->challengePw,
  26741. (word32)XSTRLEN(cert->challengePw));
  26742. }
  26743. }
  26744. else {
  26745. /* Leave out challenge password attribute items. */
  26746. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  26747. CERTREQBODYASN_IDX_ATTRS_CPW_SEQ, certReqBodyASN_Length);
  26748. }
  26749. if (extSz > 0) {
  26750. /* Set extension attribute OID. */
  26751. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_OID], attrExtensionRequestOid,
  26752. sizeof(attrExtensionRequestOid));
  26753. /* Leave space for data. */
  26754. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_BODY], NULL, extSz);
  26755. }
  26756. else {
  26757. /* Leave out extension attribute items. */
  26758. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  26759. CERTREQBODYASN_IDX_EXT_SEQ, certReqBodyASN_Length);
  26760. }
  26761. /* Calculate size of encoded certificate request body. */
  26762. ret = SizeASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length,
  26763. &sz);
  26764. }
  26765. /* Check buffer is big enough for encoded data. */
  26766. if ((ret == 0) && (sz > (int)derSz)) {
  26767. ret = BUFFER_E;
  26768. }
  26769. if (ret == 0 && derBuffer != NULL) {
  26770. /* Encode certificate request body into buffer. */
  26771. SetASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length, derBuffer);
  26772. /* Put in generated data */
  26773. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26774. if (sbjRawSz == 0)
  26775. #endif
  26776. {
  26777. /* Encode subject name into space in buffer. */
  26778. ret = SetNameEx(
  26779. (byte*)dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.data,
  26780. dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.length,
  26781. &cert->subject, cert->heap);
  26782. }
  26783. }
  26784. if (ret >= 0 && derBuffer != NULL) {
  26785. /* Encode public key into space in buffer. */
  26786. ret = EncodePublicKey(cert->keyType,
  26787. (byte*)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.data,
  26788. dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.length,
  26789. rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
  26790. }
  26791. if ((ret >= 0 && derBuffer != NULL) &&
  26792. (!dataASN[CERTREQBODYASN_IDX_EXT_BODY].noOut)) {
  26793. /* Encode extensions into space in buffer. */
  26794. ret = EncodeExtensions(cert,
  26795. (byte*)dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.data,
  26796. dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.length, 1);
  26797. }
  26798. if (ret >= 0) {
  26799. /* Store encoded certifcate request body size. */
  26800. cert->bodySz = sz;
  26801. /* Return the encoding size. */
  26802. ret = sz;
  26803. }
  26804. FREE_ASNSETDATA(dataASN, cert->heap);
  26805. return ret;
  26806. #endif /* WOLFSSL_ASN_TEMPLATE */
  26807. }
  26808. int wc_MakeCertReq_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  26809. void* key)
  26810. {
  26811. RsaKey* rsaKey = NULL;
  26812. DsaKey* dsaKey = NULL;
  26813. ecc_key* eccKey = NULL;
  26814. ed25519_key* ed25519Key = NULL;
  26815. ed448_key* ed448Key = NULL;
  26816. falcon_key* falconKey = NULL;
  26817. dilithium_key* dilithiumKey = NULL;
  26818. sphincs_key* sphincsKey = NULL;
  26819. if (keyType == RSA_TYPE)
  26820. rsaKey = (RsaKey*)key;
  26821. else if (keyType == DSA_TYPE)
  26822. dsaKey = (DsaKey*)key;
  26823. else if (keyType == ECC_TYPE)
  26824. eccKey = (ecc_key*)key;
  26825. else if (keyType == ED25519_TYPE)
  26826. ed25519Key = (ed25519_key*)key;
  26827. else if (keyType == ED448_TYPE)
  26828. ed448Key = (ed448_key*)key;
  26829. else if (keyType == FALCON_LEVEL1_TYPE)
  26830. falconKey = (falcon_key*)key;
  26831. else if (keyType == FALCON_LEVEL5_TYPE)
  26832. falconKey = (falcon_key*)key;
  26833. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  26834. dilithiumKey = (dilithium_key*)key;
  26835. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  26836. dilithiumKey = (dilithium_key*)key;
  26837. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  26838. dilithiumKey = (dilithium_key*)key;
  26839. else if (keyType == DILITHIUM_AES_LEVEL2_TYPE)
  26840. dilithiumKey = (dilithium_key*)key;
  26841. else if (keyType == DILITHIUM_AES_LEVEL3_TYPE)
  26842. dilithiumKey = (dilithium_key*)key;
  26843. else if (keyType == DILITHIUM_AES_LEVEL5_TYPE)
  26844. dilithiumKey = (dilithium_key*)key;
  26845. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  26846. sphincsKey = (sphincs_key*)key;
  26847. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  26848. sphincsKey = (sphincs_key*)key;
  26849. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  26850. sphincsKey = (sphincs_key*)key;
  26851. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  26852. sphincsKey = (sphincs_key*)key;
  26853. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  26854. sphincsKey = (sphincs_key*)key;
  26855. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  26856. sphincsKey = (sphincs_key*)key;
  26857. return MakeCertReq(cert, derBuffer, derSz, rsaKey, dsaKey, eccKey,
  26858. ed25519Key, ed448Key, falconKey, dilithiumKey,
  26859. sphincsKey);
  26860. }
  26861. WOLFSSL_ABI
  26862. int wc_MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  26863. RsaKey* rsaKey, ecc_key* eccKey)
  26864. {
  26865. return MakeCertReq(cert, derBuffer, derSz, rsaKey, NULL, eccKey, NULL,
  26866. NULL, NULL, NULL, NULL);
  26867. }
  26868. #endif /* WOLFSSL_CERT_REQ */
  26869. static int SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  26870. RsaKey* rsaKey, ecc_key* eccKey, ed25519_key* ed25519Key,
  26871. ed448_key* ed448Key, falcon_key* falconKey,
  26872. dilithium_key* dilithiumKey, sphincs_key* sphincsKey,
  26873. WC_RNG* rng)
  26874. {
  26875. int sigSz = 0;
  26876. void* heap = NULL;
  26877. CertSignCtx* certSignCtx;
  26878. #ifndef WOLFSSL_ASYNC_CRYPT
  26879. CertSignCtx certSignCtx_lcl;
  26880. certSignCtx = &certSignCtx_lcl;
  26881. XMEMSET(certSignCtx, 0, sizeof(CertSignCtx));
  26882. #else
  26883. certSignCtx = NULL;
  26884. #endif
  26885. if (requestSz < 0)
  26886. return requestSz;
  26887. /* locate ctx */
  26888. if (rsaKey) {
  26889. #ifndef NO_RSA
  26890. #ifdef WOLFSSL_ASYNC_CRYPT
  26891. certSignCtx = &rsaKey->certSignCtx;
  26892. #endif
  26893. heap = rsaKey->heap;
  26894. #else
  26895. return NOT_COMPILED_IN;
  26896. #endif /* NO_RSA */
  26897. }
  26898. else if (eccKey) {
  26899. #ifdef HAVE_ECC
  26900. #ifdef WOLFSSL_ASYNC_CRYPT
  26901. certSignCtx = &eccKey->certSignCtx;
  26902. #endif
  26903. heap = eccKey->heap;
  26904. #else
  26905. return NOT_COMPILED_IN;
  26906. #endif /* HAVE_ECC */
  26907. }
  26908. #ifdef WOLFSSL_ASYNC_CRYPT
  26909. if (certSignCtx == NULL) {
  26910. return BAD_FUNC_ARG;
  26911. }
  26912. #endif
  26913. if (certSignCtx->sig == NULL) {
  26914. certSignCtx->sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, heap,
  26915. DYNAMIC_TYPE_TMP_BUFFER);
  26916. if (certSignCtx->sig == NULL)
  26917. return MEMORY_E;
  26918. }
  26919. sigSz = MakeSignature(certSignCtx, buf, requestSz, certSignCtx->sig,
  26920. MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key,
  26921. falconKey, dilithiumKey, sphincsKey, rng, sType, heap);
  26922. #ifdef WOLFSSL_ASYNC_CRYPT
  26923. if (sigSz == WC_PENDING_E) {
  26924. /* Not free'ing certSignCtx->sig here because it could still be in use
  26925. * with async operations. */
  26926. return sigSz;
  26927. }
  26928. #endif
  26929. if (sigSz >= 0) {
  26930. if (requestSz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
  26931. sigSz = BUFFER_E;
  26932. else
  26933. sigSz = AddSignature(buf, requestSz, certSignCtx->sig, sigSz,
  26934. sType);
  26935. }
  26936. XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  26937. certSignCtx->sig = NULL;
  26938. return sigSz;
  26939. }
  26940. int wc_SignCert_ex(int requestSz, int sType, byte* buf, word32 buffSz,
  26941. int keyType, void* key, WC_RNG* rng)
  26942. {
  26943. RsaKey* rsaKey = NULL;
  26944. ecc_key* eccKey = NULL;
  26945. ed25519_key* ed25519Key = NULL;
  26946. ed448_key* ed448Key = NULL;
  26947. falcon_key* falconKey = NULL;
  26948. dilithium_key* dilithiumKey = NULL;
  26949. sphincs_key* sphincsKey = NULL;
  26950. if (keyType == RSA_TYPE)
  26951. rsaKey = (RsaKey*)key;
  26952. else if (keyType == ECC_TYPE)
  26953. eccKey = (ecc_key*)key;
  26954. else if (keyType == ED25519_TYPE)
  26955. ed25519Key = (ed25519_key*)key;
  26956. else if (keyType == ED448_TYPE)
  26957. ed448Key = (ed448_key*)key;
  26958. else if (keyType == FALCON_LEVEL1_TYPE)
  26959. falconKey = (falcon_key*)key;
  26960. else if (keyType == FALCON_LEVEL5_TYPE)
  26961. falconKey = (falcon_key*)key;
  26962. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  26963. dilithiumKey = (dilithium_key*)key;
  26964. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  26965. dilithiumKey = (dilithium_key*)key;
  26966. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  26967. dilithiumKey = (dilithium_key*)key;
  26968. else if (keyType == DILITHIUM_AES_LEVEL2_TYPE)
  26969. dilithiumKey = (dilithium_key*)key;
  26970. else if (keyType == DILITHIUM_AES_LEVEL3_TYPE)
  26971. dilithiumKey = (dilithium_key*)key;
  26972. else if (keyType == DILITHIUM_AES_LEVEL5_TYPE)
  26973. dilithiumKey = (dilithium_key*)key;
  26974. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  26975. sphincsKey = (sphincs_key*)key;
  26976. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  26977. sphincsKey = (sphincs_key*)key;
  26978. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  26979. sphincsKey = (sphincs_key*)key;
  26980. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  26981. sphincsKey = (sphincs_key*)key;
  26982. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  26983. sphincsKey = (sphincs_key*)key;
  26984. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  26985. sphincsKey = (sphincs_key*)key;
  26986. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, ed25519Key,
  26987. ed448Key, falconKey, dilithiumKey, sphincsKey, rng);
  26988. }
  26989. int wc_SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  26990. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng)
  26991. {
  26992. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, NULL, NULL,
  26993. NULL, NULL, NULL, rng);
  26994. }
  26995. WOLFSSL_ABI
  26996. int wc_MakeSelfCert(Cert* cert, byte* buf, word32 buffSz,
  26997. RsaKey* key, WC_RNG* rng)
  26998. {
  26999. int ret;
  27000. ret = wc_MakeCert(cert, buf, buffSz, key, NULL, rng);
  27001. if (ret < 0)
  27002. return ret;
  27003. return wc_SignCert(cert->bodySz, cert->sigType,
  27004. buf, buffSz, key, NULL, rng);
  27005. }
  27006. #ifdef WOLFSSL_CERT_EXT
  27007. /* Get raw subject from cert, which may contain OIDs not parsed by Decode.
  27008. The raw subject pointer will only be valid while "cert" is valid. */
  27009. WOLFSSL_ABI
  27010. int wc_GetSubjectRaw(byte **subjectRaw, Cert *cert)
  27011. {
  27012. int rc = BAD_FUNC_ARG;
  27013. if ((subjectRaw != NULL) && (cert != NULL)) {
  27014. *subjectRaw = cert->sbjRaw;
  27015. rc = 0;
  27016. }
  27017. return rc;
  27018. }
  27019. /* Set KID from public key */
  27020. static int SetKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey,
  27021. ed25519_key* ed25519Key, ed448_key* ed448Key,
  27022. falcon_key* falconKey,
  27023. dilithium_key* dilithiumKey,
  27024. sphincs_key *sphincsKey, int kid_type)
  27025. {
  27026. byte *buf;
  27027. int bufferSz, ret;
  27028. if (cert == NULL ||
  27029. (rsakey == NULL && eckey == NULL && ed25519Key == NULL &&
  27030. ed448Key == NULL && falconKey == NULL && dilithiumKey == NULL &&
  27031. sphincsKey == NULL) ||
  27032. (kid_type != SKID_TYPE && kid_type != AKID_TYPE))
  27033. return BAD_FUNC_ARG;
  27034. buf = (byte *)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap,
  27035. DYNAMIC_TYPE_TMP_BUFFER);
  27036. if (buf == NULL)
  27037. return MEMORY_E;
  27038. /* Public Key */
  27039. bufferSz = -1;
  27040. #ifndef NO_RSA
  27041. /* RSA public key */
  27042. if (rsakey != NULL)
  27043. bufferSz = SetRsaPublicKey(buf, rsakey, MAX_PUBLIC_KEY_SZ, 0);
  27044. #endif
  27045. #ifdef HAVE_ECC
  27046. /* ECC public key */
  27047. if (eckey != NULL)
  27048. bufferSz = SetEccPublicKey(buf, eckey, MAX_PUBLIC_KEY_SZ, 0, 0);
  27049. #endif
  27050. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  27051. /* ED25519 public key */
  27052. if (ed25519Key != NULL) {
  27053. bufferSz = wc_Ed25519PublicKeyToDer(ed25519Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  27054. }
  27055. #endif
  27056. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  27057. /* ED448 public key */
  27058. if (ed448Key != NULL) {
  27059. bufferSz = wc_Ed448PublicKeyToDer(ed448Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  27060. }
  27061. #endif
  27062. #if defined(HAVE_PQC)
  27063. #if defined(HAVE_FALCON)
  27064. if (falconKey != NULL) {
  27065. bufferSz = wc_Falcon_PublicKeyToDer(falconKey, buf, MAX_PUBLIC_KEY_SZ,
  27066. 0);
  27067. }
  27068. #endif
  27069. #if defined(HAVE_DILITHIUM)
  27070. if (dilithiumKey != NULL) {
  27071. bufferSz = wc_Dilithium_PublicKeyToDer(dilithiumKey, buf,
  27072. MAX_PUBLIC_KEY_SZ, 0);
  27073. }
  27074. #endif
  27075. #if defined(HAVE_SPHINCS)
  27076. if (sphincsKey != NULL) {
  27077. bufferSz = wc_Sphincs_PublicKeyToDer(sphincsKey, buf,
  27078. MAX_PUBLIC_KEY_SZ, 0);
  27079. }
  27080. #endif
  27081. #endif /* HAVE_PQC */
  27082. if (bufferSz <= 0) {
  27083. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27084. return PUBLIC_KEY_E;
  27085. }
  27086. /* Compute SKID by hashing public key */
  27087. if (kid_type == SKID_TYPE) {
  27088. ret = CalcHashId(buf, bufferSz, cert->skid);
  27089. cert->skidSz = KEYID_SIZE;
  27090. }
  27091. else if (kid_type == AKID_TYPE) {
  27092. ret = CalcHashId(buf, bufferSz, cert->akid);
  27093. cert->akidSz = KEYID_SIZE;
  27094. }
  27095. else
  27096. ret = BAD_FUNC_ARG;
  27097. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27098. return ret;
  27099. }
  27100. int wc_SetSubjectKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  27101. {
  27102. RsaKey* rsaKey = NULL;
  27103. ecc_key* eccKey = NULL;
  27104. ed25519_key* ed25519Key = NULL;
  27105. ed448_key* ed448Key = NULL;
  27106. falcon_key* falconKey = NULL;
  27107. dilithium_key* dilithiumKey = NULL;
  27108. sphincs_key* sphincsKey = NULL;
  27109. if (keyType == RSA_TYPE)
  27110. rsaKey = (RsaKey*)key;
  27111. else if (keyType == ECC_TYPE)
  27112. eccKey = (ecc_key*)key;
  27113. else if (keyType == ED25519_TYPE)
  27114. ed25519Key = (ed25519_key*)key;
  27115. else if (keyType == ED448_TYPE)
  27116. ed448Key = (ed448_key*)key;
  27117. else if (keyType == FALCON_LEVEL1_TYPE)
  27118. falconKey = (falcon_key*)key;
  27119. else if (keyType == FALCON_LEVEL5_TYPE)
  27120. falconKey = (falcon_key*)key;
  27121. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27122. dilithiumKey = (dilithium_key*)key;
  27123. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27124. dilithiumKey = (dilithium_key*)key;
  27125. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27126. dilithiumKey = (dilithium_key*)key;
  27127. else if (keyType == DILITHIUM_AES_LEVEL2_TYPE)
  27128. dilithiumKey = (dilithium_key*)key;
  27129. else if (keyType == DILITHIUM_AES_LEVEL3_TYPE)
  27130. dilithiumKey = (dilithium_key*)key;
  27131. else if (keyType == DILITHIUM_AES_LEVEL5_TYPE)
  27132. dilithiumKey = (dilithium_key*)key;
  27133. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27134. sphincsKey = (sphincs_key*)key;
  27135. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27136. sphincsKey = (sphincs_key*)key;
  27137. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27138. sphincsKey = (sphincs_key*)key;
  27139. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27140. sphincsKey = (sphincs_key*)key;
  27141. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27142. sphincsKey = (sphincs_key*)key;
  27143. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27144. sphincsKey = (sphincs_key*)key;
  27145. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  27146. falconKey, dilithiumKey, sphincsKey,
  27147. SKID_TYPE);
  27148. }
  27149. /* Set SKID from RSA or ECC public key */
  27150. int wc_SetSubjectKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  27151. {
  27152. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
  27153. NULL, SKID_TYPE);
  27154. }
  27155. int wc_SetAuthKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  27156. {
  27157. RsaKey* rsaKey = NULL;
  27158. ecc_key* eccKey = NULL;
  27159. ed25519_key* ed25519Key = NULL;
  27160. ed448_key* ed448Key = NULL;
  27161. falcon_key* falconKey = NULL;
  27162. dilithium_key* dilithiumKey = NULL;
  27163. sphincs_key* sphincsKey = NULL;
  27164. if (keyType == RSA_TYPE)
  27165. rsaKey = (RsaKey*)key;
  27166. else if (keyType == ECC_TYPE)
  27167. eccKey = (ecc_key*)key;
  27168. else if (keyType == ED25519_TYPE)
  27169. ed25519Key = (ed25519_key*)key;
  27170. else if (keyType == ED448_TYPE)
  27171. ed448Key = (ed448_key*)key;
  27172. else if (keyType == FALCON_LEVEL1_TYPE)
  27173. falconKey = (falcon_key*)key;
  27174. else if (keyType == FALCON_LEVEL5_TYPE)
  27175. falconKey = (falcon_key*)key;
  27176. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27177. dilithiumKey = (dilithium_key*)key;
  27178. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27179. dilithiumKey = (dilithium_key*)key;
  27180. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27181. dilithiumKey = (dilithium_key*)key;
  27182. else if (keyType == DILITHIUM_AES_LEVEL2_TYPE)
  27183. dilithiumKey = (dilithium_key*)key;
  27184. else if (keyType == DILITHIUM_AES_LEVEL3_TYPE)
  27185. dilithiumKey = (dilithium_key*)key;
  27186. else if (keyType == DILITHIUM_AES_LEVEL5_TYPE)
  27187. dilithiumKey = (dilithium_key*)key;
  27188. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27189. sphincsKey = (sphincs_key*)key;
  27190. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27191. sphincsKey = (sphincs_key*)key;
  27192. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27193. sphincsKey = (sphincs_key*)key;
  27194. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27195. sphincsKey = (sphincs_key*)key;
  27196. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27197. sphincsKey = (sphincs_key*)key;
  27198. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27199. sphincsKey = (sphincs_key*)key;
  27200. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  27201. falconKey, dilithiumKey, sphincsKey,
  27202. AKID_TYPE);
  27203. }
  27204. /* Set SKID from RSA or ECC public key */
  27205. int wc_SetAuthKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  27206. {
  27207. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
  27208. NULL, AKID_TYPE);
  27209. }
  27210. #if !defined(NO_FILESYSTEM) && !defined(NO_ASN_CRYPT)
  27211. /* Set SKID from public key file in PEM */
  27212. int wc_SetSubjectKeyId(Cert *cert, const char* file)
  27213. {
  27214. int ret, derSz;
  27215. byte* der;
  27216. word32 idx;
  27217. RsaKey *rsakey = NULL;
  27218. ecc_key *eckey = NULL;
  27219. if (cert == NULL || file == NULL)
  27220. return BAD_FUNC_ARG;
  27221. der = (byte*)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap, DYNAMIC_TYPE_CERT);
  27222. if (der == NULL) {
  27223. WOLFSSL_MSG("wc_SetSubjectKeyId memory Problem");
  27224. return MEMORY_E;
  27225. }
  27226. derSz = MAX_PUBLIC_KEY_SZ;
  27227. XMEMSET(der, 0, derSz);
  27228. derSz = wc_PemPubKeyToDer(file, der, derSz);
  27229. if (derSz <= 0) {
  27230. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27231. return derSz;
  27232. }
  27233. /* Load PubKey in internal structure */
  27234. #ifndef NO_RSA
  27235. rsakey = (RsaKey*) XMALLOC(sizeof(RsaKey), cert->heap, DYNAMIC_TYPE_RSA);
  27236. if (rsakey == NULL) {
  27237. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27238. return MEMORY_E;
  27239. }
  27240. if (wc_InitRsaKey(rsakey, cert->heap) != 0) {
  27241. WOLFSSL_MSG("wc_InitRsaKey failure");
  27242. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27243. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27244. return MEMORY_E;
  27245. }
  27246. idx = 0;
  27247. ret = wc_RsaPublicKeyDecode(der, &idx, rsakey, derSz);
  27248. if (ret != 0)
  27249. #endif
  27250. {
  27251. #ifndef NO_RSA
  27252. WOLFSSL_MSG("wc_RsaPublicKeyDecode failed");
  27253. wc_FreeRsaKey(rsakey);
  27254. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27255. rsakey = NULL;
  27256. #endif
  27257. #ifdef HAVE_ECC
  27258. /* Check to load ecc public key */
  27259. eckey = (ecc_key*) XMALLOC(sizeof(ecc_key), cert->heap,
  27260. DYNAMIC_TYPE_ECC);
  27261. if (eckey == NULL) {
  27262. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27263. return MEMORY_E;
  27264. }
  27265. if (wc_ecc_init(eckey) != 0) {
  27266. WOLFSSL_MSG("wc_ecc_init failure");
  27267. wc_ecc_free(eckey);
  27268. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27269. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27270. return MEMORY_E;
  27271. }
  27272. idx = 0;
  27273. ret = wc_EccPublicKeyDecode(der, &idx, eckey, derSz);
  27274. if (ret != 0) {
  27275. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  27276. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27277. wc_ecc_free(eckey);
  27278. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27279. return PUBLIC_KEY_E;
  27280. }
  27281. #else
  27282. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27283. return PUBLIC_KEY_E;
  27284. #endif /* HAVE_ECC */
  27285. }
  27286. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27287. ret = wc_SetSubjectKeyIdFromPublicKey(cert, rsakey, eckey);
  27288. #ifndef NO_RSA
  27289. wc_FreeRsaKey(rsakey);
  27290. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27291. #endif
  27292. #ifdef HAVE_ECC
  27293. wc_ecc_free(eckey);
  27294. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27295. #endif
  27296. return ret;
  27297. }
  27298. #endif /* !NO_FILESYSTEM && !NO_ASN_CRYPT */
  27299. static int SetAuthKeyIdFromDcert(Cert* cert, DecodedCert* decoded)
  27300. {
  27301. int ret = 0;
  27302. /* Subject Key Id not found !! */
  27303. if (decoded->extSubjKeyIdSet == 0) {
  27304. ret = ASN_NO_SKID;
  27305. }
  27306. /* SKID invalid size */
  27307. else if (sizeof(cert->akid) < sizeof(decoded->extSubjKeyId)) {
  27308. ret = MEMORY_E;
  27309. }
  27310. else {
  27311. /* Put the SKID of CA to AKID of certificate */
  27312. XMEMCPY(cert->akid, decoded->extSubjKeyId, KEYID_SIZE);
  27313. cert->akidSz = KEYID_SIZE;
  27314. }
  27315. return ret;
  27316. }
  27317. /* Set AKID from certificate contains in buffer (DER encoded) */
  27318. int wc_SetAuthKeyIdFromCert(Cert *cert, const byte *der, int derSz)
  27319. {
  27320. int ret = 0;
  27321. if (cert == NULL) {
  27322. ret = BAD_FUNC_ARG;
  27323. }
  27324. else {
  27325. /* Check if decodedCert is cached */
  27326. if (cert->der != der) {
  27327. /* Allocate cache for the decoded cert */
  27328. ret = wc_SetCert_LoadDer(cert, der, derSz);
  27329. }
  27330. if (ret >= 0) {
  27331. ret = SetAuthKeyIdFromDcert(cert, (DecodedCert*)cert->decodedCert);
  27332. #ifndef WOLFSSL_CERT_GEN_CACHE
  27333. wc_SetCert_Free(cert);
  27334. #endif
  27335. }
  27336. }
  27337. return ret;
  27338. }
  27339. #ifndef NO_FILESYSTEM
  27340. /* Set AKID from certificate file in PEM */
  27341. int wc_SetAuthKeyId(Cert *cert, const char* file)
  27342. {
  27343. int ret;
  27344. DerBuffer* der = NULL;
  27345. if (cert == NULL || file == NULL)
  27346. return BAD_FUNC_ARG;
  27347. ret = wc_PemCertToDer_ex(file, &der);
  27348. if (ret == 0)
  27349. {
  27350. ret = wc_SetAuthKeyIdFromCert(cert, der->buffer, der->length);
  27351. FreeDer(&der);
  27352. }
  27353. return ret;
  27354. }
  27355. #endif /* !NO_FILESYSTEM */
  27356. /* Set KeyUsage from human readable string */
  27357. int wc_SetKeyUsage(Cert *cert, const char *value)
  27358. {
  27359. int ret = 0;
  27360. char *token, *str, *ptr;
  27361. word32 len;
  27362. if (cert == NULL || value == NULL)
  27363. return BAD_FUNC_ARG;
  27364. cert->keyUsage = 0;
  27365. /* duplicate string (including terminator) */
  27366. len = (word32)XSTRLEN(value);
  27367. str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27368. if (str == NULL)
  27369. return MEMORY_E;
  27370. XMEMCPY(str, value, len+1);
  27371. /* parse value, and set corresponding Key Usage value */
  27372. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  27373. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27374. return KEYUSAGE_E;
  27375. }
  27376. while (token != NULL)
  27377. {
  27378. if (!XSTRCASECMP(token, "digitalSignature"))
  27379. cert->keyUsage |= KEYUSE_DIGITAL_SIG;
  27380. else if (!XSTRCASECMP(token, "nonRepudiation") ||
  27381. !XSTRCASECMP(token, "contentCommitment"))
  27382. cert->keyUsage |= KEYUSE_CONTENT_COMMIT;
  27383. else if (!XSTRCASECMP(token, "keyEncipherment"))
  27384. cert->keyUsage |= KEYUSE_KEY_ENCIPHER;
  27385. else if (!XSTRCASECMP(token, "dataEncipherment"))
  27386. cert->keyUsage |= KEYUSE_DATA_ENCIPHER;
  27387. else if (!XSTRCASECMP(token, "keyAgreement"))
  27388. cert->keyUsage |= KEYUSE_KEY_AGREE;
  27389. else if (!XSTRCASECMP(token, "keyCertSign"))
  27390. cert->keyUsage |= KEYUSE_KEY_CERT_SIGN;
  27391. else if (!XSTRCASECMP(token, "cRLSign"))
  27392. cert->keyUsage |= KEYUSE_CRL_SIGN;
  27393. else if (!XSTRCASECMP(token, "encipherOnly"))
  27394. cert->keyUsage |= KEYUSE_ENCIPHER_ONLY;
  27395. else if (!XSTRCASECMP(token, "decipherOnly"))
  27396. cert->keyUsage |= KEYUSE_DECIPHER_ONLY;
  27397. else {
  27398. ret = KEYUSAGE_E;
  27399. break;
  27400. }
  27401. token = XSTRTOK(NULL, ",", &ptr);
  27402. }
  27403. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27404. return ret;
  27405. }
  27406. /* Set ExtendedKeyUsage from human readable string */
  27407. int wc_SetExtKeyUsage(Cert *cert, const char *value)
  27408. {
  27409. int ret = 0;
  27410. char *token, *str, *ptr;
  27411. word32 len;
  27412. if (cert == NULL || value == NULL)
  27413. return BAD_FUNC_ARG;
  27414. cert->extKeyUsage = 0;
  27415. /* duplicate string (including terminator) */
  27416. len = (word32)XSTRLEN(value);
  27417. str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27418. if (str == NULL)
  27419. return MEMORY_E;
  27420. XMEMCPY(str, value, len+1);
  27421. /* parse value, and set corresponding Key Usage value */
  27422. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  27423. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27424. return EXTKEYUSAGE_E;
  27425. }
  27426. while (token != NULL)
  27427. {
  27428. if (!XSTRCASECMP(token, "any"))
  27429. cert->extKeyUsage |= EXTKEYUSE_ANY;
  27430. else if (!XSTRCASECMP(token, "serverAuth"))
  27431. cert->extKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  27432. else if (!XSTRCASECMP(token, "clientAuth"))
  27433. cert->extKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  27434. else if (!XSTRCASECMP(token, "codeSigning"))
  27435. cert->extKeyUsage |= EXTKEYUSE_CODESIGN;
  27436. else if (!XSTRCASECMP(token, "emailProtection"))
  27437. cert->extKeyUsage |= EXTKEYUSE_EMAILPROT;
  27438. else if (!XSTRCASECMP(token, "timeStamping"))
  27439. cert->extKeyUsage |= EXTKEYUSE_TIMESTAMP;
  27440. else if (!XSTRCASECMP(token, "OCSPSigning"))
  27441. cert->extKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  27442. else {
  27443. ret = EXTKEYUSAGE_E;
  27444. break;
  27445. }
  27446. token = XSTRTOK(NULL, ",", &ptr);
  27447. }
  27448. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27449. return ret;
  27450. }
  27451. #ifdef WOLFSSL_EKU_OID
  27452. /*
  27453. * cert structure to set EKU oid in
  27454. * oid the oid in byte representation
  27455. * sz size of oid buffer
  27456. * idx index of array to place oid
  27457. *
  27458. * returns 0 on success
  27459. */
  27460. int wc_SetExtKeyUsageOID(Cert *cert, const char *in, word32 sz, byte idx,
  27461. void* heap)
  27462. {
  27463. byte oid[MAX_OID_SZ];
  27464. word32 oidSz = MAX_OID_SZ;
  27465. if (idx >= CTC_MAX_EKU_NB || sz >= CTC_MAX_EKU_OID_SZ) {
  27466. WOLFSSL_MSG("Either idx or sz was too large");
  27467. return BAD_FUNC_ARG;
  27468. }
  27469. if (EncodePolicyOID(oid, &oidSz, in, heap) != 0) {
  27470. return BUFFER_E;
  27471. }
  27472. XMEMCPY(cert->extKeyUsageOID[idx], oid, oidSz);
  27473. cert->extKeyUsageOIDSz[idx] = oidSz;
  27474. cert->extKeyUsage |= EXTKEYUSE_USER;
  27475. return 0;
  27476. }
  27477. #endif /* WOLFSSL_EKU_OID */
  27478. #if defined(WOLFSSL_ASN_TEMPLATE) && defined(WOLFSSL_CERT_GEN) && \
  27479. defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_ENCODING) && \
  27480. defined(WOLFSSL_CERT_EXT)
  27481. int wc_SetCustomExtension(Cert *cert, int critical, const char *oid,
  27482. const byte *der, word32 derSz) {
  27483. CertExtension *ext;
  27484. byte encodedOid[MAX_OID_SZ];
  27485. word32 encodedOidSz = MAX_OID_SZ;
  27486. int ret;
  27487. if (cert == NULL || oid == NULL || der == NULL || derSz == 0) {
  27488. return BAD_FUNC_ARG;
  27489. }
  27490. if (cert->customCertExtCount >= NUM_CUSTOM_EXT) {
  27491. return MEMORY_E;
  27492. }
  27493. /* Make sure we can properly parse the OID. */
  27494. ret = EncodePolicyOID(encodedOid, &encodedOidSz, oid, NULL);
  27495. if (ret != 0) {
  27496. return ret;
  27497. }
  27498. ext = &cert->customCertExt[cert->customCertExtCount];
  27499. ext->oid = oid;
  27500. ext->crit = (critical == 0) ? 0 : 1;
  27501. ext->val = der;
  27502. ext->valSz = derSz;
  27503. cert->customCertExtCount++;
  27504. return 0;
  27505. }
  27506. #endif
  27507. #endif /* WOLFSSL_CERT_EXT */
  27508. #ifdef WOLFSSL_ALT_NAMES
  27509. static int SetAltNamesFromDcert(Cert* cert, DecodedCert* decoded)
  27510. {
  27511. int ret = 0;
  27512. cert->altNamesSz = 0;
  27513. if (decoded->altNames) {
  27514. ret = FlattenAltNames(cert->altNames,
  27515. sizeof(cert->altNames), decoded->altNames);
  27516. if (ret >= 0) {
  27517. cert->altNamesSz = ret;
  27518. ret = 0;
  27519. }
  27520. }
  27521. return ret;
  27522. }
  27523. #ifndef NO_FILESYSTEM
  27524. /* Set Alt Names from der cert, return 0 on success */
  27525. static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz)
  27526. {
  27527. int ret;
  27528. #ifdef WOLFSSL_SMALL_STACK
  27529. DecodedCert* decoded;
  27530. #else
  27531. DecodedCert decoded[1];
  27532. #endif
  27533. if (derSz < 0)
  27534. return derSz;
  27535. #ifdef WOLFSSL_SMALL_STACK
  27536. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), cert->heap,
  27537. DYNAMIC_TYPE_TMP_BUFFER);
  27538. if (decoded == NULL)
  27539. return MEMORY_E;
  27540. #endif
  27541. InitDecodedCert(decoded, der, derSz, NULL);
  27542. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  27543. if (ret < 0) {
  27544. WOLFSSL_MSG("ParseCertRelative error");
  27545. }
  27546. else {
  27547. ret = SetAltNamesFromDcert(cert, decoded);
  27548. }
  27549. FreeDecodedCert(decoded);
  27550. #ifdef WOLFSSL_SMALL_STACK
  27551. XFREE(decoded, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27552. #endif
  27553. return ret < 0 ? ret : 0;
  27554. }
  27555. #endif
  27556. static int SetDatesFromDcert(Cert* cert, DecodedCert* decoded)
  27557. {
  27558. int ret = 0;
  27559. if (decoded->beforeDate == NULL || decoded->afterDate == NULL) {
  27560. WOLFSSL_MSG("Couldn't extract dates");
  27561. ret = -1;
  27562. }
  27563. else if (decoded->beforeDateLen > MAX_DATE_SIZE ||
  27564. decoded->afterDateLen > MAX_DATE_SIZE) {
  27565. WOLFSSL_MSG("Bad date size");
  27566. ret = -1;
  27567. }
  27568. else {
  27569. XMEMCPY(cert->beforeDate, decoded->beforeDate, decoded->beforeDateLen);
  27570. XMEMCPY(cert->afterDate, decoded->afterDate, decoded->afterDateLen);
  27571. cert->beforeDateSz = decoded->beforeDateLen;
  27572. cert->afterDateSz = decoded->afterDateLen;
  27573. }
  27574. return ret;
  27575. }
  27576. #endif /* WOLFSSL_ALT_NAMES */
  27577. static void SetNameFromDcert(CertName* cn, DecodedCert* decoded)
  27578. {
  27579. int sz;
  27580. if (decoded->subjectCN) {
  27581. sz = (decoded->subjectCNLen < CTC_NAME_SIZE) ? decoded->subjectCNLen
  27582. : CTC_NAME_SIZE - 1;
  27583. XSTRNCPY(cn->commonName, decoded->subjectCN, sz);
  27584. cn->commonName[sz] = '\0';
  27585. cn->commonNameEnc = decoded->subjectCNEnc;
  27586. }
  27587. if (decoded->subjectC) {
  27588. sz = (decoded->subjectCLen < CTC_NAME_SIZE) ? decoded->subjectCLen
  27589. : CTC_NAME_SIZE - 1;
  27590. XSTRNCPY(cn->country, decoded->subjectC, sz);
  27591. cn->country[sz] = '\0';
  27592. cn->countryEnc = decoded->subjectCEnc;
  27593. }
  27594. if (decoded->subjectST) {
  27595. sz = (decoded->subjectSTLen < CTC_NAME_SIZE) ? decoded->subjectSTLen
  27596. : CTC_NAME_SIZE - 1;
  27597. XSTRNCPY(cn->state, decoded->subjectST, sz);
  27598. cn->state[sz] = '\0';
  27599. cn->stateEnc = decoded->subjectSTEnc;
  27600. }
  27601. if (decoded->subjectL) {
  27602. sz = (decoded->subjectLLen < CTC_NAME_SIZE) ? decoded->subjectLLen
  27603. : CTC_NAME_SIZE - 1;
  27604. XSTRNCPY(cn->locality, decoded->subjectL, sz);
  27605. cn->locality[sz] = '\0';
  27606. cn->localityEnc = decoded->subjectLEnc;
  27607. }
  27608. if (decoded->subjectO) {
  27609. sz = (decoded->subjectOLen < CTC_NAME_SIZE) ? decoded->subjectOLen
  27610. : CTC_NAME_SIZE - 1;
  27611. XSTRNCPY(cn->org, decoded->subjectO, sz);
  27612. cn->org[sz] = '\0';
  27613. cn->orgEnc = decoded->subjectOEnc;
  27614. }
  27615. if (decoded->subjectOU) {
  27616. sz = (decoded->subjectOULen < CTC_NAME_SIZE) ? decoded->subjectOULen
  27617. : CTC_NAME_SIZE - 1;
  27618. XSTRNCPY(cn->unit, decoded->subjectOU, sz);
  27619. cn->unit[sz] = '\0';
  27620. cn->unitEnc = decoded->subjectOUEnc;
  27621. }
  27622. if (decoded->subjectSN) {
  27623. sz = (decoded->subjectSNLen < CTC_NAME_SIZE) ? decoded->subjectSNLen
  27624. : CTC_NAME_SIZE - 1;
  27625. XSTRNCPY(cn->sur, decoded->subjectSN, sz);
  27626. cn->sur[sz] = '\0';
  27627. cn->surEnc = decoded->subjectSNEnc;
  27628. }
  27629. if (decoded->subjectSND) {
  27630. sz = (decoded->subjectSNDLen < CTC_NAME_SIZE) ? decoded->subjectSNDLen
  27631. : CTC_NAME_SIZE - 1;
  27632. XSTRNCPY(cn->serialDev, decoded->subjectSND, sz);
  27633. cn->serialDev[sz] = '\0';
  27634. cn->serialDevEnc = decoded->subjectSNDEnc;
  27635. }
  27636. if (decoded->subjectUID) {
  27637. sz = (decoded->subjectUIDLen < CTC_NAME_SIZE) ? decoded->subjectUIDLen
  27638. : CTC_NAME_SIZE - 1;
  27639. XSTRNCPY(cn->userId, decoded->subjectUID, sz);
  27640. cn->userId[sz] = '\0';
  27641. cn->userIdEnc = decoded->subjectUIDEnc;
  27642. }
  27643. #ifdef WOLFSSL_CERT_EXT
  27644. if (decoded->subjectBC) {
  27645. sz = (decoded->subjectBCLen < CTC_NAME_SIZE) ? decoded->subjectBCLen
  27646. : CTC_NAME_SIZE - 1;
  27647. XSTRNCPY(cn->busCat, decoded->subjectBC, sz);
  27648. cn->busCat[sz] = '\0';
  27649. cn->busCatEnc = decoded->subjectBCEnc;
  27650. }
  27651. if (decoded->subjectJC) {
  27652. sz = (decoded->subjectJCLen < CTC_NAME_SIZE) ? decoded->subjectJCLen
  27653. : CTC_NAME_SIZE - 1;
  27654. XSTRNCPY(cn->joiC, decoded->subjectJC, sz);
  27655. cn->joiC[sz] = '\0';
  27656. cn->joiCEnc = decoded->subjectJCEnc;
  27657. }
  27658. if (decoded->subjectJS) {
  27659. sz = (decoded->subjectJSLen < CTC_NAME_SIZE) ? decoded->subjectJSLen
  27660. : CTC_NAME_SIZE - 1;
  27661. XSTRNCPY(cn->joiSt, decoded->subjectJS, sz);
  27662. cn->joiSt[sz] = '\0';
  27663. cn->joiStEnc = decoded->subjectJSEnc;
  27664. }
  27665. #endif
  27666. if (decoded->subjectEmail) {
  27667. sz = (decoded->subjectEmailLen < CTC_NAME_SIZE)
  27668. ? decoded->subjectEmailLen : CTC_NAME_SIZE - 1;
  27669. XSTRNCPY(cn->email, decoded->subjectEmail, sz);
  27670. cn->email[sz] = '\0';
  27671. }
  27672. #if defined(WOLFSSL_CERT_NAME_ALL) && \
  27673. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
  27674. if (decoded->subjectN) {
  27675. sz = (decoded->subjectNLen < CTC_NAME_SIZE) ? decoded->subjectNLen
  27676. : CTC_NAME_SIZE - 1;
  27677. XSTRNCPY(cn->dnName, decoded->subjectN, sz);
  27678. cn->dnName[sz] = '\0';
  27679. cn->dnNameEnc = decoded->subjectNEnc;
  27680. }
  27681. if (decoded->subjectI) {
  27682. sz = (decoded->subjectILen < CTC_NAME_SIZE) ? decoded->subjectILen
  27683. : CTC_NAME_SIZE - 1;
  27684. XSTRNCPY(cn->initials, decoded->subjectI, sz);
  27685. cn->initials[sz] = '\0';
  27686. cn->initialsEnc = decoded->subjectIEnc;
  27687. }
  27688. if (decoded->subjectGN) {
  27689. sz = (decoded->subjectGNLen < CTC_NAME_SIZE) ? decoded->subjectGNLen
  27690. : CTC_NAME_SIZE - 1;
  27691. XSTRNCPY(cn->givenName, decoded->subjectGN, sz);
  27692. cn->givenName[sz] = '\0';
  27693. cn->givenNameEnc = decoded->subjectGNEnc;
  27694. }
  27695. if (decoded->subjectDNQ) {
  27696. sz = (decoded->subjectDNQLen < CTC_NAME_SIZE) ? decoded->subjectDNQLen
  27697. : CTC_NAME_SIZE - 1;
  27698. XSTRNCPY(cn->dnQualifier, decoded->subjectDNQ, sz);
  27699. cn->dnQualifier[sz] = '\0';
  27700. cn->dnQualifierEnc = decoded->subjectDNQEnc;
  27701. }
  27702. #endif /* WOLFSSL_CERT_NAME_ALL */
  27703. }
  27704. #ifndef NO_FILESYSTEM
  27705. /* Set cn name from der buffer, return 0 on success */
  27706. static int SetNameFromCert(CertName* cn, const byte* der, int derSz)
  27707. {
  27708. int ret;
  27709. #ifdef WOLFSSL_SMALL_STACK
  27710. DecodedCert* decoded;
  27711. #else
  27712. DecodedCert decoded[1];
  27713. #endif
  27714. if (derSz < 0)
  27715. return derSz;
  27716. #ifdef WOLFSSL_SMALL_STACK
  27717. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  27718. DYNAMIC_TYPE_TMP_BUFFER);
  27719. if (decoded == NULL)
  27720. return MEMORY_E;
  27721. #endif
  27722. InitDecodedCert(decoded, der, derSz, NULL);
  27723. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  27724. if (ret < 0) {
  27725. WOLFSSL_MSG("ParseCertRelative error");
  27726. }
  27727. else {
  27728. SetNameFromDcert(cn, decoded);
  27729. }
  27730. FreeDecodedCert(decoded);
  27731. #ifdef WOLFSSL_SMALL_STACK
  27732. XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  27733. #endif
  27734. return ret < 0 ? ret : 0;
  27735. }
  27736. /* Set cert issuer from issuerFile in PEM */
  27737. WOLFSSL_ABI
  27738. int wc_SetIssuer(Cert* cert, const char* issuerFile)
  27739. {
  27740. int ret;
  27741. DerBuffer* der = NULL;
  27742. if (cert == NULL || issuerFile == NULL)
  27743. return BAD_FUNC_ARG;
  27744. ret = wc_PemCertToDer_ex(issuerFile, &der);
  27745. if (ret == 0) {
  27746. cert->selfSigned = 0;
  27747. ret = SetNameFromCert(&cert->issuer, der->buffer, der->length);
  27748. FreeDer(&der);
  27749. }
  27750. return ret;
  27751. }
  27752. /* Set cert subject from subjectFile in PEM */
  27753. WOLFSSL_ABI
  27754. int wc_SetSubject(Cert* cert, const char* subjectFile)
  27755. {
  27756. int ret;
  27757. DerBuffer* der = NULL;
  27758. if (cert == NULL || subjectFile == NULL)
  27759. return BAD_FUNC_ARG;
  27760. ret = wc_PemCertToDer_ex(subjectFile, &der);
  27761. if (ret == 0) {
  27762. ret = SetNameFromCert(&cert->subject, der->buffer, der->length);
  27763. FreeDer(&der);
  27764. }
  27765. return ret;
  27766. }
  27767. #ifdef WOLFSSL_ALT_NAMES
  27768. /* Set alt names from file in PEM */
  27769. WOLFSSL_ABI
  27770. int wc_SetAltNames(Cert* cert, const char* file)
  27771. {
  27772. int ret;
  27773. DerBuffer* der = NULL;
  27774. if (cert == NULL) {
  27775. return BAD_FUNC_ARG;
  27776. }
  27777. ret = wc_PemCertToDer_ex(file, &der);
  27778. if (ret == 0) {
  27779. ret = SetAltNamesFromCert(cert, der->buffer, der->length);
  27780. FreeDer(&der);
  27781. }
  27782. return ret;
  27783. }
  27784. #endif /* WOLFSSL_ALT_NAMES */
  27785. #endif /* !NO_FILESYSTEM */
  27786. /* Set cert issuer from DER buffer */
  27787. WOLFSSL_ABI
  27788. int wc_SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
  27789. {
  27790. int ret = 0;
  27791. if (cert == NULL) {
  27792. ret = BAD_FUNC_ARG;
  27793. }
  27794. else {
  27795. cert->selfSigned = 0;
  27796. /* Check if decodedCert is cached */
  27797. if (cert->der != der) {
  27798. /* Allocate cache for the decoded cert */
  27799. ret = wc_SetCert_LoadDer(cert, der, derSz);
  27800. }
  27801. if (ret >= 0) {
  27802. SetNameFromDcert(&cert->issuer, (DecodedCert*)cert->decodedCert);
  27803. #ifndef WOLFSSL_CERT_GEN_CACHE
  27804. wc_SetCert_Free(cert);
  27805. #endif
  27806. }
  27807. }
  27808. return ret;
  27809. }
  27810. /* Set cert subject from DER buffer */
  27811. WOLFSSL_ABI
  27812. int wc_SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
  27813. {
  27814. int ret = 0;
  27815. if (cert == NULL) {
  27816. ret = BAD_FUNC_ARG;
  27817. }
  27818. else {
  27819. /* Check if decodedCert is cached */
  27820. if (cert->der != der) {
  27821. /* Allocate cache for the decoded cert */
  27822. ret = wc_SetCert_LoadDer(cert, der, derSz);
  27823. }
  27824. if (ret >= 0) {
  27825. SetNameFromDcert(&cert->subject, (DecodedCert*)cert->decodedCert);
  27826. #ifndef WOLFSSL_CERT_GEN_CACHE
  27827. wc_SetCert_Free(cert);
  27828. #endif
  27829. }
  27830. }
  27831. return ret;
  27832. }
  27833. #ifdef WOLFSSL_CERT_EXT
  27834. /* Set cert raw subject from DER buffer */
  27835. WOLFSSL_ABI
  27836. int wc_SetSubjectRaw(Cert* cert, const byte* der, int derSz)
  27837. {
  27838. int ret = 0;
  27839. if (cert == NULL) {
  27840. ret = BAD_FUNC_ARG;
  27841. }
  27842. else {
  27843. /* Check if decodedCert is cached */
  27844. if (cert->der != der) {
  27845. /* Allocate cache for the decoded cert */
  27846. ret = wc_SetCert_LoadDer(cert, der, derSz);
  27847. }
  27848. if (ret >= 0) {
  27849. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  27850. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  27851. (int)sizeof(CertName))) {
  27852. XMEMCPY(cert->sbjRaw,
  27853. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  27854. ((DecodedCert*)cert->decodedCert)->subjectRawLen);
  27855. }
  27856. #ifndef WOLFSSL_CERT_GEN_CACHE
  27857. wc_SetCert_Free(cert);
  27858. #endif
  27859. }
  27860. }
  27861. return ret;
  27862. }
  27863. /* Set cert raw issuer from DER buffer */
  27864. WOLFSSL_ABI
  27865. int wc_SetIssuerRaw(Cert* cert, const byte* der, int derSz)
  27866. {
  27867. int ret = 0;
  27868. if (cert == NULL) {
  27869. ret = BAD_FUNC_ARG;
  27870. }
  27871. else {
  27872. /* Check if decodedCert is cached */
  27873. if (cert->der != der) {
  27874. /* Allocate cache for the decoded cert */
  27875. ret = wc_SetCert_LoadDer(cert, der, derSz);
  27876. }
  27877. if (ret >= 0) {
  27878. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  27879. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  27880. (int)sizeof(CertName))) {
  27881. /* Copy the subject to the issuer field */
  27882. XMEMCPY(cert->issRaw,
  27883. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  27884. ((DecodedCert*)cert->decodedCert)->subjectRawLen);
  27885. }
  27886. #ifndef WOLFSSL_CERT_GEN_CACHE
  27887. wc_SetCert_Free(cert);
  27888. #endif
  27889. }
  27890. }
  27891. return ret;
  27892. }
  27893. #endif
  27894. #ifdef WOLFSSL_ALT_NAMES
  27895. /* Set cert alt names from DER buffer */
  27896. WOLFSSL_ABI
  27897. int wc_SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
  27898. {
  27899. int ret = 0;
  27900. if (cert == NULL) {
  27901. ret = BAD_FUNC_ARG;
  27902. }
  27903. else {
  27904. /* Check if decodedCert is cached */
  27905. if (cert->der != der) {
  27906. /* Allocate cache for the decoded cert */
  27907. ret = wc_SetCert_LoadDer(cert, der, derSz);
  27908. }
  27909. if (ret >= 0) {
  27910. ret = SetAltNamesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  27911. #ifndef WOLFSSL_CERT_GEN_CACHE
  27912. wc_SetCert_Free(cert);
  27913. #endif
  27914. }
  27915. }
  27916. return(ret);
  27917. }
  27918. /* Set cert dates from DER buffer */
  27919. WOLFSSL_ABI
  27920. int wc_SetDatesBuffer(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, derSz);
  27931. }
  27932. if (ret >= 0) {
  27933. ret = SetDatesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  27934. #ifndef WOLFSSL_CERT_GEN_CACHE
  27935. wc_SetCert_Free(cert);
  27936. #endif
  27937. }
  27938. }
  27939. return(ret);
  27940. }
  27941. #endif /* WOLFSSL_ALT_NAMES */
  27942. #endif /* WOLFSSL_CERT_GEN */
  27943. #if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) \
  27944. || defined(OPENSSL_EXTRA)
  27945. /* Encode OID string representation to ITU-T X.690 format */
  27946. int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap)
  27947. {
  27948. word32 val, idx = 0, nb_val;
  27949. char *token, *str, *ptr;
  27950. word32 len;
  27951. (void)heap;
  27952. if (out == NULL || outSz == NULL || *outSz < 2 || in == NULL)
  27953. return BAD_FUNC_ARG;
  27954. /* duplicate string (including terminator) */
  27955. len = (word32)XSTRLEN(in);
  27956. str = (char *)XMALLOC(len+1, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27957. if (str == NULL)
  27958. return MEMORY_E;
  27959. XMEMCPY(str, in, len+1);
  27960. nb_val = 0;
  27961. /* parse value, and set corresponding Policy OID value */
  27962. token = XSTRTOK(str, ".", &ptr);
  27963. while (token != NULL)
  27964. {
  27965. val = (word32)XATOI(token);
  27966. if (nb_val == 0) {
  27967. if (val > 2) {
  27968. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27969. return ASN_OBJECT_ID_E;
  27970. }
  27971. out[idx] = (byte)(40 * val);
  27972. }
  27973. else if (nb_val == 1) {
  27974. if (val > 127) {
  27975. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27976. return ASN_OBJECT_ID_E;
  27977. }
  27978. if (idx > *outSz) {
  27979. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27980. return BUFFER_E;
  27981. }
  27982. out[idx++] += (byte)val;
  27983. }
  27984. else {
  27985. word32 tb = 0, x;
  27986. int i = 0;
  27987. byte oid[MAX_OID_SZ];
  27988. while (val >= 128) {
  27989. x = val % 128;
  27990. val /= 128;
  27991. oid[i++] = (byte) (((tb++) ? 0x80 : 0) | x);
  27992. }
  27993. if ((idx+(word32)i) >= *outSz) {
  27994. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27995. return BUFFER_E;
  27996. }
  27997. oid[i] = (byte) (((tb++) ? 0x80 : 0) | val);
  27998. /* push value in the right order */
  27999. while (i >= 0)
  28000. out[idx++] = oid[i--];
  28001. }
  28002. token = XSTRTOK(NULL, ".", &ptr);
  28003. nb_val++;
  28004. }
  28005. *outSz = idx;
  28006. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28007. return 0;
  28008. }
  28009. #endif /* WOLFSSL_CERT_EXT || OPENSSL_EXTRA */
  28010. #endif /* !NO_CERTS */
  28011. #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
  28012. /* Helper function for wolfSSL_i2d_DHparams */
  28013. int StoreDHparams(byte* out, word32* outLen, mp_int* p, mp_int* g)
  28014. {
  28015. #ifndef WOLFSSL_ASN_TEMPLATE
  28016. word32 idx = 0;
  28017. word32 total;
  28018. WOLFSSL_ENTER("StoreDHparams");
  28019. if (out == NULL) {
  28020. WOLFSSL_MSG("Null buffer error");
  28021. return BUFFER_E;
  28022. }
  28023. /* determine size */
  28024. /* integer - g */
  28025. idx = SetASNIntMP(g, -1, NULL);
  28026. /* integer - p */
  28027. idx += SetASNIntMP(p, -1, NULL);
  28028. total = idx;
  28029. /* sequence */
  28030. idx += SetSequence(idx, NULL);
  28031. /* make sure output fits in buffer */
  28032. if (idx > *outLen) {
  28033. return BUFFER_E;
  28034. }
  28035. /* write DH parameters */
  28036. /* sequence - for P and G only */
  28037. idx = SetSequence(total, out);
  28038. /* integer - p */
  28039. idx += SetASNIntMP(p, -1, out + idx);
  28040. /* integer - g */
  28041. idx += SetASNIntMP(g, -1, out + idx);
  28042. *outLen = idx;
  28043. return 0;
  28044. #else
  28045. ASNSetData dataASN[dhParamASN_Length];
  28046. int ret = 0;
  28047. int sz = 0;
  28048. WOLFSSL_ENTER("StoreDHparams");
  28049. if (out == NULL) {
  28050. ret = BUFFER_E;
  28051. }
  28052. if (ret == 0) {
  28053. XMEMSET(dataASN, 0, sizeof(dataASN));
  28054. /* Set mp_int containing p and g. */
  28055. SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], p);
  28056. SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], g);
  28057. /* privateValueLength not encoded. */
  28058. dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
  28059. /* Calculate the size of the DH parameters. */
  28060. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  28061. }
  28062. /* Check buffer is big enough for encoding. */
  28063. if ((ret == 0) && ((int)*outLen < sz)) {
  28064. ret = BUFFER_E;
  28065. }
  28066. if (ret == 0) {
  28067. /* Encode the DH parameters into buffer. */
  28068. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, out);
  28069. /* Set the actual encoding size. */
  28070. *outLen = sz;
  28071. }
  28072. return ret;
  28073. #endif /* WOLFSSL_ASN_TEMPLATE */
  28074. }
  28075. #endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
  28076. #if defined(HAVE_ECC) || !defined(NO_DSA)
  28077. #ifdef WOLFSSL_ASN_TEMPLATE
  28078. /* ASN.1 template for DSA signature.
  28079. * RFC 5912, 6 - DSA-Sig-Value
  28080. */
  28081. static const ASNItem dsaSigASN[] = {
  28082. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28083. /* r */
  28084. /* R */ { 1, ASN_INTEGER, 0, 0, 0 },
  28085. /* s */
  28086. /* S */ { 1, ASN_INTEGER, 0, 0, 0 },
  28087. };
  28088. enum {
  28089. DSASIGASN_IDX_SEQ = 0,
  28090. DSASIGASN_IDX_R,
  28091. DSASIGASN_IDX_S,
  28092. };
  28093. #define dsaSigASN_Length (sizeof(dsaSigASN) / sizeof(ASNItem))
  28094. #endif
  28095. /* Der Encode r & s ints into out, outLen is (in/out) size */
  28096. int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
  28097. {
  28098. #ifndef WOLFSSL_ASN_TEMPLATE
  28099. word32 idx = 0;
  28100. int rSz; /* encoding size */
  28101. int sSz;
  28102. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  28103. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  28104. int rLeadingZero = mp_leading_bit(r);
  28105. int sLeadingZero = mp_leading_bit(s);
  28106. int rLen = mp_unsigned_bin_size(r); /* big int size */
  28107. int sLen = mp_unsigned_bin_size(s);
  28108. if (*outLen < (rLen + rLeadingZero + sLen + sLeadingZero +
  28109. headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
  28110. return BUFFER_E;
  28111. idx = SetSequence(rLen + rLeadingZero + sLen+sLeadingZero + headerSz, out);
  28112. /* store r */
  28113. rSz = SetASNIntMP(r, *outLen - idx, &out[idx]);
  28114. if (rSz < 0)
  28115. return rSz;
  28116. idx += rSz;
  28117. /* store s */
  28118. sSz = SetASNIntMP(s, *outLen - idx, &out[idx]);
  28119. if (sSz < 0)
  28120. return sSz;
  28121. idx += sSz;
  28122. *outLen = idx;
  28123. return 0;
  28124. #else
  28125. ASNSetData dataASN[dsaSigASN_Length];
  28126. int ret;
  28127. int sz;
  28128. /* Clear dynamic data and set mp_ints r and s */
  28129. XMEMSET(dataASN, 0, sizeof(dataASN));
  28130. SetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
  28131. SetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
  28132. /* Calculate size of encoding. */
  28133. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  28134. /* Check buffer is big enough for encoding. */
  28135. if ((ret == 0) && ((int)*outLen < sz)) {
  28136. ret = BUFFER_E;
  28137. }
  28138. if (ret == 0) {
  28139. /* Encode DSA signature into buffer. */
  28140. SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  28141. /* Set the actual encoding size. */
  28142. *outLen = sz;
  28143. }
  28144. return ret;
  28145. #endif /* WOLFSSL_ASN_TEMPLATE */
  28146. }
  28147. #ifndef WOLFSSL_ASN_TEMPLATE
  28148. /* determine if leading bit is set */
  28149. static int is_leading_bit_set(const byte* input, word32 sz)
  28150. {
  28151. byte c = 0;
  28152. if (sz > 0)
  28153. c = input[0];
  28154. return (c & 0x80) != 0;
  28155. }
  28156. static int trim_leading_zeros(const byte** input, word32 sz)
  28157. {
  28158. int i, leadingZeroCount = 0;
  28159. const byte* tmp = *input;
  28160. for (i=0; i<(int)sz; i++) {
  28161. if (tmp[i] != 0)
  28162. break;
  28163. leadingZeroCount++;
  28164. }
  28165. /* catch all zero case */
  28166. if (sz > 0 && leadingZeroCount == (int)sz) {
  28167. leadingZeroCount--;
  28168. }
  28169. *input += leadingZeroCount;
  28170. sz -= leadingZeroCount;
  28171. return sz;
  28172. }
  28173. #endif
  28174. /* Der Encode r & s ints into out, outLen is (in/out) size */
  28175. /* All input/outputs are assumed to be big-endian */
  28176. int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen,
  28177. const byte* s, word32 sLen)
  28178. {
  28179. #ifndef WOLFSSL_ASN_TEMPLATE
  28180. int ret;
  28181. word32 idx;
  28182. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  28183. int rAddLeadZero, sAddLeadZero;
  28184. if ((out == NULL) || (outLen == NULL) || (r == NULL) || (s == NULL))
  28185. return BAD_FUNC_ARG;
  28186. /* Trim leading zeros */
  28187. rLen = trim_leading_zeros(&r, rLen);
  28188. sLen = trim_leading_zeros(&s, sLen);
  28189. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  28190. /* Add leading zero if MSB is set */
  28191. rAddLeadZero = is_leading_bit_set(r, rLen);
  28192. sAddLeadZero = is_leading_bit_set(s, sLen);
  28193. if (*outLen < (rLen + rAddLeadZero + sLen + sAddLeadZero +
  28194. headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
  28195. return BUFFER_E;
  28196. idx = SetSequence(rLen+rAddLeadZero + sLen+sAddLeadZero + headerSz, out);
  28197. /* store r */
  28198. ret = SetASNInt(rLen, rAddLeadZero ? 0x80 : 0x00, &out[idx]);
  28199. if (ret < 0)
  28200. return ret;
  28201. idx += ret;
  28202. XMEMCPY(&out[idx], r, rLen);
  28203. idx += rLen;
  28204. /* store s */
  28205. ret = SetASNInt(sLen, sAddLeadZero ? 0x80 : 0x00, &out[idx]);
  28206. if (ret < 0)
  28207. return ret;
  28208. idx += ret;
  28209. XMEMCPY(&out[idx], s, sLen);
  28210. idx += sLen;
  28211. *outLen = idx;
  28212. return 0;
  28213. #else
  28214. ASNSetData dataASN[dsaSigASN_Length];
  28215. int ret;
  28216. int sz;
  28217. /* Clear dynamic data and set buffers for r and s */
  28218. XMEMSET(dataASN, 0, sizeof(dataASN));
  28219. SetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
  28220. SetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
  28221. /* Calculate size of encoding. */
  28222. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  28223. /* Check buffer is big enough for encoding. */
  28224. if ((ret == 0) && ((int)*outLen < sz)) {
  28225. ret = BUFFER_E;
  28226. }
  28227. if (ret == 0) {
  28228. /* Encode DSA signature into buffer. */
  28229. SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  28230. /* Set the actual encoding size. */
  28231. *outLen = sz;
  28232. }
  28233. return ret;
  28234. #endif /* WOLFSSL_ASN_TEMPLATE */
  28235. }
  28236. /* Der Decode ECC-DSA Signature with R/S as unsigned bin */
  28237. /* All input/outputs are assumed to be big-endian */
  28238. int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen,
  28239. byte* s, word32* sLen)
  28240. {
  28241. #ifndef WOLFSSL_ASN_TEMPLATE
  28242. int ret;
  28243. word32 idx = 0;
  28244. int len = 0;
  28245. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  28246. return ASN_ECC_KEY_E;
  28247. }
  28248. #ifndef NO_STRICT_ECDSA_LEN
  28249. /* enable strict length checking for signature */
  28250. if (sigLen != idx + (word32)len) {
  28251. return ASN_ECC_KEY_E;
  28252. }
  28253. #else
  28254. /* allow extra signature bytes at end */
  28255. if ((word32)len > (sigLen - idx)) {
  28256. return ASN_ECC_KEY_E;
  28257. }
  28258. #endif
  28259. ret = GetASNInt(sig, &idx, &len, sigLen);
  28260. if (ret != 0)
  28261. return ret;
  28262. if (rLen)
  28263. *rLen = len;
  28264. if (r)
  28265. XMEMCPY(r, (byte*)sig + idx, len);
  28266. idx += len;
  28267. ret = GetASNInt(sig, &idx, &len, sigLen);
  28268. if (ret != 0)
  28269. return ret;
  28270. if (sLen)
  28271. *sLen = len;
  28272. if (s)
  28273. XMEMCPY(s, (byte*)sig + idx, len);
  28274. #ifndef NO_STRICT_ECDSA_LEN
  28275. /* sanity check that the index has been advanced all the way to the end of
  28276. * the buffer */
  28277. if (idx + len != sigLen) {
  28278. ret = ASN_ECC_KEY_E;
  28279. }
  28280. #endif
  28281. return ret;
  28282. #else
  28283. ASNGetData dataASN[dsaSigASN_Length];
  28284. word32 idx = 0;
  28285. /* Clear dynamic data and set buffers to put r and s into. */
  28286. XMEMSET(dataASN, 0, sizeof(dataASN));
  28287. GetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
  28288. GetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
  28289. /* Decode the DSA signature. */
  28290. return GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 1, sig, &idx,
  28291. sigLen);
  28292. #endif /* WOLFSSL_ASN_TEMPLATE */
  28293. }
  28294. int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
  28295. {
  28296. #ifndef WOLFSSL_ASN_TEMPLATE
  28297. word32 idx = 0;
  28298. int len = 0;
  28299. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  28300. return ASN_ECC_KEY_E;
  28301. }
  28302. #ifndef NO_STRICT_ECDSA_LEN
  28303. /* enable strict length checking for signature */
  28304. if (sigLen != idx + (word32)len) {
  28305. return ASN_ECC_KEY_E;
  28306. }
  28307. #else
  28308. /* allow extra signature bytes at end */
  28309. if ((word32)len > (sigLen - idx)) {
  28310. return ASN_ECC_KEY_E;
  28311. }
  28312. #endif
  28313. if (GetIntPositive(r, sig, &idx, sigLen) < 0) {
  28314. return ASN_ECC_KEY_E;
  28315. }
  28316. if (GetIntPositive(s, sig, &idx, sigLen) < 0) {
  28317. mp_clear(r);
  28318. return ASN_ECC_KEY_E;
  28319. }
  28320. #ifndef NO_STRICT_ECDSA_LEN
  28321. /* sanity check that the index has been advanced all the way to the end of
  28322. * the buffer */
  28323. if (idx != sigLen) {
  28324. mp_clear(r);
  28325. mp_clear(s);
  28326. return ASN_ECC_KEY_E;
  28327. }
  28328. #endif
  28329. return 0;
  28330. #else
  28331. ASNGetData dataASN[dsaSigASN_Length];
  28332. word32 idx = 0;
  28333. int ret;
  28334. /* Clear dynamic data and set mp_ints to put r and s into. */
  28335. XMEMSET(dataASN, 0, sizeof(dataASN));
  28336. GetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
  28337. GetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
  28338. /* Decode the DSA signature. */
  28339. ret = GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 1, sig, &idx,
  28340. sigLen);
  28341. #ifndef NO_STRICT_ECDSA_LEN
  28342. /* sanity check that the index has been advanced all the way to the end of
  28343. * the buffer */
  28344. if ((ret == 0) && (idx != sigLen)) {
  28345. mp_clear(r);
  28346. mp_clear(s);
  28347. ret = ASN_ECC_KEY_E;
  28348. }
  28349. #endif
  28350. return ret;
  28351. #endif /* WOLFSSL_ASN_TEMPLATE */
  28352. }
  28353. #endif
  28354. #ifdef WOLFSSL_ASN_TEMPLATE
  28355. #ifdef WOLFSSL_CUSTOM_CURVES
  28356. /* Convert data to hex string.
  28357. *
  28358. * Big-endian byte array is converted to big-endian hexadecimal string.
  28359. *
  28360. * @param [in] input Buffer containing data.
  28361. * @param [in] inSz Size of data in buffer.
  28362. * @param [out] out Buffer to hold hex string.
  28363. */
  28364. static void DataToHexString(const byte* input, word32 inSz, char* out)
  28365. {
  28366. static const char hexChar[] = { '0', '1', '2', '3', '4', '5', '6', '7',
  28367. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  28368. word32 i;
  28369. /* Converting a byte of data at a time to two hex characters. */
  28370. for (i = 0; i < inSz; i++) {
  28371. out[i*2 + 0] = hexChar[input[i] >> 4];
  28372. out[i*2 + 1] = hexChar[input[i] & 0xf];
  28373. }
  28374. /* NUL terminate string. */
  28375. out[i * 2] = '\0';
  28376. }
  28377. /* Convert data to hex string and place in allocated buffer.
  28378. *
  28379. * Big-endian byte array is converted to big-endian hexadecimal string.
  28380. *
  28381. * @param [in] input Buffer containing data.
  28382. * @param [in] inSz Size of data in buffer.
  28383. * @param [out] out Allocated buffer holding hex string.
  28384. * @param [in] heap Dynamic memory allocation hint.
  28385. * @param [in] heapType Type of heap to use.
  28386. * @return 0 on succcess.
  28387. * @return MEMORY_E when dynamic memory allocation fails.
  28388. */
  28389. static int DataToHexStringAlloc(const byte* input, word32 inSz, char** out,
  28390. void* heap, int heapType)
  28391. {
  28392. int ret = 0;
  28393. char* str;
  28394. /* Allocate for 2 string characters ber byte plus NUL. */
  28395. str = (char*)XMALLOC(inSz * 2 + 1, heap, heapType);
  28396. if (str == NULL) {
  28397. ret = MEMORY_E;
  28398. }
  28399. else {
  28400. /* Convert to hex string. */
  28401. DataToHexString(input, inSz, str);
  28402. *out = str;
  28403. }
  28404. (void)heap;
  28405. (void)heapType;
  28406. return ret;
  28407. }
  28408. /* ASN.1 template for SpecifiedECDomain.
  28409. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  28410. * NOTE: characteristic-two-field not supported. */
  28411. static const ASNItem eccSpecifiedASN[] = {
  28412. /* version */
  28413. /* VER */ { 0, ASN_INTEGER, 0, 0, 0 },
  28414. /* fieldID */
  28415. /* PRIME_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28416. /* prime-field or characteristic-two-field */
  28417. /* PRIME_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  28418. /* Prime-p */
  28419. /* PRIME_P */ { 1, ASN_INTEGER, 0, 0, 0 },
  28420. /* fieldID */
  28421. /* PARAM_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28422. /* a */
  28423. /* PARAM_A */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28424. /* b */
  28425. /* PARAM_B */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28426. /* seed */
  28427. /* PARAM_SEED */ { 1, ASN_BIT_STRING, 0, 0, 1 },
  28428. /* base */
  28429. /* BASE */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  28430. /* order */
  28431. /* ORDER */ { 0, ASN_INTEGER, 0, 0, 0 },
  28432. /* cofactor */
  28433. /* COFACTOR */ { 0, ASN_INTEGER, 0, 0, 1 },
  28434. /* hash */
  28435. /* HASH_SEQ */ { 0, ASN_SEQUENCE, 0, 0, 1 },
  28436. };
  28437. enum {
  28438. ECCSPECIFIEDASN_IDX_VER = 0,
  28439. ECCSPECIFIEDASN_IDX_PRIME_SEQ,
  28440. ECCSPECIFIEDASN_IDX_PRIME_OID,
  28441. ECCSPECIFIEDASN_IDX_PRIME_P,
  28442. ECCSPECIFIEDASN_IDX_PARAM_SEQ,
  28443. ECCSPECIFIEDASN_IDX_PARAM_A,
  28444. ECCSPECIFIEDASN_IDX_PARAM_B,
  28445. ECCSPECIFIEDASN_IDX_PARAM_SEED,
  28446. ECCSPECIFIEDASN_IDX_BASE,
  28447. ECCSPECIFIEDASN_IDX_ORDER,
  28448. ECCSPECIFIEDASN_IDX_COFACTOR,
  28449. ECCSPECIFIEDASN_IDX_HASH_SEQ,
  28450. };
  28451. /* Number of items in ASN.1 template for SpecifiedECDomain. */
  28452. #define eccSpecifiedASN_Length (sizeof(eccSpecifiedASN) / sizeof(ASNItem))
  28453. /* OID indicating the prime field is explicity defined. */
  28454. static const byte primeFieldOID[] = {
  28455. 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01
  28456. };
  28457. static const char ecSetCustomName[] = "Custom";
  28458. /* Explicit EC parameter values. */
  28459. static int EccSpecifiedECDomainDecode(const byte* input, word32 inSz,
  28460. ecc_key* key)
  28461. {
  28462. DECL_ASNGETDATA(dataASN, eccSpecifiedASN_Length);
  28463. int ret = 0;
  28464. ecc_set_type* curve;
  28465. word32 idx = 0;
  28466. byte version;
  28467. byte cofactor;
  28468. const byte *base;
  28469. word32 baseLen;
  28470. /* Allocate a new parameter set. */
  28471. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  28472. DYNAMIC_TYPE_ECC_BUFFER);
  28473. if (curve == NULL)
  28474. ret = MEMORY_E;
  28475. CALLOC_ASNGETDATA(dataASN, eccSpecifiedASN_Length, ret, key->heap);
  28476. if (ret == 0) {
  28477. /* Clear out parameters and set fields to indicate it is custom. */
  28478. XMEMSET(curve, 0, sizeof(*curve));
  28479. /* Set name to be: "Custom" */
  28480. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28481. curve->name = ecSetCustomName;
  28482. #else
  28483. XMEMCPY((void*)curve->name, ecSetCustomName, sizeof(ecSetCustomName));
  28484. #endif
  28485. curve->id = ECC_CURVE_CUSTOM;
  28486. /* Get version, must have prime field OID and get co-factor. */
  28487. GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_VER], &version);
  28488. GetASN_ExpBuffer(&dataASN[ECCSPECIFIEDASN_IDX_PRIME_OID],
  28489. primeFieldOID, sizeof(primeFieldOID));
  28490. GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_COFACTOR], &cofactor);
  28491. /* Decode the explicit parameters. */
  28492. ret = GetASN_Items(eccSpecifiedASN, dataASN, eccSpecifiedASN_Length, 1,
  28493. input, &idx, inSz);
  28494. }
  28495. /* Version must be 1 or 2 for supporting explicit parameters. */
  28496. if ((ret == 0) && (version < 1 || version > 3)) {
  28497. ret = ASN_PARSE_E;
  28498. }
  28499. /* Only version 2 and above can have a seed. */
  28500. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_PARAM_SEED].tag != 0) &&
  28501. (version < 2)) {
  28502. ret = ASN_PARSE_E;
  28503. }
  28504. /* Only version 2 and above can have a hash algorithm. */
  28505. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_HASH_SEQ].tag != 0) &&
  28506. (version < 2)) {
  28507. ret = ASN_PARSE_E;
  28508. }
  28509. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_COFACTOR].tag != 0)) {
  28510. /* Store optional co-factor. */
  28511. curve->cofactor = cofactor;
  28512. }
  28513. if (ret == 0) {
  28514. /* Length of the prime in bytes is the curve size. */
  28515. curve->size =
  28516. (int)dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length;
  28517. /* Base point: 0x04 <x> <y> (must be uncompressed). */
  28518. GetASN_GetConstRef(&dataASN[ECCSPECIFIEDASN_IDX_BASE], &base,
  28519. &baseLen);
  28520. if ((baseLen < (word32)curve->size * 2 + 1) || (base[0] != 0x4)) {
  28521. ret = ASN_PARSE_E;
  28522. }
  28523. }
  28524. /* Put the curve parameters into the set.
  28525. * Convert the big-endian number byte array to a big-endian string.
  28526. */
  28527. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28528. /* Allocate buffer to put hex strings into. */
  28529. if (ret == 0) {
  28530. /* Base X-ordinate */
  28531. ret = DataToHexStringAlloc(base + 1, curve->size,
  28532. (char**)&curve->Gx, key->heap,
  28533. DYNAMIC_TYPE_ECC_BUFFER);
  28534. }
  28535. if (ret == 0) {
  28536. /* Base Y-ordinate */
  28537. ret = DataToHexStringAlloc(base + 1 + curve->size, curve->size,
  28538. (char**)&curve->Gy, key->heap,
  28539. DYNAMIC_TYPE_ECC_BUFFER);
  28540. }
  28541. if (ret == 0) {
  28542. /* Prime */
  28543. ret = DataToHexStringAlloc(
  28544. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
  28545. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
  28546. (char**)&curve->prime, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28547. }
  28548. if (ret == 0) {
  28549. /* Parameter A */
  28550. ret = DataToHexStringAlloc(
  28551. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
  28552. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
  28553. (char**)&curve->Af, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28554. }
  28555. if (ret == 0) {
  28556. /* Parameter B */
  28557. ret = DataToHexStringAlloc(
  28558. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
  28559. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
  28560. (char**)&curve->Bf, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28561. }
  28562. if (ret == 0) {
  28563. /* Order of curve */
  28564. ret = DataToHexStringAlloc(
  28565. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
  28566. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
  28567. (char**)&curve->order, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28568. }
  28569. #else
  28570. if (ret == 0) {
  28571. /* Base X-ordinate */
  28572. DataToHexString(base + 1, curve->size, curve->Gx);
  28573. /* Base Y-ordinate */
  28574. DataToHexString(base + 1 + curve->size, curve->size, curve->Gy);
  28575. /* Prime */
  28576. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
  28577. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
  28578. curve->prime);
  28579. /* Parameter A */
  28580. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
  28581. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
  28582. curve->Af);
  28583. /* Parameter B */
  28584. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
  28585. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
  28586. curve->Bf);
  28587. /* Order of curve */
  28588. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
  28589. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
  28590. curve->order);
  28591. }
  28592. #endif /* WOLFSSL_ECC_CURVE_STATIC */
  28593. /* Store parameter set in key. */
  28594. if ((ret == 0) && (wc_ecc_set_custom_curve(key, curve) < 0)) {
  28595. ret = ASN_PARSE_E;
  28596. }
  28597. if (ret == 0) {
  28598. /* The parameter set was allocated.. */
  28599. key->deallocSet = 1;
  28600. }
  28601. if ((ret != 0) && (curve != NULL)) {
  28602. /* Failed to set parameters so free paramter set. */
  28603. wc_ecc_free_curve(curve, key->heap);
  28604. }
  28605. FREE_ASNGETDATA(dataASN, key->heap);
  28606. return ret;
  28607. }
  28608. #endif /* WOLFSSL_CUSTOM_CURVES */
  28609. #endif /* WOLFSSL_ASN_TEMPLATE */
  28610. #ifdef HAVE_ECC
  28611. #ifdef WOLFSSL_ASN_TEMPLATE
  28612. /* ASN.1 template for ECC private key.
  28613. * SEC.1 Ver 2.0, C.4 - Syntax for Elliptic Curve Private Keys
  28614. */
  28615. static const ASNItem eccKeyASN[] = {
  28616. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28617. /* version */
  28618. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  28619. /* privateKey */
  28620. /* PKEY */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28621. /* parameters */
  28622. /* PARAMS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PARAMS, 1, 1, 1 },
  28623. /* named */
  28624. /* CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  28625. /* specified */
  28626. /* CURVEPARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  28627. /* publicKey */
  28628. /* PUBKEY */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PUBKEY, 1, 1, 1 },
  28629. /* Uncompressed point - X9.62. */
  28630. /* PUBKEY_VAL, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  28631. };
  28632. enum {
  28633. ECCKEYASN_IDX_SEQ = 0,
  28634. ECCKEYASN_IDX_VER,
  28635. ECCKEYASN_IDX_PKEY,
  28636. ECCKEYASN_IDX_PARAMS,
  28637. ECCKEYASN_IDX_CURVEID,
  28638. ECCKEYASN_IDX_CURVEPARAMS,
  28639. ECCKEYASN_IDX_PUBKEY,
  28640. ECCKEYASN_IDX_PUBKEY_VAL,
  28641. };
  28642. /* Number of items in ASN.1 template for ECC private key. */
  28643. #define eccKeyASN_Length (sizeof(eccKeyASN) / sizeof(ASNItem))
  28644. #endif
  28645. WOLFSSL_ABI
  28646. int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
  28647. word32 inSz)
  28648. {
  28649. #ifndef WOLFSSL_ASN_TEMPLATE
  28650. word32 oidSum;
  28651. int version, length;
  28652. int privSz, pubSz = 0;
  28653. byte b;
  28654. int ret = 0;
  28655. int curve_id = ECC_CURVE_DEF;
  28656. #ifdef WOLFSSL_SMALL_STACK
  28657. byte* priv;
  28658. byte* pub = NULL;
  28659. #else
  28660. byte priv[ECC_MAXSIZE+1];
  28661. byte pub[2*(ECC_MAXSIZE+1)]; /* public key has two parts plus header */
  28662. #endif
  28663. word32 algId = 0;
  28664. byte* pubData = NULL;
  28665. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  28666. return BAD_FUNC_ARG;
  28667. /* if has pkcs8 header skip it */
  28668. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  28669. /* ignore error, did not have pkcs8 header */
  28670. }
  28671. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28672. return ASN_PARSE_E;
  28673. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  28674. return ASN_PARSE_E;
  28675. if (*inOutIdx >= inSz)
  28676. return ASN_PARSE_E;
  28677. b = input[*inOutIdx];
  28678. *inOutIdx += 1;
  28679. /* priv type */
  28680. if (b != 4 && b != 6 && b != 7)
  28681. return ASN_PARSE_E;
  28682. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  28683. return ASN_PARSE_E;
  28684. privSz = length;
  28685. if (privSz > ECC_MAXSIZE)
  28686. return BUFFER_E;
  28687. #ifdef WOLFSSL_SMALL_STACK
  28688. priv = (byte*)XMALLOC(privSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28689. if (priv == NULL)
  28690. return MEMORY_E;
  28691. #endif
  28692. /* priv key */
  28693. XMEMCPY(priv, &input[*inOutIdx], privSz);
  28694. *inOutIdx += length;
  28695. if ((*inOutIdx + 1) < inSz) {
  28696. /* prefix 0, may have */
  28697. b = input[*inOutIdx];
  28698. if (b == ECC_PREFIX_0) {
  28699. *inOutIdx += 1;
  28700. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  28701. ret = ASN_PARSE_E;
  28702. else {
  28703. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType,
  28704. inSz);
  28705. if (ret == 0) {
  28706. if ((ret = CheckCurve(oidSum)) < 0)
  28707. ret = ECC_CURVE_OID_E;
  28708. else {
  28709. curve_id = ret;
  28710. ret = 0;
  28711. }
  28712. }
  28713. }
  28714. }
  28715. }
  28716. if (ret == 0 && (*inOutIdx + 1) < inSz) {
  28717. /* prefix 1 */
  28718. b = input[*inOutIdx];
  28719. *inOutIdx += 1;
  28720. if (b != ECC_PREFIX_1) {
  28721. ret = ASN_ECC_KEY_E;
  28722. }
  28723. else if (GetLength(input, inOutIdx, &length, inSz) <= 0) {
  28724. ret = ASN_PARSE_E;
  28725. }
  28726. else {
  28727. /* key header */
  28728. ret = CheckBitString(input, inOutIdx, &length, inSz, 0, NULL);
  28729. if (ret == 0) {
  28730. /* pub key */
  28731. pubSz = length;
  28732. if (pubSz > 2*(ECC_MAXSIZE+1))
  28733. ret = BUFFER_E;
  28734. else {
  28735. #ifdef WOLFSSL_SMALL_STACK
  28736. pub = (byte*)XMALLOC(pubSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28737. if (pub == NULL)
  28738. ret = MEMORY_E;
  28739. else
  28740. #endif
  28741. {
  28742. XMEMCPY(pub, &input[*inOutIdx], pubSz);
  28743. *inOutIdx += length;
  28744. pubData = pub;
  28745. }
  28746. }
  28747. }
  28748. }
  28749. }
  28750. if (ret == 0) {
  28751. ret = wc_ecc_import_private_key_ex(priv, privSz, pubData, pubSz, key,
  28752. curve_id);
  28753. }
  28754. #ifdef WOLFSSL_SMALL_STACK
  28755. XFREE(priv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28756. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28757. #endif
  28758. return ret;
  28759. #else
  28760. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  28761. byte version;
  28762. int ret = 0;
  28763. int curve_id = ECC_CURVE_DEF;
  28764. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  28765. word32 algId = 0;
  28766. #endif
  28767. /* Validate parameters. */
  28768. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  28769. ret = BAD_FUNC_ARG;
  28770. }
  28771. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  28772. /* if has pkcs8 header skip it */
  28773. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  28774. /* ignore error, did not have pkcs8 header */
  28775. }
  28776. #endif
  28777. CALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  28778. if (ret == 0) {
  28779. /* Get the version and set the expected OID type. */
  28780. GetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], &version);
  28781. GetASN_OID(&dataASN[ECCKEYASN_IDX_CURVEID], oidCurveType);
  28782. /* Decode the private ECC key. */
  28783. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  28784. inOutIdx, inSz);
  28785. }
  28786. /* Only version 1 supported. */
  28787. if ((ret == 0) && (version != 1)) {
  28788. ret = ASN_PARSE_E;
  28789. }
  28790. /* Curve Parameters are optional. */
  28791. if ((ret == 0) && (dataASN[ECCKEYASN_IDX_PARAMS].tag != 0)) {
  28792. if (dataASN[ECCKEYASN_IDX_CURVEID].tag != 0) {
  28793. /* Named curve - check and get id. */
  28794. curve_id = CheckCurve(dataASN[ECCKEYASN_IDX_CURVEID].data.oid.sum);
  28795. if (curve_id < 0) {
  28796. ret = ECC_CURVE_OID_E;
  28797. }
  28798. }
  28799. else {
  28800. #ifdef WOLFSSL_CUSTOM_CURVES
  28801. /* Parse explicit parameters. */
  28802. ret = EccSpecifiedECDomainDecode(
  28803. dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.data,
  28804. dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.length, key);
  28805. #else
  28806. /* Explicit parameters not supported in build configuration. */
  28807. ret = ASN_PARSE_E;
  28808. #endif
  28809. }
  28810. }
  28811. if (ret == 0) {
  28812. /* Import private key value and public point (may be NULL). */
  28813. ret = wc_ecc_import_private_key_ex(
  28814. dataASN[ECCKEYASN_IDX_PKEY].data.ref.data,
  28815. dataASN[ECCKEYASN_IDX_PKEY].data.ref.length,
  28816. dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.data,
  28817. dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.length,
  28818. key, curve_id);
  28819. }
  28820. FREE_ASNGETDATA(dataASN, key->heap);
  28821. return ret;
  28822. #endif
  28823. }
  28824. #ifdef WOLFSSL_CUSTOM_CURVES
  28825. #ifndef WOLFSSL_ASN_TEMPLATE
  28826. /* returns 0 on success */
  28827. static int ASNToHexString(const byte* input, word32* inOutIdx, char** out,
  28828. word32 inSz, void* heap, int heapType)
  28829. {
  28830. int len;
  28831. int i;
  28832. char* str;
  28833. word32 localIdx;
  28834. byte tag;
  28835. if (*inOutIdx >= inSz) {
  28836. return BUFFER_E;
  28837. }
  28838. localIdx = *inOutIdx;
  28839. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 && tag == ASN_INTEGER) {
  28840. if (GetASNInt(input, inOutIdx, &len, inSz) < 0)
  28841. return ASN_PARSE_E;
  28842. }
  28843. else {
  28844. if (GetOctetString(input, inOutIdx, &len, inSz) < 0)
  28845. return ASN_PARSE_E;
  28846. }
  28847. str = (char*)XMALLOC(len * 2 + 1, heap, heapType);
  28848. if (str == NULL) {
  28849. return MEMORY_E;
  28850. }
  28851. for (i=0; i<len; i++)
  28852. ByteToHexStr(input[*inOutIdx + i], str + i*2);
  28853. str[len*2] = '\0';
  28854. *inOutIdx += len;
  28855. *out = str;
  28856. (void)heap;
  28857. (void)heapType;
  28858. return 0;
  28859. }
  28860. static int EccKeyParamCopy(char** dst, char* src)
  28861. {
  28862. int ret = 0;
  28863. #ifdef WOLFSSL_ECC_CURVE_STATIC
  28864. word32 length;
  28865. #endif
  28866. if (dst == NULL || src == NULL)
  28867. return BAD_FUNC_ARG;
  28868. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28869. *dst = src;
  28870. #else
  28871. length = (int)XSTRLEN(src) + 1;
  28872. if (length > MAX_ECC_STRING) {
  28873. WOLFSSL_MSG("ECC Param too large for buffer");
  28874. ret = BUFFER_E;
  28875. }
  28876. else {
  28877. XSTRNCPY(*dst, src, MAX_ECC_STRING);
  28878. }
  28879. XFREE(src, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28880. #endif
  28881. return ret;
  28882. }
  28883. #endif /* !WOLFSSL_ASN_TEMPLATE */
  28884. #endif /* WOLFSSL_CUSTOM_CURVES */
  28885. WOLFSSL_ABI
  28886. int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx,
  28887. ecc_key* key, word32 inSz)
  28888. {
  28889. #ifndef WOLFSSL_ASN_TEMPLATE
  28890. int ret;
  28891. int version, length;
  28892. int curve_id = ECC_CURVE_DEF;
  28893. word32 oidSum, localIdx;
  28894. byte tag, isPrivFormat = 0;
  28895. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  28896. return BAD_FUNC_ARG;
  28897. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28898. return ASN_PARSE_E;
  28899. /* Check if ECC private key is being used and skip private portion */
  28900. if (GetMyVersion(input, inOutIdx, &version, inSz) >= 0) {
  28901. isPrivFormat = 1;
  28902. /* Type private key */
  28903. if (*inOutIdx >= inSz)
  28904. return ASN_PARSE_E;
  28905. tag = input[*inOutIdx];
  28906. *inOutIdx += 1;
  28907. if (tag != 4 && tag != 6 && tag != 7)
  28908. return ASN_PARSE_E;
  28909. /* Skip Private Key */
  28910. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  28911. return ASN_PARSE_E;
  28912. if (length > ECC_MAXSIZE)
  28913. return BUFFER_E;
  28914. *inOutIdx += length;
  28915. /* Private Curve Header */
  28916. if (*inOutIdx >= inSz)
  28917. return ASN_PARSE_E;
  28918. tag = input[*inOutIdx];
  28919. *inOutIdx += 1;
  28920. if (tag != ECC_PREFIX_0)
  28921. return ASN_ECC_KEY_E;
  28922. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  28923. return ASN_PARSE_E;
  28924. }
  28925. /* Standard ECC public key */
  28926. else {
  28927. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28928. return ASN_PARSE_E;
  28929. ret = SkipObjectId(input, inOutIdx, inSz);
  28930. if (ret != 0)
  28931. return ret;
  28932. }
  28933. if (*inOutIdx >= inSz) {
  28934. return BUFFER_E;
  28935. }
  28936. localIdx = *inOutIdx;
  28937. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 &&
  28938. tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  28939. #ifdef WOLFSSL_CUSTOM_CURVES
  28940. ecc_set_type* curve;
  28941. int len;
  28942. char* point = NULL;
  28943. ret = 0;
  28944. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  28945. DYNAMIC_TYPE_ECC_BUFFER);
  28946. if (curve == NULL)
  28947. ret = MEMORY_E;
  28948. if (ret == 0) {
  28949. static const char customName[] = "Custom";
  28950. XMEMSET(curve, 0, sizeof(*curve));
  28951. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28952. curve->name = customName;
  28953. #else
  28954. XMEMCPY((void*)curve->name, customName, sizeof(customName));
  28955. #endif
  28956. curve->id = ECC_CURVE_CUSTOM;
  28957. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28958. ret = ASN_PARSE_E;
  28959. }
  28960. if (ret == 0) {
  28961. GetInteger7Bit(input, inOutIdx, inSz);
  28962. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28963. ret = ASN_PARSE_E;
  28964. }
  28965. if (ret == 0) {
  28966. char* p = NULL;
  28967. SkipObjectId(input, inOutIdx, inSz);
  28968. ret = ASNToHexString(input, inOutIdx, &p, inSz,
  28969. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28970. if (ret == 0) {
  28971. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28972. ret = EccKeyParamCopy((char**)&curve->prime, p);
  28973. #else
  28974. const char *_tmp_ptr = &curve->prime[0];
  28975. ret = EccKeyParamCopy((char**)&_tmp_ptr, p);
  28976. #endif
  28977. }
  28978. }
  28979. if (ret == 0) {
  28980. curve->size = (int)XSTRLEN(curve->prime) / 2;
  28981. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28982. ret = ASN_PARSE_E;
  28983. }
  28984. if (ret == 0) {
  28985. char* af = NULL;
  28986. ret = ASNToHexString(input, inOutIdx, &af, inSz,
  28987. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28988. if (ret == 0) {
  28989. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28990. ret = EccKeyParamCopy((char**)&curve->Af, af);
  28991. #else
  28992. const char *_tmp_ptr = &curve->Af[0];
  28993. ret = EccKeyParamCopy((char**)&_tmp_ptr, af);
  28994. #endif
  28995. }
  28996. }
  28997. if (ret == 0) {
  28998. char* bf = NULL;
  28999. ret = ASNToHexString(input, inOutIdx, &bf, inSz,
  29000. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29001. if (ret == 0) {
  29002. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29003. ret = EccKeyParamCopy((char**)&curve->Bf, bf);
  29004. #else
  29005. const char *_tmp_ptr = &curve->Bf[0];
  29006. ret = EccKeyParamCopy((char**)&_tmp_ptr, bf);
  29007. #endif
  29008. }
  29009. }
  29010. if (ret == 0) {
  29011. localIdx = *inOutIdx;
  29012. if (*inOutIdx < inSz && GetASNTag(input, &localIdx, &tag, inSz)
  29013. == 0 && tag == ASN_BIT_STRING) {
  29014. len = 0;
  29015. ret = GetASNHeader(input, ASN_BIT_STRING, inOutIdx, &len, inSz);
  29016. if (ret > 0)
  29017. ret = 0; /* reset on success */
  29018. *inOutIdx += len;
  29019. }
  29020. }
  29021. if (ret == 0) {
  29022. ret = ASNToHexString(input, inOutIdx, (char**)&point, inSz,
  29023. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29024. /* sanity check that point buffer is not smaller than the expected
  29025. * size to hold ( 0 4 || Gx || Gy )
  29026. * where Gx and Gy are each the size of curve->size * 2 */
  29027. if (ret == 0 && (int)XSTRLEN(point) < (curve->size * 4) + 2) {
  29028. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29029. ret = BUFFER_E;
  29030. }
  29031. }
  29032. if (ret == 0) {
  29033. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29034. curve->Gx = (const char*)XMALLOC(curve->size * 2 + 2, key->heap,
  29035. DYNAMIC_TYPE_ECC_BUFFER);
  29036. curve->Gy = (const char*)XMALLOC(curve->size * 2 + 2, key->heap,
  29037. DYNAMIC_TYPE_ECC_BUFFER);
  29038. if (curve->Gx == NULL || curve->Gy == NULL) {
  29039. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29040. ret = MEMORY_E;
  29041. }
  29042. #else
  29043. if (curve->size * 2 + 2 > MAX_ECC_STRING) {
  29044. WOLFSSL_MSG("curve size is too large to fit in buffer");
  29045. ret = BUFFER_E;
  29046. }
  29047. #endif
  29048. }
  29049. if (ret == 0) {
  29050. char* o = NULL;
  29051. XMEMCPY((char*)curve->Gx, point + 2, curve->size * 2);
  29052. XMEMCPY((char*)curve->Gy, point + curve->size * 2 + 2,
  29053. curve->size * 2);
  29054. ((char*)curve->Gx)[curve->size * 2] = '\0';
  29055. ((char*)curve->Gy)[curve->size * 2] = '\0';
  29056. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29057. ret = ASNToHexString(input, inOutIdx, &o, inSz,
  29058. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29059. if (ret == 0) {
  29060. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29061. ret = EccKeyParamCopy((char**)&curve->order, o);
  29062. #else
  29063. const char *_tmp_ptr = &curve->order[0];
  29064. ret = EccKeyParamCopy((char**)&_tmp_ptr, o);
  29065. #endif
  29066. }
  29067. }
  29068. if (ret == 0) {
  29069. curve->cofactor = GetInteger7Bit(input, inOutIdx, inSz);
  29070. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29071. curve->oid = NULL;
  29072. #else
  29073. XMEMSET((void*)curve->oid, 0, sizeof(curve->oid));
  29074. #endif
  29075. curve->oidSz = 0;
  29076. curve->oidSum = 0;
  29077. if (wc_ecc_set_custom_curve(key, curve) < 0) {
  29078. ret = ASN_PARSE_E;
  29079. }
  29080. key->deallocSet = 1;
  29081. curve = NULL;
  29082. }
  29083. if (curve != NULL)
  29084. wc_ecc_free_curve(curve, key->heap);
  29085. if (ret < 0)
  29086. return ret;
  29087. #else
  29088. return ASN_PARSE_E;
  29089. #endif /* WOLFSSL_CUSTOM_CURVES */
  29090. }
  29091. else {
  29092. /* ecc params information */
  29093. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType, inSz);
  29094. if (ret != 0)
  29095. return ret;
  29096. /* get curve id */
  29097. if ((ret = CheckCurve(oidSum)) < 0)
  29098. return ECC_CURVE_OID_E;
  29099. else {
  29100. curve_id = ret;
  29101. }
  29102. }
  29103. if (isPrivFormat) {
  29104. /* Public Curve Header - skip */
  29105. if (*inOutIdx >= inSz)
  29106. return ASN_PARSE_E;
  29107. tag = input[*inOutIdx];
  29108. *inOutIdx += 1;
  29109. if (tag != ECC_PREFIX_1)
  29110. return ASN_ECC_KEY_E;
  29111. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  29112. return ASN_PARSE_E;
  29113. }
  29114. /* key header */
  29115. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  29116. if (ret != 0)
  29117. return ret;
  29118. /* This is the raw point data compressed or uncompressed. */
  29119. if (wc_ecc_import_x963_ex(input + *inOutIdx, length, key,
  29120. curve_id) != 0) {
  29121. return ASN_ECC_KEY_E;
  29122. }
  29123. *inOutIdx += length;
  29124. return 0;
  29125. #else
  29126. /* eccKeyASN is longer than eccPublicKeyASN. */
  29127. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  29128. int ret = 0;
  29129. int curve_id = ECC_CURVE_DEF;
  29130. int oidIdx = ECCPUBLICKEYASN_IDX_ALGOID_CURVEID;
  29131. #ifdef WOLFSSL_CUSTOM_CURVES
  29132. int specIdx = ECCPUBLICKEYASN_IDX_ALGOID_PARAMS;
  29133. #endif
  29134. int pubIdx = ECCPUBLICKEYASN_IDX_PUBKEY;
  29135. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  29136. ret = BAD_FUNC_ARG;
  29137. }
  29138. ALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  29139. if (ret == 0) {
  29140. /* Clear dynamic data for ECC public key. */
  29141. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccPublicKeyASN_Length);
  29142. /* Set required ECDSA OID and ignore the curve OID type. */
  29143. GetASN_ExpBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], keyEcdsaOid,
  29144. sizeof(keyEcdsaOid));
  29145. GetASN_OID(&dataASN[oidIdx], oidIgnoreType);
  29146. /* Decode the public ECC key. */
  29147. ret = GetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length, 1,
  29148. input, inOutIdx, inSz);
  29149. if (ret != 0) {
  29150. oidIdx = ECCKEYASN_IDX_CURVEID;
  29151. #ifdef WOLFSSL_CUSTOM_CURVES
  29152. specIdx = ECCKEYASN_IDX_CURVEPARAMS;
  29153. #endif
  29154. pubIdx = ECCKEYASN_IDX_PUBKEY_VAL;
  29155. /* Clear dynamic data for ECC private key. */
  29156. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccKeyASN_Length);
  29157. /* Check named curve OID type. */
  29158. GetASN_OID(&dataASN[oidIdx], oidIgnoreType);
  29159. /* Try private key format .*/
  29160. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  29161. inOutIdx, inSz);
  29162. if (ret != 0) {
  29163. ret = ASN_PARSE_E;
  29164. }
  29165. }
  29166. }
  29167. if (ret == 0) {
  29168. if (dataASN[oidIdx].tag != 0) {
  29169. /* Named curve - check and get id. */
  29170. curve_id = CheckCurve(dataASN[oidIdx].data.oid.sum);
  29171. if (curve_id < 0) {
  29172. ret = ASN_OBJECT_ID_E;
  29173. }
  29174. }
  29175. else {
  29176. #ifdef WOLFSSL_CUSTOM_CURVES
  29177. /* Parse explicit parameters. */
  29178. ret = EccSpecifiedECDomainDecode(dataASN[specIdx].data.ref.data,
  29179. dataASN[specIdx].data.ref.length, key);
  29180. #else
  29181. /* Explicit parameters not supported in build configuration. */
  29182. ret = ASN_PARSE_E;
  29183. #endif
  29184. }
  29185. }
  29186. if (ret == 0) {
  29187. /* Import public point. */
  29188. ret = wc_ecc_import_x963_ex(dataASN[pubIdx].data.ref.data,
  29189. dataASN[pubIdx].data.ref.length, key, curve_id);
  29190. if (ret != 0) {
  29191. ret = ASN_ECC_KEY_E;
  29192. }
  29193. }
  29194. FREE_ASNGETDATA(dataASN, key->heap);
  29195. return ret;
  29196. #endif /* WOLFSSL_ASN_TEMPLATE */
  29197. }
  29198. #if defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  29199. /* build DER formatted ECC key, include optional public key if requested,
  29200. * return length on success, negative on error */
  29201. static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen,
  29202. int pubIn, int curveIn)
  29203. {
  29204. #ifndef WOLFSSL_ASN_TEMPLATE
  29205. byte curve[MAX_ALGO_SZ+2];
  29206. byte ver[MAX_VERSION_SZ];
  29207. byte seq[MAX_SEQ_SZ];
  29208. int ret, totalSz, curveSz, verSz;
  29209. int privHdrSz = ASN_ECC_HEADER_SZ;
  29210. int pubHdrSz = ASN_ECC_CONTEXT_SZ + ASN_ECC_HEADER_SZ;
  29211. #ifdef WOLFSSL_NO_MALLOC
  29212. byte prv[MAX_ECC_BYTES + ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  29213. byte pub[(MAX_ECC_BYTES * 2) + 1 + ASN_ECC_CONTEXT_SZ +
  29214. ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  29215. #else
  29216. byte *prv = NULL, *pub = NULL;
  29217. #endif
  29218. word32 idx = 0, prvidx = 0, pubidx = 0, curveidx = 0;
  29219. word32 seqSz, privSz, pubSz = ECC_BUFSIZE;
  29220. if (key == NULL || (output == NULL && inLen == NULL))
  29221. return BAD_FUNC_ARG;
  29222. if (curveIn) {
  29223. /* curve */
  29224. curve[curveidx++] = ECC_PREFIX_0;
  29225. curveidx++ /* to put the size after computation */;
  29226. curveSz = SetCurve(key, curve+curveidx, MAX_ALGO_SZ);
  29227. if (curveSz < 0)
  29228. return curveSz;
  29229. /* set computed size */
  29230. curve[1] = (byte)curveSz;
  29231. curveidx += curveSz;
  29232. }
  29233. /* private */
  29234. privSz = key->dp->size;
  29235. #ifdef WOLFSSL_QNX_CAAM
  29236. /* check if is a black key, and add MAC size if needed */
  29237. if (key->blackKey > 0 && key->blackKey != CAAM_BLACK_KEY_ECB) {
  29238. privSz = privSz + WC_CAAM_MAC_SZ;
  29239. }
  29240. #endif
  29241. #ifndef WOLFSSL_NO_MALLOC
  29242. prv = (byte*)XMALLOC(privSz + privHdrSz + MAX_SEQ_SZ,
  29243. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29244. if (prv == NULL) {
  29245. return MEMORY_E;
  29246. }
  29247. #else
  29248. if (sizeof(prv) < privSz + privHdrSz + MAX_SEQ_SZ) {
  29249. return BUFFER_E;
  29250. }
  29251. #endif
  29252. if (privSz < ASN_LONG_LENGTH) {
  29253. prvidx += SetOctetString8Bit(privSz, &prv[prvidx]);
  29254. }
  29255. else {
  29256. prvidx += SetOctetString(privSz, &prv[prvidx]);
  29257. }
  29258. ret = wc_ecc_export_private_only(key, prv + prvidx, &privSz);
  29259. if (ret < 0) {
  29260. #ifndef WOLFSSL_NO_MALLOC
  29261. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29262. #endif
  29263. return ret;
  29264. }
  29265. prvidx += privSz;
  29266. /* pubIn */
  29267. if (pubIn) {
  29268. PRIVATE_KEY_UNLOCK();
  29269. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  29270. PRIVATE_KEY_LOCK();
  29271. if (ret != LENGTH_ONLY_E) {
  29272. #ifndef WOLFSSL_NO_MALLOC
  29273. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29274. #endif
  29275. return ret;
  29276. }
  29277. #ifndef WOLFSSL_NO_MALLOC
  29278. pub = (byte*)XMALLOC(pubSz + pubHdrSz + MAX_SEQ_SZ,
  29279. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29280. if (pub == NULL) {
  29281. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29282. return MEMORY_E;
  29283. }
  29284. #else
  29285. if (sizeof(pub) < pubSz + pubHdrSz + MAX_SEQ_SZ) {
  29286. return BUFFER_E;
  29287. }
  29288. #endif
  29289. pub[pubidx++] = ECC_PREFIX_1;
  29290. if (pubSz > 128) /* leading zero + extra size byte */
  29291. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 2, pub+pubidx);
  29292. else /* leading zero */
  29293. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 1, pub+pubidx);
  29294. /* SetBitString adds leading zero */
  29295. pubidx += SetBitString(pubSz, 0, pub + pubidx);
  29296. PRIVATE_KEY_UNLOCK();
  29297. ret = wc_ecc_export_x963(key, pub + pubidx, &pubSz);
  29298. PRIVATE_KEY_LOCK();
  29299. if (ret != 0) {
  29300. #ifndef WOLFSSL_NO_MALLOC
  29301. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29302. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29303. #endif
  29304. return ret;
  29305. }
  29306. pubidx += pubSz;
  29307. }
  29308. /* make headers */
  29309. verSz = SetMyVersion(1, ver, FALSE);
  29310. seqSz = SetSequence(verSz + prvidx + pubidx + curveidx, seq);
  29311. totalSz = prvidx + pubidx + curveidx + verSz + seqSz;
  29312. if (output == NULL) {
  29313. *inLen = totalSz;
  29314. #ifndef WOLFSSL_NO_MALLOC
  29315. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29316. if (pubIn) {
  29317. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29318. }
  29319. #endif
  29320. return LENGTH_ONLY_E;
  29321. }
  29322. if (inLen != NULL && totalSz > (int)*inLen) {
  29323. #ifndef WOLFSSL_NO_MALLOC
  29324. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29325. if (pubIn) {
  29326. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29327. }
  29328. #endif
  29329. return BAD_FUNC_ARG;
  29330. }
  29331. /* write out */
  29332. /* seq */
  29333. XMEMCPY(output + idx, seq, seqSz);
  29334. idx = seqSz;
  29335. /* ver */
  29336. XMEMCPY(output + idx, ver, verSz);
  29337. idx += verSz;
  29338. /* private */
  29339. XMEMCPY(output + idx, prv, prvidx);
  29340. idx += prvidx;
  29341. #ifndef WOLFSSL_NO_MALLOC
  29342. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29343. #endif
  29344. /* curve */
  29345. XMEMCPY(output + idx, curve, curveidx);
  29346. idx += curveidx;
  29347. /* pubIn */
  29348. if (pubIn) {
  29349. XMEMCPY(output + idx, pub, pubidx);
  29350. /* idx += pubidx; not used after write, if more data remove comment */
  29351. #ifndef WOLFSSL_NO_MALLOC
  29352. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29353. #endif
  29354. }
  29355. return totalSz;
  29356. #else
  29357. DECL_ASNSETDATA(dataASN, eccKeyASN_Length);
  29358. word32 privSz, pubSz;
  29359. int sz = 0;
  29360. int ret = 0;
  29361. int curveIdSz = 0;
  29362. /* Check validity of parameters. */
  29363. if ((key == NULL) || ((output == NULL) && (inLen == NULL))) {
  29364. ret = BAD_FUNC_ARG;
  29365. }
  29366. /* Check key has parameters when encoding curve. */
  29367. if ((ret == 0) && curveIn && (key->dp == NULL)) {
  29368. ret = BAD_FUNC_ARG;
  29369. }
  29370. CALLOC_ASNSETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  29371. if (ret == 0) {
  29372. /* Private key size is the curve size. */
  29373. privSz = key->dp->size;
  29374. if (pubIn) {
  29375. /* Get the length of the public key. */
  29376. PRIVATE_KEY_UNLOCK();
  29377. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  29378. PRIVATE_KEY_LOCK();
  29379. if (ret == LENGTH_ONLY_E)
  29380. ret = 0;
  29381. }
  29382. }
  29383. if (ret == 0) {
  29384. /* Version: 1 */
  29385. SetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], 1);
  29386. /* Leave space for private key. */
  29387. SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PKEY], NULL, privSz);
  29388. if (curveIn) {
  29389. /* Get length of the named curve OID to put into the encoding. */
  29390. curveIdSz = SetCurve(key, NULL, 0);
  29391. if (curveIdSz < 0) {
  29392. ret = curveIdSz;
  29393. }
  29394. /* Curve OID */
  29395. SetASN_ReplaceBuffer(&dataASN[ECCKEYASN_IDX_CURVEID], NULL,
  29396. curveIdSz);
  29397. /* TODO: add support for SpecifiedECDomain curve. */
  29398. dataASN[ECCKEYASN_IDX_CURVEPARAMS].noOut = 1;
  29399. }
  29400. else {
  29401. SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PARAMS,
  29402. eccKeyASN_Length);
  29403. }
  29404. if (ret == 0) {
  29405. if (pubIn) {
  29406. /* Leave space for public key. */
  29407. SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PUBKEY_VAL], NULL, pubSz);
  29408. }
  29409. else {
  29410. /* Don't write out public key. */
  29411. SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PUBKEY,
  29412. eccKeyASN_Length);
  29413. }
  29414. /* Calculate size of the private key encoding. */
  29415. ret = SizeASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, &sz);
  29416. }
  29417. }
  29418. /* Return the size if no buffer. */
  29419. if ((ret == 0) && (output == NULL)) {
  29420. *inLen = sz;
  29421. ret = LENGTH_ONLY_E;
  29422. }
  29423. /* Check the buffer is big enough. */
  29424. if ((ret == 0) && (inLen != NULL) && (sz > (int)*inLen)) {
  29425. ret = BAD_FUNC_ARG;
  29426. }
  29427. if ((ret == 0) && (output != NULL)) {
  29428. /* Encode the private key. */
  29429. SetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, output);
  29430. if (curveIn) {
  29431. /* Put named curve OID data into encoding. */
  29432. curveIdSz = SetCurve(key,
  29433. (byte*)dataASN[ECCKEYASN_IDX_CURVEID].data.buffer.data,
  29434. curveIdSz);
  29435. if (curveIdSz < 0) {
  29436. ret = curveIdSz;
  29437. }
  29438. }
  29439. if (ret == 0) {
  29440. /* Export the private value into the buffer. */
  29441. ret = wc_ecc_export_private_only(key,
  29442. (byte*)dataASN[ECCKEYASN_IDX_PKEY].data.buffer.data, &privSz);
  29443. }
  29444. if ((ret == 0) && pubIn) {
  29445. /* Export the public point into the buffer. */
  29446. PRIVATE_KEY_UNLOCK();
  29447. ret = wc_ecc_export_x963(key,
  29448. (byte*)dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.buffer.data,
  29449. &pubSz);
  29450. PRIVATE_KEY_LOCK();
  29451. }
  29452. }
  29453. if (ret == 0) {
  29454. /* Return the encoding size. */
  29455. ret = sz;
  29456. }
  29457. FREE_ASNSETDATA(dataASN, key->heap);
  29458. return ret;
  29459. #endif
  29460. }
  29461. /* Write a Private ecc key, including public to DER format,
  29462. * length on success else < 0 */
  29463. WOLFSSL_ABI
  29464. int wc_EccKeyToDer(ecc_key* key, byte* output, word32 inLen)
  29465. {
  29466. return wc_BuildEccKeyDer(key, output, &inLen, 1, 1);
  29467. }
  29468. /* Write only private ecc key to DER format,
  29469. * length on success else < 0 */
  29470. int wc_EccKeyDerSize(ecc_key* key, int pub)
  29471. {
  29472. word32 sz = 0;
  29473. int ret;
  29474. ret = wc_BuildEccKeyDer(key, NULL, &sz, pub, 1);
  29475. if (ret != LENGTH_ONLY_E) {
  29476. return ret;
  29477. }
  29478. return sz;
  29479. }
  29480. /* Write only private ecc key to DER format,
  29481. * length on success else < 0 */
  29482. int wc_EccPrivateKeyToDer(ecc_key* key, byte* output, word32 inLen)
  29483. {
  29484. return wc_BuildEccKeyDer(key, output, &inLen, 0, 1);
  29485. }
  29486. #ifdef HAVE_PKCS8
  29487. /* Write only private ecc key or both private and public parts to unencrypted
  29488. * PKCS#8 format.
  29489. *
  29490. * If output is NULL, places required PKCS#8 buffer size in outLen and
  29491. * returns LENGTH_ONLY_E.
  29492. *
  29493. * return length on success else < 0 */
  29494. static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen,
  29495. int includePublic)
  29496. {
  29497. int ret, tmpDerSz;
  29498. int algoID = 0;
  29499. word32 oidSz = 0;
  29500. word32 pkcs8Sz = 0;
  29501. const byte* curveOID = NULL;
  29502. #ifdef WOLFSSL_NO_MALLOC
  29503. byte tmpDer[ECC_BUFSIZE];
  29504. #else
  29505. byte* tmpDer = NULL;
  29506. #endif
  29507. word32 sz = ECC_BUFSIZE;
  29508. if (key == NULL || key->dp == NULL || outLen == NULL)
  29509. return BAD_FUNC_ARG;
  29510. /* set algoID, get curve OID */
  29511. algoID = ECDSAk;
  29512. ret = wc_ecc_get_oid(key->dp->oidSum, &curveOID, &oidSz);
  29513. if (ret < 0)
  29514. return ret;
  29515. #ifndef WOLFSSL_NO_MALLOC
  29516. /* temp buffer for plain DER key */
  29517. tmpDer = (byte*)XMALLOC(ECC_BUFSIZE, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29518. if (tmpDer == NULL)
  29519. return MEMORY_E;
  29520. #endif
  29521. XMEMSET(tmpDer, 0, ECC_BUFSIZE);
  29522. ret = wc_BuildEccKeyDer(key, tmpDer, &sz, includePublic, 0);
  29523. if (ret < 0) {
  29524. #ifndef WOLFSSL_NO_MALLOC
  29525. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29526. #endif
  29527. return ret;
  29528. }
  29529. tmpDerSz = ret;
  29530. /* get pkcs8 expected output size */
  29531. ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, tmpDer, tmpDerSz, algoID,
  29532. curveOID, oidSz);
  29533. if (ret != LENGTH_ONLY_E) {
  29534. #ifndef WOLFSSL_NO_MALLOC
  29535. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29536. #endif
  29537. return ret;
  29538. }
  29539. if (output == NULL) {
  29540. #ifndef WOLFSSL_NO_MALLOC
  29541. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29542. #endif
  29543. *outLen = pkcs8Sz;
  29544. return LENGTH_ONLY_E;
  29545. }
  29546. else if (*outLen < pkcs8Sz) {
  29547. #ifndef WOLFSSL_NO_MALLOC
  29548. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29549. #endif
  29550. WOLFSSL_MSG("Input buffer too small for ECC PKCS#8 key");
  29551. return BUFFER_E;
  29552. }
  29553. ret = wc_CreatePKCS8Key(output, &pkcs8Sz, tmpDer, tmpDerSz,
  29554. algoID, curveOID, oidSz);
  29555. if (ret < 0) {
  29556. #ifndef WOLFSSL_NO_MALLOC
  29557. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29558. #endif
  29559. return ret;
  29560. }
  29561. #ifndef WOLFSSL_NO_MALLOC
  29562. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29563. #endif
  29564. *outLen = ret;
  29565. return ret;
  29566. }
  29567. /* Write only private ecc key to unencrypted PKCS#8 format.
  29568. *
  29569. * return length on success else < 0 */
  29570. int wc_EccPrivateKeyToPKCS8(ecc_key* key, byte* output, word32* outLen)
  29571. {
  29572. return eccToPKCS8(key, output, outLen, 0);
  29573. }
  29574. /* Write both private and public ecc keys to unencrypted PKCS#8 format.
  29575. *
  29576. * return length on success else < 0 */
  29577. int wc_EccKeyToPKCS8(ecc_key* key, byte* output,
  29578. word32* outLen)
  29579. {
  29580. return eccToPKCS8(key, output, outLen, 1);
  29581. }
  29582. #endif /* HAVE_PKCS8 */
  29583. #endif /* HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  29584. #endif /* HAVE_ECC */
  29585. #ifdef WC_ENABLE_ASYM_KEY_IMPORT
  29586. #ifdef WOLFSSL_ASN_TEMPLATE
  29587. /* ASN.1 template for Ed25519 and Ed448 private key.
  29588. * RFC 8410, 7 - Private Key Format (but public value is EXPLICIT OCTET_STRING)
  29589. */
  29590. static const ASNItem edKeyASN[] = {
  29591. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  29592. /* Version */
  29593. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  29594. /* privateKeyAlgorithm */
  29595. /* PKEYALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  29596. /* PKEYALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  29597. /* privateKey */
  29598. /* PKEY */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  29599. /* CurvePrivateKey */
  29600. /* PKEY_CURVEPKEY */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  29601. /* attributes */
  29602. /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_ATTRS, 1, 1, 1 },
  29603. /* publicKey */
  29604. /* PUBKEY */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY, 0, 0, 1 },
  29605. };
  29606. enum {
  29607. EDKEYASN_IDX_SEQ = 0,
  29608. EDKEYASN_IDX_VER,
  29609. EDKEYASN_IDX_PKEYALGO_SEQ,
  29610. EDKEYASN_IDX_PKEYALGO_OID,
  29611. EDKEYASN_IDX_PKEY,
  29612. EDKEYASN_IDX_PKEY_CURVEPKEY,
  29613. EDKEYASN_IDX_ATTRS,
  29614. EDKEYASN_IDX_PUBKEY,
  29615. };
  29616. /* Number of items in ASN.1 template for Ed25519 and Ed448 private key. */
  29617. #define edKeyASN_Length (sizeof(edKeyASN) / sizeof(ASNItem))
  29618. #endif
  29619. #if ((defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)) \
  29620. || (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)) \
  29621. || (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)) \
  29622. || (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)) \
  29623. || (defined(HAVE_PQC) && defined(HAVE_FALCON)) \
  29624. || (defined(HAVE_PQC) && defined(HAVE_DILITHIUM)) \
  29625. || (defined(HAVE_PQC) && defined(HAVE_SPHINCS)))
  29626. int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz,
  29627. byte* privKey, word32* privKeyLen,
  29628. byte* pubKey, word32* pubKeyLen, int keyType)
  29629. {
  29630. #ifndef WOLFSSL_ASN_TEMPLATE
  29631. word32 oid;
  29632. int version, length, endKeyIdx, privSz, pubSz;
  29633. const byte* priv;
  29634. const byte* pub;
  29635. #else
  29636. int ret = 0;
  29637. DECL_ASNGETDATA(dataASN, edKeyASN_Length);
  29638. CALLOC_ASNGETDATA(dataASN, edKeyASN_Length, ret, NULL);
  29639. #endif
  29640. if (input == NULL || inOutIdx == NULL || inSz == 0 ||
  29641. privKey == NULL || privKeyLen == NULL) {
  29642. return BAD_FUNC_ARG;
  29643. }
  29644. #ifndef WOLFSSL_ASN_TEMPLATE
  29645. if (GetSequence(input, inOutIdx, &length, inSz) >= 0) {
  29646. endKeyIdx = *inOutIdx + length;
  29647. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  29648. return ASN_PARSE_E;
  29649. if (version != 0) {
  29650. WOLFSSL_MSG("Unrecognized version of ED25519 private key");
  29651. return ASN_PARSE_E;
  29652. }
  29653. if (GetAlgoId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  29654. return ASN_PARSE_E;
  29655. if (oid != (word32)keyType)
  29656. return ASN_PARSE_E;
  29657. if (GetOctetString(input, inOutIdx, &length, inSz) < 0)
  29658. return ASN_PARSE_E;
  29659. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  29660. return ASN_PARSE_E;
  29661. priv = input + *inOutIdx;
  29662. *inOutIdx += privSz;
  29663. }
  29664. else {
  29665. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  29666. return ASN_PARSE_E;
  29667. priv = input + *inOutIdx;
  29668. *inOutIdx += privSz;
  29669. endKeyIdx = *inOutIdx;
  29670. }
  29671. if ((word32)privSz > *privKeyLen)
  29672. return BUFFER_E;
  29673. if (endKeyIdx == (int)*inOutIdx) {
  29674. *privKeyLen = privSz;
  29675. XMEMCPY(privKey, priv, *privKeyLen);
  29676. if (pubKeyLen != NULL)
  29677. *pubKeyLen = 0;
  29678. }
  29679. else {
  29680. if (pubKeyLen == NULL) {
  29681. return BAD_FUNC_ARG;
  29682. }
  29683. if (GetASNHeader(input, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY | 1,
  29684. inOutIdx, &pubSz, inSz) < 0) {
  29685. return ASN_PARSE_E;
  29686. }
  29687. if ((word32)pubSz > *pubKeyLen)
  29688. return BUFFER_E;
  29689. pub = input + *inOutIdx;
  29690. *inOutIdx += pubSz;
  29691. *privKeyLen = privSz;
  29692. XMEMCPY(privKey, priv, *privKeyLen);
  29693. *pubKeyLen = pubSz;
  29694. if (pubKey != NULL)
  29695. XMEMCPY(pubKey, pub, *pubKeyLen);
  29696. }
  29697. if (endKeyIdx != (int)*inOutIdx)
  29698. return ASN_PARSE_E;
  29699. return 0;
  29700. #else
  29701. if (ret == 0) {
  29702. /* Require OID. */
  29703. word32 oidSz;
  29704. const byte* oid = OidFromId(keyType, oidKeyType, &oidSz);
  29705. GetASN_ExpBuffer(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], oid, oidSz);
  29706. /* Parse full private key. */
  29707. ret = GetASN_Items(edKeyASN, dataASN, edKeyASN_Length, 1, input,
  29708. inOutIdx, inSz);
  29709. if (ret != 0) {
  29710. /* Parse just the OCTET_STRING. */
  29711. ret = GetASN_Items(&edKeyASN[EDKEYASN_IDX_PKEY_CURVEPKEY],
  29712. &dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], 1, 0, input,
  29713. inOutIdx, inSz);
  29714. if (ret != 0) {
  29715. ret = ASN_PARSE_E;
  29716. }
  29717. }
  29718. }
  29719. /* Check the private value length is correct. */
  29720. if ((ret == 0) && dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length
  29721. > *privKeyLen) {
  29722. ret = ASN_PARSE_E;
  29723. }
  29724. if ((ret == 0) && dataASN[EDKEYASN_IDX_PUBKEY].tag == 0) {
  29725. *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
  29726. XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
  29727. *privKeyLen);
  29728. if (pubKeyLen != NULL)
  29729. *pubKeyLen = 0;
  29730. }
  29731. else if ((ret == 0) &&
  29732. (pubKeyLen != NULL) &&
  29733. (dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
  29734. ret = ASN_PARSE_E;
  29735. }
  29736. else if (ret == 0) {
  29737. /* Import private and public value. */
  29738. *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
  29739. XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
  29740. *privKeyLen);
  29741. if (pubKeyLen != NULL)
  29742. *pubKeyLen = dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length;
  29743. if (pubKey != NULL && pubKeyLen != NULL)
  29744. XMEMCPY(pubKey, dataASN[EDKEYASN_IDX_PUBKEY].data.ref.data,
  29745. *pubKeyLen);
  29746. }
  29747. FREE_ASNGETDATA(dataASN, NULL);
  29748. return ret;
  29749. #endif /* WOLFSSL_ASN_TEMPLATE */
  29750. }
  29751. int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz,
  29752. byte* pubKey, word32* pubKeyLen, int keyType)
  29753. {
  29754. int ret = 0;
  29755. #ifndef WOLFSSL_ASN_TEMPLATE
  29756. int length;
  29757. word32 oid;
  29758. #else
  29759. word32 len;
  29760. DECL_ASNGETDATA(dataASN, edPubKeyASN_Length);
  29761. #endif
  29762. if (input == NULL || inSz == 0 || inOutIdx == NULL ||
  29763. pubKey == NULL || pubKeyLen == NULL) {
  29764. return BAD_FUNC_ARG;
  29765. }
  29766. #ifndef WOLFSSL_ASN_TEMPLATE
  29767. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29768. return ASN_PARSE_E;
  29769. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29770. return ASN_PARSE_E;
  29771. if (GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  29772. return ASN_PARSE_E;
  29773. if (oid != (word32)keyType)
  29774. return ASN_PARSE_E;
  29775. /* key header */
  29776. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  29777. if (ret != 0)
  29778. return ret;
  29779. /* check that the value found is not too large for pubKey buffer */
  29780. if ((word32)length > *pubKeyLen)
  29781. return ASN_PARSE_E;
  29782. /* check that input buffer is exhausted */
  29783. if (*inOutIdx + (word32)length != inSz)
  29784. return ASN_PARSE_E;
  29785. /* This is the raw point data compressed or uncompressed. */
  29786. *pubKeyLen = length;
  29787. XMEMCPY(pubKey, input + *inOutIdx, *pubKeyLen);
  29788. #else
  29789. len = inSz - *inOutIdx;
  29790. CALLOC_ASNGETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
  29791. if (ret == 0) {
  29792. /* Require OID. */
  29793. word32 oidSz;
  29794. const byte* oid = OidFromId(keyType, oidKeyType, &oidSz);
  29795. GetASN_ExpBuffer(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], oid, oidSz);
  29796. /* Decode Ed25519 private key. */
  29797. ret = GetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, 1, input,
  29798. inOutIdx, inSz);
  29799. if (ret != 0)
  29800. ret = ASN_PARSE_E;
  29801. /* check that input buffer is exhausted */
  29802. if (*inOutIdx != inSz)
  29803. ret = ASN_PARSE_E;
  29804. }
  29805. /* Check the public value length is correct. */
  29806. if ((ret == 0) &&
  29807. (dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
  29808. ret = ASN_PARSE_E;
  29809. }
  29810. /* Check that the all the buffer was used. */
  29811. if ((ret == 0) &&
  29812. (GetASNItem_Length(dataASN[EDPUBKEYASN_IDX_SEQ], input) != len)) {
  29813. ret = ASN_PARSE_E;
  29814. }
  29815. if (ret == 0) {
  29816. *pubKeyLen = dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length;
  29817. XMEMCPY(pubKey, dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.data,
  29818. *pubKeyLen);
  29819. }
  29820. FREE_ASNGETDATA(dataASN, NULL);
  29821. #endif /* WOLFSSL_ASN_TEMPLATE */
  29822. return ret;
  29823. }
  29824. #endif
  29825. #endif /* WC_ENABLE_ASYM_KEY_IMPORT */
  29826. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  29827. int wc_Ed25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  29828. ed25519_key* key, word32 inSz)
  29829. {
  29830. int ret;
  29831. byte privKey[ED25519_KEY_SIZE], pubKey[ED25519_PUB_KEY_SIZE];
  29832. word32 privKeyLen = (word32)sizeof(privKey);
  29833. word32 pubKeyLen = (word32)sizeof(pubKey);
  29834. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  29835. return BAD_FUNC_ARG;
  29836. }
  29837. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  29838. pubKey, &pubKeyLen, ED25519k);
  29839. if (ret == 0) {
  29840. if (pubKeyLen == 0) {
  29841. ret = wc_ed25519_import_private_only(privKey, privKeyLen, key);
  29842. }
  29843. else {
  29844. ret = wc_ed25519_import_private_key(privKey, privKeyLen,
  29845. pubKey, pubKeyLen, key);
  29846. }
  29847. }
  29848. return ret;
  29849. }
  29850. int wc_Ed25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  29851. ed25519_key* key, word32 inSz)
  29852. {
  29853. int ret;
  29854. byte pubKey[ED25519_PUB_KEY_SIZE];
  29855. word32 pubKeyLen = (word32)sizeof(pubKey);
  29856. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  29857. return BAD_FUNC_ARG;
  29858. }
  29859. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  29860. pubKey, &pubKeyLen, ED25519k);
  29861. if (ret == 0) {
  29862. ret = wc_ed25519_import_public(pubKey, pubKeyLen, key);
  29863. }
  29864. return ret;
  29865. }
  29866. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */
  29867. #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)
  29868. int wc_Curve25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  29869. curve25519_key* key, word32 inSz)
  29870. {
  29871. int ret;
  29872. byte privKey[CURVE25519_KEYSIZE];
  29873. word32 privKeyLen = CURVE25519_KEYSIZE;
  29874. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  29875. return BAD_FUNC_ARG;
  29876. }
  29877. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  29878. NULL, NULL, X25519k);
  29879. if (ret == 0) {
  29880. ret = wc_curve25519_import_private(privKey, privKeyLen, key);
  29881. }
  29882. return ret;
  29883. }
  29884. int wc_Curve25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  29885. curve25519_key* key, word32 inSz)
  29886. {
  29887. int ret;
  29888. byte pubKey[CURVE25519_KEYSIZE];
  29889. word32 pubKeyLen = (word32)sizeof(pubKey);
  29890. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  29891. return BAD_FUNC_ARG;
  29892. }
  29893. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  29894. pubKey, &pubKeyLen, X25519k);
  29895. if (ret == 0) {
  29896. ret = wc_curve25519_import_public(pubKey, pubKeyLen, key);
  29897. }
  29898. return ret;
  29899. }
  29900. #endif /* HAVE_CURVE25519 && HAVE_ED25519_KEY_IMPORT */
  29901. #ifdef WC_ENABLE_ASYM_KEY_EXPORT
  29902. /* Build ASN.1 formatted key based on RFC 5958 (Asymmetric Key Packages)
  29903. *
  29904. * Pass NULL for output to get the size of the encoding.
  29905. *
  29906. * @param [in] privKey private key buffer
  29907. * @param [in] privKeyLen private ket buffer length
  29908. * @param [in] pubKey public key buffer (optional)
  29909. * @param [in] pubKeyLen public ket buffer length
  29910. * @param [out] output Buffer to put encoded data in (optional)
  29911. * @param [in] outLen Size of buffer in bytes
  29912. * @param [in] keyType is "enum Key_Sum" like ED25519k
  29913. * @return Size of encoded data in bytes on success
  29914. * @return BAD_FUNC_ARG when key is NULL.
  29915. * @return MEMORY_E when dynamic memory allocation failed.
  29916. */
  29917. int SetAsymKeyDer(const byte* privKey, word32 privKeyLen,
  29918. const byte* pubKey, word32 pubKeyLen,
  29919. byte* output, word32 outLen, int keyType)
  29920. {
  29921. int ret = 0;
  29922. #ifndef WOLFSSL_ASN_TEMPLATE
  29923. word32 idx = 0, seqSz, verSz, algoSz, privSz, pubSz = 0, sz;
  29924. #else
  29925. DECL_ASNSETDATA(dataASN, edKeyASN_Length);
  29926. int sz;
  29927. #endif
  29928. /* Validate parameters. */
  29929. if (privKey == NULL || outLen == 0) {
  29930. return BAD_FUNC_ARG;
  29931. }
  29932. #ifndef WOLFSSL_ASN_TEMPLATE
  29933. /* calculate size */
  29934. if (pubKey) {
  29935. pubSz = 2 + pubKeyLen;
  29936. }
  29937. privSz = 2 + 2 + privKeyLen;
  29938. algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
  29939. verSz = 3; /* version is 3 bytes (enum + id + version(byte)) */
  29940. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, NULL);
  29941. sz = seqSz + verSz + algoSz + privSz + pubSz;
  29942. /* checkout output size */
  29943. if (output != NULL && sz > outLen) {
  29944. ret = BAD_FUNC_ARG;
  29945. }
  29946. if (ret == 0 && output != NULL) {
  29947. /* write out */
  29948. /* seq */
  29949. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, output);
  29950. idx = seqSz;
  29951. /* ver */
  29952. SetMyVersion(0, output + idx, FALSE);
  29953. idx += verSz;
  29954. /* algo */
  29955. algoSz = SetAlgoID(keyType, output + idx, oidKeyType, 0);
  29956. idx += algoSz;
  29957. /* privKey */
  29958. idx += SetOctetString(2 + privKeyLen, output + idx);
  29959. idx += SetOctetString(privKeyLen, output + idx);
  29960. XMEMCPY(output + idx, privKey, privKeyLen);
  29961. idx += privKeyLen;
  29962. /* pubKey */
  29963. if (pubKey) {
  29964. idx += SetHeader(ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY |
  29965. 1, pubKeyLen, output + idx);
  29966. XMEMCPY(output + idx, pubKey, pubKeyLen);
  29967. idx += pubKeyLen;
  29968. }
  29969. sz = idx;
  29970. }
  29971. if (ret == 0) {
  29972. /* Return size of encoding. */
  29973. ret = sz;
  29974. }
  29975. #else
  29976. CALLOC_ASNSETDATA(dataASN, edKeyASN_Length, ret, NULL);
  29977. if (ret == 0) {
  29978. /* Set version = 0 */
  29979. SetASN_Int8Bit(&dataASN[EDKEYASN_IDX_VER], 0);
  29980. /* Set OID. */
  29981. SetASN_OID(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], keyType, oidKeyType);
  29982. /* Leave space for private key. */
  29983. SetASN_Buffer(&dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], NULL, privKeyLen);
  29984. /* Don't write out attributes. */
  29985. dataASN[EDKEYASN_IDX_ATTRS].noOut = 1;
  29986. if (pubKey) {
  29987. /* Leave space for public key. */
  29988. SetASN_Buffer(&dataASN[EDKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
  29989. }
  29990. else {
  29991. /* Don't put out public part. */
  29992. SetASNItem_NoOutNode(dataASN, edKeyASN, EDKEYASN_IDX_PUBKEY,
  29993. edKeyASN_Length);
  29994. }
  29995. /* Calculate the size of encoding. */
  29996. ret = SizeASN_Items(edKeyASN, dataASN, edKeyASN_Length, &sz);
  29997. }
  29998. /* Check buffer is big enough. */
  29999. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  30000. ret = BAD_FUNC_ARG;
  30001. }
  30002. if ((ret == 0) && (output != NULL)) {
  30003. /* Encode private key. */
  30004. SetASN_Items(edKeyASN, dataASN, edKeyASN_Length, output);
  30005. /* Put private value into space provided. */
  30006. XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.buffer.data,
  30007. privKey, privKeyLen);
  30008. if (pubKey != NULL) {
  30009. /* Put public value into space provided. */
  30010. XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PUBKEY].data.buffer.data,
  30011. pubKey, pubKeyLen);
  30012. }
  30013. }
  30014. if (ret == 0) {
  30015. /* Return size of encoding. */
  30016. ret = sz;
  30017. }
  30018. FREE_ASNSETDATA(dataASN, NULL);
  30019. #endif
  30020. return ret;
  30021. }
  30022. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  30023. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  30024. /* Write a Private ED25519 key, including public to DER format,
  30025. * length on success else < 0 */
  30026. int wc_Ed25519KeyToDer(ed25519_key* key, byte* output, word32 inLen)
  30027. {
  30028. if (key == NULL) {
  30029. return BAD_FUNC_ARG;
  30030. }
  30031. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  30032. key->p, ED25519_PUB_KEY_SIZE, output, inLen, ED25519k);
  30033. }
  30034. /* Write only private ED25519 key to DER format,
  30035. * length on success else < 0 */
  30036. int wc_Ed25519PrivateKeyToDer(ed25519_key* key, byte* output, word32 inLen)
  30037. {
  30038. if (key == NULL) {
  30039. return BAD_FUNC_ARG;
  30040. }
  30041. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  30042. NULL, 0, output, inLen, ED25519k);
  30043. }
  30044. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  30045. #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_EXPORT)
  30046. /* Write only private Curve25519 key to DER format,
  30047. * length on success else < 0 */
  30048. int wc_Curve25519PrivateKeyToDer(curve25519_key* key, byte* output, word32 inLen)
  30049. {
  30050. int ret;
  30051. byte privKey[CURVE25519_KEYSIZE];
  30052. word32 privKeyLen = CURVE25519_KEYSIZE;
  30053. if (key == NULL) {
  30054. return BAD_FUNC_ARG;
  30055. }
  30056. ret = wc_curve25519_export_private_raw(key, privKey, &privKeyLen);
  30057. if (ret == 0) {
  30058. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  30059. X25519k);
  30060. }
  30061. return ret;
  30062. }
  30063. /* Write a public Curve25519 key to DER format,
  30064. * length on success else < 0 */
  30065. int wc_Curve25519PublicKeyToDer(curve25519_key* key, byte* output, word32 inLen,
  30066. int withAlg)
  30067. {
  30068. int ret;
  30069. byte pubKey[CURVE25519_PUB_KEY_SIZE];
  30070. word32 pubKeyLen = (word32)sizeof(pubKey);
  30071. if (key == NULL || output == NULL) {
  30072. return BAD_FUNC_ARG;
  30073. }
  30074. ret = wc_curve25519_export_public(key, pubKey, &pubKeyLen);
  30075. if (ret == 0) {
  30076. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  30077. X25519k, withAlg);
  30078. }
  30079. return ret;
  30080. }
  30081. #endif /* HAVE_CURVE25519 && HAVE_CURVE25519_KEY_EXPORT */
  30082. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  30083. int wc_Ed448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30084. ed448_key* key, word32 inSz)
  30085. {
  30086. int ret;
  30087. byte privKey[ED448_KEY_SIZE], pubKey[ED448_PUB_KEY_SIZE];
  30088. word32 privKeyLen = (word32)sizeof(privKey);
  30089. word32 pubKeyLen = (word32)sizeof(pubKey);
  30090. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30091. return BAD_FUNC_ARG;
  30092. }
  30093. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30094. pubKey, &pubKeyLen, ED448k);
  30095. if (ret == 0) {
  30096. if (pubKeyLen == 0) {
  30097. ret = wc_ed448_import_private_only(privKey, privKeyLen, key);
  30098. }
  30099. else {
  30100. ret = wc_ed448_import_private_key(privKey, privKeyLen,
  30101. pubKey, pubKeyLen, key);
  30102. }
  30103. }
  30104. return ret;
  30105. }
  30106. int wc_Ed448PublicKeyDecode(const byte* input, word32* inOutIdx,
  30107. ed448_key* key, word32 inSz)
  30108. {
  30109. int ret;
  30110. byte pubKey[ED448_PUB_KEY_SIZE];
  30111. word32 pubKeyLen = (word32)sizeof(pubKey);
  30112. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30113. return BAD_FUNC_ARG;
  30114. }
  30115. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30116. pubKey, &pubKeyLen, ED448k);
  30117. if (ret == 0) {
  30118. ret = wc_ed448_import_public(pubKey, pubKeyLen, key);
  30119. }
  30120. return ret;
  30121. }
  30122. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */
  30123. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)
  30124. int wc_Curve448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30125. curve448_key* key, word32 inSz)
  30126. {
  30127. int ret;
  30128. byte privKey[CURVE448_KEY_SIZE];
  30129. word32 privKeyLen = CURVE448_KEY_SIZE;
  30130. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30131. return BAD_FUNC_ARG;
  30132. }
  30133. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30134. NULL, NULL, X448k);
  30135. if (ret == 0) {
  30136. ret = wc_curve448_import_private(privKey, privKeyLen, key);
  30137. }
  30138. return ret;
  30139. }
  30140. int wc_Curve448PublicKeyDecode(const byte* input, word32* inOutIdx,
  30141. curve448_key* key, word32 inSz)
  30142. {
  30143. int ret;
  30144. byte pubKey[CURVE448_PUB_KEY_SIZE];
  30145. word32 pubKeyLen = (word32)sizeof(pubKey);
  30146. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30147. return BAD_FUNC_ARG;
  30148. }
  30149. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30150. pubKey, &pubKeyLen, X448k);
  30151. if (ret == 0) {
  30152. ret = wc_curve448_import_public(pubKey, pubKeyLen, key);
  30153. }
  30154. return ret;
  30155. }
  30156. #endif /* HAVE_CURVE448 && HAVE_ED448_KEY_IMPORT */
  30157. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  30158. /* Write a Private ecc key, including public to DER format,
  30159. * length on success else < 0 */
  30160. int wc_Ed448KeyToDer(ed448_key* key, byte* output, word32 inLen)
  30161. {
  30162. if (key == NULL) {
  30163. return BAD_FUNC_ARG;
  30164. }
  30165. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  30166. key->p, ED448_KEY_SIZE, output, inLen, ED448k);
  30167. }
  30168. /* Write only private ecc key to DER format,
  30169. * length on success else < 0 */
  30170. int wc_Ed448PrivateKeyToDer(ed448_key* key, byte* output, word32 inLen)
  30171. {
  30172. if (key == NULL) {
  30173. return BAD_FUNC_ARG;
  30174. }
  30175. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  30176. NULL, 0, output, inLen, ED448k);
  30177. }
  30178. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  30179. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_EXPORT)
  30180. /* Write private Curve448 key to DER format,
  30181. * length on success else < 0 */
  30182. int wc_Curve448PrivateKeyToDer(curve448_key* key, byte* output, word32 inLen)
  30183. {
  30184. int ret;
  30185. byte privKey[CURVE448_KEY_SIZE];
  30186. word32 privKeyLen = CURVE448_KEY_SIZE;
  30187. if (key == NULL) {
  30188. return BAD_FUNC_ARG;
  30189. }
  30190. ret = wc_curve448_export_private_raw(key, privKey, &privKeyLen);
  30191. if (ret == 0) {
  30192. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  30193. X448k);
  30194. }
  30195. return ret;
  30196. }
  30197. /* Write a public Curve448 key to DER format,
  30198. * length on success else < 0 */
  30199. int wc_Curve448PublicKeyToDer(curve448_key* key, byte* output, word32 inLen,
  30200. int withAlg)
  30201. {
  30202. int ret;
  30203. byte pubKey[CURVE448_PUB_KEY_SIZE];
  30204. word32 pubKeyLen = (word32)sizeof(pubKey);
  30205. if (key == NULL || output == NULL) {
  30206. return BAD_FUNC_ARG;
  30207. }
  30208. ret = wc_curve448_export_public(key, pubKey, &pubKeyLen);
  30209. if (ret == 0) {
  30210. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  30211. X448k, withAlg);
  30212. }
  30213. return ret;
  30214. }
  30215. #endif /* HAVE_CURVE448 && HAVE_CURVE448_KEY_EXPORT */
  30216. #ifndef WOLFSSL_ASN_TEMPLATE
  30217. #if (defined(HAVE_OCSP) || defined(HAVE_CRL)) && !defined(WOLFCRYPT_ONLY)
  30218. /* Get raw Date only, no processing, 0 on success */
  30219. static int GetBasicDate(const byte* source, word32* idx, byte* date,
  30220. byte* format, int maxIdx)
  30221. {
  30222. int ret, length;
  30223. const byte *datePtr = NULL;
  30224. WOLFSSL_ENTER("GetBasicDate");
  30225. ret = GetDateInfo(source, idx, &datePtr, format, &length, maxIdx);
  30226. if (ret < 0)
  30227. return ret;
  30228. XMEMCPY(date, datePtr, length);
  30229. return 0;
  30230. }
  30231. #endif /* HAVE_OCSP || HAVE_CRL */
  30232. #endif /* WOLFSSL_ASN_TEMPLATE */
  30233. #if defined(HAVE_OCSP) && !defined(WOLFCRYPT_ONLY)
  30234. #ifndef WOLFSSL_ASN_TEMPLATE
  30235. static int GetEnumerated(const byte* input, word32* inOutIdx, int *value,
  30236. int sz)
  30237. {
  30238. word32 idx = *inOutIdx;
  30239. word32 len;
  30240. byte tag;
  30241. WOLFSSL_ENTER("GetEnumerated");
  30242. *value = 0;
  30243. if (GetASNTag(input, &idx, &tag, sz) < 0)
  30244. return ASN_PARSE_E;
  30245. if (tag != ASN_ENUMERATED)
  30246. return ASN_PARSE_E;
  30247. if ((int)idx >= sz)
  30248. return BUFFER_E;
  30249. len = input[idx++];
  30250. if (len > 4 || (int)(len + idx) > sz)
  30251. return ASN_PARSE_E;
  30252. while (len--) {
  30253. *value = *value << 8 | input[idx++];
  30254. }
  30255. *inOutIdx = idx;
  30256. return *value;
  30257. }
  30258. #endif /* !WOLFSSL_ASN_TEMPLATE */
  30259. #ifdef WOLFSSL_ASN_TEMPLATE
  30260. /* ASN.1 template for OCSP single response.
  30261. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30262. */
  30263. static const ASNItem singleResponseASN[] = {
  30264. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30265. /* certId */
  30266. /* CID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  30267. /* hashAlgorithm */
  30268. /* CID_HASHALGO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  30269. /* CID_HASHALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  30270. /* CID_HASHALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  30271. /* issuerNameHash */
  30272. /* CID_ISSUERHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  30273. /* issuerKeyHash */
  30274. /* CID_ISSUERKEYHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  30275. /* serialNumber */
  30276. /* CID_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
  30277. /* certStatus - CHOICE */
  30278. /* good [0] IMPLICIT NULL */
  30279. /* CS_GOOD */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 2 },
  30280. /* revoked [1] IMPLICIT RevokedInfo */
  30281. /* CS_REVOKED */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 2 },
  30282. /* revocationTime */
  30283. /* CS_REVOKED_TIME */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30284. /* revocationReason [0] EXPLICIT CRLReason OPTIONAL */
  30285. /* CS_REVOKED_REASON */ { 2, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 1 },
  30286. /* crlReason */
  30287. /* CS_REVOKED_REASON_VAL */ { 3, ASN_ENUMERATED, 0, 0, 0 },
  30288. /* unknown [2] IMPLICIT UnknownInfo ::= NULL */
  30289. /* UNKNOWN */ { 1, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 2 },
  30290. /* thisUpdate */
  30291. /* THISUPDATE_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30292. /* nextUpdate */
  30293. /* NEXTUPDATE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  30294. /* NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30295. /* singleExtensions */
  30296. /* EXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  30297. };
  30298. enum {
  30299. SINGLERESPONSEASN_IDX_SEQ = 0,
  30300. SINGLERESPONSEASN_IDX_CID_SEQ,
  30301. SINGLERESPONSEASN_IDX_CID_HASHALGO_SEQ,
  30302. SINGLERESPONSEASN_IDX_CID_HASHALGO_OID,
  30303. SINGLERESPONSEASN_IDX_CID_HASHALGO_NULL,
  30304. SINGLERESPONSEASN_IDX_CID_ISSUERHASH,
  30305. SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH,
  30306. SINGLERESPONSEASN_IDX_CID_SERIAL,
  30307. SINGLERESPONSEASN_IDX_CS_GOOD,
  30308. SINGLERESPONSEASN_IDX_CS_REVOKED,
  30309. SINGLERESPONSEASN_IDX_CS_REVOKED_TIME,
  30310. SINGLERESPONSEASN_IDX_CS_REVOKED_REASON,
  30311. SINGLERESPONSEASN_IDX_CS_REVOKED_REASON_VAL,
  30312. SINGLERESPONSEASN_IDX_UNKNOWN,
  30313. SINGLERESPONSEASN_IDX_THISUPDATE_GT,
  30314. SINGLERESPONSEASN_IDX_NEXTUPDATE,
  30315. SINGLERESPONSEASN_IDX_NEXTUPDATE_GT,
  30316. SINGLERESPONSEASN_IDX_EXT,
  30317. };
  30318. /* Number of items in ASN.1 template for OCSP single response. */
  30319. #define singleResponseASN_Length (sizeof(singleResponseASN) / sizeof(ASNItem))
  30320. #endif
  30321. static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size,
  30322. int wrapperSz, OcspEntry* single)
  30323. {
  30324. #ifndef WOLFSSL_ASN_TEMPLATE
  30325. word32 idx = *ioIndex, prevIndex, oid, localIdx, certIdIdx;
  30326. int length;
  30327. int ret;
  30328. byte tag;
  30329. WOLFSSL_ENTER("DecodeSingleResponse");
  30330. prevIndex = idx;
  30331. /* Wrapper around the Single Response */
  30332. if (GetSequence(source, &idx, &length, size) < 0)
  30333. return ASN_PARSE_E;
  30334. /* Wrapper around the CertID */
  30335. certIdIdx = idx;
  30336. if (GetSequence(source, &idx, &length, size) < 0)
  30337. return ASN_PARSE_E;
  30338. single->rawCertId = source + certIdIdx;
  30339. /* Hash algorithm */
  30340. ret = GetAlgoId(source, &idx, &oid, oidIgnoreType, size);
  30341. if (ret < 0)
  30342. return ret;
  30343. single->hashAlgoOID = oid;
  30344. /* Save reference to the hash of CN */
  30345. ret = GetOctetString(source, &idx, &length, size);
  30346. if (ret < 0)
  30347. return ret;
  30348. if (length > (int)sizeof(single->issuerHash))
  30349. return BUFFER_E;
  30350. XMEMCPY(single->issuerHash, source + idx, length);
  30351. idx += length;
  30352. /* Save reference to the hash of the issuer public key */
  30353. ret = GetOctetString(source, &idx, &length, size);
  30354. if (ret < 0)
  30355. return ret;
  30356. if (length > (int)sizeof(single->issuerKeyHash))
  30357. return BUFFER_E;
  30358. XMEMCPY(single->issuerKeyHash, source + idx, length);
  30359. idx += length;
  30360. /* Get serial number */
  30361. if (wc_GetSerialNumber(source, &idx, single->status->serial,
  30362. &single->status->serialSz, size) < 0)
  30363. return ASN_PARSE_E;
  30364. single->rawCertIdSize = idx - certIdIdx;
  30365. if (idx >= size)
  30366. return BUFFER_E;
  30367. /* CertStatus */
  30368. switch (source[idx++])
  30369. {
  30370. case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
  30371. single->status->status = CERT_GOOD;
  30372. idx++;
  30373. break;
  30374. case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
  30375. single->status->status = CERT_REVOKED;
  30376. if (GetLength(source, &idx, &length, size) < 0)
  30377. return ASN_PARSE_E;
  30378. idx += length;
  30379. break;
  30380. case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
  30381. single->status->status = CERT_UNKNOWN;
  30382. idx++;
  30383. break;
  30384. default:
  30385. return ASN_PARSE_E;
  30386. }
  30387. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  30388. single->status->thisDateAsn = source + idx;
  30389. localIdx = 0;
  30390. if (GetDateInfo(single->status->thisDateAsn, &localIdx, NULL,
  30391. (byte*)&single->status->thisDateParsed.type,
  30392. &single->status->thisDateParsed.length, size) < 0)
  30393. return ASN_PARSE_E;
  30394. XMEMCPY(single->status->thisDateParsed.data,
  30395. single->status->thisDateAsn + localIdx - single->status->thisDateParsed.length,
  30396. single->status->thisDateParsed.length);
  30397. #endif
  30398. if (GetBasicDate(source, &idx, single->status->thisDate,
  30399. &single->status->thisDateFormat, size) < 0)
  30400. return ASN_PARSE_E;
  30401. #ifndef NO_ASN_TIME
  30402. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  30403. if (!XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, BEFORE))
  30404. return ASN_BEFORE_DATE_E;
  30405. #endif
  30406. #endif
  30407. /* The following items are optional. Only check for them if there is more
  30408. * unprocessed data in the singleResponse wrapper. */
  30409. localIdx = idx;
  30410. if (((int)(idx - prevIndex) < wrapperSz) &&
  30411. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30412. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  30413. {
  30414. idx++;
  30415. if (GetLength(source, &idx, &length, size) < 0)
  30416. return ASN_PARSE_E;
  30417. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  30418. single->status->nextDateAsn = source + idx;
  30419. localIdx = 0;
  30420. if (GetDateInfo(single->status->nextDateAsn, &localIdx, NULL,
  30421. (byte*)&single->status->nextDateParsed.type,
  30422. &single->status->nextDateParsed.length, size) < 0)
  30423. return ASN_PARSE_E;
  30424. XMEMCPY(single->status->nextDateParsed.data,
  30425. single->status->nextDateAsn + localIdx - single->status->nextDateParsed.length,
  30426. single->status->nextDateParsed.length);
  30427. #endif
  30428. if (GetBasicDate(source, &idx, single->status->nextDate,
  30429. &single->status->nextDateFormat, size) < 0)
  30430. return ASN_PARSE_E;
  30431. #ifndef NO_ASN_TIME
  30432. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  30433. if (!XVALIDATE_DATE(single->status->nextDate, single->status->nextDateFormat, AFTER))
  30434. return ASN_AFTER_DATE_E;
  30435. #endif
  30436. #endif
  30437. }
  30438. /* Skip the optional extensions in singleResponse. */
  30439. localIdx = idx;
  30440. if (((int)(idx - prevIndex) < wrapperSz) &&
  30441. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30442. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  30443. {
  30444. idx++;
  30445. if (GetLength(source, &idx, &length, size) < 0)
  30446. return ASN_PARSE_E;
  30447. idx += length;
  30448. }
  30449. *ioIndex = idx;
  30450. return 0;
  30451. #else
  30452. DECL_ASNGETDATA(dataASN, singleResponseASN_Length);
  30453. int ret = 0;
  30454. CertStatus* cs = NULL;
  30455. word32 serialSz;
  30456. word32 issuerHashLen;
  30457. word32 issuerKeyHashLen;
  30458. word32 thisDateLen;
  30459. word32 nextDateLen;
  30460. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30461. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30462. WOLFSSL_ASN1_TIME *at;
  30463. #endif
  30464. (void)wrapperSz;
  30465. WOLFSSL_ENTER("DecodeSingleResponse");
  30466. CALLOC_ASNGETDATA(dataASN, singleResponseASN_Length, ret, NULL);
  30467. if (ret == 0) {
  30468. /* Certificate Status field. */
  30469. cs = single->status;
  30470. /* Set maximum lengths for data. */
  30471. issuerHashLen = OCSP_DIGEST_SIZE;
  30472. issuerKeyHashLen = OCSP_DIGEST_SIZE;
  30473. serialSz = EXTERNAL_SERIAL_SIZE;
  30474. thisDateLen = MAX_DATE_SIZE;
  30475. nextDateLen = MAX_DATE_SIZE;
  30476. /* Set OID type, buffers to hold data and variables to hold size. */
  30477. GetASN_OID(&dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID],
  30478. oidHashType);
  30479. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERHASH],
  30480. single->issuerHash, &issuerHashLen);
  30481. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH],
  30482. single->issuerKeyHash, &issuerKeyHashLen);
  30483. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_SERIAL], cs->serial,
  30484. &serialSz);
  30485. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT],
  30486. cs->thisDate, &thisDateLen);
  30487. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT],
  30488. cs->nextDate, &nextDateLen);
  30489. /* TODO: decode revoked time and reason. */
  30490. /* Decode OCSP single response. */
  30491. ret = GetASN_Items(singleResponseASN, dataASN, singleResponseASN_Length,
  30492. 1, source, ioIndex, size);
  30493. }
  30494. /* Validate the issuer hash length is the size required. */
  30495. if ((ret == 0) && (issuerHashLen != OCSP_DIGEST_SIZE)) {
  30496. ret = ASN_PARSE_E;
  30497. }
  30498. /* Validate the issuer key hash length is the size required. */
  30499. if ((ret == 0) && (issuerKeyHashLen != OCSP_DIGEST_SIZE)) {
  30500. ret = ASN_PARSE_E;
  30501. }
  30502. if (ret == 0) {
  30503. /* Store serial size. */
  30504. cs->serialSz = serialSz;
  30505. /* Determine status by which item was found. */
  30506. if (dataASN[SINGLERESPONSEASN_IDX_CS_GOOD].tag != 0) {
  30507. cs->status = CERT_GOOD;
  30508. }
  30509. if (dataASN[SINGLERESPONSEASN_IDX_CS_REVOKED].tag != 0) {
  30510. cs->status = CERT_REVOKED;
  30511. }
  30512. if (dataASN[SINGLERESPONSEASN_IDX_UNKNOWN].tag != 0) {
  30513. cs->status = CERT_UNKNOWN;
  30514. }
  30515. /* Store the thisDate format - only one possible. */
  30516. cs->thisDateFormat = ASN_GENERALIZED_TIME;
  30517. #if !defined(NO_ASN_TIME) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  30518. /* Check date is a valid string and BEFORE now. */
  30519. if (!XVALIDATE_DATE(cs->thisDate, ASN_GENERALIZED_TIME, BEFORE)) {
  30520. ret = ASN_BEFORE_DATE_E;
  30521. }
  30522. }
  30523. if (ret == 0) {
  30524. #endif
  30525. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30526. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30527. /* Store ASN.1 version of thisDate. */
  30528. cs->thisDateAsn = GetASNItem_Addr(
  30529. dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT], source);
  30530. at = &cs->thisDateParsed;
  30531. at->type = ASN_GENERALIZED_TIME;
  30532. XMEMCPY(at->data, cs->thisDate, thisDateLen);
  30533. at->length = thisDateLen;
  30534. #endif
  30535. }
  30536. if ((ret == 0) &&
  30537. (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
  30538. /* Store the nextDate format - only one possible. */
  30539. cs->nextDateFormat = ASN_GENERALIZED_TIME;
  30540. #if !defined(NO_ASN_TIME) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  30541. /* Check date is a valid string and AFTER now. */
  30542. if (!XVALIDATE_DATE(cs->nextDate, ASN_GENERALIZED_TIME, AFTER)) {
  30543. ret = ASN_AFTER_DATE_E;
  30544. }
  30545. }
  30546. if ((ret == 0) &&
  30547. (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
  30548. #endif
  30549. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30550. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30551. /* Store ASN.1 version of thisDate. */
  30552. cs->nextDateAsn = GetASNItem_Addr(
  30553. dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT], source);
  30554. at = &cs->nextDateParsed;
  30555. at->type = ASN_GENERALIZED_TIME;
  30556. XMEMCPY(at->data, cs->nextDate, nextDateLen);
  30557. at->length = nextDateLen;
  30558. #endif
  30559. }
  30560. if (ret == 0) {
  30561. /* OcspEntry now used. */
  30562. single->used = 1;
  30563. }
  30564. FREE_ASNGETDATA(dataASN, NULL);
  30565. return ret;
  30566. #endif
  30567. }
  30568. #ifdef WOLFSSL_ASN_TEMPLATE
  30569. /* ASN.1 template for OCSP response extension header.
  30570. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30571. */
  30572. static const ASNItem respExtHdrASN[] = {
  30573. /* responseExtensions */
  30574. /* EXT */ { 0, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 0 },
  30575. /* extensions */
  30576. /* EXT_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  30577. };
  30578. enum {
  30579. RESPEXTHDRASN_IDX_EXT = 0,
  30580. RESPEXTHDRASN_IDX_EXT_SEQ,
  30581. };
  30582. /* Number of items in ASN.1 template for OCSP response extension header. */
  30583. #define respExtHdrASN_Length (sizeof(respExtHdrASN) / sizeof(ASNItem))
  30584. #endif
  30585. static int DecodeOcspRespExtensions(byte* source, word32* ioIndex,
  30586. OcspResponse* resp, word32 sz)
  30587. {
  30588. #ifndef WOLFSSL_ASN_TEMPLATE
  30589. word32 idx = *ioIndex;
  30590. int length;
  30591. int ext_bound; /* boundary index for the sequence of extensions */
  30592. word32 oid;
  30593. int ret;
  30594. byte tag;
  30595. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  30596. if ((idx + 1) > sz)
  30597. return BUFFER_E;
  30598. if (GetASNTag(source, &idx, &tag, sz) < 0)
  30599. return ASN_PARSE_E;
  30600. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  30601. return ASN_PARSE_E;
  30602. if (GetLength(source, &idx, &length, sz) < 0)
  30603. return ASN_PARSE_E;
  30604. if (GetSequence(source, &idx, &length, sz) < 0)
  30605. return ASN_PARSE_E;
  30606. ext_bound = idx + length;
  30607. while (idx < (word32)ext_bound) {
  30608. word32 localIdx;
  30609. if (GetSequence(source, &idx, &length, sz) < 0) {
  30610. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  30611. return ASN_PARSE_E;
  30612. }
  30613. oid = 0;
  30614. if (GetObjectId(source, &idx, &oid, oidOcspType, sz) < 0) {
  30615. WOLFSSL_MSG("\tfail: OBJECT ID");
  30616. return ASN_PARSE_E;
  30617. }
  30618. /* check for critical flag */
  30619. if ((idx + 1) > (word32)sz) {
  30620. WOLFSSL_MSG("\tfail: malformed buffer");
  30621. return BUFFER_E;
  30622. }
  30623. localIdx = idx;
  30624. if (GetASNTag(source, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  30625. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  30626. ret = GetBoolean(source, &idx, sz);
  30627. if (ret < 0)
  30628. return ret;
  30629. }
  30630. ret = GetOctetString(source, &idx, &length, sz);
  30631. if (ret < 0)
  30632. return ret;
  30633. if (oid == OCSP_NONCE_OID) {
  30634. /* get data inside extra OCTET_STRING */
  30635. ret = GetOctetString(source, &idx, &length, sz);
  30636. if (ret < 0)
  30637. return ret;
  30638. resp->nonce = source + idx;
  30639. resp->nonceSz = length;
  30640. }
  30641. idx += length;
  30642. }
  30643. *ioIndex = idx;
  30644. return 0;
  30645. #else
  30646. /* certExtASN_Length is greater than respExtHdrASN_Length */
  30647. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  30648. int ret = 0;
  30649. word32 idx = *ioIndex;
  30650. word32 maxIdx = 0;
  30651. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  30652. CALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, resp->heap);
  30653. if (ret == 0) {
  30654. /* Check for header and move past. */
  30655. ret = GetASN_Items(respExtHdrASN, dataASN, respExtHdrASN_Length, 0,
  30656. source, &idx, sz);
  30657. }
  30658. if (ret == 0) {
  30659. /* Keep end extensions index for total length check. */
  30660. maxIdx = idx + dataASN[RESPEXTHDRASN_IDX_EXT_SEQ].length;
  30661. }
  30662. /* Step through all extensions. */
  30663. while ((ret == 0) && (idx < maxIdx)) {
  30664. /* Clear dynamic data, set OID type to expect. */
  30665. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  30666. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidOcspType);
  30667. /* TODO: check criticality. */
  30668. /* Decode OCSP response extension. */
  30669. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0,
  30670. source, &idx, sz);
  30671. if (ret == 0) {
  30672. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  30673. int length = dataASN[CERTEXTASN_IDX_VAL].length;
  30674. if (oid == OCSP_NONCE_OID) {
  30675. /* Extract nonce data. */
  30676. ret = GetOctetString(source, &idx, &length, sz);
  30677. if (ret >= 0) {
  30678. ret = 0;
  30679. /* get data inside extra OCTET_STRING */
  30680. resp->nonce = source + idx;
  30681. resp->nonceSz = length;
  30682. }
  30683. }
  30684. /* Ignore all other extension types. */
  30685. /* Skip over rest of extension. */
  30686. idx += length;
  30687. }
  30688. }
  30689. /* Return index after extensions. */
  30690. *ioIndex = idx;
  30691. FREE_ASNGETDATA(dataASN, resp->heap);
  30692. return ret;
  30693. #endif
  30694. }
  30695. #ifdef WOLFSSL_ASN_TEMPLATE
  30696. /* ASN.1 template for OCSP ResponseData.
  30697. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30698. */
  30699. static const ASNItem ocspRespDataASN[] = {
  30700. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30701. /* version DEFAULT v1 */
  30702. /* VER_PRESENT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  30703. /* VER */ { 2, ASN_INTEGER, 1, 0, 0 },
  30704. /* byName */
  30705. /* BYNAME */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  30706. /* byKey */
  30707. /* BYKEY */ { 1, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 2 },
  30708. /* producedAt */
  30709. /* PA */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0, },
  30710. /* responses */
  30711. /* RESP */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  30712. /* responseExtensions */
  30713. /* RESPEXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 }
  30714. };
  30715. enum {
  30716. OCSPRESPDATAASN_IDX_SEQ = 0,
  30717. OCSPRESPDATAASN_IDX_VER_PRESENT,
  30718. OCSPRESPDATAASN_IDX_VER,
  30719. OCSPRESPDATAASN_IDX_BYNAME,
  30720. OCSPRESPDATAASN_IDX_BYKEY,
  30721. OCSPRESPDATAASN_IDX_PA,
  30722. OCSPRESPDATAASN_IDX_RESP,
  30723. OCSPRESPDATAASN_IDX_RESPEXT,
  30724. };
  30725. /* Number of items in ASN.1 template for OCSP ResponseData. */
  30726. #define ocspRespDataASN_Length (sizeof(ocspRespDataASN) / sizeof(ASNItem))
  30727. #endif
  30728. static int DecodeResponseData(byte* source, word32* ioIndex,
  30729. OcspResponse* resp, word32 size)
  30730. {
  30731. #ifndef WOLFSSL_ASN_TEMPLATE
  30732. word32 idx = *ioIndex, prev_idx, localIdx;
  30733. int length;
  30734. int version;
  30735. int ret;
  30736. byte tag;
  30737. int wrapperSz;
  30738. OcspEntry* single;
  30739. WOLFSSL_ENTER("DecodeResponseData");
  30740. resp->response = source + idx;
  30741. prev_idx = idx;
  30742. if (GetSequence(source, &idx, &length, size) < 0)
  30743. return ASN_PARSE_E;
  30744. resp->responseSz = length + idx - prev_idx;
  30745. /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
  30746. * item isn't an EXPLICIT[0], then set version to zero and move
  30747. * onto the next item.
  30748. */
  30749. localIdx = idx;
  30750. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30751. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
  30752. {
  30753. idx += 2; /* Eat the value and length */
  30754. if (GetMyVersion(source, &idx, &version, size) < 0)
  30755. return ASN_PARSE_E;
  30756. } else
  30757. version = 0;
  30758. localIdx = idx;
  30759. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30760. ( tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1) ||
  30761. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2) ))
  30762. {
  30763. idx++; /* advance past ASN tag */
  30764. if (GetLength(source, &idx, &length, size) < 0)
  30765. return ASN_PARSE_E;
  30766. idx += length;
  30767. }
  30768. else
  30769. return ASN_PARSE_E;
  30770. /* save pointer to the producedAt time */
  30771. if (GetBasicDate(source, &idx, resp->producedDate,
  30772. &resp->producedDateFormat, size) < 0)
  30773. return ASN_PARSE_E;
  30774. /* Outer wrapper of the SEQUENCE OF Single Responses. */
  30775. if (GetSequence(source, &idx, &wrapperSz, size) < 0)
  30776. return ASN_PARSE_E;
  30777. localIdx = idx;
  30778. single = resp->single;
  30779. while (idx - localIdx < (word32)wrapperSz) {
  30780. ret = DecodeSingleResponse(source, &idx, size, wrapperSz, single);
  30781. if (ret < 0)
  30782. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  30783. if (idx - localIdx < (word32)wrapperSz) {
  30784. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  30785. DYNAMIC_TYPE_OCSP_ENTRY);
  30786. if (single->next == NULL) {
  30787. return MEMORY_E;
  30788. }
  30789. XMEMSET(single->next, 0, sizeof(OcspEntry));
  30790. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  30791. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  30792. if (single->next->status == NULL) {
  30793. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  30794. single->next = NULL;
  30795. return MEMORY_E;
  30796. }
  30797. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  30798. single->next->isDynamic = 1;
  30799. single = single->next;
  30800. }
  30801. }
  30802. /*
  30803. * Check the length of the ResponseData against the current index to
  30804. * see if there are extensions, they are optional.
  30805. */
  30806. if (idx - prev_idx < resp->responseSz)
  30807. if (DecodeOcspRespExtensions(source, &idx, resp, size) < 0)
  30808. return ASN_PARSE_E;
  30809. *ioIndex = idx;
  30810. return 0;
  30811. #else
  30812. DECL_ASNGETDATA(dataASN, ocspRespDataASN_Length);
  30813. int ret = 0;
  30814. byte version;
  30815. word32 dateSz, idx = *ioIndex;
  30816. OcspEntry* single;
  30817. WOLFSSL_ENTER("DecodeResponseData");
  30818. CALLOC_ASNGETDATA(dataASN, ocspRespDataASN_Length, ret, resp->heap);
  30819. if (ret == 0) {
  30820. resp->response = source + idx;
  30821. /* Default, not present, is v1 = 0. */
  30822. version = 0;
  30823. /* Max size of date supported. */
  30824. dateSz = MAX_DATE_SIZE;
  30825. /* Set the where to put version an produced date. */
  30826. GetASN_Int8Bit(&dataASN[OCSPRESPDATAASN_IDX_VER], &version);
  30827. GetASN_Buffer(&dataASN[OCSPRESPDATAASN_IDX_PA], resp->producedDate,
  30828. &dateSz);
  30829. /* Decode the ResponseData. */
  30830. ret = GetASN_Items(ocspRespDataASN, dataASN, ocspRespDataASN_Length,
  30831. 1, source, ioIndex, size);
  30832. }
  30833. /* Only support v1 == 0 */
  30834. if ((ret == 0) && (version != 0)) {
  30835. ret = ASN_PARSE_E;
  30836. }
  30837. /* Ensure date is a minimal size. */
  30838. if ((ret == 0) && (dateSz < MIN_DATE_SIZE)) {
  30839. ret = ASN_PARSE_E;
  30840. }
  30841. if (ret == 0) {
  30842. /* TODO: use byName/byKey fields. */
  30843. /* Store size of response. */
  30844. resp->responseSz = *ioIndex - idx;
  30845. /* Store date format/tag. */
  30846. resp->producedDateFormat = dataASN[OCSPRESPDATAASN_IDX_PA].tag;
  30847. /* Get the index of the responses SEQUENCE. */
  30848. idx = GetASNItem_DataIdx(dataASN[OCSPRESPDATAASN_IDX_RESP], source);
  30849. /* Start with the pre-existing OcspEntry. */
  30850. single = resp->single;
  30851. }
  30852. while ((ret == 0) && (idx < dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset)) {
  30853. /* Allocate and use a new OCSP entry if this is used. */
  30854. if (single->used) {
  30855. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  30856. DYNAMIC_TYPE_OCSP_ENTRY);
  30857. if (single->next == NULL) {
  30858. ret = MEMORY_E;
  30859. }
  30860. else {
  30861. XMEMSET(single->next, 0, sizeof(OcspEntry));
  30862. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  30863. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  30864. if (single->next->status == NULL) {
  30865. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  30866. single->next = NULL;
  30867. ret = MEMORY_E;
  30868. }
  30869. else {
  30870. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  30871. /* Entry to be freed. */
  30872. single->next->isDynamic = 1;
  30873. /* used will be 0 (false) */
  30874. single = single->next;
  30875. }
  30876. }
  30877. }
  30878. if (ret == 0) {
  30879. /* Decode SingleResponse into OcspEntry. */
  30880. ret = DecodeSingleResponse(source, &idx,
  30881. dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset,
  30882. dataASN[OCSPRESPDATAASN_IDX_RESP].length, single);
  30883. /* single->used set on successful decode. */
  30884. }
  30885. }
  30886. /* Check if there were extensions. */
  30887. if ((ret == 0) &&
  30888. (dataASN[OCSPRESPDATAASN_IDX_RESPEXT].data.buffer.data != NULL)) {
  30889. /* Get index of [1] */
  30890. idx = dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset;
  30891. /* Decode the response extensions. */
  30892. if (DecodeOcspRespExtensions(source, &idx, resp, *ioIndex) < 0) {
  30893. ret = ASN_PARSE_E;
  30894. }
  30895. }
  30896. FREE_ASNGETDATA(dataASN, resp->heap);
  30897. return ret;
  30898. #endif
  30899. }
  30900. #ifndef WOLFSSL_ASN_TEMPLATE
  30901. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  30902. static int DecodeCerts(byte* source,
  30903. word32* ioIndex, OcspResponse* resp, word32 size)
  30904. {
  30905. word32 idx = *ioIndex;
  30906. byte tag;
  30907. WOLFSSL_ENTER("DecodeCerts");
  30908. if (GetASNTag(source, &idx, &tag, size) < 0)
  30909. return ASN_PARSE_E;
  30910. if (tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
  30911. {
  30912. int length;
  30913. if (GetLength(source, &idx, &length, size) < 0)
  30914. return ASN_PARSE_E;
  30915. if (GetSequence(source, &idx, &length, size) < 0)
  30916. return ASN_PARSE_E;
  30917. resp->cert = source + idx;
  30918. resp->certSz = length;
  30919. idx += length;
  30920. }
  30921. *ioIndex = idx;
  30922. return 0;
  30923. }
  30924. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  30925. #endif /* !WOLFSSL_ASN_TEMPLATE */
  30926. #ifdef WOLFSSL_ASN_TEMPLATE
  30927. /* ASN.1 template for BasicOCSPResponse.
  30928. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30929. */
  30930. static const ASNItem ocspBasicRespASN[] = {
  30931. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30932. /* tbsResponseData */
  30933. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0, },
  30934. /* signatureAlgorithm */
  30935. /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0, },
  30936. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  30937. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  30938. /* parameters */
  30939. #ifdef WC_RSA_PSS
  30940. /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  30941. #endif
  30942. /* signature */
  30943. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  30944. /* certs */
  30945. /* CERTS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  30946. /* CERTS_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0, },
  30947. };
  30948. enum {
  30949. OCSPBASICRESPASN_IDX_SEQ = 0,
  30950. OCSPBASICRESPASN_IDX_TBS_SEQ,
  30951. OCSPBASICRESPASN_IDX_SIGALGO,
  30952. OCSPBASICRESPASN_IDX_SIGALGO_OID,
  30953. OCSPBASICRESPASN_IDX_SIGALGO_NULL,
  30954. #ifdef WC_RSA_PSS
  30955. OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS,
  30956. #endif
  30957. OCSPBASICRESPASN_IDX_SIGNATURE,
  30958. OCSPBASICRESPASN_IDX_CERTS,
  30959. OCSPBASICRESPASN_IDX_CERTS_SEQ,
  30960. };
  30961. /* Number of items in ASN.1 template for BasicOCSPResponse. */
  30962. #define ocspBasicRespASN_Length (sizeof(ocspBasicRespASN) / sizeof(ASNItem))
  30963. #endif /* WOLFSSL_ASN_TEMPLATE */
  30964. static int DecodeBasicOcspResponse(byte* source, word32* ioIndex,
  30965. OcspResponse* resp, word32 size, void* cm, void* heap, int noVerify)
  30966. {
  30967. #ifndef WOLFSSL_ASN_TEMPLATE
  30968. int length;
  30969. word32 idx = *ioIndex;
  30970. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  30971. word32 end_index;
  30972. #endif
  30973. int ret;
  30974. int sigLength;
  30975. const byte* sigParams = NULL;
  30976. word32 sigParamsSz = 0;
  30977. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  30978. (void)heap;
  30979. if (GetSequence(source, &idx, &length, size) < 0)
  30980. return ASN_PARSE_E;
  30981. if (idx + length > size)
  30982. return ASN_INPUT_E;
  30983. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  30984. end_index = idx + length;
  30985. #endif
  30986. if ((ret = DecodeResponseData(source, &idx, resp, size)) < 0)
  30987. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  30988. /* Get the signature algorithm */
  30989. if (GetAlgoId(source, &idx, &resp->sigOID, oidSigType, size) < 0) {
  30990. return ASN_PARSE_E;
  30991. }
  30992. #ifdef WC_RSA_PSS
  30993. else if (resp->sigOID == CTC_RSASSAPSS) {
  30994. word32 sz;
  30995. int len;
  30996. const byte* params;
  30997. sz = idx;
  30998. params = source + idx;
  30999. if (GetSequence(source, &idx, &len, size) < 0)
  31000. ret = ASN_PARSE_E;
  31001. if (ret == 0) {
  31002. idx += len;
  31003. sigParams = params;
  31004. sigParamsSz = idx - sz;
  31005. }
  31006. }
  31007. #endif
  31008. ret = CheckBitString(source, &idx, &sigLength, size, 1, NULL);
  31009. if (ret != 0)
  31010. return ret;
  31011. resp->sigSz = sigLength;
  31012. resp->sig = source + idx;
  31013. idx += sigLength;
  31014. /*
  31015. * Check the length of the BasicOcspResponse against the current index to
  31016. * see if there are certificates, they are optional.
  31017. */
  31018. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31019. if (idx < end_index)
  31020. {
  31021. int cert_inited = 0;
  31022. #ifdef WOLFSSL_SMALL_STACK
  31023. DecodedCert *cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  31024. DYNAMIC_TYPE_TMP_BUFFER);
  31025. if (cert == NULL)
  31026. return MEMORY_E;
  31027. #else
  31028. DecodedCert cert[1];
  31029. #endif
  31030. do {
  31031. if (DecodeCerts(source, &idx, resp, size) < 0) {
  31032. ret = ASN_PARSE_E;
  31033. break;
  31034. }
  31035. InitDecodedCert(cert, resp->cert, resp->certSz, heap);
  31036. cert_inited = 1;
  31037. /* Don't verify if we don't have access to Cert Manager. */
  31038. ret = ParseCertRelative(cert, CERT_TYPE,
  31039. noVerify ? NO_VERIFY : VERIFY_OCSP_CERT,
  31040. cm);
  31041. if (ret < 0) {
  31042. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  31043. break;
  31044. }
  31045. #ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK
  31046. if ((cert->extExtKeyUsage & EXTKEYUSE_OCSP_SIGN) == 0) {
  31047. if (XMEMCMP(cert->subjectHash,
  31048. resp->single->issuerHash, OCSP_DIGEST_SIZE) == 0) {
  31049. WOLFSSL_MSG("\tOCSP Response signed by issuer");
  31050. }
  31051. else {
  31052. WOLFSSL_MSG("\tOCSP Responder key usage check failed");
  31053. #ifdef OPENSSL_EXTRA
  31054. resp->verifyError = OCSP_BAD_ISSUER;
  31055. #else
  31056. ret = BAD_OCSP_RESPONDER;
  31057. break;
  31058. #endif
  31059. }
  31060. }
  31061. #endif
  31062. /* ConfirmSignature is blocking here */
  31063. ret = ConfirmSignature(
  31064. &cert->sigCtx,
  31065. resp->response, resp->responseSz,
  31066. cert->publicKey, cert->pubKeySize, cert->keyOID,
  31067. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31068. NULL);
  31069. if (ret != 0) {
  31070. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31071. ret = ASN_OCSP_CONFIRM_E;
  31072. break;
  31073. }
  31074. } while(0);
  31075. if (cert_inited)
  31076. FreeDecodedCert(cert);
  31077. #ifdef WOLFSSL_SMALL_STACK
  31078. XFREE(cert, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31079. #endif
  31080. if (ret != 0)
  31081. return ret;
  31082. }
  31083. else
  31084. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  31085. {
  31086. Signer* ca;
  31087. int sigValid = -1;
  31088. #ifndef NO_SKID
  31089. ca = GetCA(cm, resp->single->issuerKeyHash);
  31090. #else
  31091. ca = GetCA(cm, resp->single->issuerHash);
  31092. #endif
  31093. if (ca) {
  31094. SignatureCtx sigCtx;
  31095. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  31096. /* ConfirmSignature is blocking here */
  31097. sigValid = ConfirmSignature(&sigCtx, resp->response,
  31098. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  31099. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31100. NULL);
  31101. }
  31102. if (ca == NULL || sigValid != 0) {
  31103. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31104. return ASN_OCSP_CONFIRM_E;
  31105. }
  31106. (void)noVerify;
  31107. }
  31108. *ioIndex = idx;
  31109. return 0;
  31110. #else
  31111. DECL_ASNGETDATA(dataASN, ocspBasicRespASN_Length);
  31112. int ret = 0;
  31113. word32 idx = *ioIndex;
  31114. const byte* sigParams = NULL;
  31115. word32 sigParamsSz = 0;
  31116. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31117. #ifdef WOLFSSL_SMALL_STACK
  31118. DecodedCert* cert = NULL;
  31119. #else
  31120. DecodedCert cert[1];
  31121. #endif
  31122. int certInit = 0;
  31123. #endif
  31124. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  31125. (void)heap;
  31126. CALLOC_ASNGETDATA(dataASN, ocspBasicRespASN_Length, ret, heap);
  31127. if (ret == 0) {
  31128. /* Set expecting signature OID. */
  31129. GetASN_OID(&dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID], oidSigType);
  31130. /* Decode BasicOCSPResponse. */
  31131. ret = GetASN_Items(ocspBasicRespASN, dataASN, ocspBasicRespASN_Length,
  31132. 1, source, &idx, size);
  31133. }
  31134. if (ret == 0) {
  31135. word32 dataIdx = 0;
  31136. /* Decode the response data. */
  31137. if (DecodeResponseData(
  31138. GetASNItem_Addr(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source),
  31139. &dataIdx, resp,
  31140. GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source)
  31141. ) < 0) {
  31142. ret = ASN_PARSE_E;
  31143. }
  31144. }
  31145. #ifdef WC_RSA_PSS
  31146. if (ret == 0 && (dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS].tag != 0)) {
  31147. sigParams = GetASNItem_Addr(
  31148. dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
  31149. source);
  31150. sigParamsSz =
  31151. GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
  31152. source);
  31153. }
  31154. #endif
  31155. if (ret == 0) {
  31156. /* Get the signature OID and signature. */
  31157. resp->sigOID = dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID].data.oid.sum;
  31158. GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_SIGNATURE], &resp->sig,
  31159. &resp->sigSz);
  31160. }
  31161. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31162. if ((ret == 0) &&
  31163. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31164. /* TODO: support more than one certificate. */
  31165. /* Store reference to certificate BER data. */
  31166. GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ], &resp->cert,
  31167. &resp->certSz);
  31168. /* Allocate a certificate object to decode cert into. */
  31169. #ifdef WOLFSSL_SMALL_STACK
  31170. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), heap,
  31171. DYNAMIC_TYPE_TMP_BUFFER);
  31172. if (cert == NULL) {
  31173. ret = MEMORY_E;
  31174. }
  31175. }
  31176. if ((ret == 0) &&
  31177. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31178. #endif
  31179. /* Initialize the crtificate object. */
  31180. InitDecodedCert(cert, resp->cert, resp->certSz, heap);
  31181. certInit = 1;
  31182. /* Parse the certificate and don't verify if we don't have access to
  31183. * Cert Manager. */
  31184. ret = ParseCertRelative(cert, CERT_TYPE, noVerify ? NO_VERIFY : VERIFY,
  31185. cm);
  31186. if (ret < 0) {
  31187. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  31188. }
  31189. }
  31190. if ((ret == 0) &&
  31191. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31192. /* TODO: ConfirmSignature is blocking here */
  31193. /* Check the signature of the response. */
  31194. ret = ConfirmSignature(&cert->sigCtx, resp->response, resp->responseSz,
  31195. cert->publicKey, cert->pubKeySize, cert->keyOID, resp->sig,
  31196. resp->sigSz, resp->sigOID, NULL, 0, NULL);
  31197. if (ret != 0) {
  31198. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31199. ret = ASN_OCSP_CONFIRM_E;
  31200. }
  31201. }
  31202. if ((ret == 0) &&
  31203. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data == NULL))
  31204. #else
  31205. if (ret == 0)
  31206. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  31207. {
  31208. Signer* ca;
  31209. int sigValid = -1;
  31210. /* Resonse didn't have a certificate - lookup CA. */
  31211. #ifndef NO_SKID
  31212. ca = GetCA(cm, resp->single->issuerKeyHash);
  31213. #else
  31214. ca = GetCA(cm, resp->single->issuerHash);
  31215. #endif
  31216. if (ca) {
  31217. SignatureCtx sigCtx;
  31218. /* Initialize he signature context. */
  31219. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  31220. /* TODO: ConfirmSignature is blocking here */
  31221. /* Check the signature of the response CA public key. */
  31222. sigValid = ConfirmSignature(&sigCtx, resp->response,
  31223. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  31224. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31225. NULL);
  31226. }
  31227. if ((ca == NULL) || (sigValid != 0)) {
  31228. /* Didn't find certificate or signature verificate failed. */
  31229. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31230. ret = ASN_OCSP_CONFIRM_E;
  31231. }
  31232. }
  31233. if (ret == 0) {
  31234. /* Update the position to after response data. */
  31235. *ioIndex = idx;
  31236. }
  31237. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31238. if (certInit) {
  31239. FreeDecodedCert(cert);
  31240. }
  31241. #ifdef WOLFSSL_SMALL_STACK
  31242. if (cert != NULL) {
  31243. /* Dispose of certificate object. */
  31244. XFREE(cert, heap, DYNAMIC_TYPE_TMP_BUFFER);
  31245. }
  31246. #endif
  31247. #endif
  31248. FREE_ASNGETDATA(dataASN, heap);
  31249. return ret;
  31250. #endif /* WOLFSSL_ASN_TEMPLATE */
  31251. }
  31252. void InitOcspResponse(OcspResponse* resp, OcspEntry* single, CertStatus* status,
  31253. byte* source, word32 inSz, void* heap)
  31254. {
  31255. WOLFSSL_ENTER("InitOcspResponse");
  31256. XMEMSET(status, 0, sizeof(CertStatus));
  31257. XMEMSET(single, 0, sizeof(OcspEntry));
  31258. XMEMSET(resp, 0, sizeof(OcspResponse));
  31259. single->status = status;
  31260. resp->responseStatus = -1;
  31261. resp->single = single;
  31262. resp->source = source;
  31263. resp->maxIdx = inSz;
  31264. resp->heap = heap;
  31265. }
  31266. void FreeOcspResponse(OcspResponse* resp)
  31267. {
  31268. OcspEntry *single, *next;
  31269. if (resp != NULL) {
  31270. for (single = resp->single; single; single = next) {
  31271. next = single->next;
  31272. if (single->isDynamic) {
  31273. XFREE(single->status, resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  31274. XFREE(single, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  31275. }
  31276. }
  31277. }
  31278. }
  31279. #ifdef WOLFSSL_ASN_TEMPLATE
  31280. /* ASN.1 template for OCSPResponse.
  31281. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  31282. */
  31283. static const ASNItem ocspResponseASN[] = {
  31284. /* OCSPResponse ::= SEQUENCE */
  31285. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31286. /* responseStatus OCSPResponseStatus */
  31287. /* STATUS */ { 1, ASN_ENUMERATED, 0, 0, 0, },
  31288. /* responseBytes [0] EXPLICIT ResponseBytes OPTIONAL */
  31289. /* BYTES */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  31290. /* ResponseBytes ::= SEQUENCE */
  31291. /* BYTES_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  31292. /* responseType OBJECT IDENTIFIER */
  31293. /* BYTES_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  31294. /* response OCTET STRING */
  31295. /* BYTES_VAL */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  31296. };
  31297. enum {
  31298. OCSPRESPONSEASN_IDX_SEQ = 0,
  31299. OCSPRESPONSEASN_IDX_STATUS,
  31300. OCSPRESPONSEASN_IDX_BYTES,
  31301. OCSPRESPONSEASN_IDX_BYTES_SEQ,
  31302. OCSPRESPONSEASN_IDX_BYTES_TYPE,
  31303. OCSPRESPONSEASN_IDX_BYTES_VAL,
  31304. };
  31305. /* Number of items in ASN.1 template for OCSPResponse. */
  31306. #define ocspResponseASN_Length (sizeof(ocspResponseASN) / sizeof(ASNItem))
  31307. #endif /* WOLFSSL_ASN_TEMPLATE */
  31308. int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, int noVerify)
  31309. {
  31310. #ifndef WOLFSSL_ASN_TEMPLATE
  31311. int ret;
  31312. int length = 0;
  31313. word32 idx = 0;
  31314. byte* source = resp->source;
  31315. word32 size = resp->maxIdx;
  31316. word32 oid;
  31317. byte tag;
  31318. WOLFSSL_ENTER("OcspResponseDecode");
  31319. /* peel the outer SEQUENCE wrapper */
  31320. if (GetSequence(source, &idx, &length, size) < 0) {
  31321. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31322. return ASN_PARSE_E;
  31323. }
  31324. /* First get the responseStatus, an ENUMERATED */
  31325. if (GetEnumerated(source, &idx, &resp->responseStatus, size) < 0) {
  31326. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31327. return ASN_PARSE_E;
  31328. }
  31329. if (resp->responseStatus != OCSP_SUCCESSFUL) {
  31330. WOLFSSL_LEAVE("OcspResponseDecode", 0);
  31331. return 0;
  31332. }
  31333. /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
  31334. if (idx >= size) {
  31335. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31336. return ASN_PARSE_E;
  31337. }
  31338. if (GetASNTag(source, &idx, &tag, size) < 0) {
  31339. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31340. return ASN_PARSE_E;
  31341. }
  31342. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC)) {
  31343. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31344. return ASN_PARSE_E;
  31345. }
  31346. if (GetLength(source, &idx, &length, size) < 0) {
  31347. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31348. return ASN_PARSE_E;
  31349. }
  31350. /* Get the responseBytes SEQUENCE */
  31351. if (GetSequence(source, &idx, &length, size) < 0) {
  31352. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31353. return ASN_PARSE_E;
  31354. }
  31355. /* Check ObjectID for the resposeBytes */
  31356. if (GetObjectId(source, &idx, &oid, oidOcspType, size) < 0) {
  31357. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31358. return ASN_PARSE_E;
  31359. }
  31360. if (oid != OCSP_BASIC_OID) {
  31361. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31362. return ASN_PARSE_E;
  31363. }
  31364. ret = GetOctetString(source, &idx, &length, size);
  31365. if (ret < 0) {
  31366. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31367. return ret;
  31368. }
  31369. ret = DecodeBasicOcspResponse(source, &idx, resp, size, cm, heap, noVerify);
  31370. if (ret < 0) {
  31371. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31372. return ret;
  31373. }
  31374. WOLFSSL_LEAVE("OcspResponseDecode", 0);
  31375. return 0;
  31376. #else
  31377. DECL_ASNGETDATA(dataASN, ocspResponseASN_Length);
  31378. int ret = 0;
  31379. word32 idx = 0, size = resp->maxIdx;
  31380. byte* source = resp->source;
  31381. byte status;
  31382. byte* basic;
  31383. word32 basicSz;
  31384. WOLFSSL_ENTER("OcspResponseDecode");
  31385. CALLOC_ASNGETDATA(dataASN, ocspResponseASN_Length, ret, resp->heap);
  31386. if (ret == 0) {
  31387. /* Set variable to put status in and expect OCSP OID. */
  31388. GetASN_Int8Bit(&dataASN[OCSPRESPONSEASN_IDX_STATUS], &status);
  31389. GetASN_OID(&dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE], oidOcspType);
  31390. /* Decode OCSPResponse (and ResponseBytes). */
  31391. ret = GetASN_Items(ocspResponseASN, dataASN, ocspResponseASN_Length, 1,
  31392. source, &idx, size);
  31393. }
  31394. if (ret == 0) {
  31395. /* Get response. */
  31396. resp->responseStatus = status;
  31397. if (dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE].data.oid.sum
  31398. == OCSP_BASIC_OID) {
  31399. /* Get reference to BasicOCSPResponse. */
  31400. GetASN_GetRef(&dataASN[OCSPRESPONSEASN_IDX_BYTES_VAL], &basic,
  31401. &basicSz);
  31402. idx = 0;
  31403. /* Decode BasicOCSPResponse. */
  31404. ret = DecodeBasicOcspResponse(basic, &idx, resp, basicSz, cm, heap,
  31405. noVerify);
  31406. }
  31407. /* Only support BasicOCSPResponse. */
  31408. else {
  31409. ret = ASN_PARSE_E;
  31410. }
  31411. }
  31412. FREE_ASNGETDATA(dataASN, resp->heap);
  31413. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31414. return ret;
  31415. #endif /* WOLFSSL_ASN_TEMPLATE */
  31416. }
  31417. #ifdef WOLFSSL_ASN_TEMPLATE
  31418. /* ASN.1 template for OCSP nonce extension.
  31419. * RFC 6960, 4.4.1 - Nonce
  31420. * X.509: RFC 5280, 4.1 - Basic Certificate Fields. (Extension)
  31421. */
  31422. static const ASNItem ocspNonceExtASN[] = {
  31423. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31424. /* Extension */
  31425. /* EXT */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  31426. /* extnId */
  31427. /* EXT_OID */ {2, ASN_OBJECT_ID, 0, 0, 0 },
  31428. /* critcal not encoded. */
  31429. /* extnValue */
  31430. /* EXT_VAL */ {2, ASN_OCTET_STRING, 0, 1, 0 },
  31431. /* nonce */
  31432. /* EXT_NONCE */ {3, ASN_OCTET_STRING, 0, 0, 0 },
  31433. };
  31434. enum {
  31435. OCSPNONCEEXTASN_IDX_SEQ = 0,
  31436. OCSPNONCEEXTASN_IDX_EXT,
  31437. OCSPNONCEEXTASN_IDX_EXT_OID,
  31438. OCSPNONCEEXTASN_IDX_EXT_VAL,
  31439. OCSPNONCEEXTASN_IDX_EXT_NONCE,
  31440. };
  31441. /* Number of items in ASN.1 template for OCSP nonce extension. */
  31442. #define ocspNonceExtASN_Length (sizeof(ocspNonceExtASN) / sizeof(ASNItem))
  31443. #endif /* WOLFSSL_ASN_TEMPLATE */
  31444. word32 EncodeOcspRequestExtensions(OcspRequest* req, byte* output, word32 size)
  31445. {
  31446. const byte NonceObjId[] = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07,
  31447. 0x30, 0x01, 0x02 };
  31448. #ifndef WOLFSSL_ASN_TEMPLATE
  31449. byte seqArray[5][MAX_SEQ_SZ];
  31450. word32 seqSz[5], totalSz = (word32)sizeof(NonceObjId);
  31451. WOLFSSL_ENTER("SetOcspReqExtensions");
  31452. if (!req || !output || !req->nonceSz)
  31453. return 0;
  31454. totalSz += req->nonceSz;
  31455. totalSz += seqSz[0] = SetOctetString(req->nonceSz, seqArray[0]);
  31456. totalSz += seqSz[1] = SetOctetString(req->nonceSz + seqSz[0], seqArray[1]);
  31457. totalSz += seqSz[2] = SetObjectId(sizeof(NonceObjId), seqArray[2]);
  31458. totalSz += seqSz[3] = SetSequence(totalSz, seqArray[3]);
  31459. totalSz += seqSz[4] = SetSequence(totalSz, seqArray[4]);
  31460. if (totalSz > size)
  31461. return 0;
  31462. totalSz = 0;
  31463. XMEMCPY(output + totalSz, seqArray[4], seqSz[4]);
  31464. totalSz += seqSz[4];
  31465. XMEMCPY(output + totalSz, seqArray[3], seqSz[3]);
  31466. totalSz += seqSz[3];
  31467. XMEMCPY(output + totalSz, seqArray[2], seqSz[2]);
  31468. totalSz += seqSz[2];
  31469. XMEMCPY(output + totalSz, NonceObjId, sizeof(NonceObjId));
  31470. totalSz += (word32)sizeof(NonceObjId);
  31471. XMEMCPY(output + totalSz, seqArray[1], seqSz[1]);
  31472. totalSz += seqSz[1];
  31473. XMEMCPY(output + totalSz, seqArray[0], seqSz[0]);
  31474. totalSz += seqSz[0];
  31475. XMEMCPY(output + totalSz, req->nonce, req->nonceSz);
  31476. totalSz += req->nonceSz;
  31477. return totalSz;
  31478. #else
  31479. int ret = 0;
  31480. WOLFSSL_ENTER("SetOcspReqExtensions");
  31481. /* Check request has nonce to write in extension. */
  31482. if (req != NULL && req->nonceSz != 0) {
  31483. DECL_ASNSETDATA(dataASN, ocspNonceExtASN_Length);
  31484. int sz;
  31485. CALLOC_ASNSETDATA(dataASN, ocspNonceExtASN_Length, ret, req->heap);
  31486. /* Set nonce extension OID and nonce. */
  31487. SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_OID], NonceObjId,
  31488. sizeof(NonceObjId));
  31489. SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_NONCE], req->nonce,
  31490. req->nonceSz);
  31491. /* Calculate size of nonce extension. */
  31492. ret = SizeASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
  31493. &sz);
  31494. /* Check buffer big enough for encoding if supplied. */
  31495. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  31496. ret = BUFFER_E;
  31497. }
  31498. if ((ret == 0) && (output != NULL)) {
  31499. /* Encode nonce extension. */
  31500. SetASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
  31501. output);
  31502. }
  31503. if (ret == 0) {
  31504. /* Return size of encoding. */
  31505. ret = sz;
  31506. }
  31507. FREE_ASNSETDATA(dataASN, req->heap);
  31508. }
  31509. return ret;
  31510. #endif /* WOLFSSL_ASN_TEMPLATE */
  31511. }
  31512. #ifdef WOLFSSL_ASN_TEMPLATE
  31513. /* ASN.1 template for OCSPRequest.
  31514. * RFC 6960, 4.1.1 - ASN.1 Specification of the OCSP Request
  31515. */
  31516. static const ASNItem ocspRequestASN[] = {
  31517. /* OCSPRequest */
  31518. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31519. /* tbsRequest */
  31520. /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  31521. /* version not written - v1 */
  31522. /* requestorName not written */
  31523. /* requestList */
  31524. /* TBS_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  31525. /* Request */
  31526. /* TBS_LIST */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  31527. /* reqCert */
  31528. /* TBS_REQ_CID */ { 4, ASN_SEQUENCE, 1, 1, 0 },
  31529. /* hashAlgorithm */
  31530. /* TBS_REQ_HASH */ { 5, ASN_SEQUENCE, 1, 1, 0 },
  31531. /* TBS_REQ_HASH_OID */ { 6, ASN_OBJECT_ID, 0, 0, 0 },
  31532. /* issuerNameHash */
  31533. /* TBS_REQ_ISSUER */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  31534. /* issuerKeyHash */
  31535. /* TBS_REQ_ISSUERKEY */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  31536. /* serialNumber */
  31537. /* TBS_REQ_SERIAL */ { 5, ASN_INTEGER, 0, 0, 0 },
  31538. /* requestExtensions */
  31539. /* TBS_REQEXT */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 0 },
  31540. /* optionalSignature not written. */
  31541. };
  31542. enum {
  31543. OCSPREQUESTASN_IDX_SEQ = 0,
  31544. OCSPREQUESTASN_IDX_TBS,
  31545. OCSPREQUESTASN_IDX_TBS_SEQ,
  31546. OCSPREQUESTASN_IDX_TBS_LIST,
  31547. OCSPREQUESTASN_IDX_TBS_REQ_CID,
  31548. OCSPREQUESTASN_IDX_TBS_REQ_HASH,
  31549. OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID,
  31550. OCSPREQUESTASN_IDX_TBS_REQ_ISSUER,
  31551. OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY,
  31552. OCSPREQUESTASN_IDX_TBS_REQ_SERIAL,
  31553. OCSPREQUESTASN_IDX_TBS_REQEXT,
  31554. };
  31555. /* Number of items in ASN.1 template for OCSPRequest. */
  31556. #define ocspRequestASN_Length (sizeof(ocspRequestASN) / sizeof(ASNItem))
  31557. #endif
  31558. int EncodeOcspRequest(OcspRequest* req, byte* output, word32 size)
  31559. {
  31560. #ifndef WOLFSSL_ASN_TEMPLATE
  31561. byte seqArray[5][MAX_SEQ_SZ];
  31562. /* The ASN.1 of the OCSP Request is an onion of sequences */
  31563. byte algoArray[MAX_ALGO_SZ];
  31564. byte issuerArray[MAX_ENCODED_DIG_SZ];
  31565. byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
  31566. byte snArray[MAX_SN_SZ];
  31567. byte extArray[MAX_OCSP_EXT_SZ];
  31568. word32 seqSz[5], algoSz, issuerSz, issuerKeySz, extSz, totalSz;
  31569. int i, snSz;
  31570. WOLFSSL_ENTER("EncodeOcspRequest");
  31571. #ifdef NO_SHA
  31572. algoSz = SetAlgoID(SHA256h, algoArray, oidHashType, 0);
  31573. #else
  31574. algoSz = SetAlgoID(SHAh, algoArray, oidHashType, 0);
  31575. #endif
  31576. issuerSz = SetDigest(req->issuerHash, KEYID_SIZE, issuerArray);
  31577. issuerKeySz = SetDigest(req->issuerKeyHash, KEYID_SIZE, issuerKeyArray);
  31578. snSz = SetSerialNumber(req->serial, req->serialSz, snArray,
  31579. MAX_SN_SZ, MAX_SN_SZ);
  31580. extSz = 0;
  31581. if (snSz < 0)
  31582. return snSz;
  31583. if (req->nonceSz) {
  31584. /* TLS Extensions use this function too - put extensions after
  31585. * ASN.1: Context Specific [2].
  31586. */
  31587. extSz = EncodeOcspRequestExtensions(req, extArray + 2,
  31588. OCSP_NONCE_EXT_SZ);
  31589. extSz += SetExplicit(2, extSz, extArray);
  31590. }
  31591. totalSz = algoSz + issuerSz + issuerKeySz + snSz;
  31592. for (i = 4; i >= 0; i--) {
  31593. seqSz[i] = SetSequence(totalSz, seqArray[i]);
  31594. totalSz += seqSz[i];
  31595. if (i == 2) totalSz += extSz;
  31596. }
  31597. if (output == NULL)
  31598. return totalSz;
  31599. if (totalSz > size)
  31600. return BUFFER_E;
  31601. totalSz = 0;
  31602. for (i = 0; i < 5; i++) {
  31603. XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
  31604. totalSz += seqSz[i];
  31605. }
  31606. XMEMCPY(output + totalSz, algoArray, algoSz);
  31607. totalSz += algoSz;
  31608. XMEMCPY(output + totalSz, issuerArray, issuerSz);
  31609. totalSz += issuerSz;
  31610. XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
  31611. totalSz += issuerKeySz;
  31612. XMEMCPY(output + totalSz, snArray, snSz);
  31613. totalSz += snSz;
  31614. if (extSz != 0) {
  31615. XMEMCPY(output + totalSz, extArray, extSz);
  31616. totalSz += extSz;
  31617. }
  31618. return totalSz;
  31619. #else
  31620. DECL_ASNSETDATA(dataASN, ocspRequestASN_Length);
  31621. word32 extSz = 0;
  31622. int sz = 0;
  31623. int ret = 0;
  31624. WOLFSSL_ENTER("EncodeOcspRequest");
  31625. CALLOC_ASNSETDATA(dataASN, ocspRequestASN_Length, ret, req->heap);
  31626. if (ret == 0) {
  31627. /* Set OID of hash algorithm use on issuer and key. */
  31628. #ifdef NO_SHA
  31629. SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHA256h,
  31630. oidHashType);
  31631. #else
  31632. SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHAh,
  31633. oidHashType);
  31634. #endif
  31635. /* Set issuer, issuer key hash and serial number of certificate being
  31636. * checked. */
  31637. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUER],
  31638. req->issuerHash, KEYID_SIZE);
  31639. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY],
  31640. req->issuerKeyHash, KEYID_SIZE);
  31641. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_SERIAL],
  31642. req->serial, req->serialSz);
  31643. /* Only extension to write is nonce - check if one to encode. */
  31644. if (req->nonceSz) {
  31645. /* Get size of extensions and leave space for them in encoding. */
  31646. ret = extSz = EncodeOcspRequestExtensions(req, NULL, 0);
  31647. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT], NULL, extSz);
  31648. if (ret > 0) {
  31649. ret = 0;
  31650. }
  31651. }
  31652. else {
  31653. /* Don't write out extensions. */
  31654. dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].noOut = 1;
  31655. }
  31656. }
  31657. if (ret == 0) {
  31658. /* Calculate size of encoding. */
  31659. ret = SizeASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length,
  31660. &sz);
  31661. }
  31662. /* Check buffer big enough for encoding if supplied. */
  31663. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  31664. ret = BUFFER_E;
  31665. }
  31666. if ((ret == 0) && (output != NULL)) {
  31667. /* Encode OCSPRequest. */
  31668. SetASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length, output);
  31669. if (req->nonceSz) {
  31670. /* Encode extensions into space provided. */
  31671. ret = EncodeOcspRequestExtensions(req,
  31672. (byte*)dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].data.buffer.data,
  31673. extSz);
  31674. if (ret > 0) {
  31675. ret = 0;
  31676. }
  31677. }
  31678. }
  31679. if (ret == 0) {
  31680. /* Return size of encoding. */
  31681. ret = sz;
  31682. }
  31683. FREE_ASNSETDATA(dataASN, req->heap);
  31684. return ret;
  31685. #endif /* WOLFSSL_ASN_TEMPLATE */
  31686. }
  31687. int InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce,
  31688. void* heap)
  31689. {
  31690. int ret;
  31691. WOLFSSL_ENTER("InitOcspRequest");
  31692. if (req == NULL)
  31693. return BAD_FUNC_ARG;
  31694. XMEMSET(req, 0, sizeof(OcspRequest));
  31695. req->heap = heap;
  31696. if (cert) {
  31697. XMEMCPY(req->issuerHash, cert->issuerHash, KEYID_SIZE);
  31698. XMEMCPY(req->issuerKeyHash, cert->issuerKeyHash, KEYID_SIZE);
  31699. req->serial = (byte*)XMALLOC(cert->serialSz, req->heap,
  31700. DYNAMIC_TYPE_OCSP_REQUEST);
  31701. if (req->serial == NULL)
  31702. return MEMORY_E;
  31703. XMEMCPY(req->serial, cert->serial, cert->serialSz);
  31704. req->serialSz = cert->serialSz;
  31705. if (cert->extAuthInfoSz != 0 && cert->extAuthInfo != NULL) {
  31706. req->url = (byte*)XMALLOC(cert->extAuthInfoSz + 1, req->heap,
  31707. DYNAMIC_TYPE_OCSP_REQUEST);
  31708. if (req->url == NULL) {
  31709. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP);
  31710. return MEMORY_E;
  31711. }
  31712. XMEMCPY(req->url, cert->extAuthInfo, cert->extAuthInfoSz);
  31713. req->urlSz = cert->extAuthInfoSz;
  31714. req->url[req->urlSz] = 0;
  31715. }
  31716. }
  31717. if (useNonce) {
  31718. WC_RNG rng;
  31719. #ifndef HAVE_FIPS
  31720. ret = wc_InitRng_ex(&rng, req->heap, INVALID_DEVID);
  31721. #else
  31722. ret = wc_InitRng(&rng);
  31723. #endif
  31724. if (ret != 0) {
  31725. WOLFSSL_MSG("\tCannot initialize RNG. Skipping the OCSP Nonce.");
  31726. } else {
  31727. if (wc_RNG_GenerateBlock(&rng, req->nonce, MAX_OCSP_NONCE_SZ) != 0)
  31728. WOLFSSL_MSG("\tCannot run RNG. Skipping the OCSP Nonce.");
  31729. else
  31730. req->nonceSz = MAX_OCSP_NONCE_SZ;
  31731. wc_FreeRng(&rng);
  31732. }
  31733. }
  31734. return 0;
  31735. }
  31736. void FreeOcspRequest(OcspRequest* req)
  31737. {
  31738. WOLFSSL_ENTER("FreeOcspRequest");
  31739. if (req) {
  31740. if (req->serial)
  31741. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  31742. req->serial = NULL;
  31743. #ifdef OPENSSL_EXTRA
  31744. if (req->serialInt) {
  31745. if (req->serialInt->isDynamic) {
  31746. XFREE(req->serialInt->data, NULL, DYNAMIC_TYPE_OPENSSL);
  31747. }
  31748. XFREE(req->serialInt, NULL, DYNAMIC_TYPE_OPENSSL);
  31749. }
  31750. req->serialInt = NULL;
  31751. #endif
  31752. if (req->url)
  31753. XFREE(req->url, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  31754. req->url = NULL;
  31755. }
  31756. }
  31757. int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
  31758. {
  31759. int cmp = -1; /* default as not matching, cmp gets set on each check */
  31760. OcspEntry *single, *next, *prev = NULL, *top;
  31761. WOLFSSL_ENTER("CompareOcspReqResp");
  31762. if (req == NULL) {
  31763. WOLFSSL_MSG("\tReq missing");
  31764. return -1;
  31765. }
  31766. if (resp == NULL || resp->single == NULL) {
  31767. WOLFSSL_MSG("\tResp missing");
  31768. return 1;
  31769. }
  31770. /* Nonces are not critical. The responder may not necessarily add
  31771. * the nonce to the response. */
  31772. if (req->nonceSz && resp->nonce != NULL
  31773. #ifndef WOLFSSL_FORCE_OCSP_NONCE_CHECK
  31774. && resp->nonceSz != 0
  31775. #endif
  31776. ) {
  31777. cmp = req->nonceSz - resp->nonceSz;
  31778. if (cmp != 0) {
  31779. WOLFSSL_MSG("\tnonceSz mismatch");
  31780. return cmp;
  31781. }
  31782. cmp = XMEMCMP(req->nonce, resp->nonce, req->nonceSz);
  31783. if (cmp != 0) {
  31784. WOLFSSL_MSG("\tnonce mismatch");
  31785. return cmp;
  31786. }
  31787. }
  31788. /* match based on found status and return */
  31789. for (single = resp->single; single; single = next) {
  31790. cmp = req->serialSz - single->status->serialSz;
  31791. if (cmp == 0) {
  31792. cmp = XMEMCMP(req->serial, single->status->serial, req->serialSz)
  31793. || XMEMCMP(req->issuerHash, single->issuerHash, OCSP_DIGEST_SIZE)
  31794. || XMEMCMP(req->issuerKeyHash, single->issuerKeyHash, OCSP_DIGEST_SIZE);
  31795. if (cmp == 0) {
  31796. /* match found */
  31797. if (resp->single != single && prev) {
  31798. /* move to top of list */
  31799. top = resp->single;
  31800. resp->single = single;
  31801. prev->next = single->next;
  31802. single->next = top;
  31803. }
  31804. break;
  31805. }
  31806. }
  31807. next = single->next;
  31808. prev = single;
  31809. }
  31810. if (cmp != 0) {
  31811. WOLFSSL_MSG("\trequest and response mismatch");
  31812. return cmp;
  31813. }
  31814. return 0;
  31815. }
  31816. #endif /* HAVE_OCSP */
  31817. #ifdef WOLFSSL_ASN_TEMPLATE
  31818. /* ASN.1 template for certificate name hash. */
  31819. static const ASNItem nameHashASN[] = {
  31820. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  31821. /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  31822. };
  31823. enum {
  31824. NAMEHASHASN_IDX_OID = 0,
  31825. NAMEHASHASN_IDX_NAME,
  31826. };
  31827. /* Number of items in ASN.1 template for certificate name hash. */
  31828. #define nameHashASN_Length (sizeof(nameHashASN) / sizeof(ASNItem))
  31829. #endif /* WOLFSSL_ASN_TEMPLATE */
  31830. /* store WC_SHA hash of NAME */
  31831. int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx)
  31832. {
  31833. #ifndef WOLFSSL_ASN_TEMPLATE
  31834. int length; /* length of all distinguished names */
  31835. int ret;
  31836. word32 dummy;
  31837. byte tag;
  31838. WOLFSSL_ENTER("GetNameHash");
  31839. dummy = *idx;
  31840. if (GetASNTag(source, &dummy, &tag, maxIdx) == 0 && tag == ASN_OBJECT_ID) {
  31841. WOLFSSL_MSG("Trying optional prefix...");
  31842. if (GetLength(source, idx, &length, maxIdx) < 0)
  31843. return ASN_PARSE_E;
  31844. *idx += length;
  31845. WOLFSSL_MSG("Got optional prefix");
  31846. }
  31847. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  31848. * calculated over the entire DER encoding of the Name field, including
  31849. * the tag and length. */
  31850. dummy = *idx;
  31851. if (GetSequence(source, idx, &length, maxIdx) < 0)
  31852. return ASN_PARSE_E;
  31853. ret = CalcHashId(source + dummy, length + *idx - dummy, hash);
  31854. *idx += length;
  31855. return ret;
  31856. #else
  31857. ASNGetData dataASN[nameHashASN_Length];
  31858. int ret;
  31859. XMEMSET(dataASN, 0, sizeof(dataASN));
  31860. /* Ignore the OID even when present. */
  31861. GetASN_OID(&dataASN[NAMEHASHASN_IDX_OID], oidIgnoreType);
  31862. /* Decode certificate name. */
  31863. ret = GetASN_Items(nameHashASN, dataASN, nameHashASN_Length, 0, source, idx,
  31864. maxIdx);
  31865. if (ret == 0) {
  31866. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  31867. * calculated over the entire DER encoding of the Name field, including
  31868. * the tag and length. */
  31869. /* Calculate hash of complete name including SEQUENCE. */
  31870. ret = CalcHashId(
  31871. GetASNItem_Addr(dataASN[NAMEHASHASN_IDX_NAME], source),
  31872. GetASNItem_Length(dataASN[NAMEHASHASN_IDX_NAME], source),
  31873. hash);
  31874. }
  31875. return ret;
  31876. #endif /* WOLFSSL_ASN_TEMPLATE */
  31877. }
  31878. #if defined(HAVE_CRL) && !defined(WOLFCRYPT_ONLY)
  31879. #ifdef OPENSSL_EXTRA
  31880. static char* GetNameFromDer(const byte* source, int sz)
  31881. {
  31882. char* out;
  31883. out = (char*)XMALLOC(sz, NULL, DYNAMIC_TYPE_OPENSSL);
  31884. if (out == NULL) {
  31885. WOLFSSL_MSG("Name malloc failed");
  31886. return NULL;
  31887. }
  31888. XMEMCPY(out, source, sz);
  31889. return out;
  31890. }
  31891. #endif
  31892. /* initialize decoded CRL */
  31893. void InitDecodedCRL(DecodedCRL* dcrl, void* heap)
  31894. {
  31895. WOLFSSL_MSG("InitDecodedCRL");
  31896. XMEMSET(dcrl, 0, sizeof(DecodedCRL));
  31897. dcrl->heap = heap;
  31898. #ifdef WOLFSSL_HEAP_TEST
  31899. dcrl->heap = (void*)WOLFSSL_HEAP_TEST;
  31900. #endif
  31901. }
  31902. /* free decoded CRL resources */
  31903. void FreeDecodedCRL(DecodedCRL* dcrl)
  31904. {
  31905. RevokedCert* tmp = dcrl->certs;
  31906. WOLFSSL_MSG("FreeDecodedCRL");
  31907. while(tmp) {
  31908. RevokedCert* next = tmp->next;
  31909. XFREE(tmp, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  31910. tmp = next;
  31911. }
  31912. #ifdef OPENSSL_EXTRA
  31913. if (dcrl->issuer != NULL)
  31914. XFREE(dcrl->issuer, NULL, DYNAMIC_TYPE_OPENSSL);
  31915. #endif
  31916. }
  31917. #ifdef WOLFSSL_ASN_TEMPLATE
  31918. /* ASN.1 template for revoked certificates.
  31919. * X.509: RFC 5280, 5.1 - CRL Fields
  31920. */
  31921. static const ASNItem revokedASN[] = {
  31922. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31923. /* userCertificate CertificateSerialNumber */
  31924. /* CERT */ { 1, ASN_INTEGER, 0, 0, 0 },
  31925. /* revocationDate Time */
  31926. /* TIME_UTC */ { 1, ASN_UTC_TIME, 0, 0, 2 },
  31927. /* TIME_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 2 },
  31928. /* crlEntryExensions Extensions */
  31929. /* TIME_EXT */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  31930. };
  31931. enum {
  31932. REVOKEDASN_IDX_SEQ = 0,
  31933. REVOKEDASN_IDX_CERT,
  31934. REVOKEDASN_IDX_TIME_UTC,
  31935. REVOKEDASN_IDX_TIME_GT,
  31936. REVOKEDASN_IDX_TIME_EXT,
  31937. };
  31938. /* Number of items in ASN.1 template for revoked certificates. */
  31939. #define revokedASN_Length (sizeof(revokedASN) / sizeof(ASNItem))
  31940. #endif
  31941. /* Get Revoked Cert list, 0 on success */
  31942. static int GetRevoked(RevokedCert* rcert, const byte* buff, word32* idx,
  31943. DecodedCRL* dcrl, int maxIdx)
  31944. {
  31945. #ifndef WOLFSSL_ASN_TEMPLATE
  31946. #ifndef NO_ASN_TIME
  31947. int ret;
  31948. #endif
  31949. int len;
  31950. word32 end;
  31951. RevokedCert* rc;
  31952. #ifdef CRL_STATIC_REVOKED_LIST
  31953. int totalCerts = 0;
  31954. #endif
  31955. WOLFSSL_ENTER("GetRevoked");
  31956. if (GetSequence(buff, idx, &len, maxIdx) < 0)
  31957. return ASN_PARSE_E;
  31958. end = *idx + len;
  31959. #ifdef CRL_STATIC_REVOKED_LIST
  31960. totalCerts = dcrl->totalCerts;
  31961. if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
  31962. return MEMORY_E;
  31963. }
  31964. rc = &rcert[totalCerts];
  31965. ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
  31966. if (ret < 0) {
  31967. WOLFSSL_MSG("wc_GetSerialNumber error");
  31968. return ret;
  31969. }
  31970. #else
  31971. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  31972. DYNAMIC_TYPE_REVOKED);
  31973. if (rc == NULL) {
  31974. WOLFSSL_MSG("Alloc Revoked Cert failed");
  31975. return MEMORY_E;
  31976. }
  31977. ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
  31978. if (ret < 0) {
  31979. WOLFSSL_MSG("wc_GetSerialNumber error");
  31980. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  31981. return ret;
  31982. }
  31983. /* add to list */
  31984. rc->next = dcrl->certs;
  31985. dcrl->certs = rc;
  31986. (void)rcert;
  31987. #endif /* CRL_STATIC_REVOKED_LIST */
  31988. dcrl->totalCerts++;
  31989. /* get date */
  31990. #ifndef NO_ASN_TIME
  31991. ret = GetBasicDate(buff, idx, rc->revDate, &rc->revDateFormat, maxIdx);
  31992. if (ret < 0) {
  31993. WOLFSSL_MSG("Expecting Date");
  31994. return ret;
  31995. }
  31996. #endif
  31997. /* skip extensions */
  31998. *idx = end;
  31999. return 0;
  32000. #else
  32001. DECL_ASNGETDATA(dataASN, revokedASN_Length);
  32002. int ret = 0;
  32003. word32 serialSz = EXTERNAL_SERIAL_SIZE;
  32004. word32 revDateSz = MAX_DATE_SIZE;
  32005. RevokedCert* rc;
  32006. #ifdef CRL_STATIC_REVOKED_LIST
  32007. int totalCerts = dcrl->totalCerts;
  32008. if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
  32009. return MEMORY_E;
  32010. }
  32011. rc = &rcert[totalCerts];
  32012. #else
  32013. /* Allocate a new revoked certificate object. */
  32014. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  32015. DYNAMIC_TYPE_CRL);
  32016. if (rc == NULL) {
  32017. ret = MEMORY_E;
  32018. }
  32019. #endif /* CRL_STATIC_REVOKED_LIST */
  32020. CALLOC_ASNGETDATA(dataASN, revokedASN_Length, ret, dcrl->heap);
  32021. if (ret == 0) {
  32022. /* Set buffer to place serial number into. */
  32023. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_CERT], rc->serialNumber,
  32024. &serialSz);
  32025. /* Set buffer to store revocation date. */
  32026. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_UTC], rc->revDate,
  32027. &revDateSz);
  32028. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_GT], rc->revDate,
  32029. &revDateSz);
  32030. /* Decode the Revoked */
  32031. ret = GetASN_Items(revokedASN, dataASN, revokedASN_Length, 1, buff, idx,
  32032. maxIdx);
  32033. }
  32034. if (ret == 0) {
  32035. /* Store size of serial number. */
  32036. rc->serialSz = serialSz;
  32037. rc->revDateFormat = (dataASN[REVOKEDASN_IDX_TIME_UTC].tag != 0)
  32038. ? dataASN[REVOKEDASN_IDX_TIME_UTC].tag
  32039. : dataASN[REVOKEDASN_IDX_TIME_GT].tag;
  32040. /* TODO: use extensions, only v2 */
  32041. /* Add revoked certificate to chain. */
  32042. #ifndef CRL_STATIC_REVOKED_LIST
  32043. rc->next = dcrl->certs;
  32044. dcrl->certs = rc;
  32045. #endif
  32046. dcrl->totalCerts++;
  32047. }
  32048. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32049. #ifndef CRL_STATIC_REVOKED_LIST
  32050. if ((ret != 0) && (rc != NULL)) {
  32051. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_CRL);
  32052. }
  32053. (void)rcert;
  32054. #endif
  32055. return ret;
  32056. #endif /* WOLFSSL_ASN_TEMPLATE */
  32057. }
  32058. #ifdef WOLFSSL_ASN_TEMPLATE
  32059. /* Parse the revoked certificates of a CRL.
  32060. *
  32061. * @param [in] dcrl Decoded CRL object.
  32062. * @param [in] buff Buffer holding CRL.
  32063. * @param [in] idx Index into buffer of revoked certificates.
  32064. * @param [in] maxIdx Maximum index of revoked cartificates data.
  32065. * @return 0 on success.
  32066. * @return ASN_PARSE_E on failure.
  32067. */
  32068. static int ParseCRL_RevokedCerts(RevokedCert* rcert, DecodedCRL* dcrl,
  32069. const byte* buff, word32 idx, word32 maxIdx)
  32070. {
  32071. int ret = 0;
  32072. /* Parse each revoked cerificate. */
  32073. while ((ret == 0) && (idx < maxIdx)) {
  32074. /* Parse a revoked certificate. */
  32075. if (GetRevoked(rcert, buff, &idx, dcrl, maxIdx) < 0) {
  32076. ret = ASN_PARSE_E;
  32077. }
  32078. }
  32079. return ret;
  32080. }
  32081. #endif /* WOLFSSL_ASN_TEMPLATE */
  32082. #ifndef WOLFSSL_ASN_TEMPLATE
  32083. /* Get CRL Signature, 0 on success */
  32084. static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
  32085. int maxIdx)
  32086. {
  32087. int length;
  32088. int ret;
  32089. WOLFSSL_ENTER("GetCRL_Signature");
  32090. ret = CheckBitString(source, idx, &length, maxIdx, 1, NULL);
  32091. if (ret != 0)
  32092. return ret;
  32093. dcrl->sigLength = length;
  32094. dcrl->signature = (byte*)&source[*idx];
  32095. *idx += dcrl->sigLength;
  32096. return 0;
  32097. }
  32098. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32099. int VerifyCRL_Signature(SignatureCtx* sigCtx, const byte* toBeSigned,
  32100. word32 tbsSz, const byte* signature, word32 sigSz,
  32101. word32 signatureOID, Signer *ca, void* heap)
  32102. {
  32103. /* try to confirm/verify signature */
  32104. #ifndef IGNORE_KEY_EXTENSIONS
  32105. if ((ca->keyUsage & KEYUSE_CRL_SIGN) == 0) {
  32106. WOLFSSL_MSG("CA cannot sign CRLs");
  32107. WOLFSSL_ERROR_VERBOSE(ASN_CRL_NO_SIGNER_E);
  32108. return ASN_CRL_NO_SIGNER_E;
  32109. }
  32110. #endif /* IGNORE_KEY_EXTENSIONS */
  32111. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  32112. if (ConfirmSignature(sigCtx, toBeSigned, tbsSz, ca->publicKey,
  32113. ca->pubKeySize, ca->keyOID, signature, sigSz,
  32114. signatureOID, NULL, 0, NULL) != 0) {
  32115. WOLFSSL_MSG("CRL Confirm signature failed");
  32116. WOLFSSL_ERROR_VERBOSE(ASN_CRL_CONFIRM_E);
  32117. return ASN_CRL_CONFIRM_E;
  32118. }
  32119. return 0;
  32120. }
  32121. #ifdef WOLFSSL_ASN_TEMPLATE
  32122. /* Find the signer for the CRL and verify the signature.
  32123. *
  32124. * @param [in] dcrl Decoded CRL object.
  32125. * @param [in] buff Buffer holding CRL.
  32126. * @param [in] cm Certificate manager object.
  32127. * @return 0 on success.
  32128. * @return ASN_CRL_NO_SIGNER_E when no signer found.
  32129. * @return ASN_CRL_CONFIRM_E when signature did not verify.
  32130. */
  32131. static int PaseCRL_CheckSignature(DecodedCRL* dcrl, const byte* buff, void* cm)
  32132. {
  32133. int ret = 0;
  32134. Signer* ca = NULL;
  32135. SignatureCtx sigCtx;
  32136. /* OpenSSL doesn't add skid by default for CRLs cause firefox chokes.
  32137. * If experiencing issues uncomment NO_SKID define in CRL section of
  32138. * wolfssl/wolfcrypt/settings.h */
  32139. #ifndef NO_SKID
  32140. if (dcrl->extAuthKeyIdSet) {
  32141. /* more unique than issuerHash */
  32142. ca = GetCA(cm, dcrl->extAuthKeyId);
  32143. }
  32144. /* Check issuerHash matched CA's subjectNameHash. */
  32145. if ((ca != NULL) && (XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  32146. KEYID_SIZE) != 0)) {
  32147. ca = NULL;
  32148. }
  32149. if (ca == NULL) {
  32150. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  32151. /* If AKID is available then this CA doesn't have the public
  32152. * key required */
  32153. if (ca && dcrl->extAuthKeyIdSet) {
  32154. WOLFSSL_MSG("CA SKID doesn't match AKID");
  32155. ca = NULL;
  32156. }
  32157. }
  32158. #else
  32159. ca = GetCA(cm, dcrl->issuerHash);
  32160. #endif /* !NO_SKID */
  32161. WOLFSSL_MSG("About to verify CRL signature");
  32162. if (ca == NULL) {
  32163. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  32164. ret = ASN_CRL_NO_SIGNER_E;
  32165. WOLFSSL_ERROR_VERBOSE(ret);
  32166. }
  32167. if (ret == 0) {
  32168. WOLFSSL_MSG("Found CRL issuer CA");
  32169. /* Verify CRL signature with CA. */
  32170. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  32171. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  32172. dcrl->signatureOID, ca, dcrl->heap);
  32173. }
  32174. return ret;
  32175. }
  32176. #endif
  32177. #ifndef WOLFSSL_ASN_TEMPLATE
  32178. static int ParseCRL_CertList(RevokedCert* rcert, DecodedCRL* dcrl,
  32179. const byte* buf,word32* inOutIdx, int sz, int verify)
  32180. {
  32181. word32 oid, dateIdx, idx, checkIdx;
  32182. int length;
  32183. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  32184. int doNextDate = 1;
  32185. #endif
  32186. byte tag;
  32187. if (dcrl == NULL || inOutIdx == NULL || buf == NULL) {
  32188. return BAD_FUNC_ARG;
  32189. }
  32190. /* may have version */
  32191. idx = *inOutIdx;
  32192. checkIdx = idx;
  32193. if (GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag == ASN_INTEGER) {
  32194. if (GetMyVersion(buf, &idx, &dcrl->version, sz) < 0)
  32195. return ASN_PARSE_E;
  32196. dcrl->version++;
  32197. }
  32198. if (GetAlgoId(buf, &idx, &oid, oidIgnoreType, sz) < 0)
  32199. return ASN_PARSE_E;
  32200. checkIdx = idx;
  32201. if (GetSequence(buf, &checkIdx, &length, sz) < 0) {
  32202. return ASN_PARSE_E;
  32203. }
  32204. #ifdef OPENSSL_EXTRA
  32205. dcrl->issuerSz = length + (checkIdx - idx);
  32206. dcrl->issuer = (byte*)GetNameFromDer(buf + idx, (int)dcrl->issuerSz);
  32207. #endif
  32208. if (GetNameHash(buf, &idx, dcrl->issuerHash, sz) < 0)
  32209. return ASN_PARSE_E;
  32210. if (GetBasicDate(buf, &idx, dcrl->lastDate, &dcrl->lastDateFormat, sz) < 0)
  32211. return ASN_PARSE_E;
  32212. dateIdx = idx;
  32213. if (GetBasicDate(buf, &idx, dcrl->nextDate, &dcrl->nextDateFormat, sz) < 0)
  32214. {
  32215. #ifndef WOLFSSL_NO_CRL_NEXT_DATE
  32216. (void)dateIdx;
  32217. return ASN_PARSE_E;
  32218. #else
  32219. dcrl->nextDateFormat = ASN_OTHER_TYPE; /* skip flag */
  32220. doNextDate = 0;
  32221. idx = dateIdx;
  32222. #endif
  32223. }
  32224. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  32225. if (doNextDate)
  32226. #endif
  32227. {
  32228. #ifndef NO_ASN_TIME
  32229. if (verify != NO_VERIFY &&
  32230. !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  32231. WOLFSSL_MSG("CRL after date is no longer valid");
  32232. WOLFSSL_ERROR_VERBOSE(CRL_CERT_DATE_ERR);
  32233. return CRL_CERT_DATE_ERR;
  32234. }
  32235. #else
  32236. (void)verify;
  32237. #endif
  32238. }
  32239. checkIdx = idx;
  32240. if (idx != dcrl->sigIndex &&
  32241. GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag != CRL_EXTENSIONS) {
  32242. int len;
  32243. if (GetSequence(buf, &idx, &len, sz) < 0)
  32244. return ASN_PARSE_E;
  32245. len += idx;
  32246. while (idx < (word32)len) {
  32247. if (GetRevoked(rcert, buf, &idx, dcrl, len) < 0)
  32248. return ASN_PARSE_E;
  32249. }
  32250. }
  32251. *inOutIdx = idx;
  32252. return 0;
  32253. }
  32254. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32255. #ifndef NO_SKID
  32256. static int ParseCRL_AuthKeyIdExt(const byte* input, int sz, DecodedCRL* dcrl)
  32257. {
  32258. #ifndef WOLFSSL_ASN_TEMPLATE
  32259. word32 idx = 0;
  32260. int length = 0, ret = 0;
  32261. byte tag;
  32262. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  32263. if (GetSequence(input, &idx, &length, sz) < 0) {
  32264. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  32265. return ASN_PARSE_E;
  32266. }
  32267. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  32268. return ASN_PARSE_E;
  32269. }
  32270. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  32271. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  32272. return 0;
  32273. }
  32274. if (GetLength(input, &idx, &length, sz) <= 0) {
  32275. WOLFSSL_MSG("\tfail: extension data length");
  32276. return ASN_PARSE_E;
  32277. }
  32278. dcrl->extAuthKeyIdSet = 1;
  32279. /* Get the hash or hash of the hash if wrong size. */
  32280. ret = GetHashId(input + idx, length, dcrl->extAuthKeyId);
  32281. return ret;
  32282. #else
  32283. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  32284. int ret = 0;
  32285. word32 idx = 0;
  32286. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  32287. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, dcrl->heap);
  32288. if (ret == 0) {
  32289. /* Parse an authority key identifier. */
  32290. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  32291. &idx, sz);
  32292. }
  32293. if (ret == 0) {
  32294. /* Key id is optional. */
  32295. if (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data == NULL) {
  32296. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  32297. }
  32298. else {
  32299. /* Get the hash or hash of the hash if wrong size. */
  32300. ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  32301. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  32302. dcrl->extAuthKeyId);
  32303. }
  32304. }
  32305. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32306. return ret;
  32307. #endif /* WOLFSSL_ASN_TEMPLATE */
  32308. }
  32309. #endif
  32310. #ifndef WOLFSSL_ASN_TEMPLATE
  32311. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf,
  32312. word32* inOutIdx, word32 sz)
  32313. {
  32314. int length;
  32315. word32 idx;
  32316. word32 ext_bound; /* boundary index for the sequence of extensions */
  32317. word32 oid;
  32318. byte tag;
  32319. WOLFSSL_ENTER("ParseCRL_Extensions");
  32320. (void)dcrl;
  32321. if (inOutIdx == NULL)
  32322. return BAD_FUNC_ARG;
  32323. idx = *inOutIdx;
  32324. /* CRL Extensions are optional */
  32325. if ((idx + 1) > sz)
  32326. return 0;
  32327. /* CRL Extensions are optional */
  32328. if (GetASNTag(buf, &idx, &tag, sz) < 0)
  32329. return 0;
  32330. /* CRL Extensions are optional */
  32331. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  32332. return 0;
  32333. if (GetLength(buf, &idx, &length, sz) < 0)
  32334. return ASN_PARSE_E;
  32335. if (GetSequence(buf, &idx, &length, sz) < 0)
  32336. return ASN_PARSE_E;
  32337. ext_bound = idx + length;
  32338. while (idx < (word32)ext_bound) {
  32339. word32 localIdx;
  32340. int ret;
  32341. if (GetSequence(buf, &idx, &length, sz) < 0) {
  32342. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  32343. return ASN_PARSE_E;
  32344. }
  32345. oid = 0;
  32346. if (GetObjectId(buf, &idx, &oid, oidCrlExtType, sz) < 0) {
  32347. WOLFSSL_MSG("\tfail: OBJECT ID");
  32348. return ASN_PARSE_E;
  32349. }
  32350. /* check for critical flag */
  32351. if ((idx + 1) > (word32)sz) {
  32352. WOLFSSL_MSG("\tfail: malformed buffer");
  32353. return BUFFER_E;
  32354. }
  32355. localIdx = idx;
  32356. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  32357. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  32358. ret = GetBoolean(buf, &idx, sz);
  32359. if (ret < 0)
  32360. return ret;
  32361. }
  32362. ret = GetOctetString(buf, &idx, &length, sz);
  32363. if (ret < 0)
  32364. return ret;
  32365. if (oid == AUTH_KEY_OID) {
  32366. #ifndef NO_SKID
  32367. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  32368. if (ret < 0) {
  32369. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  32370. return ret;
  32371. }
  32372. #endif
  32373. }
  32374. else if (oid == CRL_NUMBER_OID) {
  32375. localIdx = idx;
  32376. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 &&
  32377. tag == ASN_INTEGER) {
  32378. ret = GetASNInt(buf, &idx, &length, sz);
  32379. if (ret < 0) {
  32380. WOLFSSL_MSG("\tcouldn't parse CRL number extension");
  32381. return ret;
  32382. }
  32383. else {
  32384. if (length > 1) {
  32385. int i;
  32386. #ifdef WOLFSSL_SMALL_STACK
  32387. mp_int* m = (mp_int*)XMALLOC(sizeof(*m), NULL,
  32388. DYNAMIC_TYPE_BIGINT);
  32389. if (m == NULL) {
  32390. return MEMORY_E;
  32391. }
  32392. #else
  32393. mp_int m[1];
  32394. #endif
  32395. if (mp_init(m) != MP_OKAY) {
  32396. ret = MP_INIT_E;
  32397. }
  32398. if (ret == 0)
  32399. ret = mp_read_unsigned_bin(m, buf + idx, length);
  32400. if (ret != MP_OKAY)
  32401. ret = BUFFER_E;
  32402. if (ret == 0) {
  32403. dcrl->crlNumber = 0;
  32404. for (i = 0; i < (*m).used; ++i) {
  32405. if (i > (CHAR_BIT *
  32406. (int)sizeof(word32) / DIGIT_BIT)) {
  32407. break;
  32408. }
  32409. dcrl->crlNumber |= ((word32)(*m).dp[i]) <<
  32410. (DIGIT_BIT * i);
  32411. }
  32412. }
  32413. mp_free(m);
  32414. #ifdef WOLFSSL_SMALL_STACK
  32415. XFREE(m, NULL, DYNAMIC_TYPE_BIGINT);
  32416. #endif
  32417. if (ret != 0)
  32418. return ret;
  32419. }
  32420. else {
  32421. dcrl->crlNumber = buf[idx];
  32422. }
  32423. }
  32424. }
  32425. }
  32426. idx += length;
  32427. }
  32428. *inOutIdx = idx;
  32429. return 0;
  32430. }
  32431. #else
  32432. /* Parse the extensions of a CRL.
  32433. *
  32434. * @param [in] dcrl Decoded CRL object.
  32435. * @param [in] buff Buffer holding CRL.
  32436. * @param [in] idx Index into buffer of extensions.
  32437. * @param [in] maxIdx Maximum index of extension data.
  32438. * @return 0 on success.
  32439. * @return ASN_PARSE_E on failure.
  32440. */
  32441. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf, word32 idx,
  32442. word32 maxIdx)
  32443. {
  32444. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  32445. int ret = 0;
  32446. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, dcrl->heap);
  32447. while ((ret == 0) && (idx < maxIdx)) {
  32448. byte critical = 0;
  32449. /* Clear dynamic data. */
  32450. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  32451. /* Ensure OID is an extention type. */
  32452. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  32453. /* Set criticality variable. */
  32454. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  32455. /* Parse extension wrapper. */
  32456. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, buf, &idx,
  32457. maxIdx);
  32458. if (ret == 0) {
  32459. /* OID in extension. */
  32460. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  32461. /* Length of extension data. */
  32462. int length = dataASN[CERTEXTASN_IDX_VAL].length;
  32463. if (oid == AUTH_KEY_OID) {
  32464. #ifndef NO_SKID
  32465. /* Parse Authority Key Id extesion.
  32466. * idx is at start of OCTET_STRING data. */
  32467. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  32468. if (ret != 0) {
  32469. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  32470. }
  32471. #endif
  32472. }
  32473. /* TODO: Parse CRL Number extension */
  32474. /* TODO: check criticality */
  32475. /* Move index on to next extension. */
  32476. idx += length;
  32477. }
  32478. }
  32479. if (ret < 0) {
  32480. ret = ASN_PARSE_E;
  32481. }
  32482. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32483. return ret;
  32484. }
  32485. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32486. #ifdef WOLFSSL_ASN_TEMPLATE
  32487. /* ASN.1 template for a CRL- CertificateList.
  32488. * X.509: RFC 5280, 5.1 - CRL Fields
  32489. */
  32490. static const ASNItem crlASN[] = {
  32491. /* CertificateList */
  32492. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  32493. /* tbsCertList */
  32494. /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  32495. /* version Version OPTIONAL if present must be v2 */
  32496. /* TBS_VER */ { 2, ASN_INTEGER, 0, 0, 1 },
  32497. /* signature */
  32498. /* TBS_SIGALGO */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  32499. /* TBS_SIGALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  32500. /* TBS_SIGALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  32501. /* issuer */
  32502. /* TBS_ISSUER */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  32503. /* thisUpdate */
  32504. /* TBS_THISUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 2 },
  32505. /* TBS_THISUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 2 },
  32506. /* nextUpdate */
  32507. /* TBS_NEXTUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 3 },
  32508. /* TBS_NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 3 },
  32509. /* revokedCertificates */
  32510. /* TBS_REVOKEDCERTS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  32511. /* crlExtensions */
  32512. /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  32513. /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
  32514. /* signatureAlgorithm */
  32515. /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  32516. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  32517. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  32518. /* signatureValue */
  32519. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  32520. };
  32521. enum {
  32522. CRLASN_IDX_SEQ = 0,
  32523. CRLASN_IDX_TBS,
  32524. CRLASN_IDX_TBS_VER,
  32525. CRLASN_IDX_TBS_SIGALGO,
  32526. CRLASN_IDX_TBS_SIGALGO_OID,
  32527. CRLASN_IDX_TBS_SIGALGO_NULL,
  32528. CRLASN_IDX_TBS_ISSUER,
  32529. CRLASN_IDX_TBS_THISUPDATE_UTC,
  32530. CRLASN_IDX_TBS_THISUPDATE_GT,
  32531. CRLASN_IDX_TBS_NEXTUPDATE_UTC,
  32532. CRLASN_IDX_TBS_NEXTUPDATE_GT,
  32533. CRLASN_IDX_TBS_REVOKEDCERTS,
  32534. CRLASN_IDX_TBS_EXT,
  32535. CRLASN_IDX_TBS_EXT_SEQ,
  32536. CRLASN_IDX_SIGALGO,
  32537. CRLASN_IDX_SIGALGO_OID,
  32538. CRLASN_IDX_SIGALGO_NULL,
  32539. CRLASN_IDX_SIGNATURE,
  32540. };
  32541. /* Number of items in ASN.1 template for a CRL- CertificateList. */
  32542. #define crlASN_Length (sizeof(crlASN) / sizeof(ASNItem))
  32543. #endif
  32544. /* parse crl buffer into decoded state, 0 on success */
  32545. int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz,
  32546. int verify, void* cm)
  32547. {
  32548. #ifndef WOLFSSL_ASN_TEMPLATE
  32549. Signer* ca = NULL;
  32550. SignatureCtx sigCtx;
  32551. int ret = 0;
  32552. int len;
  32553. word32 idx = 0;
  32554. WOLFSSL_MSG("ParseCRL");
  32555. /* raw crl hash */
  32556. /* hash here if needed for optimized comparisons
  32557. * wc_Sha sha;
  32558. * wc_InitSha(&sha);
  32559. * wc_ShaUpdate(&sha, buff, sz);
  32560. * wc_ShaFinal(&sha, dcrl->crlHash); */
  32561. if (GetSequence(buff, &idx, &len, sz) < 0)
  32562. return ASN_PARSE_E;
  32563. dcrl->certBegin = idx;
  32564. /* Normalize sz for the length inside the outer sequence. */
  32565. sz = len + idx;
  32566. if (GetSequence(buff, &idx, &len, sz) < 0)
  32567. return ASN_PARSE_E;
  32568. dcrl->sigIndex = len + idx;
  32569. if (ParseCRL_CertList(rcert, dcrl, buff, &idx, dcrl->sigIndex, verify) < 0)
  32570. return ASN_PARSE_E;
  32571. if (ParseCRL_Extensions(dcrl, buff, &idx, dcrl->sigIndex) < 0)
  32572. return ASN_PARSE_E;
  32573. idx = dcrl->sigIndex;
  32574. if (GetAlgoId(buff, &idx, &dcrl->signatureOID, oidSigType, sz) < 0)
  32575. return ASN_PARSE_E;
  32576. if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
  32577. return ASN_PARSE_E;
  32578. /* openssl doesn't add skid by default for CRLs cause firefox chokes
  32579. if experiencing issues uncomment NO_SKID define in CRL section of
  32580. wolfssl/wolfcrypt/settings.h */
  32581. #ifndef NO_SKID
  32582. if (dcrl->extAuthKeyIdSet) {
  32583. ca = GetCA(cm, dcrl->extAuthKeyId); /* more unique than issuerHash */
  32584. }
  32585. if (ca != NULL && XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  32586. KEYID_SIZE) != 0) {
  32587. ca = NULL;
  32588. }
  32589. if (ca == NULL) {
  32590. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  32591. /* If AKID is available then this CA doesn't have the public
  32592. * key required */
  32593. if (ca && dcrl->extAuthKeyIdSet) {
  32594. WOLFSSL_MSG("CA SKID doesn't match AKID");
  32595. ca = NULL;
  32596. }
  32597. }
  32598. #else
  32599. ca = GetCA(cm, dcrl->issuerHash);
  32600. #endif /* !NO_SKID */
  32601. WOLFSSL_MSG("About to verify CRL signature");
  32602. if (ca == NULL) {
  32603. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  32604. ret = ASN_CRL_NO_SIGNER_E;
  32605. WOLFSSL_ERROR_VERBOSE(ret);
  32606. goto end;
  32607. }
  32608. WOLFSSL_MSG("Found CRL issuer CA");
  32609. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  32610. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  32611. dcrl->signatureOID, ca, dcrl->heap);
  32612. end:
  32613. return ret;
  32614. #else
  32615. DECL_ASNGETDATA(dataASN, crlASN_Length);
  32616. int ret = 0;
  32617. /* Default version - v1 = 0 */
  32618. byte version = 0;
  32619. word32 idx = 0;
  32620. /* Size of buffer for date. */
  32621. word32 lastDateSz = MAX_DATE_SIZE;
  32622. word32 nextDateSz = MAX_DATE_SIZE;
  32623. WOLFSSL_MSG("ParseCRL");
  32624. CALLOC_ASNGETDATA(dataASN, crlASN_Length, ret, dcrl->heap);
  32625. if (ret == 0) {
  32626. /* Set variable to store version. */
  32627. GetASN_Int8Bit(&dataASN[CRLASN_IDX_TBS_VER], &version);
  32628. /* Set expecting signature OID. */
  32629. GetASN_OID(&dataASN[CRLASN_IDX_TBS_SIGALGO_OID], oidSigType);
  32630. /* Set buffer to put last and next date into. */
  32631. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC], dcrl->lastDate,
  32632. &lastDateSz);
  32633. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_GT], dcrl->lastDate,
  32634. &lastDateSz);
  32635. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC], dcrl->nextDate,
  32636. &nextDateSz);
  32637. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT], dcrl->nextDate,
  32638. &nextDateSz);
  32639. /* Set expecting signature OID. */
  32640. GetASN_OID(&dataASN[CRLASN_IDX_SIGALGO_OID], oidSigType);
  32641. /* Decode the CRL. */
  32642. ret = GetASN_Items(crlASN, dataASN, crlASN_Length, 1, buff, &idx, sz);
  32643. }
  32644. /* Version must be v2 = 1 if present. */
  32645. if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_VER].tag != 0) &&
  32646. (version != 1)) {
  32647. ret = ASN_PARSE_E;
  32648. }
  32649. /* Check minimum size of last date. */
  32650. if ((ret == 0) && (lastDateSz < MIN_DATE_SIZE)) {
  32651. ret = ASN_PARSE_E;
  32652. }
  32653. /* Check minimum size of next date. */
  32654. if ((ret == 0) && (nextDateSz < MIN_DATE_SIZE)) {
  32655. ret = ASN_PARSE_E;
  32656. }
  32657. /* 'signatureAlgorithm' OID must be the same as 'signature' OID. */
  32658. if ((ret == 0) && (dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum !=
  32659. dataASN[CRLASN_IDX_TBS_SIGALGO_OID].data.oid.sum)) {
  32660. ret = ASN_PARSE_E;
  32661. }
  32662. if (ret == 0) {
  32663. /* Store version */
  32664. dcrl->version = ++version;
  32665. /* Store offset of to be signed part. */
  32666. dcrl->certBegin = dataASN[CRLASN_IDX_TBS].offset;
  32667. /* Store index of signature. */
  32668. dcrl->sigIndex = dataASN[CRLASN_IDX_SIGALGO].offset;
  32669. /* Store address and length of signature data. */
  32670. GetASN_GetRef(&dataASN[CRLASN_IDX_SIGNATURE], &dcrl->signature,
  32671. &dcrl->sigLength);
  32672. /* Get the signature OID. */
  32673. dcrl->signatureOID = dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum;
  32674. /* Get the format/tag of the last and next date. */
  32675. dcrl->lastDateFormat = (dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag != 0)
  32676. ? dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag
  32677. : dataASN[CRLASN_IDX_TBS_THISUPDATE_GT].tag;
  32678. dcrl->nextDateFormat = (dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag != 0)
  32679. ? dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag
  32680. : dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT].tag;
  32681. #ifndef NO_ASN_TIME
  32682. if (dcrl->nextDateFormat != 0) {
  32683. /* Next date was set, so validate it. */
  32684. if (verify != NO_VERIFY &&
  32685. !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  32686. WOLFSSL_MSG("CRL after date is no longer valid");
  32687. ret = CRL_CERT_DATE_ERR;
  32688. WOLFSSL_ERROR_VERBOSE(ret);
  32689. }
  32690. }
  32691. }
  32692. if (ret == 0) {
  32693. #endif
  32694. #ifdef OPENSSL_EXTRA
  32695. /* Parse and store the issuer name. */
  32696. dcrl->issuerSz = GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER],
  32697. buff);
  32698. dcrl->issuer = (byte*)GetNameFromDer((byte*)GetASNItem_Addr(
  32699. dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  32700. (int)dcrl->issuerSz);
  32701. /* Calculate the Hash id from the issuer name. */
  32702. ret = CalcHashId(GetASNItem_Addr(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  32703. dcrl->issuerSz, dcrl->issuerHash);
  32704. if (ret < 0) {
  32705. ret = ASN_PARSE_E;
  32706. }
  32707. #endif
  32708. }
  32709. if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_REVOKEDCERTS].tag != 0)) {
  32710. /* Parse revoked cerificates - starting after SEQUENCE OF. */
  32711. ret = ParseCRL_RevokedCerts(rcert, dcrl, buff,
  32712. GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff),
  32713. GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff));
  32714. }
  32715. if (ret == 0) {
  32716. /* Parse the extensions - starting after SEQUENCE OF. */
  32717. ret = ParseCRL_Extensions(dcrl, buff,
  32718. GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff),
  32719. GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff));
  32720. }
  32721. if (ret == 0) {
  32722. /* Find signer and verify signature. */
  32723. ret = PaseCRL_CheckSignature(dcrl, buff, cm);
  32724. }
  32725. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32726. return ret;
  32727. #endif /* WOLFSSL_ASN_TEMPLATE */
  32728. }
  32729. #endif /* HAVE_CRL */
  32730. #ifdef WOLFSSL_CERT_PIV
  32731. #ifdef WOLFSSL_ASN_TEMPLATE
  32732. /* Template for PIV. */
  32733. static const ASNItem pivASN[] = {
  32734. /* CERT */ { 0, ASN_PIV_CERT, 0, 0, 0 },
  32735. /* NONCE */ { 0, ASN_PIV_NONCE, 0, 0, 1 },
  32736. /* SIGNEDNONCE */ { 0, ASN_PIV_SIGNED_NONCE, 0, 0, 1 },
  32737. };
  32738. enum {
  32739. PIVASN_IDX_CERT = 0,
  32740. PIVASN_IDX_NONCE,
  32741. PIVASN_IDX_SIGNEDNONCE,
  32742. };
  32743. #define pivASN_Length (sizeof(pivASN) / sizeof(ASNItem))
  32744. static const ASNItem pivCertASN[] = {
  32745. /* 0x53 = 0x40 | 0x13 */
  32746. /* CERT */ { 1, ASN_APPLICATION | 0x13, 0, 1, 0 },
  32747. /* 0x70 = 0x40 | 0x10 + 0x20 (CONSTRUCTED) */
  32748. /* X509 */ { 2, ASN_APPLICATION | 0x10, 1, 0, 0 },
  32749. /* 0x71 = 0x40 | 0x11 + 0x20 (CONSTRUCTED) */
  32750. /* INFO */ { 2, ASN_APPLICATION | 0x11, 1, 0, 1 },
  32751. /* 0xFE = 0xC0 | 0x1E + 0x20 (CONSTRUCTED) */
  32752. /* ERR */ { 2, ASN_PRIVATE | 0x1e, 1, 0, 1 },
  32753. };
  32754. enum {
  32755. PIVCERTASN_IDX_CERT,
  32756. PIVCERTASN_IDX_X509,
  32757. PIVCERTASN_IDX_INFO,
  32758. PIVCERTASN_IDX_ERR,
  32759. };
  32760. #define pivCertASN_Length (sizeof(pivCertASN) / sizeof(ASNItem))
  32761. #endif
  32762. int wc_ParseCertPIV(wc_CertPIV* piv, const byte* buf, word32 totalSz)
  32763. {
  32764. #ifndef WOLFSSL_ASN_TEMPLATE
  32765. int length = 0;
  32766. word32 idx = 0;
  32767. WOLFSSL_ENTER("wc_ParseCertPIV");
  32768. if (piv == NULL || buf == NULL || totalSz == 0)
  32769. return BAD_FUNC_ARG;
  32770. XMEMSET(piv, 0, sizeof(wc_CertPIV));
  32771. /* Detect Identiv PIV (with 0x0A, 0x0B and 0x0C sections) */
  32772. /* Certificate (0A 82 05FA) */
  32773. if (GetASNHeader(buf, ASN_PIV_CERT, &idx, &length, totalSz) >= 0) {
  32774. /* Identiv Type PIV card */
  32775. piv->isIdentiv = 1;
  32776. piv->cert = &buf[idx];
  32777. piv->certSz = length;
  32778. idx += length;
  32779. /* Nonce (0B 14) */
  32780. if (GetASNHeader(buf, ASN_PIV_NONCE, &idx, &length, totalSz) >= 0) {
  32781. piv->nonce = &buf[idx];
  32782. piv->nonceSz = length;
  32783. idx += length;
  32784. }
  32785. /* Signed Nonce (0C 82 0100) */
  32786. if (GetASNHeader(buf, ASN_PIV_SIGNED_NONCE, &idx, &length, totalSz) >= 0) {
  32787. piv->signedNonce = &buf[idx];
  32788. piv->signedNonceSz = length;
  32789. }
  32790. idx = 0;
  32791. buf = piv->cert;
  32792. totalSz = piv->certSz;
  32793. }
  32794. /* Certificate Buffer Total Size (53 82 05F6) */
  32795. if (GetASNHeader(buf, ASN_APPLICATION | ASN_PRINTABLE_STRING, &idx,
  32796. &length, totalSz) < 0) {
  32797. return ASN_PARSE_E;
  32798. }
  32799. /* PIV Certificate (70 82 05ED) */
  32800. if (GetASNHeader(buf, ASN_PIV_TAG_CERT, &idx, &length,
  32801. totalSz) < 0) {
  32802. return ASN_PARSE_E;
  32803. }
  32804. /* Capture certificate buffer pointer and length */
  32805. piv->cert = &buf[idx];
  32806. piv->certSz = length;
  32807. idx += length;
  32808. /* PIV Certificate Info (71 01 00) */
  32809. if (GetASNHeader(buf, ASN_PIV_TAG_CERT_INFO, &idx, &length,
  32810. totalSz) >= 0) {
  32811. if (length >= 1) {
  32812. piv->compression = (buf[idx] & ASN_PIV_CERT_INFO_COMPRESSED);
  32813. piv->isX509 = ((buf[idx] & ASN_PIV_CERT_INFO_ISX509) != 0);
  32814. }
  32815. idx += length;
  32816. }
  32817. /* PIV Error Detection (FE 00) */
  32818. if (GetASNHeader(buf, ASN_PIV_TAG_ERR_DET, &idx, &length,
  32819. totalSz) >= 0) {
  32820. piv->certErrDet = &buf[idx];
  32821. piv->certErrDetSz = length;
  32822. idx += length;
  32823. }
  32824. return 0;
  32825. #else
  32826. /* pivCertASN_Length is longer than pivASN_Length */
  32827. DECL_ASNGETDATA(dataASN, pivCertASN_Length);
  32828. int ret = 0;
  32829. word32 idx;
  32830. byte info;
  32831. WOLFSSL_ENTER("wc_ParseCertPIV");
  32832. ALLOC_ASNGETDATA(dataASN, pivCertASN_Length, ret, NULL);
  32833. if (ret == 0) {
  32834. /* Clear dynamic data. */
  32835. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivASN_Length);
  32836. /* Start parsing from start of buffer. */
  32837. idx = 0;
  32838. /* Parse Identiv wrapper. */
  32839. ret = GetASN_Items(pivASN, dataASN, pivASN_Length, 1, buf, &idx,
  32840. totalSz);
  32841. if (ret == 0) {
  32842. /* Identiv wrapper found. */
  32843. piv->isIdentiv = 1;
  32844. /* Get nonce reference. */
  32845. if (dataASN[PIVASN_IDX_NONCE].tag != 0) {
  32846. GetASN_GetConstRef(&dataASN[PIVASN_IDX_NONCE], &piv->nonce,
  32847. &piv->nonceSz);
  32848. }
  32849. /* Get signedNonce reference. */
  32850. if (dataASN[PIVASN_IDX_SIGNEDNONCE].tag != 0) {
  32851. GetASN_GetConstRef(&dataASN[PIVASN_IDX_SIGNEDNONCE],
  32852. &piv->signedNonce, &piv->signedNonceSz);
  32853. }
  32854. /* Get the certificate data for parsing. */
  32855. GetASN_GetConstRef(&dataASN[PIVASN_IDX_CERT], &buf, &totalSz);
  32856. }
  32857. ret = 0;
  32858. }
  32859. if (ret == 0) {
  32860. /* Clear dynamic data and set variable to put cert info into. */
  32861. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivCertASN_Length);
  32862. GetASN_Int8Bit(&dataASN[PIVCERTASN_IDX_INFO], &info);
  32863. /* Start parsing from start of buffer. */
  32864. idx = 0;
  32865. /* Parse PIV cetificate data. */
  32866. ret = GetASN_Items(pivCertASN, dataASN, pivCertASN_Length, 1, buf, &idx,
  32867. totalSz);
  32868. if (ret == 0) {
  32869. /* Get X.509 certificate reference. */
  32870. GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_X509], &piv->cert,
  32871. &piv->certSz);
  32872. /* Set the certificate info if available. */
  32873. if (dataASN[PIVCERTASN_IDX_INFO].tag != 0) {
  32874. /* Bits 1 and 2 are compression. */
  32875. piv->compression = info & ASN_PIV_CERT_INFO_COMPRESSED;
  32876. /* Bits 3 is X509 flag. */
  32877. piv->isX509 = ((info & ASN_PIV_CERT_INFO_ISX509) != 0);
  32878. }
  32879. /* Get X.509 certificate error detection reference. */
  32880. GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_ERR], &piv->certErrDet,
  32881. &piv->certErrDetSz);
  32882. }
  32883. ret = 0;
  32884. }
  32885. FREE_ASNGETDATA(dataASN, NULL);
  32886. return ret;
  32887. #endif /* WOLFSSL_ASN_TEMPLATE */
  32888. }
  32889. #endif /* WOLFSSL_CERT_PIV */
  32890. #ifdef HAVE_SMIME
  32891. /*****************************************************************************
  32892. * wc_MIME_parse_headers - Reads the char array in and parses out MIME headers
  32893. * and parameters into headers. Will continue until in has no more content.
  32894. *
  32895. * RETURNS:
  32896. * returns zero on success, non-zero on error.
  32897. */
  32898. int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers)
  32899. {
  32900. MimeHdr* nextHdr = NULL;
  32901. MimeHdr* curHdr = NULL;
  32902. MimeParam* nextParam = NULL;
  32903. size_t start = 0;
  32904. size_t end = 0;
  32905. char* nameAttr = NULL;
  32906. char* bodyVal = NULL;
  32907. MimeTypes mimeType = MIME_HDR;
  32908. MimeStatus mimeStatus = MIME_NAMEATTR;
  32909. int ret = -1;
  32910. size_t pos = 0;
  32911. size_t lineLen = 0;
  32912. char* curLine = NULL;
  32913. char* ptr = NULL;
  32914. if (in == NULL || inLen <= 0 || in[inLen] != '\0' || headers == NULL) {
  32915. ret = BAD_FUNC_ARG;
  32916. goto error;
  32917. }
  32918. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL, DYNAMIC_TYPE_PKCS7);
  32919. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  32920. DYNAMIC_TYPE_PKCS7);
  32921. if (nextHdr == NULL || nextParam == NULL) {
  32922. ret = MEMORY_E;
  32923. goto error;
  32924. }
  32925. XMEMSET(nextHdr, 0, (word32)sizeof(MimeHdr));
  32926. XMEMSET(nextParam, 0, (word32)sizeof(MimeParam));
  32927. curLine = XSTRTOK(in, "\r\n", &ptr);
  32928. if (curLine == NULL) {
  32929. ret = ASN_PARSE_E;
  32930. goto error;
  32931. }
  32932. while (curLine != NULL) {
  32933. /* Leftover from previous line, add params to previous header. */
  32934. if (curLine[0] == ' ' && curHdr) {
  32935. mimeType = MIME_PARAM;
  32936. }
  32937. else {
  32938. mimeType = MIME_HDR;
  32939. }
  32940. start = 0;
  32941. lineLen = XSTRLEN(curLine);
  32942. if (lineLen == 0) {
  32943. ret = BAD_FUNC_ARG;
  32944. goto error;
  32945. }
  32946. for (pos = 0; pos < lineLen; pos++) {
  32947. char cur = curLine[pos];
  32948. if (mimeStatus == MIME_NAMEATTR && ((cur == ':' &&
  32949. mimeType == MIME_HDR) || (cur == '=' &&
  32950. mimeType == MIME_PARAM)) && pos >= 1) {
  32951. mimeStatus = MIME_BODYVAL;
  32952. end = pos-1;
  32953. if (nameAttr != NULL)
  32954. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  32955. ret = wc_MIME_header_strip(curLine, &nameAttr, start, end);
  32956. if (ret) {
  32957. goto error;
  32958. }
  32959. start = pos+1;
  32960. }
  32961. else if (mimeStatus == MIME_BODYVAL && cur == ';' && pos >= 1) {
  32962. end = pos-1;
  32963. if (bodyVal != NULL)
  32964. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  32965. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  32966. if (ret) {
  32967. goto error;
  32968. }
  32969. if (mimeType == MIME_HDR) {
  32970. nextHdr->name = nameAttr;
  32971. nameAttr = NULL;
  32972. nextHdr->body = bodyVal;
  32973. bodyVal = NULL;
  32974. nextHdr->next = curHdr;
  32975. curHdr = nextHdr;
  32976. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  32977. DYNAMIC_TYPE_PKCS7);
  32978. if (nextHdr == NULL) {
  32979. ret = MEMORY_E;
  32980. goto error;
  32981. }
  32982. XMEMSET(nextHdr, 0, (word32)sizeof(MimeHdr));
  32983. }
  32984. else {
  32985. nextParam->attribute = nameAttr;
  32986. nameAttr = NULL;
  32987. nextParam->value = bodyVal;
  32988. bodyVal = NULL;
  32989. nextParam->next = curHdr->params;
  32990. curHdr->params = nextParam;
  32991. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  32992. DYNAMIC_TYPE_PKCS7);
  32993. if (nextParam == NULL) {
  32994. ret = MEMORY_E;
  32995. goto error;
  32996. }
  32997. XMEMSET(nextParam, 0, (word32)sizeof(MimeParam));
  32998. }
  32999. mimeType = MIME_PARAM;
  33000. mimeStatus = MIME_NAMEATTR;
  33001. start = pos+1;
  33002. }
  33003. }
  33004. end = lineLen-1;
  33005. /* Omit newline characters. */
  33006. while ((curLine[end] == '\r' || curLine[end] == '\n') && end > 0) {
  33007. end--;
  33008. }
  33009. if (end >= start && mimeStatus == MIME_BODYVAL) {
  33010. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  33011. if (ret) {
  33012. goto error;
  33013. }
  33014. if (mimeType == MIME_HDR) {
  33015. nextHdr->name = nameAttr;
  33016. nameAttr = NULL;
  33017. nextHdr->body = bodyVal;
  33018. bodyVal = NULL;
  33019. nextHdr->next = curHdr;
  33020. curHdr = nextHdr;
  33021. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  33022. DYNAMIC_TYPE_PKCS7);
  33023. if (nextHdr == NULL) {
  33024. ret = MEMORY_E;
  33025. goto error;
  33026. }
  33027. XMEMSET(nextHdr, 0, (word32)sizeof(MimeHdr));
  33028. } else {
  33029. nextParam->attribute = nameAttr;
  33030. nameAttr = NULL;
  33031. nextParam->value = bodyVal;
  33032. bodyVal = NULL;
  33033. nextParam->next = curHdr->params;
  33034. curHdr->params = nextParam;
  33035. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  33036. DYNAMIC_TYPE_PKCS7);
  33037. if (nextParam == NULL) {
  33038. ret = MEMORY_E;
  33039. goto error;
  33040. }
  33041. XMEMSET(nextParam, 0, (word32)sizeof(MimeParam));
  33042. }
  33043. }
  33044. curLine = XSTRTOK(NULL, "\r\n", &ptr);
  33045. mimeStatus = MIME_NAMEATTR;
  33046. }
  33047. *headers = curHdr;
  33048. ret = 0; /* success if at this point */
  33049. error:
  33050. if (ret != 0)
  33051. wc_MIME_free_hdrs(curHdr);
  33052. wc_MIME_free_hdrs(nextHdr);
  33053. if (nameAttr != NULL)
  33054. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  33055. if (bodyVal != NULL)
  33056. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  33057. XFREE(nextParam, NULL, DYNAMIC_TYPE_PKCS7);
  33058. return ret;
  33059. }
  33060. /*****************************************************************************
  33061. * wc_MIME_header_strip - Reads the string in from indices start to end, strips
  33062. * out disallowed/separator characters and places the rest into *out.
  33063. *
  33064. * RETURNS:
  33065. * returns zero on success, non-zero on error.
  33066. */
  33067. int wc_MIME_header_strip(char* in, char** out, size_t start, size_t end)
  33068. {
  33069. size_t inPos = start;
  33070. size_t outPos = 0;
  33071. size_t inLen = 0;
  33072. if (end < start || in == NULL || out == NULL) {
  33073. return BAD_FUNC_ARG;
  33074. }
  33075. inLen = XSTRLEN(in);
  33076. if (start > inLen || end > inLen) {
  33077. return BAD_FUNC_ARG;
  33078. }
  33079. *out = (char*)XMALLOC(((end-start)+2)*sizeof(char), NULL,
  33080. DYNAMIC_TYPE_PKCS7);
  33081. if (*out == NULL) {
  33082. return MEMORY_E;
  33083. }
  33084. while (inPos <= end) {
  33085. if (in[inPos] >= MIME_HEADER_ASCII_MIN && in[inPos] <=
  33086. MIME_HEADER_ASCII_MAX && in[inPos] != ';' && in[inPos] != '\"') {
  33087. (*out)[outPos] = in[inPos];
  33088. outPos++;
  33089. }
  33090. inPos++;
  33091. }
  33092. (*out)[outPos] = '\0';
  33093. return 0;
  33094. }
  33095. /*****************************************************************************
  33096. * wc_MIME_find_header_name - Searches through all given headers until a header with
  33097. * a name matching the provided name is found.
  33098. *
  33099. * RETURNS:
  33100. * returns a pointer to the found header, if no match was found, returns NULL.
  33101. */
  33102. MimeHdr* wc_MIME_find_header_name(const char* name, MimeHdr* header)
  33103. {
  33104. while (header) {
  33105. if (!XSTRCMP(name, header->name)) {
  33106. return header;
  33107. }
  33108. header = header->next;
  33109. }
  33110. return header;
  33111. }
  33112. /*****************************************************************************
  33113. * wc_MIME_find_param_attr - Searches through all parameters until a parameter
  33114. * with a attribute matching the provided attribute is found.
  33115. *
  33116. * RETURNS:
  33117. * returns a pointer to the found parameter, if no match was found,
  33118. * returns NULL.
  33119. */
  33120. MimeParam* wc_MIME_find_param_attr(const char* attribute,
  33121. MimeParam* param)
  33122. {
  33123. while (param) {
  33124. if (!XSTRCMP(attribute, param->attribute)) {
  33125. return param;
  33126. }
  33127. param = param->next;
  33128. }
  33129. return param;
  33130. }
  33131. /*****************************************************************************
  33132. * wc_MIME_single_canonicalize - Canonicalize a line by converting the trailing
  33133. * line ending to CRLF.
  33134. *
  33135. * line - input line to canonicalize
  33136. * len - length of line in chars on input, length of output array on return
  33137. *
  33138. * RETURNS:
  33139. * returns a pointer to a canonicalized line on success, NULL on error.
  33140. */
  33141. char* wc_MIME_single_canonicalize(const char* line, word32* len)
  33142. {
  33143. size_t end = 0;
  33144. char* canonLine = NULL;
  33145. if (line == NULL || len == NULL || *len == 0) {
  33146. return NULL;
  33147. }
  33148. end = *len;
  33149. while (end >= 1 && ((line[end-1] == '\r') || (line[end-1] == '\n'))) {
  33150. end--;
  33151. }
  33152. /* Need 2 chars for \r\n and 1 for EOL */
  33153. canonLine = (char*)XMALLOC((end+3)*sizeof(char), NULL, DYNAMIC_TYPE_PKCS7);
  33154. if (canonLine == NULL) {
  33155. return NULL;
  33156. }
  33157. XMEMCPY(canonLine, line, end);
  33158. canonLine[end] = '\r';
  33159. canonLine[end+1] = '\n';
  33160. canonLine[end+2] = '\0';
  33161. *len = (word32)(end + 3);
  33162. return canonLine;
  33163. }
  33164. /*****************************************************************************
  33165. * wc_MIME_free_hdrs - Frees all MIME headers, parameters and strings starting from
  33166. * the provided header pointer.
  33167. *
  33168. * RETURNS:
  33169. * returns zero on success, non-zero on error.
  33170. */
  33171. int wc_MIME_free_hdrs(MimeHdr* head)
  33172. {
  33173. MimeHdr* curHdr = NULL;
  33174. MimeParam* curParam = NULL;
  33175. while (head) {
  33176. while (head->params) {
  33177. curParam = head->params;
  33178. head->params = head->params->next;
  33179. XFREE(curParam->attribute, NULL, DYNAMIC_TYPE_PKCS7);
  33180. XFREE(curParam->value, NULL, DYNAMIC_TYPE_PKCS7);
  33181. XFREE(curParam, NULL, DYNAMIC_TYPE_PKCS7);
  33182. }
  33183. curHdr = head;
  33184. head = head->next;
  33185. XFREE(curHdr->name, NULL, DYNAMIC_TYPE_PKCS7);
  33186. XFREE(curHdr->body, NULL, DYNAMIC_TYPE_PKCS7);
  33187. XFREE(curHdr, NULL, DYNAMIC_TYPE_PKCS7);
  33188. }
  33189. return 0;
  33190. }
  33191. #endif /* HAVE_SMIME */
  33192. #undef ERROR_OUT
  33193. #endif /* !NO_ASN */
  33194. #ifdef WOLFSSL_SEP
  33195. #endif /* WOLFSSL_SEP */