asn.c 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806
  1. /* asn.c
  2. *
  3. * Copyright (C) 2006-2023 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. /*
  22. * DESCRIPTION
  23. * This library provides the interface to Abstract Syntax Notation One (ASN.1)
  24. * objects.
  25. * ASN.1 is a standard interface description language for defining data
  26. * structures that can be serialized and deserialized in a cross-platform way.
  27. *
  28. * Encoding of ASN.1 is either using Basic Encoding Rules (BER) or
  29. * Distinguished Encoding Rules (DER). DER has only one possible encoding for a
  30. * ASN.1 description and the data.
  31. * Encode using DER and decode BER or DER.
  32. *
  33. * Provides routines to convert BER into DER. Replaces indefinite length
  34. * encoded items with explicit lengths.
  35. */
  36. #ifdef HAVE_CONFIG_H
  37. #include <config.h>
  38. #endif
  39. #include <wolfssl/wolfcrypt/settings.h>
  40. /*
  41. ASN Options:
  42. * NO_ASN_TIME_CHECK: Disables ASN time checks (avoiding the ASN_BEFORE_DATE_E
  43. * and ASN_AFTER_DATE_E errors). Safer ways to avoid date errors would be to
  44. * set the WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY flag when calling the _ex versions of
  45. * cert loading functions or to define the WOLFSSL_NO_OCSP_DATE_CHECK macro to
  46. * skip OCSP date errors. Defining NO_ASN_TIME_CHECK will skip ALL date checks
  47. * and could pose a security risk.
  48. * NO_ASN_TIME: Disables time parts of the ASN code for systems without an RTC
  49. or wishing to save space.
  50. * IGNORE_NAME_CONSTRAINTS: Skip ASN name checks.
  51. * ASN_DUMP_OID: Allows dump of OID information for debugging.
  52. * RSA_DECODE_EXTRA: Decodes extra information in RSA public key.
  53. * WOLFSSL_CERT_GEN: Cert generation. Saves extra certificate info in GetName.
  54. * WOLFSSL_NO_ASN_STRICT: Disable strict RFC compliance checks to
  55. restore 3.13.0 behavior.
  56. * WOLFSSL_NO_OCSP_OPTIONAL_CERTS: Skip optional OCSP certs (responder issuer
  57. must still be trusted)
  58. * WOLFSSL_NO_TRUSTED_CERTS_VERIFY: Workaround for situation where entire cert
  59. chain is not loaded. This only matches on subject and public key and
  60. does not perform a PKI validation, so it is not a secure solution.
  61. Only enabled for OCSP.
  62. * WOLFSSL_NO_OCSP_ISSUER_CHECK: Can be defined for backwards compatibility to
  63. disable checking of OCSP subject hash with issuer hash.
  64. * WOLFSSL_SMALL_CERT_VERIFY: Verify the certificate signature without using
  65. DecodedCert. Doubles up on some code but allows smaller dynamic memory
  66. usage.
  67. * WOLFSSL_NO_OCSP_DATE_CHECK: Disable date checks for OCSP responses. This
  68. may be required when the system's real-time clock is not very accurate.
  69. It is recommended to enforce the nonce check instead if possible.
  70. * WOLFSSL_FORCE_OCSP_NONCE_CHECK: Require nonces to be available in OCSP
  71. responses. The nonces are optional and may not be supported by all
  72. responders. If it can be ensured that the used responder sends nonces this
  73. option may improve security.
  74. * WOLFSSL_ASN_TEMPLATE: Encoding and decoding using a template.
  75. * WOLFSSL_DEBUG_ASN_TEMPLATE: Enables debugging output when using ASN.1
  76. templates.
  77. * WOLFSSL_ASN_TEMPLATE_TYPE_CHECK: Use ASN functions to better test compiler
  78. type issues for testing
  79. * CRLDP_VALIDATE_DATA: For ASN template only, validates the reason data
  80. * WOLFSSL_AKID_NAME: Enable support for full AuthorityKeyIdentifier extension.
  81. Only supports copying full AKID from an existing certificate.
  82. * WOLFSSL_CUSTOM_OID: Enable custom OID support for subject and request
  83. extensions
  84. * WOLFSSL_HAVE_ISSUER_NAMES: Store pointers to issuer name components and their
  85. lengths and encodings.
  86. * WOLFSSL_SUBJ_DIR_ATTR: Enable support for SubjectDirectoryAttributes
  87. extension.
  88. * WOLFSSL_SUBJ_INFO_ACC: Enable support for SubjectInfoAccess extension.
  89. * WOLFSSL_FPKI: Enable support for FPKI (Federal PKI) extensions.
  90. * WOLFSSL_CERT_NAME_ALL: Adds more certificate name capability at the
  91. cost of taking up more memory. Adds initials, givenname, dnQualifer for
  92. example.
  93. * WC_ASN_HASH_SHA256: Force use of SHA2-256 for the internal hash ID calcs.
  94. */
  95. #include <wolfssl/wolfcrypt/error-crypt.h>
  96. #ifndef NO_RSA
  97. #include <wolfssl/wolfcrypt/rsa.h>
  98. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  99. extern int wc_InitRsaHw(RsaKey* key);
  100. #endif
  101. #endif
  102. #ifndef NO_ASN
  103. #include <wolfssl/wolfcrypt/asn.h>
  104. #include <wolfssl/wolfcrypt/coding.h>
  105. #include <wolfssl/wolfcrypt/md2.h>
  106. #include <wolfssl/wolfcrypt/hmac.h>
  107. #include <wolfssl/wolfcrypt/pwdbased.h>
  108. #include <wolfssl/wolfcrypt/des3.h>
  109. #include <wolfssl/wolfcrypt/aes.h>
  110. #include <wolfssl/wolfcrypt/rc2.h>
  111. #include <wolfssl/wolfcrypt/wc_encrypt.h>
  112. #include <wolfssl/wolfcrypt/logging.h>
  113. #include <wolfssl/wolfcrypt/random.h>
  114. #include <wolfssl/wolfcrypt/hash.h>
  115. #ifdef NO_INLINE
  116. #include <wolfssl/wolfcrypt/misc.h>
  117. #else
  118. #define WOLFSSL_MISC_INCLUDED
  119. #include <wolfcrypt/src/misc.c>
  120. #endif
  121. #ifndef NO_RC4
  122. #include <wolfssl/wolfcrypt/arc4.h>
  123. #endif
  124. #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
  125. #include <wolfssl/wolfcrypt/sha512.h>
  126. #endif
  127. #ifndef NO_SHA256
  128. #include <wolfssl/wolfcrypt/sha256.h>
  129. #endif
  130. #ifdef HAVE_ECC
  131. #include <wolfssl/wolfcrypt/ecc.h>
  132. #endif
  133. #ifdef HAVE_ED25519
  134. #include <wolfssl/wolfcrypt/ed25519.h>
  135. #endif
  136. #ifdef HAVE_CURVE25519
  137. #include <wolfssl/wolfcrypt/curve25519.h>
  138. #endif
  139. #ifdef HAVE_ED448
  140. #include <wolfssl/wolfcrypt/ed448.h>
  141. #endif
  142. #ifdef HAVE_CURVE448
  143. #include <wolfssl/wolfcrypt/curve448.h>
  144. #endif
  145. #ifdef HAVE_PQC
  146. #if defined(HAVE_FALCON)
  147. #include <wolfssl/wolfcrypt/falcon.h>
  148. #endif
  149. #if defined(HAVE_DILITHIUM)
  150. #include <wolfssl/wolfcrypt/dilithium.h>
  151. #endif
  152. #if defined(HAVE_SPHINCS)
  153. #include <wolfssl/wolfcrypt/sphincs.h>
  154. #endif
  155. #endif
  156. #ifdef WOLFSSL_QNX_CAAM
  157. #include <wolfssl/wolfcrypt/port/caam/wolfcaam.h>
  158. #endif
  159. #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  160. #include <wolfssl/wolfcrypt/port/Renesas/renesas_cmn.h>
  161. #endif
  162. #ifndef NO_DSA
  163. #include <wolfssl/wolfcrypt/dsa.h>
  164. #else
  165. typedef void* DsaKey;
  166. #endif
  167. #ifdef WOLF_CRYPTO_CB
  168. #include <wolfssl/wolfcrypt/cryptocb.h>
  169. #endif
  170. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  171. #include <wolfssl/internal.h>
  172. #include <wolfssl/openssl/objects.h>
  173. #endif
  174. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  175. !defined(WOLFCRYPT_ONLY)
  176. #define WOLFSSL_X509_NAME_AVAILABLE
  177. #endif
  178. #ifdef _MSC_VER
  179. /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
  180. #pragma warning(disable: 4996)
  181. #endif
  182. #define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
  183. #if !defined(NO_SKID) && (!defined(HAVE_FIPS) || !defined(HAVE_FIPS_VERSION))
  184. #if !defined(HAVE_SELFTEST) || (defined(HAVE_SELFTEST) && \
  185. (!defined(HAVE_SELFTEST_VERSION) || \
  186. HAVE_SELFTEST_VERSION < 2))
  187. #ifndef WOLFSSL_AES_KEY_SIZE_ENUM
  188. #define WOLFSSL_AES_KEY_SIZE_ENUM
  189. enum Asn_Misc {
  190. AES_IV_SIZE = 16,
  191. AES_128_KEY_SIZE = 16,
  192. AES_192_KEY_SIZE = 24,
  193. AES_256_KEY_SIZE = 32
  194. };
  195. #endif
  196. #endif /* HAVE_SELFTEST */
  197. #endif
  198. #if defined(WOLFSSL_ASN_PRINT) || defined(WOLFSSL_DEBUG_ASN_TEMPLATE)
  199. /* String representations of tags. */
  200. static const char* tagString[4][32] = {
  201. /* Universal */
  202. {
  203. "EOC",
  204. "BOOLEAN",
  205. "INTEGER",
  206. "BIT STRING",
  207. "OCTET STRING",
  208. "NULL",
  209. "OBJECT ID",
  210. "ObjectDescriptor",
  211. "INSTANCE OF",
  212. "REAL",
  213. "ENUMERATED",
  214. "EMBEDDED PDV",
  215. "UT8String",
  216. "RELATIVE-OID",
  217. "(0x0e) 14",
  218. "(0x0f) 15",
  219. "SEQUENCE",
  220. "SET",
  221. "NumericString",
  222. "PrintableString",
  223. "T61String",
  224. "VideotexString",
  225. "IA5String",
  226. "UTCTime",
  227. "GeneralizedTime",
  228. "GraphicString",
  229. "ISO646String",
  230. "GeneralString",
  231. "UniversalString",
  232. "CHARACTER STRING",
  233. "BMPString",
  234. "(0x1f) 31",
  235. },
  236. /* Application */
  237. {
  238. "[A 0]", "[A 1]", "[A 2]", "[A 3]",
  239. "[A 4]", "[A 5]", "[A 6]", "[A 7]",
  240. "[A 8]", "[A 9]", "[A 10]", "[A 11]",
  241. "[A 12]", "[A 13]", "[A 14]", "[A 15]",
  242. "[A 16]", "[A 17]", "[A 18]", "[A 19]",
  243. "[A 20]", "[A 21]", "[A 22]", "[A 23]",
  244. "[A 24]", "[A 25]", "[A 26]", "[A 27]",
  245. "[A 28]", "[A 20]", "[A 30]", "[A 31]"
  246. },
  247. /* Context-Specific */
  248. {
  249. "[0]", "[1]", "[2]", "[3]", "[4]", "[5]", "[6]", "[7]",
  250. "[8]", "[9]", "[10]", "[11]", "[12]", "[13]", "[14]", "[15]",
  251. "[16]", "[17]", "[18]", "[19]", "[20]", "[21]", "[22]", "[23]",
  252. "[24]", "[25]", "[26]", "[27]", "[28]", "[20]", "[30]", "[31]"
  253. },
  254. /* Private */
  255. {
  256. "[P 0]", "[P 1]", "[P 2]", "[P 3]",
  257. "[P 4]", "[P 5]", "[P 6]", "[P 7]",
  258. "[P 8]", "[P 9]", "[P 10]", "[P 11]",
  259. "[P 12]", "[P 13]", "[P 14]", "[P 15]",
  260. "[P 16]", "[P 17]", "[P 18]", "[P 19]",
  261. "[P 20]", "[P 21]", "[P 22]", "[P 23]",
  262. "[P 24]", "[P 25]", "[P 26]", "[P 27]",
  263. "[P 28]", "[P 20]", "[P 30]", "[P 31]"
  264. }
  265. };
  266. /* Converts a tag byte to string.
  267. *
  268. * @param [in] tag BER tag value to interpret.
  269. * @return String corresponding to tag.
  270. */
  271. static const char* TagString(byte tag)
  272. {
  273. return tagString[tag >> 6][tag & ASN_TYPE_MASK];
  274. }
  275. #endif
  276. /* Calculates the minimum number of bytes required to encode the value.
  277. *
  278. * Only support up to 2^24-1.
  279. *
  280. * @param [in] value Value to be encoded.
  281. * @return Number of bytes to encode value.
  282. */
  283. static word32 BytePrecision(word32 value)
  284. {
  285. word32 i;
  286. for (i = (word32)sizeof(value) - 1; i; --i)
  287. if (value >> ((i - 1) * WOLFSSL_BIT_SIZE))
  288. break;
  289. return i;
  290. }
  291. /* DER encodes the length value in output buffer.
  292. *
  293. * 0 -> 2^7-1: <len byte>.
  294. * 2^7 -> : <0x80 + #bytes> <len big-endian bytes>
  295. *
  296. * @param [in] length Value to encode.
  297. * @param [in, out] output Buffer to encode into.
  298. * @return Number of bytes used in encoding.
  299. */
  300. WOLFSSL_LOCAL word32 SetASNLength(word32 length, byte* output)
  301. {
  302. word32 i = 0;
  303. if (length < ASN_LONG_LENGTH)
  304. output[i++] = (byte)length;
  305. else {
  306. word32 j;
  307. output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);
  308. for (j = BytePrecision(length); j; --j) {
  309. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  310. i++;
  311. }
  312. }
  313. return i;
  314. }
  315. #ifdef WOLFSSL_ASN_TEMPLATE
  316. /* Calculate the size of a DER encoded length value.
  317. *
  318. * 0 -> 2^7-1: <length byte>.
  319. * 2^7 -> : <0x80 + #bytes> <big-endian length bytes>
  320. *
  321. * @param [in] length Value to encode.
  322. * @return Number of bytes required to encode.
  323. */
  324. static word32 SizeASNLength(word32 length)
  325. {
  326. return 1 + ((length >= ASN_LONG_LENGTH) ? BytePrecision(length) : 0);
  327. }
  328. /* Calculate the size of a DER encoded header.
  329. *
  330. * Header = Tag | Encoded length
  331. *
  332. * @param [in] length Length value to encode.
  333. * @return Number of bytes required to encode a DER header.
  334. */
  335. #define SizeASNHeader(length) \
  336. (1 + SizeASNLength(length))
  337. #endif
  338. #ifdef WOLFSSL_ASN_TEMPLATE
  339. #ifdef WOLFSSL_SMALL_STACK
  340. /* Declare the variable that is the dynamic data for decoding BER data.
  341. *
  342. * @param [in] name Variable name to declare.
  343. * @param [in] cnt Number of elements required.
  344. */
  345. #define DECL_ASNGETDATA(name, cnt) \
  346. ASNGetData* name = NULL
  347. /* Allocates the dynamic BER decoding data.
  348. *
  349. * @param [in] name Variable name to declare.
  350. * @param [in] cnt Number of elements required.
  351. * @param [in, out] err Error variable.
  352. * @param [in] heap Dynamic memory allocation hint.
  353. */
  354. #define ALLOC_ASNGETDATA(name, cnt, err, heap) \
  355. do { \
  356. if ((err) == 0) { \
  357. (name) = (ASNGetData*)XMALLOC(sizeof(ASNGetData) * (cnt), (heap), \
  358. DYNAMIC_TYPE_TMP_BUFFER); \
  359. if ((name) == NULL) { \
  360. (err) = MEMORY_E; \
  361. } \
  362. } \
  363. } \
  364. while (0)
  365. /* Allocates the dynamic BER decoding data and clears the memory.
  366. *
  367. * @param [in] name Variable name to declare.
  368. * @param [in] cnt Number of elements required.
  369. * @param [in, out] err Error variable.
  370. * @param [in] heap Dynamic memory allocation hint.
  371. */
  372. #define CALLOC_ASNGETDATA(name, cnt, err, heap) \
  373. do { \
  374. ALLOC_ASNGETDATA(name, cnt, err, heap); \
  375. if ((err) == 0) { \
  376. XMEMSET((name), 0, sizeof(ASNGetData) * (cnt)); \
  377. } \
  378. } \
  379. while (0)
  380. /* Disposes of the dynamic BER decoding data.
  381. *
  382. * @param [in] name Variable name to declare.
  383. * @param [in] heap Dynamic memory allocation hint.
  384. */
  385. #define FREE_ASNGETDATA(name, heap) \
  386. do { \
  387. if ((name) != NULL) { \
  388. XFREE((name), (heap), DYNAMIC_TYPE_TMP_BUFFER); \
  389. } \
  390. } \
  391. while (0)
  392. /* Declare the variable that is the dynamic data for encoding DER data.
  393. *
  394. * @param [in] name Variable name to declare.
  395. * @param [in] cnt Number of elements required.
  396. */
  397. #define DECL_ASNSETDATA(name, cnt) \
  398. ASNSetData* name = NULL
  399. /* Allocates the dynamic DER encoding data.
  400. *
  401. * @param [in] name Variable name to declare.
  402. * @param [in] cnt Number of elements required.
  403. * @param [in, out] err Error variable.
  404. * @param [in] heap Dynamic memory allocation hint.
  405. */
  406. #define ALLOC_ASNSETDATA(name, cnt, err, heap) \
  407. do { \
  408. if ((err) == 0) { \
  409. (name) = (ASNSetData*)XMALLOC(sizeof(ASNGetData) * (cnt), (heap), \
  410. DYNAMIC_TYPE_TMP_BUFFER); \
  411. if ((name) == NULL) { \
  412. (err) = MEMORY_E; \
  413. } \
  414. } \
  415. } \
  416. while (0)
  417. /* Allocates the dynamic DER encoding data and clears the memory.
  418. *
  419. * @param [in] name Variable name to declare.
  420. * @param [in] cnt Number of elements required.
  421. * @param [in, out] err Error variable.
  422. * @param [in] heap Dynamic memory allocation hint.
  423. */
  424. #define CALLOC_ASNSETDATA(name, cnt, err, heap) \
  425. do { \
  426. ALLOC_ASNSETDATA(name, cnt, err, heap); \
  427. if ((err) == 0) { \
  428. XMEMSET(name, 0, sizeof(ASNSetData) * (cnt)); \
  429. } \
  430. } \
  431. while (0)
  432. /* Disposes of the dynamic DER encoding data.
  433. *
  434. * @param [in] name Variable name to declare.
  435. * @param [in] heap Dynamic memory allocation hint.
  436. */
  437. #define FREE_ASNSETDATA(name, heap) \
  438. do { \
  439. if ((name) != NULL) { \
  440. XFREE(name, heap, DYNAMIC_TYPE_TMP_BUFFER); \
  441. } \
  442. } \
  443. while (0)
  444. #else
  445. /* Declare the variable that is the dynamic data for decoding BER data.
  446. *
  447. * @param [in] name Variable name to declare.
  448. * @param [in] cnt Number of elements required.
  449. */
  450. #define DECL_ASNGETDATA(name, cnt) \
  451. ASNGetData name[cnt]
  452. /* No implementation as declaration is static.
  453. *
  454. * @param [in] name Variable name to declare.
  455. * @param [in] cnt Number of elements required.
  456. * @param [in, out] err Error variable.
  457. * @param [in] heap Dynamic memory allocation hint.
  458. */
  459. #define ALLOC_ASNGETDATA(name, cnt, err, heap)
  460. /* Clears the memory of the dynamic BER encoding data.
  461. *
  462. * @param [in] name Variable name to declare.
  463. * @param [in] cnt Number of elements required.
  464. * @param [in, out] err Error variable.
  465. * @param [in] heap Dynamic memory allocation hint.
  466. */
  467. #define CALLOC_ASNGETDATA(name, cnt, err, heap) \
  468. XMEMSET(name, 0, sizeof(name))
  469. /* No implementation as declaration is static.
  470. *
  471. * @param [in] name Variable name to declare.
  472. * @param [in] heap Dynamic memory allocation hint.
  473. */
  474. #define FREE_ASNGETDATA(name, heap)
  475. /* Declare the variable that is the dynamic data for encoding DER data.
  476. *
  477. * @param [in] name Variable name to declare.
  478. * @param [in] cnt Number of elements required.
  479. */
  480. #define DECL_ASNSETDATA(name, cnt) \
  481. ASNSetData name[cnt]
  482. /* No implementation as declaration is static.
  483. *
  484. * @param [in] name Variable name to declare.
  485. * @param [in] cnt Number of elements required.
  486. * @param [in, out] err Error variable.
  487. * @param [in] heap Dynamic memory allocation hint.
  488. */
  489. #define ALLOC_ASNSETDATA(name, cnt, err, heap)
  490. /* Clears the memory of the dynamic BER encoding data.
  491. *
  492. * @param [in] name Variable name to declare.
  493. * @param [in] cnt Number of elements required.
  494. * @param [in, out] err Error variable.
  495. * @param [in] heap Dynamic memory allocation hint.
  496. */
  497. #define CALLOC_ASNSETDATA(name, cnt, err, heap) \
  498. XMEMSET(name, 0, sizeof(name))
  499. /* No implementation as declaration is static.
  500. *
  501. * @param [in] name Variable name to declare.
  502. * @param [in] heap Dynamic memory allocation hint.
  503. */
  504. #define FREE_ASNSETDATA(name, heap)
  505. #endif
  506. #ifdef DEBUG_WOLFSSL
  507. /* Enable this when debugging the parsing or creation of ASN.1 data. */
  508. #if 0
  509. #define WOLFSSL_DEBUG_ASN_TEMPLATE
  510. #endif
  511. #endif
  512. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  513. #include <stdarg.h>
  514. /* Log a message that has the printf format string.
  515. *
  516. * @param [in] <va_args> printf style arguments.
  517. */
  518. #define WOLFSSL_MSG_VSNPRINTF(...) \
  519. do { \
  520. char line[81]; \
  521. snprintf(line, sizeof(line) - 1, __VA_ARGS__); \
  522. line[sizeof(line) - 1] = '\0'; \
  523. WOLFSSL_MSG(line); \
  524. } \
  525. while (0)
  526. #endif
  527. /* Returns whether ASN.1 item is an integer and the Most-Significant Bit is set.
  528. *
  529. * @param [in] asn ASN.1 items to encode.
  530. * @param [in] data_a Data to place in each item. Lengths set were not known.
  531. * @param [in] i Index of item to check.
  532. * @return 1 when ASN.1 item is an integer and MSB is 1.
  533. * @erturn 0 otherwise.
  534. */
  535. #define ASNIntMSBSet(asn, data_a, i) \
  536. (((asn)[i].tag == ASN_INTEGER) && \
  537. ((data_a)[i].data.buffer.data != NULL && \
  538. ((data_a)[i].data.buffer.data[0] & 0x80) == 0x80))
  539. /* Calculate the size of a DER encoded number.
  540. *
  541. * @param [in] n Number to be encoded.
  542. * @param [in] bits Maximum number of bits to encode.
  543. * @param [in] tag BER tag e.g. INTEGER, BIT_STRING, etc.
  544. * @return Number of bytes to the ASN.1 item.
  545. */
  546. static word32 SizeASN_Num(word32 n, int bits, byte tag)
  547. {
  548. int j;
  549. word32 len;
  550. len = 1 + 1 + (word32)bits / 8;
  551. /* Discover actual size by checking for high zeros. */
  552. for (j = bits - 8; j > 0; j -= 8) {
  553. if (n >> j)
  554. break;
  555. len--;
  556. }
  557. if (tag == ASN_BIT_STRING)
  558. len++;
  559. else if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80))
  560. len++;
  561. return len;
  562. }
  563. /* Calculate the size of the data in the constructed item based on the
  564. * length of the ASN.1 items below.
  565. *
  566. * @param [in] asn ASN.1 items to encode.
  567. * @param [in, out] data Data to place in each item. Lengths set were not
  568. * known.
  569. * @param [in] idx Index of item working on.
  570. */
  571. static void SizeASN_CalcDataLength(const ASNItem* asn, ASNSetData *data,
  572. int idx, int max)
  573. {
  574. int j;
  575. data[idx].data.buffer.length = 0;
  576. /* Sum the item length of all items underneath. */
  577. for (j = idx + 1; j < max; j++) {
  578. /* Stop looking if the next ASN.1 is same level or higher. */
  579. if (asn[j].depth <= asn[idx].depth)
  580. break;
  581. /* Only add in length if it is one level below. */
  582. if (asn[j].depth - 1 == asn[idx].depth) {
  583. data[idx].data.buffer.length += data[j].length;
  584. /* The length of a header only item doesn't include the data unless
  585. * a replacement buffer is supplied.
  586. */
  587. if (asn[j].headerOnly && data[j].data.buffer.data == NULL &&
  588. data[j].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
  589. data[idx].data.buffer.length += data[j].data.buffer.length;
  590. }
  591. }
  592. }
  593. }
  594. /* Calculate the size of the DER encoding.
  595. *
  596. * Call SetASN_Items() to write encoding to a buffer.
  597. *
  598. * @param [in] asn ASN.1 items to encode.
  599. * @param [in, out] data Data to place in each item. Lengths set where not
  600. * known.
  601. * @param [in] count Count of items to encode.
  602. * @param [out] encSz Length of the DER encoding.
  603. * @return 0 on success.
  604. * @return BAD_STATE_E when the data type is not supported.
  605. */
  606. int SizeASN_Items(const ASNItem* asn, ASNSetData *data, int count, int* encSz)
  607. {
  608. int i;
  609. word32 sz = 0;
  610. word32 len;
  611. word32 dataLen;
  612. int length;
  613. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  614. WOLFSSL_ENTER("SizeASN_Items");
  615. #endif
  616. for (i = count - 1; i >= 0; i--) {
  617. /* Skip this ASN.1 item when encoding. */
  618. if (data[i].noOut) {
  619. /* Set the offset to the current size - used in writing DER. */
  620. data[i].offset = sz;
  621. continue;
  622. }
  623. len = 0;
  624. switch (data[i].dataType) {
  625. /* Calculate the size of the number of different sizes. */
  626. case ASN_DATA_TYPE_WORD8:
  627. len = SizeASN_Num(data[i].data.u8, 8, asn[i].tag);
  628. break;
  629. case ASN_DATA_TYPE_WORD16:
  630. len = SizeASN_Num(data[i].data.u16, 16, asn[i].tag);
  631. break;
  632. #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
  633. /* Not used yet! */
  634. case ASN_DATA_TYPE_WORD32:
  635. len = SizeASN_Num(data[i].data.u32, 32, asn[i].tag);
  636. break;
  637. #endif
  638. case ASN_DATA_TYPE_MP:
  639. /* Calculate the size of the MP integer data. */
  640. length = mp_unsigned_bin_size(data[i].data.mp);
  641. length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
  642. len = (word32)SizeASNHeader((word32)length) + (word32)length;
  643. break;
  644. case ASN_DATA_TYPE_REPLACE_BUFFER:
  645. /* Buffer is put in directly - use the length. */
  646. len = data[i].data.buffer.length;
  647. break;
  648. case ASN_DATA_TYPE_NONE:
  649. /* Calculate the size based on the data to be included.
  650. * Mostly used for constructed items.
  651. */
  652. if (asn[i].headerOnly) {
  653. if (data[i].data.buffer.data != NULL) {
  654. /* Force all child nodes to be ignored. Buffer
  655. * overwrites children. */
  656. {
  657. int ii;
  658. for (ii = i + 1; ii < count; ii++) {
  659. if (asn[ii].depth <= asn[i].depth)
  660. break;
  661. sz -= data[ii].length;
  662. data[ii].noOut = 1;
  663. }
  664. }
  665. }
  666. else {
  667. /* Calculate data length from items below if no buffer
  668. * supplied. */
  669. SizeASN_CalcDataLength(asn, data, i, count);
  670. }
  671. }
  672. if (asn[i].tag == ASN_BOOLEAN) {
  673. dataLen = 1;
  674. }
  675. else {
  676. dataLen = data[i].data.buffer.length;
  677. }
  678. /* BIT_STRING and INTEGER have one byte prepended. */
  679. if ((asn[i].tag == ASN_BIT_STRING) ||
  680. ASNIntMSBSet(asn, data, i)) {
  681. dataLen++;
  682. /* ASN.1 items are below and cannot include extra byte. */
  683. if (asn[i].headerOnly) {
  684. len++;
  685. }
  686. }
  687. /* Add in the size of tag and length. */
  688. len += SizeASNHeader(dataLen);
  689. /* Include data in length if not header only or if
  690. * buffer supplied. */
  691. if (!asn[i].headerOnly || data[i].data.buffer.data != NULL) {
  692. len += dataLen;
  693. }
  694. break;
  695. #ifdef DEBUG_WOLFSSL
  696. default:
  697. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  698. WOLFSSL_MSG_VSNPRINTF("%2d: %d", i, data[i].dataType);
  699. WOLFSSL_MSG("Bad data type");
  700. #endif
  701. return BAD_STATE_E;
  702. #endif
  703. }
  704. /* Set the total length of the item. */
  705. data[i].length = len;
  706. /* Add length to total size. */
  707. sz += len;
  708. /* Set the offset to the current size - used in writing DER. */
  709. data[i].offset = sz;
  710. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  711. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  712. data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
  713. asn[i].depth, "", TagString(asn[i].tag));
  714. #endif
  715. }
  716. *encSz = (int)sz;
  717. return 0;
  718. }
  719. /* Create the DER encoding of a number.
  720. *
  721. * Assumes that the out buffer is large enough for encoding.
  722. *
  723. * @param [in] n Number to be encoded.
  724. * @param [in] bits Maximum number of bits to encode.
  725. * @param [in] tag DER tag e.g. INTEGER, BIT_STRING, etc.
  726. */
  727. static void SetASN_Num(word32 n, int bits, byte* out, byte tag)
  728. {
  729. int j;
  730. word32 idx;
  731. byte len;
  732. /* Encoding: Tag (1 byte) | Length (1 byte) | Data (number) */
  733. /* Data will start at index 2 unless BIT_STRING or INTEGER */
  734. idx = 2;
  735. /* Set the length of the number based on maximum bit length. */
  736. len = (byte)(bits / 8);
  737. /* Discover actual size by checking for leading zero bytes. */
  738. for (j = bits - 8; j > 0; j -= 8) {
  739. if ((n >> j) != 0) {
  740. break;
  741. }
  742. len--;
  743. }
  744. /* Keep j, index of first non-zero byte, for writing out. */
  745. /* A BIT_STRING has the number of unused bits in last byte prepended to
  746. * data.
  747. */
  748. if (tag == ASN_BIT_STRING) {
  749. byte unusedBits = 0;
  750. byte lastByte = (byte)(n >> j);
  751. /* Quick check last bit. */
  752. if ((lastByte & 0x01) == 0x00) {
  753. unusedBits++;
  754. /* Check each bit for first least significant bit set. */
  755. while (((lastByte >> unusedBits) & 0x01) == 0x00)
  756. unusedBits++;
  757. }
  758. /* Add unused bits byte. */
  759. len++;
  760. out[idx++] = unusedBits;
  761. }
  762. /* An INTEGER has a prepended byte if MSB of number is 1 - makes encoded
  763. * value positive. */
  764. if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80)) {
  765. len++;
  766. out[idx++] = 0;
  767. }
  768. /* Go back and put in length. */
  769. out[1] = len;
  770. /* Place in the required bytes of the number. */
  771. for (; j >= 0; j -= 8)
  772. out[idx++] = (byte)(n >> j);
  773. }
  774. /* Creates the DER encoding of the ASN.1 items.
  775. *
  776. * Assumes the output buffer is large enough to hold encoding.
  777. * Must call SizeASN_Items() to determine size of encoding and offsets.
  778. *
  779. * @param [in] asn ASN.1 items to encode.
  780. * @param [in] data Data to place in each item.
  781. * @param [in] count Count of items to encode.
  782. * @param [in, out] output Buffer to write encoding into.
  783. * @return Size of the DER encoding in bytes.
  784. */
  785. int SetASN_Items(const ASNItem* asn, ASNSetData *data, int count, byte* output)
  786. {
  787. int i;
  788. int length;
  789. int err;
  790. word32 sz;
  791. word32 idx;
  792. byte* out;
  793. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  794. WOLFSSL_ENTER("SetASN_Items");
  795. #endif
  796. /* Offset of first item is the total length.
  797. * SizeASN_Items() calculated this. */
  798. sz = data[0].offset;
  799. /* Write out each item. */
  800. for (i = 0; i < count; i++) {
  801. /* Skip items not writing out. */
  802. if (data[i].noOut)
  803. continue;
  804. /* Start position to write item based on reverse offsets. */
  805. out = output + sz - data[i].offset;
  806. /* Index from start of item out. */
  807. idx = 0;
  808. if (data[i].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
  809. /* Put in the tag - not dumping in DER from buffer. */
  810. out[idx++] = asn[i].tag |
  811. (asn[i].constructed ? ASN_CONSTRUCTED : 0);
  812. }
  813. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  814. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  815. sz - data[i].offset,
  816. data[i].length, asn[i].constructed ? '+' : ' ', asn[i].depth,
  817. "", TagString(asn[i].tag));
  818. #endif
  819. switch (data[i].dataType) {
  820. /* Write out the length and data of a number. */
  821. case ASN_DATA_TYPE_WORD8:
  822. SetASN_Num(data[i].data.u8, 8, out, asn[i].tag);
  823. break;
  824. case ASN_DATA_TYPE_WORD16:
  825. SetASN_Num(data[i].data.u16, 16, out, asn[i].tag);
  826. break;
  827. #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
  828. /* Not used yet! */
  829. case ASN_DATA_TYPE_WORD32:
  830. SetASN_Num(data[i].data.u32, 32, out, asn[i].tag);
  831. break;
  832. #endif
  833. /* Write out the length and data of a multi-precision number. */
  834. case ASN_DATA_TYPE_MP:
  835. /* Get length in bytes. */
  836. length = mp_unsigned_bin_size(data[i].data.mp);
  837. /* Add one for leading zero to make encoding a positive num. */
  838. length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
  839. /* Write out length. */
  840. idx += SetASNLength((word32)length, out + idx);
  841. /* Write out leading zero to make positive. */
  842. if (mp_leading_bit(data[i].data.mp)) {
  843. out[idx++] = 0;
  844. }
  845. /* Encode number in big-endian byte array. */
  846. err = mp_to_unsigned_bin(data[i].data.mp, out + idx);
  847. if (err != MP_OKAY) {
  848. WOLFSSL_MSG("SetASN_Items: Failed to write mp_int");
  849. return MP_TO_E;
  850. }
  851. break;
  852. case ASN_DATA_TYPE_REPLACE_BUFFER:
  853. if (data[i].data.buffer.data == NULL) {
  854. /* Return pointer for caller to use. */
  855. data[i].data.buffer.data = out + idx;
  856. }
  857. else {
  858. /* Dump in the DER encoded data. */
  859. XMEMCPY(out + idx, data[i].data.buffer.data,
  860. data[i].data.buffer.length);
  861. }
  862. break;
  863. case ASN_DATA_TYPE_NONE:
  864. if (asn[i].tag == ASN_BOOLEAN) {
  865. /* Always one byte of data. */
  866. out[idx++] = 1;
  867. /* TRUE = 0xff, FALSE = 0x00 */
  868. out[idx] = data[i].data.u8 ? 0xffU : 0x00U;
  869. }
  870. else if (asn[i].tag == ASN_TAG_NULL) {
  871. /* NULL tag is always a zero length item. */
  872. out[idx] = 0;
  873. }
  874. else {
  875. word32 dataLen = data[i].data.buffer.length;
  876. /* Add one to data length for BIT_STRING unused bits and
  877. * INTEGER leading zero to make positive.
  878. */
  879. if ((asn[i].tag == ASN_BIT_STRING) ||
  880. ASNIntMSBSet(asn, data, i)) {
  881. dataLen++;
  882. }
  883. /* Write out length. */
  884. idx += SetASNLength(dataLen, out + idx);
  885. if ((asn[i].tag == ASN_BIT_STRING) ||
  886. ASNIntMSBSet(asn, data, i)) {
  887. /* Write out leading byte. BIT_STRING has no unused bits
  888. * - use number data types if needed. */
  889. out[idx++] = 0x00;
  890. }
  891. /* Record pointer for caller if data not supplied. */
  892. if (data[i].data.buffer.data == NULL) {
  893. data[i].data.buffer.data = out + idx;
  894. }
  895. /* Copy supplied data if not putting out header only or
  896. * if buffer supplied. */
  897. else if (!asn[i].headerOnly ||
  898. data[i].data.buffer.data != NULL) {
  899. /* Allow data to come from output buffer. */
  900. XMEMMOVE(out + idx, data[i].data.buffer.data,
  901. data[i].data.buffer.length);
  902. }
  903. }
  904. break;
  905. #ifdef DEBUG_WOLFSSL
  906. default:
  907. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  908. WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data[i].dataType);
  909. #endif
  910. return BAD_STATE_E;
  911. #endif
  912. }
  913. }
  914. return (int)sz;
  915. }
  916. static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
  917. word32 oidType, int length);
  918. /* Maximum supported depth in ASN.1 description. */
  919. #define GET_ASN_MAX_DEPTH 7
  920. /* Maximum number of checked numbered choices. Only one of the items with the
  921. * number is allowed.
  922. */
  923. #define GET_ASN_MAX_CHOICES 2
  924. /* Use existing function to decode BER length encoding. */
  925. #define GetASN_Length GetLength_ex
  926. /* Check an INTEGER's first byte - must be a positive number.
  927. *
  928. * @param [in] input BER encoded data.
  929. * @param [in] idx Index of BIT_STRING data.
  930. * @param [in] length Length of input data.
  931. * @param [in] positive Indicates number must be positive.
  932. * @return 0 on success.
  933. * @return ASN_PARSE_E when 0 is not required but seen.
  934. * @return ASN_EXPECT_0_E when 0 is required and not seen.
  935. */
  936. static int GetASN_Integer(const byte* input, word32 idx, int length,
  937. int positive)
  938. {
  939. #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) || \
  940. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  941. /* Check contents consist of one or more octets. */
  942. if (length == 0) {
  943. WOLFSSL_MSG("Zero length INTEGER not allowed");
  944. return ASN_PARSE_E;
  945. }
  946. #endif
  947. if (input[idx] == 0) {
  948. /* Check leading zero byte required. */
  949. if ((length > 1) && ((input[idx + 1] & 0x80) == 0)) {
  950. WOLFSSL_MSG("Zero not required on INTEGER");
  951. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  952. return ASN_PARSE_E;
  953. #endif
  954. }
  955. }
  956. /* Check whether a leading zero byte was required. */
  957. else if (positive && (input[idx] & 0x80)) {
  958. WOLFSSL_MSG("INTEGER is negative");
  959. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  960. return ASN_EXPECT_0_E;
  961. #endif /* WOLFSSL_ASN_INT_LEAD_0_ANY */
  962. }
  963. return 0;
  964. }
  965. /* Check a BIT_STRING's first byte - unused bits.
  966. *
  967. * @param [in] input BER encoded data.
  968. * @param [in] idx Index of BIT_STRING data.
  969. * @param [in] length Length of input data.
  970. * @return 0 on success.
  971. * @return ASN_PARSE_E when unused bits is invalid.
  972. */
  973. static int GetASN_BitString(const byte* input, word32 idx, int length)
  974. {
  975. #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) || \
  976. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  977. /* Check contents consist of one or more octets. */
  978. if (length == 0) {
  979. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  980. WOLFSSL_MSG("Zero length BIT STRING not allowed");
  981. #endif
  982. return ASN_PARSE_E;
  983. }
  984. #endif
  985. /* Ensure unused bits value is valid range. */
  986. if (input[idx] > 7) {
  987. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  988. WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits too big: %d > 7",
  989. input[idx]);
  990. #endif
  991. return ASN_PARSE_E;
  992. }
  993. /* Ensure unused bits are zero. */
  994. if ((byte)(input[idx + (word32)length - 1] << (8 - input[idx])) != 0) {
  995. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  996. WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits used: %d %02x",
  997. input[idx], input[idx + length - 1]);
  998. #endif
  999. return ASN_PARSE_E;
  1000. }
  1001. return 0;
  1002. }
  1003. /* Get the ASN.1 items from the BER encoding.
  1004. *
  1005. * @param [in] asn ASN.1 item expected.
  1006. * @param [in] data Data array to place found item into.
  1007. * @param [in] input BER encoded data.
  1008. * @param [in] idx Starting index of item data.
  1009. * @param [in] len Length of input buffer upto end of this item's data.
  1010. * @param [in] zeroPadded INTEGER was zero padded to make positive.
  1011. * @return 0 on success.
  1012. * @return ASN_PARSE_E when BER encoded data is invalid.
  1013. * @return ASN_EXPECT_0_E when NULL tagged item has a non-zero length.
  1014. * @return MP_INIT_E when the unable to initialize an mp_int.
  1015. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1016. * @return BAD_STATE_E when the data type is not supported.
  1017. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  1018. */
  1019. static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data,
  1020. const byte* input, word32 idx, int len,
  1021. int zeroPadded)
  1022. {
  1023. int i;
  1024. int err;
  1025. /* Parse data based on data type to extract. */
  1026. switch (data->dataType) {
  1027. /* Parse a data into a number of specified bits. */
  1028. case ASN_DATA_TYPE_WORD8:
  1029. /* Check data is small enough to fit. */
  1030. if (len != 1) {
  1031. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1032. WOLFSSL_MSG_VSNPRINTF("Expecting one byte: %d", len);
  1033. #endif
  1034. return ASN_PARSE_E;
  1035. }
  1036. /* Fill number with all of data. */
  1037. *data->data.u8 = input[idx];
  1038. break;
  1039. case ASN_DATA_TYPE_WORD16:
  1040. /* Check data is small enough to fit. */
  1041. if (len == 0 || len > 2) {
  1042. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1043. WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", len);
  1044. #endif
  1045. return ASN_PARSE_E;
  1046. }
  1047. /* Fill number with all of data. */
  1048. *data->data.u16 = 0;
  1049. for (i = 0; i < len; i++) {
  1050. *data->data.u16 <<= 8;
  1051. *data->data.u16 |= input[idx + (word32)i] ;
  1052. }
  1053. break;
  1054. case ASN_DATA_TYPE_WORD32:
  1055. /* Check data is small enough to fit. */
  1056. if (len == 0 || len > 4) {
  1057. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1058. WOLFSSL_MSG_VSNPRINTF("Expecting 1 to 4 bytes: %d", len);
  1059. #endif
  1060. return ASN_PARSE_E;
  1061. }
  1062. /* Fill number with all of data. */
  1063. *data->data.u32 = 0;
  1064. for (i = 0; i < len; i++) {
  1065. *data->data.u32 <<= 8;
  1066. *data->data.u32 |= input[idx + (word32)i] ;
  1067. }
  1068. break;
  1069. case ASN_DATA_TYPE_BUFFER:
  1070. /* Check buffer is big enough to hold data. */
  1071. if (len > (int)*data->data.buffer.length) {
  1072. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1073. WOLFSSL_MSG_VSNPRINTF("Buffer too small for data: %d %d", len,
  1074. *data->data.buffer.length);
  1075. #endif
  1076. return ASN_PARSE_E;
  1077. }
  1078. /* Copy in data and record actual length seen. */
  1079. XMEMCPY(data->data.buffer.data, input + idx, (size_t)len);
  1080. *data->data.buffer.length = (word32)len;
  1081. break;
  1082. case ASN_DATA_TYPE_EXP_BUFFER:
  1083. /* Check data is same size expected. */
  1084. if (len != (int)data->data.ref.length) {
  1085. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1086. WOLFSSL_MSG_VSNPRINTF("Data not expected length: %d %d", len,
  1087. data->data.ref.length);
  1088. #endif
  1089. return ASN_PARSE_E;
  1090. }
  1091. /* Check data is same as expected. */
  1092. if (XMEMCMP(data->data.ref.data, input + idx, (size_t)len) != 0) {
  1093. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1094. WOLFSSL_MSG("Data not as expected");
  1095. #endif
  1096. return ASN_PARSE_E;
  1097. }
  1098. break;
  1099. case ASN_DATA_TYPE_MP:
  1100. case ASN_DATA_TYPE_MP_POS_NEG:
  1101. /* Initialize mp_int and read in big-endian byte array. */
  1102. if (mp_init(data->data.mp) != MP_OKAY) {
  1103. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1104. WOLFSSL_MSG_VSNPRINTF("Failed to init mp: %p", data->data.mp);
  1105. #endif
  1106. return MP_INIT_E;
  1107. }
  1108. FALL_THROUGH;
  1109. case ASN_DATA_TYPE_MP_INITED:
  1110. err = mp_read_unsigned_bin(data->data.mp, (byte*)input + idx,
  1111. (word32)len);
  1112. if (err != 0) {
  1113. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1114. WOLFSSL_MSG_VSNPRINTF("Failed to read mp: %d", err);
  1115. #endif
  1116. mp_clear(data->data.mp);
  1117. return ASN_GETINT_E;
  1118. }
  1119. #ifdef HAVE_WOLF_BIGINT
  1120. err = wc_bigint_from_unsigned_bin(&data->data.mp->raw, input + idx,
  1121. len);
  1122. if (err != 0) {
  1123. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1124. WOLFSSL_MSG_VSNPRINTF("Failed to create bigint: %d", err);
  1125. #endif
  1126. mp_clear(data->data.mp);
  1127. return ASN_GETINT_E;
  1128. }
  1129. #endif /* HAVE_WOLF_BIGINT */
  1130. #ifdef WOLFSSL_SP_INT_NEGATIVE
  1131. /* Don't always read as positive. */
  1132. if ((data->dataType == ASN_DATA_TYPE_MP_POS_NEG) && (!zeroPadded) &&
  1133. (input[idx] & 0x80)) {
  1134. #ifdef MP_NEG
  1135. data->data.mp->sign = MP_NEG;
  1136. #else
  1137. #ifdef OPENSSL_EXTRA
  1138. /* public API wolfSSL_ASN1_INTEGER_get() depends
  1139. * indirectly on negative bignum handling here.
  1140. */
  1141. #error OPENSSL_EXTRA requires negative bignum support.
  1142. #endif
  1143. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1144. WOLFSSL_MSG_VSNPRINTF("ASN negative integer without bignum support.");
  1145. #endif
  1146. mp_clear(data->data.mp);
  1147. return ASN_GETINT_E;
  1148. #endif
  1149. }
  1150. #else
  1151. (void)zeroPadded;
  1152. #endif
  1153. break;
  1154. case ASN_DATA_TYPE_CHOICE:
  1155. /* Check if tag matched any of the choices specified. */
  1156. for (i = 0; data->data.choice[i] != 0; i++)
  1157. if (data->data.choice[i] == data->tag)
  1158. break;
  1159. if (data->data.choice[i] == 0) {
  1160. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1161. WOLFSSL_MSG("Tag didn't match a choice");
  1162. #endif
  1163. return ASN_PARSE_E;
  1164. }
  1165. /* Store data pointer and length for caller. */
  1166. data->data.ref.data = input + idx;
  1167. data->data.ref.length = (word32)len;
  1168. break;
  1169. case ASN_DATA_TYPE_NONE:
  1170. /* Default behaviour based on tag. */
  1171. if (asn->tag == ASN_BOOLEAN) {
  1172. /* BOOLEAN has only one byte of data in BER. */
  1173. if (len != 1) {
  1174. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1175. WOLFSSL_MSG_VSNPRINTF("BOOLEAN length too long: %d", len);
  1176. #endif
  1177. return ASN_PARSE_E;
  1178. }
  1179. if (data->data.u8 == NULL)
  1180. return BAD_STATE_E;
  1181. /* Store C boolean value. */
  1182. *data->data.u8 = (input[idx] != 0);
  1183. break;
  1184. }
  1185. if (asn->tag == ASN_TAG_NULL) {
  1186. /* NULL has no data in BER. */
  1187. if (len != 0) {
  1188. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1189. WOLFSSL_MSG_VSNPRINTF("NULL length too long: %d", len);
  1190. #endif
  1191. return ASN_EXPECT_0_E;
  1192. }
  1193. data->data.ref.data = input + idx;
  1194. break;
  1195. }
  1196. if (asn->tag == ASN_OBJECT_ID) {
  1197. word32 oidIdx = 0;
  1198. /* Store OID data pointer and length */
  1199. data->data.oid.data = input + idx;
  1200. data->data.oid.length = (word32)len;
  1201. /* Get the OID sum. */
  1202. err = GetOID(input + idx, &oidIdx, &data->data.oid.sum,
  1203. data->data.oid.type, len);
  1204. if (err < 0) {
  1205. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1206. WOLFSSL_MSG_VSNPRINTF("OID check failed: %d", err);
  1207. #endif
  1208. return err;
  1209. }
  1210. break;
  1211. }
  1212. /* Otherwise store data pointer and length. */
  1213. data->data.ref.data = input + idx;
  1214. data->data.ref.length = (word32)len;
  1215. break;
  1216. #ifdef DEBUG_WOLFSSL
  1217. default:
  1218. /* Bad ASN data type. */
  1219. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1220. WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data->dataType);
  1221. #endif
  1222. return BAD_STATE_E;
  1223. #endif
  1224. }
  1225. return 0;
  1226. }
  1227. /* Get the ASN.1 items from the BER encoding.
  1228. *
  1229. * @param [in] asn ASN.1 items expected.
  1230. * @param [in] data Data array to place found items into.
  1231. * @param [in] count Count of items to parse.
  1232. * @param [in] complete Whether the whole buffer is to be used up.
  1233. * @param [in] input BER encoded data.
  1234. * @param [in, out] inOutIdx On in, starting index of data.
  1235. * On out, end of parsed data.
  1236. * @param [in] length Length of input buffer.
  1237. * @return 0 on success.
  1238. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1239. * is invalid.
  1240. * @return BUFFER_E when data in buffer is too small.
  1241. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1242. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1243. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1244. * non-zero length.
  1245. * @return MP_INIT_E when the unable to initialize an mp_int.
  1246. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1247. * @return BAD_STATE_E when the data type is not supported.
  1248. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  1249. */
  1250. int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, int complete,
  1251. const byte* input, word32* inOutIdx, word32 length)
  1252. {
  1253. int i;
  1254. int j;
  1255. int err;
  1256. int len;
  1257. /* Current index into buffer. */
  1258. word32 idx = *inOutIdx;
  1259. /* Initialize the end index at each depth to be the length. */
  1260. word32 endIdx[GET_ASN_MAX_DEPTH] = { length, length, length, length, length,
  1261. length, length };
  1262. /* Set choices to -1 to indicate they haven't been seen or found. */
  1263. signed char choiceMet[GET_ASN_MAX_CHOICES] = { -1, -1 };
  1264. /* Not matching a choice right now. */
  1265. int choice = 0;
  1266. /* Current depth of ASN.1 item. */
  1267. int depth;
  1268. /* Minimum depth value seen. */
  1269. int minDepth;
  1270. /* Integer had a zero prepended. */
  1271. int zeroPadded;
  1272. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1273. WOLFSSL_ENTER("GetASN_Items");
  1274. #endif
  1275. /* Start depth at first items depth. */
  1276. minDepth = depth = asn[0].depth;
  1277. /* Check every ASN.1 item. */
  1278. for (i = 0; i < count; i++) {
  1279. /* Store offset of ASN.1 item. */
  1280. data[i].offset = idx;
  1281. /* Length of data in ASN.1 item starts empty. */
  1282. data[i].length = 0;
  1283. /* Get current item depth. */
  1284. depth = asn[i].depth;
  1285. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1286. if (depth > GET_ASN_MAX_DEPTH) {
  1287. WOLFSSL_MSG("Depth in template too large");
  1288. return ASN_PARSE_E;
  1289. }
  1290. #endif
  1291. /* Keep track of minimum depth. */
  1292. if (depth < minDepth) {
  1293. minDepth = depth;
  1294. }
  1295. /* Reset choice if different from previous. */
  1296. if (choice > 0 && asn[i].optional != choice) {
  1297. choice = 0;
  1298. }
  1299. /* Check if first of numbered choice. */
  1300. if (choice == 0 && asn[i].optional > 1) {
  1301. choice = asn[i].optional;
  1302. if (choiceMet[choice - 2] == -1) {
  1303. /* Choice seen but not found a match yet. */
  1304. choiceMet[choice - 2] = 0;
  1305. }
  1306. }
  1307. /* Check for end of data or not a choice and tag not matching. */
  1308. if (idx == endIdx[depth] || (data[i].dataType != ASN_DATA_TYPE_CHOICE &&
  1309. (input[idx] & ~ASN_CONSTRUCTED) != asn[i].tag)) {
  1310. if (asn[i].optional) {
  1311. /* Skip over ASN.1 items underneath this optional item. */
  1312. for (j = i + 1; j < count; j++) {
  1313. if (asn[i].depth >= asn[j].depth)
  1314. break;
  1315. data[j].offset = idx;
  1316. data[j].length = 0;
  1317. }
  1318. i = j - 1;
  1319. continue;
  1320. }
  1321. /* Check for end of data. */
  1322. if (idx == length) {
  1323. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1324. WOLFSSL_MSG_VSNPRINTF(
  1325. "%2d: %4d %4d %c %*s %-16s%*s (index past end)",
  1326. i, data[i].offset, data[i].length,
  1327. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1328. TagString(asn[i].tag), 6 - asn[i].depth, "");
  1329. WOLFSSL_MSG_VSNPRINTF("Index past end of data: %d %d", idx,
  1330. length);
  1331. #endif
  1332. return BUFFER_E;
  1333. }
  1334. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1335. /* Show expected versus found. */
  1336. WOLFSSL_MSG_VSNPRINTF(
  1337. "%2d: %4d %4d %c %*s %-16s%*s Tag=0x%02x (%s)",
  1338. i, data[i].offset, data[i].length,
  1339. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1340. TagString(asn[i].tag), 6 - asn[i].depth, "",
  1341. input[idx], TagString(input[idx]));
  1342. #endif
  1343. /* Check for end of data at this depth. */
  1344. if (idx == endIdx[depth]) {
  1345. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1346. WOLFSSL_MSG_VSNPRINTF("Index past outer item: %d %d", idx,
  1347. endIdx[depth]);
  1348. #endif
  1349. return ASN_PARSE_E;
  1350. }
  1351. /* Expecting an OBJECT_ID */
  1352. if (asn[i].tag == ASN_OBJECT_ID) {
  1353. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1354. WOLFSSL_MSG("Expecting OBJECT ID");
  1355. #endif
  1356. return ASN_OBJECT_ID_E;
  1357. }
  1358. /* Expecting a BIT_STRING */
  1359. if (asn[i].tag == ASN_BIT_STRING) {
  1360. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1361. WOLFSSL_MSG("Expecting BIT STRING");
  1362. #endif
  1363. return ASN_BITSTR_E;
  1364. }
  1365. /* Not the expected tag. */
  1366. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1367. WOLFSSL_MSG("Bad tag");
  1368. #endif
  1369. return ASN_PARSE_E;
  1370. }
  1371. /* Store found tag in data. */
  1372. data[i].tag = input[idx];
  1373. if (data[i].dataType != ASN_DATA_TYPE_CHOICE) {
  1374. int constructed = (input[idx] & ASN_CONSTRUCTED) == ASN_CONSTRUCTED;
  1375. /* Check constructed match expected for non-choice ASN.1 item. */
  1376. if (asn[i].constructed != constructed) {
  1377. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1378. WOLFSSL_MSG_VSNPRINTF(
  1379. "%2d: %4d %4d %c %*s %-16s%*s Tag=0x%02x (%s)",
  1380. i, data[i].offset, data[i].length,
  1381. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1382. TagString(asn[i].tag), 6 - asn[i].depth, "",
  1383. input[idx], TagString(input[idx]));
  1384. if (!constructed) {
  1385. WOLFSSL_MSG("Not constructed");
  1386. }
  1387. else {
  1388. WOLFSSL_MSG("Not expected to be constructed");
  1389. }
  1390. #endif
  1391. return ASN_PARSE_E;
  1392. }
  1393. }
  1394. /* Move index to start of length. */
  1395. idx++;
  1396. /* Get the encoded length. */
  1397. if (GetASN_Length(input, &idx, &len, endIdx[depth], 1) < 0) {
  1398. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1399. WOLFSSL_MSG_VSNPRINTF("%2d: idx=%d len=%d end=%d", i, idx, len,
  1400. endIdx[depth]);
  1401. #endif
  1402. return ASN_PARSE_E;
  1403. }
  1404. /* Store length of data. */
  1405. data[i].length = (word32)len;
  1406. /* Note the max length of items under this one. */
  1407. endIdx[depth + 1] = idx + (word32)len;
  1408. if (choice > 1) {
  1409. /* Note we found a number choice. */
  1410. choiceMet[choice - 2] = 1;
  1411. }
  1412. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1413. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  1414. data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
  1415. asn[i].depth, "", TagString(data[i].tag));
  1416. #endif
  1417. /* Assume no zero padding on INTEGER. */
  1418. zeroPadded = 0;
  1419. /* Check data types that prepended a byte. */
  1420. if (asn[i].tag == ASN_INTEGER) {
  1421. /* Check validity of first byte. */
  1422. err = GetASN_Integer(input, idx, len,
  1423. data[i].dataType == ASN_DATA_TYPE_MP ||
  1424. data[i].dataType == ASN_DATA_TYPE_MP_INITED);
  1425. if (err != 0)
  1426. return err;
  1427. if (len > 1 && input[idx] == 0) {
  1428. zeroPadded = 1;
  1429. /* Move over prepended byte. */
  1430. idx++;
  1431. len--;
  1432. }
  1433. }
  1434. else if (asn[i].tag == ASN_BIT_STRING) {
  1435. /* Check prepended byte is correct. */
  1436. err = GetASN_BitString(input, idx, len);
  1437. if (err != 0)
  1438. return err;
  1439. /* Move over prepended byte. */
  1440. idx++;
  1441. len--;
  1442. }
  1443. else if ((asn[i].tag == ASN_OBJECT_ID) && (len < 3)) {
  1444. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1445. WOLFSSL_MSG_VSNPRINTF("OID length must be 3 or more: %d", len);
  1446. #endif
  1447. return ASN_PARSE_E;
  1448. }
  1449. /* Don't parse data if only header required. */
  1450. if (asn[i].headerOnly) {
  1451. /* Store reference to data and length. */
  1452. data[i].data.ref.data = input + idx;
  1453. data[i].data.ref.length = (word32)len;
  1454. continue;
  1455. }
  1456. /* Store the data at idx in the ASN data item. */
  1457. err = GetASN_StoreData(&asn[i], &data[i], input, idx, len, zeroPadded);
  1458. if (err != 0) {
  1459. return err;
  1460. }
  1461. /* Move index to next item. */
  1462. idx += (word32)len;
  1463. /* When matched numbered choice ... */
  1464. if (asn[i].optional > 1) {
  1465. /* Skip over other ASN.1 items of the same number. */
  1466. for (j = i + 1; j < count; j++) {
  1467. if (asn[j].depth <= asn[i].depth &&
  1468. asn[j].optional != asn[i].optional) {
  1469. break;
  1470. }
  1471. }
  1472. i = j - 1;
  1473. }
  1474. }
  1475. if (complete) {
  1476. /* When expecting ASN.1 items to completely use data, check we did. */
  1477. for (j = depth; j > minDepth; j--) {
  1478. if (idx < endIdx[j]) {
  1479. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1480. WOLFSSL_MSG_VSNPRINTF(
  1481. "More data in constructed item at depth: %d", j - 1);
  1482. #endif
  1483. return ASN_PARSE_E;
  1484. }
  1485. }
  1486. }
  1487. /* Check all choices where met - found an item for them. */
  1488. for (j = 0; j < GET_ASN_MAX_CHOICES; j++) {
  1489. if (choiceMet[j] == 0) {
  1490. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1491. WOLFSSL_MSG_VSNPRINTF("No choice seen: %d", j + 2);
  1492. #endif
  1493. return ASN_PARSE_E;
  1494. }
  1495. }
  1496. /* Return index after ASN.1 data has been parsed. */
  1497. *inOutIdx = idx;
  1498. return 0;
  1499. }
  1500. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1501. /* Calculate the size of the DER encoding.
  1502. *
  1503. * Call SetASN_Items() to write encoding to a buffer.
  1504. *
  1505. * @param [in] asn ASN.1 items to encode.
  1506. * @param [in, out] data Data to place in each item. Lengths set were not
  1507. * known.
  1508. * @param [in] count Count of items to encode.
  1509. * @param [out] len Length of the DER encoding.
  1510. * @return Size of the DER encoding in bytes.
  1511. */
  1512. static int SizeASN_ItemsDebug(const char* name, const ASNItem* asn,
  1513. ASNSetData *data, int count, int* encSz)
  1514. {
  1515. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1516. return SizeASN_Items(asn, data, count, encSz);
  1517. }
  1518. /* Creates the DER encoding of the ASN.1 items.
  1519. *
  1520. * Assumes the output buffer is large enough to hold encoding.
  1521. * Must call SizeASN_Items() to determine size of encoding and offsets.
  1522. *
  1523. * Displays the template name first.
  1524. *
  1525. * @param [in] name Name of ASN.1 template.
  1526. * @param [in] asn ASN.1 items to encode.
  1527. * @param [in] data Data to place in each item.
  1528. * @param [in] count Count of items to encode.
  1529. * @param [in, out] output Buffer to write encoding into.
  1530. * @return Size of the DER encoding in bytes.
  1531. */
  1532. static int SetASN_ItemsDebug(const char* name, const ASNItem* asn,
  1533. ASNSetData *data, int count, byte* output)
  1534. {
  1535. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1536. return SetASN_Items(asn, data, count, output);
  1537. }
  1538. /* Get the ASN.1 items from the BER encoding.
  1539. *
  1540. * Displays the template name first.
  1541. *
  1542. * @param [in] name Name of ASN.1 template.
  1543. * @param [in] asn ASN.1 items expected.
  1544. * @param [in] data Data array to place found items into.
  1545. * @param [in] count Count of items to parse.
  1546. * @param [in] complete Whether the whole buffer is to be used up.
  1547. * @param [in] input BER encoded data.
  1548. * @param [in, out] inOutIdx On in, starting index of data.
  1549. * On out, end of parsed data.
  1550. * @param [in] maxIdx Maximum index of input data.
  1551. * @return 0 on success.
  1552. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1553. * is invalid.
  1554. * @return BUFFER_E when data in buffer is too small.
  1555. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1556. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1557. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1558. * non-zero length.
  1559. * @return MP_INIT_E when the unable to initialize an mp_int.
  1560. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1561. * @return BAD_STATE_E when the data type is not supported.
  1562. */
  1563. static int GetASN_ItemsDebug(const char* name, const ASNItem* asn,
  1564. ASNGetData *data, int count, int complete, const byte* input,
  1565. word32* inOutIdx, word32 maxIdx)
  1566. {
  1567. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1568. return GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx);
  1569. }
  1570. /* Calculate the size of the DER encoding.
  1571. *
  1572. * Call SetASN_Items() to write encoding to a buffer.
  1573. *
  1574. * @param [in] asn ASN.1 items to encode.
  1575. * @param [in, out] data Data to place in each item. Lengths set were not
  1576. * known.
  1577. * @param [in] count Count of items to encode.
  1578. * @param [out] len Length of the DER encoding.
  1579. * @return Size of the DER encoding in bytes.
  1580. */
  1581. #define SizeASN_Items(asn, data, count, encSz) \
  1582. SizeASN_ItemsDebug(#asn, asn, data, count, encSz)
  1583. /* Creates the DER encoding of the ASN.1 items.
  1584. *
  1585. * Assumes the output buffer is large enough to hold encoding.
  1586. * Must call SizeASN_Items() to determine size of encoding and offsets.
  1587. *
  1588. * Displays the template name first.
  1589. *
  1590. * @param [in] name Name of ASN.1 template.
  1591. * @param [in] asn ASN.1 items to encode.
  1592. * @param [in] data Data to place in each item.
  1593. * @param [in] count Count of items to encode.
  1594. * @param [in, out] output Buffer to write encoding into.
  1595. * @return Size of the DER encoding in bytes.
  1596. */
  1597. #define SetASN_Items(asn, data, count, output) \
  1598. SetASN_ItemsDebug(#asn, asn, data, count, output)
  1599. /* Get the ASN.1 items from the BER encoding.
  1600. *
  1601. * Displays the template name first.
  1602. *
  1603. * @param [in] name Name of ASN.1 template.
  1604. * @param [in] asn ASN.1 items expected.
  1605. * @param [in] data Data array to place found items into.
  1606. * @param [in] count Count of items to parse.
  1607. * @param [in] complete Whether the whole buffer is to be used up.
  1608. * @param [in] input BER encoded data.
  1609. * @param [in, out] inOutIdx On in, starting index of data.
  1610. * On out, end of parsed data.
  1611. * @param [in] maxIdx Maximum index of input data.
  1612. * @return 0 on success.
  1613. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1614. * is invalid.
  1615. * @return BUFFER_E when data in buffer is too small.
  1616. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1617. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1618. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1619. * non-zero length.
  1620. * @return MP_INIT_E when the unable to initialize an mp_int.
  1621. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1622. * @return BAD_STATE_E when the data type is not supported.
  1623. */
  1624. #define GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx) \
  1625. GetASN_ItemsDebug(#asn, asn, data, count, complete, input, inOutIdx, maxIdx)
  1626. #endif /* WOLFSSL_DEBUG_ASN_TEMPLATE */
  1627. /* Decode a BER encoded constructed sequence.
  1628. *
  1629. * @param [in] input Buffer of BER encoded data.
  1630. * @param [in, out] inOutIdx On in, index to start decoding from.
  1631. * On out, index of next encoded byte.
  1632. * @param [out] len Length of data under SEQUENCE.
  1633. * @param [in] maxIdx Maximim index of data. Index of byte after SEQ.
  1634. * @param [in] complete All data used with SEQUENCE and data under.
  1635. * @return 0 on success.
  1636. * @return BUFFER_E when not enough data to complete decode.
  1637. * @return ASN_PARSE when decoding failed.
  1638. */
  1639. static int GetASN_Sequence(const byte* input, word32* inOutIdx, int* len,
  1640. word32 maxIdx, int complete)
  1641. {
  1642. int ret = 0;
  1643. word32 idx = *inOutIdx;
  1644. /* Check buffer big enough for tag. */
  1645. if (idx + 1 > maxIdx) {
  1646. ret = BUFFER_E;
  1647. }
  1648. /* Check it is a constructed SEQUENCE. */
  1649. if ((ret == 0) && (input[idx++] != (ASN_SEQUENCE | ASN_CONSTRUCTED))) {
  1650. ret = ASN_PARSE_E;
  1651. }
  1652. /* Get the length. */
  1653. if ((ret == 0) && (GetASN_Length(input, &idx, len, maxIdx, 1) < 0)) {
  1654. ret = ASN_PARSE_E;
  1655. }
  1656. /* Check all data used if complete set. */
  1657. if ((ret == 0) && complete && (idx + (word32)*len != maxIdx)) {
  1658. ret = ASN_PARSE_E;
  1659. }
  1660. if (ret == 0) {
  1661. /* Return index of next byte of encoded data. */
  1662. *inOutIdx = idx;
  1663. }
  1664. return ret;
  1665. }
  1666. #ifdef WOLFSSL_ASN_TEMPLATE_TYPE_CHECK
  1667. /* Setup ASN data item to get an 8-bit number.
  1668. *
  1669. * @param [in] dataASN Dynamic ASN data item.
  1670. * @param [in] num Pointer to an 8-bit variable.
  1671. */
  1672. void GetASN_Int8Bit(ASNGetData *dataASN, byte* num)
  1673. {
  1674. dataASN->dataType = ASN_DATA_TYPE_WORD8;
  1675. dataASN->data.u8 = num;
  1676. }
  1677. /* Setup ASN data item to get a 16-bit number.
  1678. *
  1679. * @param [in] dataASN Dynamic ASN data item.
  1680. * @param [in] num Pointer to a 16-bit variable.
  1681. */
  1682. void GetASN_Int16Bit(ASNGetData *dataASN, word16* num)
  1683. {
  1684. dataASN->dataType = ASN_DATA_TYPE_WORD16;
  1685. dataASN->data.u16 = num;
  1686. }
  1687. /* Setup ASN data item to get a 32-bit number.
  1688. *
  1689. * @param [in] dataASN Dynamic ASN data item.
  1690. * @param [in] num Pointer to a 32-bit variable.
  1691. */
  1692. void GetASN_Int32Bit(ASNGetData *dataASN, word32* num)
  1693. {
  1694. dataASN->dataType = ASN_DATA_TYPE_WORD32;
  1695. dataASN->data.u32 = num;
  1696. }
  1697. /* Setup ASN data item to get data into a buffer of a specific length.
  1698. *
  1699. * @param [in] dataASN Dynamic ASN data item.
  1700. * @param [in] data Buffer to hold data.
  1701. * @param [in] length Length of buffer in bytes.
  1702. */
  1703. void GetASN_Buffer(ASNGetData *dataASN, byte* data, word32* length)
  1704. {
  1705. dataASN->dataType = ASN_DATA_TYPE_BUFFER;
  1706. dataASN->data.buffer.data = data;
  1707. dataASN->data.buffer.length = length;
  1708. }
  1709. /* Setup ASN data item to check parsed data against expected buffer.
  1710. *
  1711. * @param [in] dataASN Dynamic ASN data item.
  1712. * @param [in] data Buffer containing expected data.
  1713. * @param [in] length Length of buffer in bytes.
  1714. */
  1715. void GetASN_ExpBuffer(ASNGetData *dataASN, const byte* data, word32 length)
  1716. {
  1717. dataASN->dataType = ASN_DATA_TYPE_EXP_BUFFER;
  1718. dataASN->data.ref.data = data;
  1719. dataASN->data.ref.length = length;
  1720. }
  1721. /* Setup ASN data item to get a number into an mp_int.
  1722. *
  1723. * @param [in] dataASN Dynamic ASN data item.
  1724. * @param [in] num Multi-precision number object.
  1725. */
  1726. void GetASN_MP(ASNGetData *dataASN, mp_int* num)
  1727. {
  1728. dataASN->dataType = ASN_DATA_TYPE_MP;
  1729. dataASN->data.mp = num;
  1730. }
  1731. /* Setup ASN data item to get a number into an mp_int that is initialized.
  1732. *
  1733. * @param [in] dataASN Dynamic ASN data item.
  1734. * @param [in] num Multi-precision number object.
  1735. */
  1736. void GetASN_MP_Inited(ASNGetData *dataASN, mp_int* num)
  1737. {
  1738. dataASN->dataType = ASN_DATA_TYPE_MP_INITED;
  1739. dataASN->data.mp = num;
  1740. }
  1741. /* Setup ASN data item to get a positive or negative number into an mp_int.
  1742. *
  1743. * @param [in] dataASN Dynamic ASN data item.
  1744. * @param [in] num Multi-precision number object.
  1745. */
  1746. void GetASN_MP_PosNeg(ASNGetData *dataASN, mp_int* num)
  1747. {
  1748. dataASN->dataType = ASN_DATA_TYPE_MP_POS_NEG;
  1749. dataASN->data.mp = num;
  1750. }
  1751. /* Setup ASN data item to be a choice of tags.
  1752. *
  1753. * @param [in] dataASN Dynamic ASN data item.
  1754. * @param [in] options 0 terminated list of tags that are valid.
  1755. */
  1756. void GetASN_Choice(ASNGetData *dataASN, const byte* options)
  1757. {
  1758. dataASN->dataType = ASN_DATA_TYPE_CHOICE;
  1759. dataASN->data.choice = options;
  1760. }
  1761. /* Setup ASN data item to get a boolean value.
  1762. *
  1763. * @param [in] dataASN Dynamic ASN data item.
  1764. * @param [in] num Pointer to an 8-bit variable.
  1765. */
  1766. void GetASN_Boolean(ASNGetData *dataASN, byte* num)
  1767. {
  1768. dataASN->dataType = ASN_DATA_TYPE_NONE;
  1769. dataASN->data.choice = num;
  1770. }
  1771. /* Setup ASN data item to be a an OID of a specific type.
  1772. *
  1773. * @param [in] dataASN Dynamic ASN data item.
  1774. * @param [in] oidType Type of OID to expect.
  1775. */
  1776. void GetASN_OID(ASNGetData *dataASN, int oidType)
  1777. {
  1778. dataASN->data.oid.type = oidType;
  1779. }
  1780. /* Get the data and length from an ASN data item.
  1781. *
  1782. * @param [in] dataASN Dynamic ASN data item.
  1783. * @param [out] data Pointer to data of item.
  1784. * @param [out] length Length of buffer in bytes.
  1785. */
  1786. void GetASN_GetConstRef(ASNGetData * dataASN, const byte** data, word32* length)
  1787. {
  1788. *data = dataASN->data.ref.data;
  1789. *length = dataASN->data.ref.length;
  1790. }
  1791. /* Get the data and length from an ASN data item.
  1792. *
  1793. * @param [in] dataASN Dynamic ASN data item.
  1794. * @param [out] data Pointer to data of item.
  1795. * @param [out] length Length of buffer in bytes.
  1796. */
  1797. void GetASN_GetRef(ASNGetData * dataASN, byte** data, word32* length)
  1798. {
  1799. *data = (byte*)dataASN->data.ref.data;
  1800. *length = dataASN->data.ref.length;
  1801. }
  1802. /* Get the data and length from an ASN data item that is an OID.
  1803. *
  1804. * @param [in] dataASN Dynamic ASN data item.
  1805. * @param [out] data Pointer to .
  1806. * @param [out] length Length of buffer in bytes.
  1807. */
  1808. void GetASN_OIDData(ASNGetData * dataASN, byte** data, word32* length)
  1809. {
  1810. *data = (byte*)dataASN->data.oid.data;
  1811. *length = dataASN->data.oid.length;
  1812. }
  1813. /* Setup an ASN data item to set a boolean.
  1814. *
  1815. * @param [in] dataASN Dynamic ASN data item.
  1816. * @param [in] val Boolean value.
  1817. */
  1818. void SetASN_Boolean(ASNSetData *dataASN, byte val)
  1819. {
  1820. dataASN->dataType = ASN_DATA_TYPE_NONE;
  1821. dataASN->data.u8 = val;
  1822. }
  1823. /* Setup an ASN data item to set an 8-bit number.
  1824. *
  1825. * @param [in] dataASN Dynamic ASN data item.
  1826. * @param [in] num 8-bit number to set.
  1827. */
  1828. void SetASN_Int8Bit(ASNSetData *dataASN, byte num)
  1829. {
  1830. dataASN->dataType = ASN_DATA_TYPE_WORD8;
  1831. dataASN->data.u8 = num;
  1832. }
  1833. /* Setup an ASN data item to set a 16-bit number.
  1834. *
  1835. * @param [in] dataASN Dynamic ASN data item.
  1836. * @param [in] num 16-bit number to set.
  1837. */
  1838. void SetASN_Int16Bit(ASNSetData *dataASN, word16 num)
  1839. {
  1840. dataASN->dataType = ASN_DATA_TYPE_WORD16;
  1841. dataASN->data.u16 = num;
  1842. }
  1843. /* Setup an ASN data item to set the data in a buffer.
  1844. *
  1845. * @param [in] dataASN Dynamic ASN data item.
  1846. * @param [in] data Buffer containing data to set.
  1847. * @param [in] length Length of data in buffer in bytes.
  1848. */
  1849. void SetASN_Buffer(ASNSetData *dataASN, const byte* data, word32 length)
  1850. {
  1851. dataASN->data.buffer.data = data;
  1852. dataASN->data.buffer.length = length;
  1853. }
  1854. /* Setup an ASN data item to set the DER encode data in a buffer.
  1855. *
  1856. * @param [in] dataASN Dynamic ASN data item.
  1857. * @param [in] data Buffer containing BER encoded data to set.
  1858. * @param [in] length Length of data in buffer in bytes.
  1859. */
  1860. void SetASN_ReplaceBuffer(ASNSetData *dataASN, const byte* data, word32 length)
  1861. {
  1862. dataASN->dataType = ASN_DATA_TYPE_REPLACE_BUFFER;
  1863. dataASN->data.buffer.data = data;
  1864. dataASN->data.buffer.length = length;
  1865. }
  1866. /* Setup an ASN data item to set an multi-precision number.
  1867. *
  1868. * @param [in] dataASN Dynamic ASN data item.
  1869. * @param [in] num Multi-precision number.
  1870. */
  1871. void SetASN_MP(ASNSetData *dataASN, mp_int* num)
  1872. {
  1873. dataASN->dataType = ASN_DATA_TYPE_MP;
  1874. dataASN->data.mp = num;
  1875. }
  1876. /* Setup an ASN data item to set an OID based on id and type.
  1877. *
  1878. * oid and oidType pair are unique.
  1879. *
  1880. * @param [in] dataASN Dynamic ASN data item.
  1881. * @param [in] oid OID identifier.
  1882. * @param [in] oidType Type of OID.
  1883. */
  1884. void SetASN_OID(ASNSetData *dataASN, int oid, int oidType)
  1885. {
  1886. dataASN->data.buffer.data = OidFromId(oid, oidType,
  1887. &dataASN->data.buffer.length);
  1888. }
  1889. #endif /* WOLFSSL_ASN_TEMPLATE_TYPE_CHECK */
  1890. #ifdef CRLDP_VALIDATE_DATA
  1891. /* Get the data of the BIT_STRING as a 16-bit number.
  1892. *
  1893. * @param [in] dataASN Dynamic ASN data item.
  1894. * @param [out] val ASN.1 item's data as a 16-bit number.
  1895. * @return 0 on success.
  1896. * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
  1897. * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
  1898. */
  1899. static int GetASN_BitString_Int16Bit(ASNGetData* dataASN, word16* val)
  1900. {
  1901. int ret;
  1902. int i;
  1903. const byte* input = dataASN->data.ref.data;
  1904. int length = dataASN->data.ref.length;
  1905. /* Validate the BIT_STRING data. */
  1906. ret = GetASN_BitString(input, 0, length);
  1907. if (ret == 0) {
  1908. /* Skip unused bits byte. */
  1909. input++;
  1910. length--;
  1911. /* Check the data is usable. */
  1912. if (length == 0 || length > 2) {
  1913. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1914. WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", length);
  1915. #endif
  1916. ret = ASN_PARSE_E;
  1917. }
  1918. }
  1919. if (ret == 0) {
  1920. /* Fill 16-bit var with all the data. */
  1921. *val = 0;
  1922. for (i = 0; i < length; i++) {
  1923. *val <<= 8;
  1924. *val |= input[i];
  1925. }
  1926. }
  1927. return ret;
  1928. }
  1929. #endif /* CRLDP_VALIDATE_DATA */
  1930. #endif /* WOLFSSL_ASN_TEMPLATE */
  1931. /* Decode the BER/DER length field.
  1932. *
  1933. * @param [in] input BER encoded data.
  1934. * @param [in, out] inOutIdx On in, starting index of length.
  1935. * On out, end of parsed length.
  1936. * @param [out] len Length value decoded.
  1937. * @param [in] maxIdx Maximum index of input data.
  1938. * @return Length on success.
  1939. * @return ASN_PARSE_E if the encoding is invalid.
  1940. * @return BUFFER_E when not enough data to complete decode.
  1941. */
  1942. int GetLength(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  1943. {
  1944. return GetLength_ex(input, inOutIdx, len, maxIdx, 1);
  1945. }
  1946. /* Decode the BER/DER length field and check the length is valid on request.
  1947. *
  1948. * BER/DER has Type-Length-Value triplets.
  1949. * When requested will check that the Length decoded, indicating the number
  1950. * of bytes in the Value, is available in the buffer after the Length bytes.
  1951. *
  1952. * Only supporting a length upto INT_MAX.
  1953. *
  1954. * @param [in] input BER encoded data.
  1955. * @param [in, out] inOutIdx On in, starting index of length.
  1956. * On out, end of parsed length.
  1957. * @param [out] len Length value decoded.
  1958. * @param [in] maxIdx Maximum index of input data.
  1959. * @param [in] check Whether to check the buffer has at least the
  1960. * decoded length of bytes remaining.
  1961. * @return Length on success.
  1962. * @return ASN_PARSE_E if the encoding is invalid.
  1963. * @return BUFFER_E when not enough data to complete decode.
  1964. */
  1965. int GetLength_ex(const byte* input, word32* inOutIdx, int* len, word32 maxIdx,
  1966. int check)
  1967. {
  1968. int length = 0;
  1969. word32 idx = (word32)*inOutIdx;
  1970. byte b;
  1971. /* Ensure zero return length on error. */
  1972. *len = 0;
  1973. /* Check there is at least one byte available containing length information.
  1974. */
  1975. if ((idx + 1) > maxIdx) {
  1976. WOLFSSL_MSG("GetLength - bad index on input");
  1977. return BUFFER_E;
  1978. }
  1979. /* Get the first length byte. */
  1980. b = input[idx++];
  1981. /* Check if the first byte indicates the count of bytes. */
  1982. if (b >= ASN_LONG_LENGTH) {
  1983. /* Bottom 7 bits are the number of bytes to calculate length with.
  1984. * Note: 0 indicates indefinite length encoding *not* 0 bytes of length.
  1985. */
  1986. word32 bytes = b & 0x7F;
  1987. int minLen;
  1988. /* Calculate minimum length to be encoded with bytes. */
  1989. if (b == ASN_INDEF_LENGTH) {
  1990. /* Indefinite length encoding - no length bytes. */
  1991. minLen = 0;
  1992. }
  1993. else if (bytes == 1) {
  1994. minLen = 0x80;
  1995. }
  1996. /* Only support up to the number of bytes that fit into return var. */
  1997. else if (bytes > sizeof(length)) {
  1998. WOLFSSL_MSG("GetLength - overlong data length spec");
  1999. return ASN_PARSE_E;
  2000. } else {
  2001. minLen = 1 << ((bytes - 1) * 8);
  2002. }
  2003. /* Check the number of bytes required are available. */
  2004. if ((idx + bytes) > maxIdx) {
  2005. WOLFSSL_MSG("GetLength - bad long length");
  2006. return BUFFER_E;
  2007. }
  2008. /* Big-endian encoding of number. */
  2009. while (bytes--) {
  2010. b = input[idx++];
  2011. length = (length << 8) | b;
  2012. }
  2013. /* Negative value indicates we overflowed the signed int. */
  2014. if (length < 0) {
  2015. return ASN_PARSE_E;
  2016. }
  2017. /* Don't allow lengths that are longer than strictly required. */
  2018. if (length < minLen) {
  2019. return ASN_PARSE_E;
  2020. }
  2021. }
  2022. else {
  2023. /* Length in first byte. */
  2024. length = b;
  2025. }
  2026. /* When requested, check the buffer has at least length bytes left. */
  2027. if (check && ((idx + (word32)length) > maxIdx)) {
  2028. WOLFSSL_MSG("GetLength - value exceeds buffer length");
  2029. return BUFFER_E;
  2030. }
  2031. /* Return index after length encoding. */
  2032. *inOutIdx = idx;
  2033. /* Return length if valid. */
  2034. if (length > 0) {
  2035. *len = length;
  2036. }
  2037. /* Return length calculated or error code. */
  2038. return length;
  2039. }
  2040. /* Gets the tag of next BER/DER encoded item.
  2041. *
  2042. * Checks there is enough data in the buffer for the tag byte.
  2043. *
  2044. * @param [in] input BER encoded data.
  2045. * @param [in, out] inOutIdx On in, starting index of tag.
  2046. * On out, end of parsed tag.
  2047. * @param [out] tag Tag value found.
  2048. * @param [in] maxIdx Maximum index of input data.
  2049. *
  2050. * return 0 on success
  2051. * return BAD_FUNC_ARG when tag, inOutIdx or input is NULL.
  2052. * return BUFFER_E when not enough space in buffer for tag.
  2053. */
  2054. int GetASNTag(const byte* input, word32* inOutIdx, byte* tag, word32 maxIdx)
  2055. {
  2056. int ret = 0;
  2057. word32 idx = 0;
  2058. /* Check validity of parameters. */
  2059. if ((tag == NULL) || (inOutIdx == NULL) || (input == NULL)) {
  2060. ret = BAD_FUNC_ARG;
  2061. }
  2062. if (ret == 0) {
  2063. /* Get index and ensure space for tag. */
  2064. idx = *inOutIdx;
  2065. if (idx + ASN_TAG_SZ > maxIdx) {
  2066. WOLFSSL_MSG("Buffer too small for ASN tag");
  2067. ret = BUFFER_E;
  2068. }
  2069. }
  2070. if (ret == 0) {
  2071. /* Return the tag and the index after tag. */
  2072. *tag = input[idx];
  2073. *inOutIdx = idx + ASN_TAG_SZ;
  2074. }
  2075. /* Return error code. */
  2076. return ret;
  2077. }
  2078. /* Decode the DER/BER header (Type-Length) and check the length when requested.
  2079. *
  2080. * BER/DER has Type-Length-Value triplets.
  2081. * Check that the tag/type is the required value.
  2082. * When requested will check that the Length decoded, indicating the number
  2083. * of bytes in the Value, is available in the buffer after the Length bytes.
  2084. *
  2085. * Only supporting a length upto INT_MAX.
  2086. *
  2087. * @param [in] input Buffer holding DER/BER encoded data.
  2088. * @param [in] tag ASN.1 tag value expected in header.
  2089. * @param [in, out] inOutIdx On in, starting index of header.
  2090. * On out, end of parsed header.
  2091. * @param [out] len Number of bytes in the ASN.1 data.
  2092. * @param [in] maxIdx Length of data in buffer.
  2093. * @param [in] check Whether to check the buffer has at least the
  2094. * decoded length of bytes remaining.
  2095. * @return Number of bytes in the ASN.1 data on success.
  2096. * @return BUFFER_E when there is not enough data to parse.
  2097. * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
  2098. */
  2099. static int GetASNHeader_ex(const byte* input, byte tag, word32* inOutIdx,
  2100. int* len, word32 maxIdx, int check)
  2101. {
  2102. int ret = 0;
  2103. word32 idx = *inOutIdx;
  2104. byte tagFound;
  2105. int length = 0;
  2106. /* Get tag/type. */
  2107. if (GetASNTag(input, &idx, &tagFound, maxIdx) != 0) {
  2108. ret = ASN_PARSE_E;
  2109. }
  2110. /* Ensure tag is the expected value. */
  2111. if ((ret == 0) && (tagFound != tag)) {
  2112. ret = ASN_PARSE_E;
  2113. }
  2114. /* Get the encoded length. */
  2115. if ((ret == 0) && (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)) {
  2116. ret = ASN_PARSE_E;
  2117. }
  2118. if (ret == 0) {
  2119. /* Return the length of data and index after header. */
  2120. *len = length;
  2121. *inOutIdx = idx;
  2122. ret = length;
  2123. }
  2124. /* Return number of data bytes or error code. */
  2125. return ret;
  2126. }
  2127. /* Decode the DER/BER header (Type-Length) and check the length.
  2128. *
  2129. * BER/DER has Type-Length-Value triplets.
  2130. * Check that the tag/type is the required value.
  2131. * Checks that the Length decoded, indicating the number of bytes in the Value,
  2132. * is available in the buffer after the Length bytes.
  2133. *
  2134. * @param [in] input Buffer holding DER/BER encoded data.
  2135. * @param [in] tag ASN.1 tag value expected in header.
  2136. * @param [in, out] inOutIdx On in, starting index of header.
  2137. * On out, end of parsed header.
  2138. * @param [out] len Number of bytes in the ASN.1 data.
  2139. * @param [in] maxIdx Length of data in buffer.
  2140. * @return Number of bytes in the ASN.1 data on success.
  2141. * @return BUFFER_E when there is not enough data to parse.
  2142. * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
  2143. */
  2144. static int GetASNHeader(const byte* input, byte tag, word32* inOutIdx, int* len,
  2145. word32 maxIdx)
  2146. {
  2147. return GetASNHeader_ex(input, tag, inOutIdx, len, maxIdx, 1);
  2148. }
  2149. #ifndef WOLFSSL_ASN_TEMPLATE
  2150. static int GetHeader(const byte* input, byte* tag, word32* inOutIdx, int* len,
  2151. word32 maxIdx, int check)
  2152. {
  2153. word32 idx = *inOutIdx;
  2154. int length;
  2155. if ((idx + 1) > maxIdx)
  2156. return BUFFER_E;
  2157. *tag = input[idx++];
  2158. if (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)
  2159. return ASN_PARSE_E;
  2160. *len = length;
  2161. *inOutIdx = idx;
  2162. return length;
  2163. }
  2164. #endif
  2165. /* Decode the header of a BER/DER encoded SEQUENCE.
  2166. *
  2167. * @param [in] input Buffer holding DER/BER encoded data.
  2168. * @param [in, out] inOutIdx On in, starting index of header.
  2169. * On out, end of parsed header.
  2170. * @param [out] len Number of bytes in the ASN.1 data.
  2171. * @param [in] maxIdx Length of data in buffer.
  2172. * @return Number of bytes in the ASN.1 data on success.
  2173. * @return BUFFER_E when there is not enough data to parse.
  2174. * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
  2175. */
  2176. int GetSequence(const byte* input, word32* inOutIdx, int* len,
  2177. word32 maxIdx)
  2178. {
  2179. return GetASNHeader(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  2180. maxIdx);
  2181. }
  2182. /* Decode the header of a BER/DER encoded SEQUENCE.
  2183. *
  2184. * @param [in] input Buffer holding DER/BER encoded data.
  2185. * @param [in, out] inOutIdx On in, starting index of header.
  2186. * On out, end of parsed header.
  2187. * @param [out] len Number of bytes in the ASN.1 data.
  2188. * @param [in] maxIdx Length of data in buffer.
  2189. * @param [in] check Whether to check the buffer has at least the
  2190. * decoded length of bytes remaining.
  2191. * @return Number of bytes in the ASN.1 data on success.
  2192. * @return BUFFER_E when there is not enough data to parse.
  2193. * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
  2194. */
  2195. int GetSequence_ex(const byte* input, word32* inOutIdx, int* len,
  2196. word32 maxIdx, int check)
  2197. {
  2198. return GetASNHeader_ex(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  2199. maxIdx, check);
  2200. }
  2201. /* Decode the header of a BER/DER encoded SET.
  2202. *
  2203. * @param [in] input Buffer holding DER/BER encoded data.
  2204. * @param [in, out] inOutIdx On in, starting index of header.
  2205. * On out, end of parsed header.
  2206. * @param [out] len Number of bytes in the ASN.1 data.
  2207. * @param [in] maxIdx Length of data in buffer.
  2208. * @return Number of bytes in the ASN.1 data on success.
  2209. * @return BUFFER_E when there is not enough data to parse.
  2210. * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
  2211. */
  2212. int GetSet(const byte* input, word32* inOutIdx, int* len,
  2213. word32 maxIdx)
  2214. {
  2215. return GetASNHeader(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  2216. maxIdx);
  2217. }
  2218. /* Decode the header of a BER/DER encoded SET.
  2219. *
  2220. * @param [in] input Buffer holding DER/BER encoded data.
  2221. * @param [in, out] inOutIdx On in, starting index of header.
  2222. * On out, end of parsed header.
  2223. * @param [out] len Number of bytes in the ASN.1 data.
  2224. * @param [in] maxIdx Length of data in buffer.
  2225. * @param [in] check Whether to check the buffer has at least the
  2226. * decoded length of bytes remaining.
  2227. * @return Number of bytes in the ASN.1 data on success.
  2228. * @return BUFFER_E when there is not enough data to parse.
  2229. * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
  2230. */
  2231. int GetSet_ex(const byte* input, word32* inOutIdx, int* len,
  2232. word32 maxIdx, int check)
  2233. {
  2234. return GetASNHeader_ex(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  2235. maxIdx, check);
  2236. }
  2237. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_OCSP)
  2238. /* Decode the BER/DER encoded NULL.
  2239. *
  2240. * No data in a NULL ASN.1 item.
  2241. * Ensure that the all fields are as expected and move index past the element.
  2242. *
  2243. * @param [in] input Buffer holding DER/BER encoded data.
  2244. * @param [in, out] inOutIdx On in, starting index of NULL item.
  2245. * On out, end of parsed NULL item.
  2246. * @param [in] maxIdx Length of data in buffer.
  2247. * @return 0 on success.
  2248. * @return BUFFER_E when there is not enough data to parse.
  2249. * @return ASN_TAG_NULL_E when the NULL tag is not found.
  2250. * @return ASN_EXPECT_0_E when the length is not zero.
  2251. */
  2252. static int GetASNNull(const byte* input, word32* inOutIdx, word32 maxIdx)
  2253. {
  2254. int ret = 0;
  2255. word32 idx = *inOutIdx;
  2256. /* Check buffer has enough data for a NULL item. */
  2257. if ((idx + 2) > maxIdx) {
  2258. ret = BUFFER_E;
  2259. }
  2260. /* Check the tag is NULL. */
  2261. if ((ret == 0) && (input[idx++] != ASN_TAG_NULL)) {
  2262. ret = ASN_TAG_NULL_E;
  2263. }
  2264. /* Check the length is zero. */
  2265. if ((ret == 0) && (input[idx++] != 0)) {
  2266. ret = ASN_EXPECT_0_E;
  2267. }
  2268. if (ret == 0) {
  2269. /* Return the index after NULL tag. */
  2270. *inOutIdx = idx;
  2271. }
  2272. /* Return error code. */
  2273. return ret;
  2274. }
  2275. #endif
  2276. #ifndef WOLFSSL_ASN_TEMPLATE
  2277. /* Set the DER/BER encoding of the ASN.1 NULL element.
  2278. *
  2279. * output Buffer to write into.
  2280. * returns the number of bytes added to the buffer.
  2281. */
  2282. static int SetASNNull(byte* output)
  2283. {
  2284. output[0] = ASN_TAG_NULL;
  2285. output[1] = 0;
  2286. return 2;
  2287. }
  2288. #endif
  2289. #ifndef NO_CERTS
  2290. #ifndef WOLFSSL_ASN_TEMPLATE
  2291. /* Get the DER/BER encoding of an ASN.1 BOOLEAN.
  2292. *
  2293. * input Buffer holding DER/BER encoded data.
  2294. * inOutIdx Current index into buffer to parse.
  2295. * maxIdx Length of data in buffer.
  2296. * returns BUFFER_E when there is not enough data to parse.
  2297. * ASN_PARSE_E when the BOOLEAN tag is not found or length is not 1.
  2298. * Otherwise, 0 to indicate the value was false and 1 to indicate true.
  2299. */
  2300. static int GetBoolean(const byte* input, word32* inOutIdx, word32 maxIdx)
  2301. {
  2302. word32 idx = *inOutIdx;
  2303. byte b;
  2304. if ((idx + 3) > maxIdx)
  2305. return BUFFER_E;
  2306. b = input[idx++];
  2307. if (b != ASN_BOOLEAN)
  2308. return ASN_PARSE_E;
  2309. if (input[idx++] != 1)
  2310. return ASN_PARSE_E;
  2311. b = input[idx++] != 0;
  2312. *inOutIdx = idx;
  2313. return b;
  2314. }
  2315. #endif
  2316. #endif /* !NO_CERTS*/
  2317. /* Decode the header of a BER/DER encoded OCTET STRING.
  2318. *
  2319. * @param [in] input Buffer holding DER/BER encoded data.
  2320. * @param [in, out] inOutIdx On in, starting index of header.
  2321. * On out, end of parsed header.
  2322. * @param [out] len Number of bytes in the ASN.1 data.
  2323. * @param [in] maxIdx Length of data in buffer.
  2324. * @return Number of bytes in the ASN.1 data on success.
  2325. * @return BUFFER_E when there is not enough data to parse.
  2326. * @return ASN_PARSE_E when the tag is not a OCTET STRING or length is invalid.
  2327. */
  2328. int GetOctetString(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  2329. {
  2330. return GetASNHeader(input, ASN_OCTET_STRING, inOutIdx, len, maxIdx);
  2331. }
  2332. #ifndef WOLFSSL_ASN_TEMPLATE
  2333. /* Get the DER/BER encoding of an ASN.1 INTEGER header.
  2334. *
  2335. * Removes the leading zero byte when found.
  2336. *
  2337. * input Buffer holding DER/BER encoded data.
  2338. * inOutIdx Current index into buffer to parse.
  2339. * len The number of bytes in the ASN.1 data (excluding any leading zero).
  2340. * maxIdx Length of data in buffer.
  2341. * returns BUFFER_E when there is not enough data to parse.
  2342. * ASN_PARSE_E when the INTEGER tag is not found, length is invalid,
  2343. * or invalid use of or missing leading zero.
  2344. * Otherwise, 0 to indicate success.
  2345. */
  2346. static int GetASNInt(const byte* input, word32* inOutIdx, int* len,
  2347. word32 maxIdx)
  2348. {
  2349. int ret;
  2350. ret = GetASNHeader(input, ASN_INTEGER, inOutIdx, len, maxIdx);
  2351. if (ret < 0)
  2352. return ret;
  2353. if (*len > 0) {
  2354. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2355. /* check for invalid padding on negative integer.
  2356. * c.f. X.690 (ISO/IEC 8825-2:2003 (E)) 10.4.6; RFC 5280 4.1
  2357. */
  2358. if (*len > 1) {
  2359. if ((input[*inOutIdx] == 0xff) && (input[*inOutIdx + 1] & 0x80))
  2360. return ASN_PARSE_E;
  2361. }
  2362. #endif
  2363. /* remove leading zero, unless there is only one 0x00 byte */
  2364. if ((input[*inOutIdx] == 0x00) && (*len > 1)) {
  2365. (*inOutIdx)++;
  2366. (*len)--;
  2367. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2368. if (*len > 0 && (input[*inOutIdx] & 0x80) == 0)
  2369. return ASN_PARSE_E;
  2370. #endif
  2371. }
  2372. }
  2373. return 0;
  2374. }
  2375. #ifndef NO_CERTS
  2376. /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
  2377. * 7 bits.
  2378. *
  2379. * input Buffer holding DER/BER encoded data.
  2380. * inOutIdx Current index into buffer to parse.
  2381. * maxIdx Length of data in buffer.
  2382. * returns BUFFER_E when there is not enough data to parse.
  2383. * ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
  2384. * Otherwise, the 7-bit value.
  2385. */
  2386. static int GetInteger7Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
  2387. {
  2388. word32 idx = *inOutIdx;
  2389. byte b;
  2390. if ((idx + 3) > maxIdx)
  2391. return BUFFER_E;
  2392. if (GetASNTag(input, &idx, &b, maxIdx) != 0)
  2393. return ASN_PARSE_E;
  2394. if (b != ASN_INTEGER)
  2395. return ASN_PARSE_E;
  2396. if (input[idx++] != 1)
  2397. return ASN_PARSE_E;
  2398. b = input[idx++];
  2399. *inOutIdx = idx;
  2400. return b;
  2401. }
  2402. #if defined(WC_RSA_PSS) && !defined(NO_RSA)
  2403. /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
  2404. * 16 bits.
  2405. *
  2406. * input Buffer holding DER/BER encoded data.
  2407. * inOutIdx Current index into buffer to parse.
  2408. * maxIdx Length of data in buffer.
  2409. * returns BUFFER_E when there is not enough data to parse.
  2410. * ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
  2411. * Otherwise, the 16-bit value.
  2412. */
  2413. static int GetInteger16Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
  2414. {
  2415. word32 idx = *inOutIdx;
  2416. byte tag;
  2417. word16 n;
  2418. if ((idx + 2) > maxIdx)
  2419. return BUFFER_E;
  2420. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2421. return ASN_PARSE_E;
  2422. if (tag != ASN_INTEGER)
  2423. return ASN_PARSE_E;
  2424. if (input[idx] == 1) {
  2425. idx++;
  2426. if ((idx + 1) > maxIdx) {
  2427. return ASN_PARSE_E;
  2428. }
  2429. n = input[idx++];
  2430. }
  2431. else if (input[idx] == 2) {
  2432. idx++;
  2433. if ((idx + 2) > maxIdx) {
  2434. return ASN_PARSE_E;
  2435. }
  2436. n = input[idx++];
  2437. n = (n << 8) | input[idx++];
  2438. }
  2439. else
  2440. return ASN_PARSE_E;
  2441. *inOutIdx = idx;
  2442. return n;
  2443. }
  2444. #endif /* WC_RSA_PSS && !NO_RSA */
  2445. #endif /* !NO_CERTS */
  2446. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2447. #if !defined(NO_DSA) && !defined(NO_SHA)
  2448. static const char sigSha1wDsaName[] = "SHAwDSA";
  2449. static const char sigSha256wDsaName[] = "SHA256wDSA";
  2450. #endif /* NO_DSA */
  2451. #ifndef NO_RSA
  2452. #ifdef WOLFSSL_MD2
  2453. static const char sigMd2wRsaName[] = "md2WithRSAEncryption";
  2454. #endif
  2455. #ifndef NO_MD5
  2456. static const char sigMd5wRsaName[] = "md5WithRSAEncryption";
  2457. #endif
  2458. #ifndef NO_SHA
  2459. static const char sigSha1wRsaName[] = "sha1WithRSAEncryption";
  2460. #endif
  2461. #ifdef WOLFSSL_SHA224
  2462. static const char sigSha224wRsaName[] = "sha224WithRSAEncryption";
  2463. #endif
  2464. #ifndef NO_SHA256
  2465. static const char sigSha256wRsaName[] = "sha256WithRSAEncryption";
  2466. #endif
  2467. #ifdef WOLFSSL_SHA384
  2468. static const char sigSha384wRsaName[] = "sha384WithRSAEncryption";
  2469. #endif
  2470. #ifdef WOLFSSL_SHA512
  2471. static const char sigSha512wRsaName[] = "sha512WithRSAEncryption";
  2472. #endif
  2473. #ifdef WOLFSSL_SHA3
  2474. #ifndef WOLFSSL_NOSHA3_224
  2475. static const char sigSha3_224wRsaName[] = "sha3_224WithRSAEncryption";
  2476. #endif
  2477. #ifndef WOLFSSL_NOSHA3_256
  2478. static const char sigSha3_256wRsaName[] = "sha3_256WithRSAEncryption";
  2479. #endif
  2480. #ifndef WOLFSSL_NOSHA3_384
  2481. static const char sigSha3_384wRsaName[] = "sha3_384WithRSAEncryption";
  2482. #endif
  2483. #ifndef WOLFSSL_NOSHA3_512
  2484. static const char sigSha3_512wRsaName[] = "sha3_512WithRSAEncryption";
  2485. #endif
  2486. #endif
  2487. #ifdef WC_RSA_PSS
  2488. static const char sigRsaSsaPssName[] = "rsassaPss";
  2489. #endif
  2490. #endif /* NO_RSA */
  2491. #ifdef HAVE_ECC
  2492. #ifndef NO_SHA
  2493. static const char sigSha1wEcdsaName[] = "SHAwECDSA";
  2494. #endif
  2495. #ifdef WOLFSSL_SHA224
  2496. static const char sigSha224wEcdsaName[] = "SHA224wECDSA";
  2497. #endif
  2498. #ifndef NO_SHA256
  2499. static const char sigSha256wEcdsaName[] = "SHA256wECDSA";
  2500. #endif
  2501. #ifdef WOLFSSL_SHA384
  2502. static const char sigSha384wEcdsaName[] = "SHA384wECDSA";
  2503. #endif
  2504. #ifdef WOLFSSL_SHA512
  2505. static const char sigSha512wEcdsaName[] = "SHA512wECDSA";
  2506. #endif
  2507. #ifdef WOLFSSL_SHA3
  2508. #ifndef WOLFSSL_NOSHA3_224
  2509. static const char sigSha3_224wEcdsaName[] = "SHA3_224wECDSA";
  2510. #endif
  2511. #ifndef WOLFSSL_NOSHA3_256
  2512. static const char sigSha3_256wEcdsaName[] = "SHA3_256wECDSA";
  2513. #endif
  2514. #ifndef WOLFSSL_NOSHA3_384
  2515. static const char sigSha3_384wEcdsaName[] = "SHA3_384wECDSA";
  2516. #endif
  2517. #ifndef WOLFSSL_NOSHA3_512
  2518. static const char sigSha3_512wEcdsaName[] = "SHA3_512wECDSA";
  2519. #endif
  2520. #endif
  2521. #endif /* HAVE_ECC */
  2522. static const char sigUnknownName[] = "Unknown";
  2523. /* Get the human readable string for a signature type
  2524. *
  2525. * oid Oid value for signature
  2526. */
  2527. const char* GetSigName(int oid) {
  2528. switch (oid) {
  2529. #if !defined(NO_DSA) && !defined(NO_SHA)
  2530. case CTC_SHAwDSA:
  2531. return sigSha1wDsaName;
  2532. case CTC_SHA256wDSA:
  2533. return sigSha256wDsaName;
  2534. #endif /* NO_DSA && NO_SHA */
  2535. #ifndef NO_RSA
  2536. #ifdef WOLFSSL_MD2
  2537. case CTC_MD2wRSA:
  2538. return sigMd2wRsaName;
  2539. #endif
  2540. #ifndef NO_MD5
  2541. case CTC_MD5wRSA:
  2542. return sigMd5wRsaName;
  2543. #endif
  2544. #ifndef NO_SHA
  2545. case CTC_SHAwRSA:
  2546. return sigSha1wRsaName;
  2547. #endif
  2548. #ifdef WOLFSSL_SHA224
  2549. case CTC_SHA224wRSA:
  2550. return sigSha224wRsaName;
  2551. #endif
  2552. #ifndef NO_SHA256
  2553. case CTC_SHA256wRSA:
  2554. return sigSha256wRsaName;
  2555. #endif
  2556. #ifdef WOLFSSL_SHA384
  2557. case CTC_SHA384wRSA:
  2558. return sigSha384wRsaName;
  2559. #endif
  2560. #ifdef WOLFSSL_SHA512
  2561. case CTC_SHA512wRSA:
  2562. return sigSha512wRsaName;
  2563. #endif
  2564. #ifdef WOLFSSL_SHA3
  2565. #ifndef WOLFSSL_NOSHA3_224
  2566. case CTC_SHA3_224wRSA:
  2567. return sigSha3_224wRsaName;
  2568. #endif
  2569. #ifndef WOLFSSL_NOSHA3_256
  2570. case CTC_SHA3_256wRSA:
  2571. return sigSha3_256wRsaName;
  2572. #endif
  2573. #ifndef WOLFSSL_NOSHA3_384
  2574. case CTC_SHA3_384wRSA:
  2575. return sigSha3_384wRsaName;
  2576. #endif
  2577. #ifndef WOLFSSL_NOSHA3_512
  2578. case CTC_SHA3_512wRSA:
  2579. return sigSha3_512wRsaName;
  2580. #endif
  2581. #endif
  2582. #ifdef WC_RSA_PSS
  2583. case CTC_RSASSAPSS:
  2584. return sigRsaSsaPssName;
  2585. #endif
  2586. #endif /* NO_RSA */
  2587. #ifdef HAVE_ECC
  2588. #ifndef NO_SHA
  2589. case CTC_SHAwECDSA:
  2590. return sigSha1wEcdsaName;
  2591. #endif
  2592. #ifdef WOLFSSL_SHA224
  2593. case CTC_SHA224wECDSA:
  2594. return sigSha224wEcdsaName;
  2595. #endif
  2596. #ifndef NO_SHA256
  2597. case CTC_SHA256wECDSA:
  2598. return sigSha256wEcdsaName;
  2599. #endif
  2600. #ifdef WOLFSSL_SHA384
  2601. case CTC_SHA384wECDSA:
  2602. return sigSha384wEcdsaName;
  2603. #endif
  2604. #ifdef WOLFSSL_SHA512
  2605. case CTC_SHA512wECDSA:
  2606. return sigSha512wEcdsaName;
  2607. #endif
  2608. #ifdef WOLFSSL_SHA3
  2609. #ifndef WOLFSSL_NOSHA3_224
  2610. case CTC_SHA3_224wECDSA:
  2611. return sigSha3_224wEcdsaName;
  2612. #endif
  2613. #ifndef WOLFSSL_NOSHA3_256
  2614. case CTC_SHA3_256wECDSA:
  2615. return sigSha3_256wEcdsaName;
  2616. #endif
  2617. #ifndef WOLFSSL_NOSHA3_384
  2618. case CTC_SHA3_384wECDSA:
  2619. return sigSha3_384wEcdsaName;
  2620. #endif
  2621. #ifndef WOLFSSL_NOSHA3_512
  2622. case CTC_SHA3_512wECDSA:
  2623. return sigSha3_512wEcdsaName;
  2624. #endif
  2625. #endif
  2626. #endif /* HAVE_ECC */
  2627. default:
  2628. return sigUnknownName;
  2629. }
  2630. }
  2631. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7) || \
  2632. defined(OPENSSL_EXTRA)
  2633. #if !defined(NO_DSA) || defined(HAVE_ECC) || !defined(NO_CERTS) || \
  2634. (!defined(NO_RSA) && \
  2635. (defined(WOLFSSL_CERT_GEN) || \
  2636. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA))))
  2637. /* Set the DER/BER encoding of the ASN.1 INTEGER header.
  2638. *
  2639. * When output is NULL, calculate the header length only.
  2640. *
  2641. * @param [in] len Length of INTEGER data in bytes.
  2642. * @param [in] firstByte First byte of data, most significant byte of integer,
  2643. * to encode.
  2644. * @param [out] output Buffer to write into.
  2645. * @return Number of bytes added to the buffer.
  2646. */
  2647. int SetASNInt(int len, byte firstByte, byte* output)
  2648. {
  2649. int idx = 0;
  2650. if (output) {
  2651. /* Write out tag. */
  2652. output[idx] = ASN_INTEGER;
  2653. }
  2654. /* Step over tag. */
  2655. idx += ASN_TAG_SZ;
  2656. /* Check if first byte has top bit set in which case a 0 is needed to
  2657. * maintain positive value. */
  2658. if (firstByte & 0x80) {
  2659. /* Add pre-prepended byte to length of data in INTEGER. */
  2660. len++;
  2661. }
  2662. /* Encode length - passing NULL for output will not encode. */
  2663. idx += (int)SetLength((word32)len, output ? output + idx : NULL);
  2664. /* Put out pre-pended 0 as well. */
  2665. if (firstByte & 0x80) {
  2666. if (output) {
  2667. /* Write out 0 byte. */
  2668. output[idx] = 0x00;
  2669. }
  2670. /* Update index. */
  2671. idx++;
  2672. }
  2673. /* Return index after header. */
  2674. return idx;
  2675. }
  2676. #endif
  2677. #endif
  2678. #ifndef WOLFSSL_ASN_TEMPLATE
  2679. #if !defined(NO_DSA) || defined(HAVE_ECC) || (defined(WOLFSSL_CERT_GEN) && \
  2680. !defined(NO_RSA)) || ((defined(WOLFSSL_KEY_GEN) || \
  2681. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)) || \
  2682. defined(OPENSSL_EXTRA)) && !defined(NO_RSA) && !defined(HAVE_USER_RSA))
  2683. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int.
  2684. * The number is assumed to be positive.
  2685. *
  2686. * n Multi-precision integer to encode.
  2687. * maxSz Maximum size of the encoded integer.
  2688. * A negative value indicates no check of length requested.
  2689. * output Buffer to write into.
  2690. * returns BUFFER_E when the data is too long for the buffer.
  2691. * MP_TO_E when encoding the integer fails.
  2692. * Otherwise, the number of bytes added to the buffer.
  2693. */
  2694. static int SetASNIntMP(mp_int* n, int maxSz, byte* output)
  2695. {
  2696. int idx = 0;
  2697. int leadingBit;
  2698. int length;
  2699. leadingBit = mp_leading_bit(n);
  2700. length = mp_unsigned_bin_size(n);
  2701. if (maxSz >= 0 && (1 + length + (leadingBit ? 1 : 0)) > maxSz)
  2702. return BUFFER_E;
  2703. idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output);
  2704. if (maxSz >= 0 && (idx + length) > maxSz)
  2705. return BUFFER_E;
  2706. if (output) {
  2707. int err = mp_to_unsigned_bin(n, output + idx);
  2708. if (err != MP_OKAY)
  2709. return MP_TO_E;
  2710. }
  2711. idx += length;
  2712. return idx;
  2713. }
  2714. #endif
  2715. #if !defined(NO_RSA) && defined(HAVE_USER_RSA) && \
  2716. (defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA))
  2717. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int from
  2718. * an RSA key.
  2719. * The number is assumed to be positive.
  2720. *
  2721. * n Multi-precision integer to encode.
  2722. * output Buffer to write into.
  2723. * returns BUFFER_E when the data is too long for the buffer.
  2724. * MP_TO_E when encoding the integer fails.
  2725. * Otherwise, the number of bytes added to the buffer.
  2726. */
  2727. static int SetASNIntRSA(void* n, byte* output)
  2728. {
  2729. int idx = 0;
  2730. int leadingBit;
  2731. int length;
  2732. leadingBit = wc_Rsa_leading_bit(n);
  2733. length = wc_Rsa_unsigned_bin_size(n);
  2734. idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output);
  2735. if ((idx + length) > MAX_RSA_INT_SZ)
  2736. return BUFFER_E;
  2737. if (output) {
  2738. int err = wc_Rsa_to_unsigned_bin(n, output + idx, length);
  2739. if (err != MP_OKAY)
  2740. return MP_TO_E;
  2741. }
  2742. idx += length;
  2743. return idx;
  2744. }
  2745. #endif /* !NO_RSA && HAVE_USER_RSA && WOLFSSL_CERT_GEN */
  2746. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2747. #ifdef WOLFSSL_ASN_TEMPLATE
  2748. /* ASN.1 template for an INTEGER. */
  2749. static const ASNItem intASN[] = {
  2750. /* INT */ { 0, ASN_INTEGER, 0, 0, 0 }
  2751. };
  2752. enum {
  2753. INTASN_IDX_INT = 0
  2754. };
  2755. /* Number of items in ASN.1 template for an INTEGER. */
  2756. #define intASN_Length (sizeof(intASN) / sizeof(ASNItem))
  2757. #endif /* WOLFSSL_ASN_TEMPLATE */
  2758. /* Windows header clash for WinCE using GetVersion */
  2759. /* Decode Version - one byte INTEGER.
  2760. *
  2761. * @param [in] input Buffer of BER data.
  2762. * @param [in, out] inOutIdx On in, start of encoded Version.
  2763. * On out, start of next encode ASN.1 item.
  2764. * @param [out] version Number encoded in INTEGER.
  2765. * @param [in] maxIdx Maximum index of data in buffer.
  2766. * @return 0 on success.
  2767. * @return ASN_PARSE_E when encoding is invalid.
  2768. * @return BUFFER_E when data in buffer is too small.
  2769. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2770. */
  2771. int GetMyVersion(const byte* input, word32* inOutIdx,
  2772. int* version, word32 maxIdx)
  2773. {
  2774. #ifndef WOLFSSL_ASN_TEMPLATE
  2775. word32 idx = *inOutIdx;
  2776. byte tag;
  2777. if ((idx + MIN_VERSION_SZ) > maxIdx)
  2778. return ASN_PARSE_E;
  2779. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2780. return ASN_PARSE_E;
  2781. if (tag != ASN_INTEGER)
  2782. return ASN_PARSE_E;
  2783. if (input[idx++] != 0x01)
  2784. return ASN_VERSION_E;
  2785. *version = input[idx++];
  2786. *inOutIdx = idx;
  2787. return *version;
  2788. #else
  2789. ASNGetData dataASN[intASN_Length];
  2790. int ret;
  2791. byte num;
  2792. /* Clear dynamic data and set the version number variable. */
  2793. XMEMSET(dataASN, 0, sizeof(dataASN));
  2794. GetASN_Int8Bit(&dataASN[INTASN_IDX_INT], &num);
  2795. /* Decode the version (INTEGER). */
  2796. ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2797. maxIdx);
  2798. if (ret == 0) {
  2799. /* Return version through variable and return value. */
  2800. *version = num;
  2801. ret = num;
  2802. }
  2803. return ret;
  2804. #endif /* WOLFSSL_ASN_TEMPLATE */
  2805. }
  2806. #ifndef NO_PWDBASED
  2807. /* Decode small integer, 32 bits or less.
  2808. *
  2809. * @param [in] input Buffer of BER data.
  2810. * @param [in, out] inOutIdx On in, start of encoded INTEGER.
  2811. * On out, start of next encode ASN.1 item.
  2812. * @param [out] number Number encoded in INTEGER.
  2813. * @param [in] maxIdx Maximum index of data in buffer.
  2814. * @return 0 on success.
  2815. * @return ASN_PARSE_E when encoding is invalid.
  2816. * @return BUFFER_E when data in buffer is too small.
  2817. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2818. */
  2819. int GetShortInt(const byte* input, word32* inOutIdx, int* number, word32 maxIdx)
  2820. {
  2821. #ifndef WOLFSSL_ASN_TEMPLATE
  2822. word32 idx = *inOutIdx;
  2823. word32 len;
  2824. byte tag;
  2825. *number = 0;
  2826. /* check for type and length bytes */
  2827. if ((idx + 2) > maxIdx)
  2828. return BUFFER_E;
  2829. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2830. return ASN_PARSE_E;
  2831. if (tag != ASN_INTEGER)
  2832. return ASN_PARSE_E;
  2833. len = input[idx++];
  2834. if (len > 4)
  2835. return ASN_PARSE_E;
  2836. if (len + idx > maxIdx)
  2837. return ASN_PARSE_E;
  2838. while (len--) {
  2839. *number = *number << 8 | input[idx++];
  2840. }
  2841. *inOutIdx = idx;
  2842. return *number;
  2843. #else
  2844. ASNGetData dataASN[intASN_Length];
  2845. int ret;
  2846. word32 num;
  2847. /* Clear dynamic data and set the 32-bit number variable. */
  2848. XMEMSET(dataASN, 0, sizeof(dataASN));
  2849. GetASN_Int32Bit(&dataASN[INTASN_IDX_INT], &num);
  2850. /* Decode the short int (INTEGER). */
  2851. ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2852. maxIdx);
  2853. if (ret == 0) {
  2854. /* Return number through variable and return value. */
  2855. *number = (int)num;
  2856. ret = (int)num;
  2857. }
  2858. return ret;
  2859. #endif
  2860. }
  2861. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS8) || \
  2862. defined(HAVE_PKCS12)
  2863. /* Set small integer, 32 bits or less. DER encoding with no leading 0s
  2864. * returns total amount written including ASN tag and length byte on success */
  2865. int SetShortInt(byte* input, word32* inOutIdx, word32 number, word32 maxIdx)
  2866. {
  2867. word32 idx = *inOutIdx;
  2868. int len = 0;
  2869. int i;
  2870. byte ar[MAX_LENGTH_SZ];
  2871. /* check for room for type and length bytes */
  2872. if ((idx + 2) > maxIdx)
  2873. return BUFFER_E;
  2874. input[idx++] = ASN_INTEGER;
  2875. idx++; /* place holder for length byte */
  2876. if (MAX_LENGTH_SZ + idx > maxIdx)
  2877. return ASN_PARSE_E;
  2878. /* find first non zero byte */
  2879. XMEMSET(ar, 0, MAX_LENGTH_SZ);
  2880. c32toa(number, ar);
  2881. for (i = 0; i < MAX_LENGTH_SZ; i++) {
  2882. if (ar[i] != 0) {
  2883. break;
  2884. }
  2885. }
  2886. /* handle case of 0 */
  2887. if (i == MAX_LENGTH_SZ) {
  2888. input[idx++] = 0; len++;
  2889. }
  2890. for (; i < MAX_LENGTH_SZ && idx < maxIdx; i++) {
  2891. input[idx++] = ar[i]; len++;
  2892. }
  2893. /* jump back to beginning of input buffer using unaltered inOutIdx value
  2894. * and set number of bytes for integer, then update the index value */
  2895. input[*inOutIdx + 1] = (byte)len;
  2896. *inOutIdx = idx;
  2897. return len + 2; /* size of integer bytes plus ASN TAG and length byte */
  2898. }
  2899. #endif /* !WOLFSSL_ASN_TEMPLATE || HAVE_PKCS8 || HAVE_PKCS12 */
  2900. #endif /* !NO_PWDBASED */
  2901. #ifndef WOLFSSL_ASN_TEMPLATE
  2902. /* May not have one, not an error */
  2903. static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version,
  2904. word32 maxIdx)
  2905. {
  2906. word32 idx = *inOutIdx;
  2907. byte tag;
  2908. WOLFSSL_ENTER("GetExplicitVersion");
  2909. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2910. return ASN_PARSE_E;
  2911. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  2912. int ret;
  2913. *inOutIdx = ++idx; /* skip header */
  2914. ret = GetMyVersion(input, inOutIdx, version, maxIdx);
  2915. if (ret >= 0) {
  2916. /* check if version is expected value rfc 5280 4.1 {0, 1, 2} */
  2917. if (*version > MAX_X509_VERSION || *version < MIN_X509_VERSION) {
  2918. WOLFSSL_MSG("Unexpected certificate version");
  2919. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  2920. ret = ASN_VERSION_E;
  2921. }
  2922. }
  2923. return ret;
  2924. }
  2925. /* go back as is */
  2926. *version = 0;
  2927. return 0;
  2928. }
  2929. #endif
  2930. /* Decode small integer, 32 bits or less.
  2931. *
  2932. * mp_int is initialized.
  2933. *
  2934. * @param [out] mpi mp_int to hold number.
  2935. * @param [in] input Buffer of BER data.
  2936. * @param [in, out] inOutIdx On in, start of encoded INTEGER.
  2937. * On out, start of next encode ASN.1 item.
  2938. * @param [in] maxIdx Maximum index of data in buffer.
  2939. * @return 0 on success.
  2940. * @return ASN_PARSE_E when encoding is invalid.
  2941. * @return BUFFER_E when data in buffer is too small.
  2942. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2943. * @return MP_INIT_E when the unable to initialize an mp_int.
  2944. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  2945. */
  2946. int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, word32 maxIdx)
  2947. {
  2948. #ifndef WOLFSSL_ASN_TEMPLATE
  2949. word32 idx = *inOutIdx;
  2950. int ret;
  2951. int length;
  2952. ret = GetASNInt(input, &idx, &length, maxIdx);
  2953. if (ret != 0)
  2954. return ret;
  2955. if (mp_init(mpi) != MP_OKAY)
  2956. return MP_INIT_E;
  2957. if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) {
  2958. mp_clear(mpi);
  2959. return ASN_GETINT_E;
  2960. }
  2961. #ifdef HAVE_WOLF_BIGINT
  2962. if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
  2963. mp_clear(mpi);
  2964. return ASN_GETINT_E;
  2965. }
  2966. #endif /* HAVE_WOLF_BIGINT */
  2967. *inOutIdx = idx + (word32)length;
  2968. return 0;
  2969. #else
  2970. ASNGetData dataASN[intASN_Length];
  2971. /* Clear dynamic data and set the mp_int to fill with value. */
  2972. XMEMSET(dataASN, 0, sizeof(dataASN));
  2973. GetASN_MP_PosNeg(&dataASN[INTASN_IDX_INT], mpi);
  2974. /* Decode the big number (INTEGER). */
  2975. return GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2976. maxIdx);
  2977. #endif
  2978. }
  2979. #if (defined(HAVE_ECC) || !defined(NO_DSA)) && !defined(WOLFSSL_ASN_TEMPLATE)
  2980. static int GetIntPositive(mp_int* mpi, const byte* input, word32* inOutIdx,
  2981. word32 maxIdx, int initNum)
  2982. {
  2983. word32 idx = *inOutIdx;
  2984. int ret;
  2985. int length;
  2986. ret = GetASNInt(input, &idx, &length, maxIdx);
  2987. if (ret != 0)
  2988. return ret;
  2989. if (((input[idx] & 0x80) == 0x80) && (input[idx - 1] != 0x00))
  2990. return MP_INIT_E;
  2991. if (initNum) {
  2992. if (mp_init(mpi) != MP_OKAY)
  2993. return MP_INIT_E;
  2994. }
  2995. if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) {
  2996. mp_clear(mpi);
  2997. return ASN_GETINT_E;
  2998. }
  2999. #ifdef HAVE_WOLF_BIGINT
  3000. if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
  3001. mp_clear(mpi);
  3002. return ASN_GETINT_E;
  3003. }
  3004. #endif /* HAVE_WOLF_BIGINT */
  3005. *inOutIdx = idx + (word32)length;
  3006. return 0;
  3007. }
  3008. #endif /* (ECC || !NO_DSA) && !WOLFSSL_ASN_TEMPLATE */
  3009. #ifndef WOLFSSL_ASN_TEMPLATE
  3010. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA)) || !defined(NO_DSA)
  3011. static int SkipInt(const byte* input, word32* inOutIdx, word32 maxIdx)
  3012. {
  3013. word32 idx = *inOutIdx;
  3014. int ret;
  3015. int length;
  3016. ret = GetASNInt(input, &idx, &length, maxIdx);
  3017. if (ret != 0)
  3018. return ret;
  3019. *inOutIdx = idx + (word32)length;
  3020. return 0;
  3021. }
  3022. #endif
  3023. #endif /* !WOLFSSL_ASN_TEMPLATE */
  3024. #ifdef WOLFSSL_ASN_TEMPLATE
  3025. /* ASN.1 template for a BIT_STRING. */
  3026. static const ASNItem bitStringASN[] = {
  3027. /* BIT_STR */ { 0, ASN_BIT_STRING, 0, 1, 0 }
  3028. };
  3029. enum {
  3030. BITSTRINGASN_IDX_BIT_STR = 0
  3031. };
  3032. /* Number of items in ASN.1 template for a BIT_STRING. */
  3033. #define bitStringASN_Length (sizeof(bitStringASN) / sizeof(ASNItem))
  3034. #endif
  3035. /* Decode and check the BIT_STRING is valid. Return length and unused bits.
  3036. *
  3037. * @param [in] input Buffer holding BER encoding.
  3038. * @param [in, out] inOutIdx On in, start of BIT_STRING.
  3039. * On out, start of ASN.1 item after BIT_STRING.
  3040. * @param [out] len Length of BIT_STRING data.
  3041. * @param [in] maxIdx Maximum index of data in buffer.
  3042. * @param [in] zeroBits Indicates whether zero unused bits is expected.
  3043. * @param [in] unusedBits Number of unused bits in last byte.
  3044. * @return 0 on success.
  3045. * @return ASN_PARSE_E when encoding is invalid.
  3046. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  3047. * @return BUFFER_E when data in buffer is too small.
  3048. * @return ASN_EXPECT_0_E when unused bits is not zero when expected.
  3049. */
  3050. int CheckBitString(const byte* input, word32* inOutIdx, int* len,
  3051. word32 maxIdx, int zeroBits, byte* unusedBits)
  3052. {
  3053. #ifndef WOLFSSL_ASN_TEMPLATE
  3054. word32 idx = *inOutIdx;
  3055. int length;
  3056. byte b;
  3057. if (GetASNTag(input, &idx, &b, maxIdx) != 0) {
  3058. return ASN_BITSTR_E;
  3059. }
  3060. if (b != ASN_BIT_STRING) {
  3061. return ASN_BITSTR_E;
  3062. }
  3063. if (GetLength(input, &idx, &length, maxIdx) < 0)
  3064. return ASN_PARSE_E;
  3065. /* extra sanity check that length is greater than 0 */
  3066. if (length <= 0) {
  3067. WOLFSSL_MSG("Error length was 0 in CheckBitString");
  3068. return BUFFER_E;
  3069. }
  3070. if (idx + 1 > maxIdx) {
  3071. WOLFSSL_MSG("Attempted buffer read larger than input buffer");
  3072. return BUFFER_E;
  3073. }
  3074. b = input[idx];
  3075. if (zeroBits && b != 0x00)
  3076. return ASN_EXPECT_0_E;
  3077. if (b >= 0x08)
  3078. return ASN_PARSE_E;
  3079. if (b != 0) {
  3080. if ((byte)(input[idx + (word32)length - 1] << (8 - b)) != 0)
  3081. return ASN_PARSE_E;
  3082. }
  3083. idx++;
  3084. length--; /* length has been checked for greater than 0 */
  3085. *inOutIdx = idx;
  3086. if (len != NULL)
  3087. *len = length;
  3088. if (unusedBits != NULL)
  3089. *unusedBits = b;
  3090. return 0;
  3091. #else
  3092. ASNGetData dataASN[bitStringASN_Length];
  3093. int ret;
  3094. int bits;
  3095. /* Parse BIT_STRING and check validity of unused bits. */
  3096. XMEMSET(dataASN, 0, sizeof(dataASN));
  3097. /* Decode BIT_STRING. */
  3098. ret = GetASN_Items(bitStringASN, dataASN, bitStringASN_Length, 0, input,
  3099. inOutIdx, maxIdx);
  3100. if (ret == 0) {
  3101. /* Get unused bits from dynamic ASN.1 data. */
  3102. bits = GetASNItem_UnusedBits(dataASN[BITSTRINGASN_IDX_BIT_STR]);
  3103. /* Check unused bits is 0 when expected. */
  3104. if (zeroBits && (bits != 0)) {
  3105. ret = ASN_EXPECT_0_E;
  3106. }
  3107. }
  3108. if (ret == 0) {
  3109. /* Return length of data and unused bits if required. */
  3110. if (len != NULL) {
  3111. *len = (int)dataASN[BITSTRINGASN_IDX_BIT_STR].data.ref.length;
  3112. }
  3113. if (unusedBits != NULL) {
  3114. *unusedBits = (byte)bits;
  3115. }
  3116. }
  3117. return ret;
  3118. #endif
  3119. }
  3120. /* RSA (with CertGen or KeyGen) OR ECC OR ED25519 OR ED448 (with CertGen or
  3121. * KeyGen) */
  3122. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
  3123. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
  3124. defined(OPENSSL_EXTRA))) || \
  3125. (defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)) || \
  3126. ((defined(HAVE_ED25519) || defined(HAVE_ED448)) && \
  3127. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
  3128. defined(OPENSSL_EXTRA))) || \
  3129. (defined(WC_ENABLE_ASYM_KEY_EXPORT) && !defined(NO_CERT)) || \
  3130. (!defined(NO_DSA) && !defined(HAVE_SELFTEST) && defined(WOLFSSL_KEY_GEN)) || \
  3131. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA))
  3132. /* Set the DER/BER encoding of the ASN.1 BIT STRING header.
  3133. *
  3134. * When output is NULL, calculate the header length only.
  3135. *
  3136. * @param [in] len Length of BIT STRING data.
  3137. * That is, the number of least significant zero bits
  3138. * before a one.
  3139. * The last byte is the most-significant non-zero byte
  3140. * of a number.
  3141. * @param [out] output Buffer to write into.
  3142. * @return Number of bytes added to the buffer.
  3143. */
  3144. word32 SetBitString(word32 len, byte unusedBits, byte* output)
  3145. {
  3146. word32 idx = 0;
  3147. if (output) {
  3148. /* Write out tag. */
  3149. output[idx] = ASN_BIT_STRING;
  3150. }
  3151. /* Step over tag. */
  3152. idx += ASN_TAG_SZ;
  3153. /* Encode length - passing NULL for output will not encode.
  3154. * Add one to length for unused bits. */
  3155. idx += SetLength(len + 1, output ? output + idx : NULL);
  3156. if (output) {
  3157. /* Write out unused bits. */
  3158. output[idx] = unusedBits;
  3159. }
  3160. /* Skip over unused bits. */
  3161. idx++;
  3162. /* Return index after header. */
  3163. return idx;
  3164. }
  3165. #endif /* !NO_RSA || HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  3166. #ifdef ASN_BER_TO_DER
  3167. /* Convert BER to DER */
  3168. /* Pull informtation from the ASN.1 BER encoded item header */
  3169. static int GetBerHeader(const byte* data, word32* idx, word32 maxIdx,
  3170. byte* pTag, word32* pLen, int* indef)
  3171. {
  3172. int len = 0;
  3173. byte tag;
  3174. word32 i = *idx;
  3175. *indef = 0;
  3176. /* Check there is enough data for a minimal header */
  3177. if (i + 2 > maxIdx) {
  3178. return ASN_PARSE_E;
  3179. }
  3180. /* Retrieve tag */
  3181. tag = data[i++];
  3182. /* Indefinite length handled specially */
  3183. if (data[i] == ASN_INDEF_LENGTH) {
  3184. /* Check valid tag for indefinite */
  3185. if (((tag & 0xc0) == 0) && ((tag & ASN_CONSTRUCTED) == 0x00)) {
  3186. return ASN_PARSE_E;
  3187. }
  3188. i++;
  3189. *indef = 1;
  3190. }
  3191. else if (GetLength(data, &i, &len, maxIdx) < 0) {
  3192. return ASN_PARSE_E;
  3193. }
  3194. /* Return tag, length and index after BER item header */
  3195. *pTag = tag;
  3196. *pLen = (word32)len;
  3197. *idx = i;
  3198. return 0;
  3199. }
  3200. #ifndef INDEF_ITEMS_MAX
  3201. #define INDEF_ITEMS_MAX 20
  3202. #endif
  3203. /* Indef length item data */
  3204. typedef struct Indef {
  3205. word32 start;
  3206. int depth;
  3207. int headerLen;
  3208. word32 len;
  3209. } Indef;
  3210. /* Indef length items */
  3211. typedef struct IndefItems
  3212. {
  3213. Indef len[INDEF_ITEMS_MAX];
  3214. int cnt;
  3215. int idx;
  3216. int depth;
  3217. } IndefItems;
  3218. /* Get header length of current item */
  3219. static int IndefItems_HeaderLen(IndefItems* items)
  3220. {
  3221. return items->len[items->idx].headerLen;
  3222. }
  3223. /* Get data length of current item */
  3224. static word32 IndefItems_Len(IndefItems* items)
  3225. {
  3226. return items->len[items->idx].len;
  3227. }
  3228. /* Add a indefinite length item */
  3229. static int IndefItems_AddItem(IndefItems* items, word32 start)
  3230. {
  3231. int ret = 0;
  3232. int i;
  3233. if (items->cnt == INDEF_ITEMS_MAX) {
  3234. ret = MEMORY_E;
  3235. }
  3236. else {
  3237. i = items->cnt++;
  3238. items->len[i].start = start;
  3239. items->len[i].depth = items->depth++;
  3240. items->len[i].headerLen = 1;
  3241. items->len[i].len = 0;
  3242. items->idx = i;
  3243. }
  3244. return ret;
  3245. }
  3246. /* Increase data length of current item */
  3247. static void IndefItems_AddData(IndefItems* items, word32 length)
  3248. {
  3249. items->len[items->idx].len += length;
  3250. }
  3251. /* Update header length of current item to reflect data length */
  3252. static void IndefItems_UpdateHeaderLen(IndefItems* items)
  3253. {
  3254. items->len[items->idx].headerLen +=
  3255. (int)SetLength(items->len[items->idx].len, NULL);
  3256. }
  3257. /* Go to indefinite parent of current item */
  3258. static void IndefItems_Up(IndefItems* items)
  3259. {
  3260. int i;
  3261. int depth = items->len[items->idx].depth - 1;
  3262. for (i = items->cnt - 1; i >= 0; i--) {
  3263. if (items->len[i].depth == depth) {
  3264. break;
  3265. }
  3266. }
  3267. items->idx = i;
  3268. items->depth = depth + 1;
  3269. }
  3270. /* Calculate final length by adding length of indefinite child items */
  3271. static void IndefItems_CalcLength(IndefItems* items)
  3272. {
  3273. int i;
  3274. int idx = items->idx;
  3275. for (i = idx + 1; i < items->cnt; i++) {
  3276. if (items->len[i].depth == items->depth) {
  3277. items->len[idx].len += (word32)items->len[i].headerLen;
  3278. items->len[idx].len += items->len[i].len;
  3279. }
  3280. }
  3281. items->len[idx].headerLen += (int)SetLength(items->len[idx].len, NULL);
  3282. }
  3283. /* Add more data to indefinite length item */
  3284. static void IndefItems_MoreData(IndefItems* items, word32 length)
  3285. {
  3286. if (items->cnt > 0 && items->idx >= 0) {
  3287. items->len[items->idx].len += length;
  3288. }
  3289. }
  3290. /* Convert a BER encoding with indefinite length items to DER.
  3291. *
  3292. * ber BER encoded data.
  3293. * berSz Length of BER encoded data.
  3294. * der Buffer to hold DER encoded version of data.
  3295. * NULL indicates only the length is required.
  3296. * derSz The size of the buffer to hold the DER encoded data.
  3297. * Will be set if der is NULL, otherwise the value is checked as der is
  3298. * filled.
  3299. * returns ASN_PARSE_E if the BER data is invalid and BAD_FUNC_ARG if ber or
  3300. * derSz are NULL.
  3301. */
  3302. int wc_BerToDer(const byte* ber, word32 berSz, byte* der, word32* derSz)
  3303. {
  3304. int ret = 0;
  3305. word32 i, j;
  3306. #ifdef WOLFSSL_SMALL_STACK
  3307. IndefItems* indefItems = NULL;
  3308. #else
  3309. IndefItems indefItems[1];
  3310. #endif
  3311. byte tag, basic;
  3312. word32 length;
  3313. int indef;
  3314. if (ber == NULL || derSz == NULL)
  3315. return BAD_FUNC_ARG;
  3316. #ifdef WOLFSSL_SMALL_STACK
  3317. indefItems = (IndefItems *)XMALLOC(sizeof(IndefItems), NULL,
  3318. DYNAMIC_TYPE_TMP_BUFFER);
  3319. if (indefItems == NULL) {
  3320. ret = MEMORY_E;
  3321. goto end;
  3322. }
  3323. #endif
  3324. XMEMSET(indefItems, 0, sizeof(*indefItems));
  3325. /* Calculate indefinite item lengths */
  3326. for (i = 0; i < berSz; ) {
  3327. word32 start = i;
  3328. /* Get next BER item */
  3329. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3330. if (ret != 0) {
  3331. goto end;
  3332. }
  3333. if (indef) {
  3334. /* Indefinite item - add to list */
  3335. ret = IndefItems_AddItem(indefItems, i);
  3336. if (ret != 0) {
  3337. goto end;
  3338. }
  3339. if ((tag & 0xC0) == 0 &&
  3340. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3341. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3342. /* Constructed basic type - get repeating tag */
  3343. basic = (byte)(tag & (~ASN_CONSTRUCTED));
  3344. /* Add up lengths of each item below */
  3345. for (; i < berSz; ) {
  3346. /* Get next BER_item */
  3347. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3348. if (ret != 0) {
  3349. goto end;
  3350. }
  3351. /* End of content closes item */
  3352. if (tag == ASN_EOC) {
  3353. /* Must be zero length */
  3354. if (length != 0) {
  3355. ret = ASN_PARSE_E;
  3356. goto end;
  3357. }
  3358. break;
  3359. }
  3360. /* Must not be indefinite and tag must match parent */
  3361. if (indef || tag != basic) {
  3362. ret = ASN_PARSE_E;
  3363. goto end;
  3364. }
  3365. /* Add to length */
  3366. IndefItems_AddData(indefItems, length);
  3367. /* Skip data */
  3368. i += length;
  3369. }
  3370. /* Ensure we got an EOC and not end of data */
  3371. if (tag != ASN_EOC) {
  3372. ret = ASN_PARSE_E;
  3373. goto end;
  3374. }
  3375. /* Set the header length to include the length field */
  3376. IndefItems_UpdateHeaderLen(indefItems);
  3377. /* Go to indefinite parent item */
  3378. IndefItems_Up(indefItems);
  3379. }
  3380. }
  3381. else if (tag == ASN_EOC) {
  3382. /* End-of-content must be 0 length */
  3383. if (length != 0) {
  3384. ret = ASN_PARSE_E;
  3385. goto end;
  3386. }
  3387. /* Check there is an item to close - missing EOC */
  3388. if (indefItems->depth == 0) {
  3389. ret = ASN_PARSE_E;
  3390. goto end;
  3391. }
  3392. /* Finish calculation of data length for indefinite item */
  3393. IndefItems_CalcLength(indefItems);
  3394. /* Go to indefinite parent item */
  3395. IndefItems_Up(indefItems);
  3396. }
  3397. else {
  3398. /* Known length item to add in - make sure enough data for it */
  3399. if (i + length > berSz) {
  3400. ret = ASN_PARSE_E;
  3401. goto end;
  3402. }
  3403. /* Include all data - can't have indefinite inside definite */
  3404. i += length;
  3405. /* Add entire item to current indefinite item */
  3406. IndefItems_MoreData(indefItems, i - start);
  3407. }
  3408. }
  3409. /* Check we had a EOC for each indefinite item */
  3410. if (indefItems->depth != 0) {
  3411. ret = ASN_PARSE_E;
  3412. goto end;
  3413. }
  3414. /* Write out DER */
  3415. j = 0;
  3416. /* Reset index */
  3417. indefItems->idx = 0;
  3418. for (i = 0; i < berSz; ) {
  3419. word32 start = i;
  3420. /* Get item - checked above */
  3421. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3422. if (indef) {
  3423. if (der != NULL) {
  3424. /* Check enough space for header */
  3425. if (j + (word32)IndefItems_HeaderLen(indefItems) > *derSz) {
  3426. ret = BUFFER_E;
  3427. goto end;
  3428. }
  3429. if ((tag & 0xC0) == 0 &&
  3430. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3431. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3432. /* Remove constructed tag for basic types */
  3433. tag &= (byte)~ASN_CONSTRUCTED;
  3434. }
  3435. /* Add tag and length */
  3436. der[j] = tag;
  3437. (void)SetLength(IndefItems_Len(indefItems), der + j + 1);
  3438. }
  3439. /* Add header length of indefinite item */
  3440. j += (word32)IndefItems_HeaderLen(indefItems);
  3441. if ((tag & 0xC0) == 0 &&
  3442. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3443. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3444. /* For basic type - get each child item and add data */
  3445. for (; i < berSz; ) {
  3446. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3447. if (tag == ASN_EOC) {
  3448. break;
  3449. }
  3450. if (der != NULL) {
  3451. if (j + length > *derSz) {
  3452. ret = BUFFER_E;
  3453. goto end;
  3454. }
  3455. XMEMCPY(der + j, ber + i, length);
  3456. }
  3457. j += length;
  3458. i += length;
  3459. }
  3460. }
  3461. /* Move to next indef item in list */
  3462. indefItems->idx++;
  3463. }
  3464. else if (tag == ASN_EOC) {
  3465. /* End-Of-Content is not written out in DER */
  3466. }
  3467. else {
  3468. /* Write out definite length item as is. */
  3469. i += length;
  3470. if (der != NULL) {
  3471. /* Ensure space for item */
  3472. if (j + i - start > *derSz) {
  3473. ret = BUFFER_E;
  3474. goto end;
  3475. }
  3476. /* Copy item as is */
  3477. XMEMCPY(der + j, ber + start, i - start);
  3478. }
  3479. j += i - start;
  3480. }
  3481. }
  3482. /* Return the length of the DER encoded ASN.1 */
  3483. *derSz = j;
  3484. if (der == NULL) {
  3485. ret = LENGTH_ONLY_E;
  3486. }
  3487. end:
  3488. #ifdef WOLFSSL_SMALL_STACK
  3489. if (indefItems != NULL) {
  3490. XFREE(indefItems, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3491. }
  3492. #endif
  3493. return ret;
  3494. }
  3495. #endif
  3496. #ifndef WOLFSSL_ASN_TEMPLATE
  3497. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)
  3498. /* Set the DER/BER encoding of the ASN.1 BIT_STRING with a 16-bit value.
  3499. *
  3500. * val 16-bit value to encode.
  3501. * output Buffer to write into.
  3502. * returns the number of bytes added to the buffer.
  3503. */
  3504. static word32 SetBitString16Bit(word16 val, byte* output)
  3505. {
  3506. word32 idx;
  3507. int len;
  3508. byte lastByte;
  3509. byte unusedBits = 0;
  3510. if ((val >> 8) != 0) {
  3511. len = 2;
  3512. lastByte = (byte)(val >> 8);
  3513. }
  3514. else {
  3515. len = 1;
  3516. lastByte = (byte)val;
  3517. }
  3518. while (((lastByte >> unusedBits) & 0x01) == 0x00)
  3519. unusedBits++;
  3520. idx = SetBitString((word32)len, unusedBits, output);
  3521. output[idx++] = (byte)val;
  3522. if (len > 1)
  3523. output[idx++] = (byte)(val >> 8);
  3524. return idx;
  3525. }
  3526. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_CERT_GEN */
  3527. #endif /* !WOLFSSL_ASN_TEMPLATE */
  3528. /* hashType */
  3529. #ifdef WOLFSSL_MD2
  3530. static const byte hashMd2hOid[] = {42, 134, 72, 134, 247, 13, 2, 2};
  3531. #endif
  3532. #ifndef NO_MD5
  3533. static const byte hashMd5hOid[] = {42, 134, 72, 134, 247, 13, 2, 5};
  3534. #endif
  3535. #ifndef NO_SHA
  3536. static const byte hashSha1hOid[] = {43, 14, 3, 2, 26};
  3537. #endif
  3538. #ifdef WOLFSSL_SHA224
  3539. static const byte hashSha224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 4};
  3540. #endif
  3541. #ifndef NO_SHA256
  3542. static const byte hashSha256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 1};
  3543. #endif
  3544. #ifdef WOLFSSL_SHA384
  3545. static const byte hashSha384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 2};
  3546. #endif
  3547. #ifdef WOLFSSL_SHA512
  3548. static const byte hashSha512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 3};
  3549. #ifndef WOLFSSL_NOSHA512_224
  3550. static const byte hashSha512_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 5};
  3551. #endif
  3552. #ifndef WOLFSSL_NOSHA512_256
  3553. static const byte hashSha512_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 6};
  3554. #endif
  3555. #endif
  3556. #ifdef WOLFSSL_SHA3
  3557. #ifndef WOLFSSL_NOSHA3_224
  3558. static const byte hashSha3_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 7};
  3559. #endif /* WOLFSSL_NOSHA3_224 */
  3560. #ifndef WOLFSSL_NOSHA3_256
  3561. static const byte hashSha3_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 8};
  3562. #endif /* WOLFSSL_NOSHA3_256 */
  3563. #ifndef WOLFSSL_NOSHA3_384
  3564. static const byte hashSha3_384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 9};
  3565. #endif /* WOLFSSL_NOSHA3_384 */
  3566. #ifndef WOLFSSL_NOSHA3_512
  3567. static const byte hashSha3_512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 10};
  3568. #endif /* WOLFSSL_NOSHA3_512 */
  3569. #endif /* WOLFSSL_SHA3 */
  3570. /* hmacType */
  3571. #ifndef NO_HMAC
  3572. #ifdef WOLFSSL_SHA224
  3573. static const byte hmacSha224Oid[] = {42, 134, 72, 134, 247, 13, 2, 8};
  3574. #endif
  3575. #ifndef NO_SHA256
  3576. static const byte hmacSha256Oid[] = {42, 134, 72, 134, 247, 13, 2, 9};
  3577. #endif
  3578. #ifdef WOLFSSL_SHA384
  3579. static const byte hmacSha384Oid[] = {42, 134, 72, 134, 247, 13, 2, 10};
  3580. #endif
  3581. #ifdef WOLFSSL_SHA512
  3582. static const byte hmacSha512Oid[] = {42, 134, 72, 134, 247, 13, 2, 11};
  3583. #endif
  3584. #endif
  3585. /* sigType */
  3586. #if !defined(NO_DSA) && !defined(NO_SHA)
  3587. static const byte sigSha1wDsaOid[] = {42, 134, 72, 206, 56, 4, 3};
  3588. static const byte sigSha256wDsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 2};
  3589. #endif /* NO_DSA */
  3590. #ifndef NO_RSA
  3591. #ifdef WOLFSSL_MD2
  3592. static const byte sigMd2wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 2};
  3593. #endif
  3594. #ifndef NO_MD5
  3595. static const byte sigMd5wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 4};
  3596. #endif
  3597. #ifndef NO_SHA
  3598. static const byte sigSha1wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 5};
  3599. #endif
  3600. #ifdef WOLFSSL_SHA224
  3601. static const byte sigSha224wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,14};
  3602. #endif
  3603. #ifndef NO_SHA256
  3604. static const byte sigSha256wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,11};
  3605. #endif
  3606. #ifdef WOLFSSL_SHA384
  3607. static const byte sigSha384wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,12};
  3608. #endif
  3609. #ifdef WOLFSSL_SHA512
  3610. static const byte sigSha512wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,13};
  3611. #endif
  3612. #ifdef WOLFSSL_SHA3
  3613. #ifndef WOLFSSL_NOSHA3_224
  3614. static const byte sigSha3_224wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 13};
  3615. #endif
  3616. #ifndef WOLFSSL_NOSHA3_256
  3617. static const byte sigSha3_256wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 14};
  3618. #endif
  3619. #ifndef WOLFSSL_NOSHA3_384
  3620. static const byte sigSha3_384wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 15};
  3621. #endif
  3622. #ifndef WOLFSSL_NOSHA3_512
  3623. static const byte sigSha3_512wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 16};
  3624. #endif
  3625. #endif
  3626. #ifdef WC_RSA_PSS
  3627. static const byte sigRsaSsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
  3628. #endif
  3629. #endif /* NO_RSA */
  3630. #ifdef HAVE_ECC
  3631. #ifndef NO_SHA
  3632. static const byte sigSha1wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 1};
  3633. #endif
  3634. #ifdef WOLFSSL_SHA224
  3635. static const byte sigSha224wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 1};
  3636. #endif
  3637. #ifndef NO_SHA256
  3638. static const byte sigSha256wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 2};
  3639. #endif
  3640. #ifdef WOLFSSL_SHA384
  3641. static const byte sigSha384wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 3};
  3642. #endif
  3643. #ifdef WOLFSSL_SHA512
  3644. static const byte sigSha512wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 4};
  3645. #endif
  3646. #ifdef WOLFSSL_SHA3
  3647. #ifndef WOLFSSL_NOSHA3_224
  3648. static const byte sigSha3_224wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 9};
  3649. #endif
  3650. #ifndef WOLFSSL_NOSHA3_256
  3651. static const byte sigSha3_256wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 10};
  3652. #endif
  3653. #ifndef WOLFSSL_NOSHA3_384
  3654. static const byte sigSha3_384wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 11};
  3655. #endif
  3656. #ifndef WOLFSSL_NOSHA3_512
  3657. static const byte sigSha3_512wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 12};
  3658. #endif
  3659. #endif
  3660. #endif /* HAVE_ECC */
  3661. #ifdef HAVE_ED25519
  3662. static const byte sigEd25519Oid[] = {43, 101, 112};
  3663. #endif /* HAVE_ED25519 */
  3664. #ifdef HAVE_ED448
  3665. static const byte sigEd448Oid[] = {43, 101, 113};
  3666. #endif /* HAVE_ED448 */
  3667. #ifdef HAVE_PQC
  3668. #ifdef HAVE_FALCON
  3669. /* Falcon Level 1: 1 3 9999 3 1 */
  3670. static const byte sigFalcon_Level1Oid[] = {43, 206, 15, 3, 1};
  3671. /* Falcon Level 5: 1 3 9999 3 4 */
  3672. static const byte sigFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
  3673. #endif /* HAVE_FACON */
  3674. #ifdef HAVE_DILITHIUM
  3675. /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
  3676. static const byte sigDilithium_Level2Oid[] =
  3677. {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};
  3678. /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
  3679. static const byte sigDilithium_Level3Oid[] =
  3680. {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};
  3681. /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
  3682. static const byte sigDilithium_Level5Oid[] =
  3683. {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
  3684. #endif /* HAVE_DILITHIUM */
  3685. #ifdef HAVE_SPHINCS
  3686. /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
  3687. static const byte sigSphincsFast_Level1Oid[] =
  3688. {43, 206, 15, 6, 7, 4};
  3689. /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
  3690. static const byte sigSphincsFast_Level3Oid[] =
  3691. {43, 206, 15, 6, 8, 3};
  3692. /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
  3693. static const byte sigSphincsFast_Level5Oid[] =
  3694. {43, 206, 15, 6, 9, 3};
  3695. /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
  3696. static const byte sigSphincsSmall_Level1Oid[] =
  3697. {43, 206, 15, 6, 7, 10};
  3698. /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
  3699. static const byte sigSphincsSmall_Level3Oid[] =
  3700. {43, 206, 15, 6, 8, 7};
  3701. /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
  3702. static const byte sigSphincsSmall_Level5Oid[] =
  3703. {43, 206, 15, 6, 9, 7};
  3704. #endif /* HAVE_SPHINCS */
  3705. #endif /* HAVE_PQC */
  3706. /* keyType */
  3707. #ifndef NO_DSA
  3708. static const byte keyDsaOid[] = {42, 134, 72, 206, 56, 4, 1};
  3709. #endif /* NO_DSA */
  3710. #ifndef NO_RSA
  3711. static const byte keyRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 1};
  3712. #ifdef WC_RSA_PSS
  3713. static const byte keyRsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
  3714. #endif
  3715. #endif /* NO_RSA */
  3716. #ifdef HAVE_ECC
  3717. static const byte keyEcdsaOid[] = {42, 134, 72, 206, 61, 2, 1};
  3718. #endif /* HAVE_ECC */
  3719. #ifdef HAVE_ED25519
  3720. static const byte keyEd25519Oid[] = {43, 101, 112};
  3721. #endif /* HAVE_ED25519 */
  3722. #ifdef HAVE_CURVE25519
  3723. static const byte keyCurve25519Oid[] = {43, 101, 110};
  3724. #endif
  3725. #ifdef HAVE_ED448
  3726. static const byte keyEd448Oid[] = {43, 101, 113};
  3727. #endif /* HAVE_ED448 */
  3728. #ifdef HAVE_CURVE448
  3729. static const byte keyCurve448Oid[] = {43, 101, 111};
  3730. #endif /* HAVE_CURVE448 */
  3731. #ifndef NO_DH
  3732. static const byte keyDhOid[] = {42, 134, 72, 134, 247, 13, 1, 3, 1};
  3733. #endif /* !NO_DH */
  3734. #ifdef HAVE_PQC
  3735. #ifdef HAVE_FALCON
  3736. /* Falcon Level 1: 1 3 9999 3 1 */
  3737. static const byte keyFalcon_Level1Oid[] = {43, 206, 15, 3, 1};
  3738. /* Falcon Level 5: 1 3 9999 3 4 */
  3739. static const byte keyFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
  3740. #endif /* HAVE_FALCON */
  3741. #ifdef HAVE_DILITHIUM
  3742. /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
  3743. static const byte keyDilithium_Level2Oid[] =
  3744. {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};
  3745. /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
  3746. static const byte keyDilithium_Level3Oid[] =
  3747. {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};
  3748. /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
  3749. static const byte keyDilithium_Level5Oid[] =
  3750. {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
  3751. #endif /* HAVE_DILITHIUM */
  3752. #ifdef HAVE_SPHINCS
  3753. /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
  3754. static const byte keySphincsFast_Level1Oid[] =
  3755. {43, 206, 15, 6, 7, 4};
  3756. /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
  3757. static const byte keySphincsFast_Level3Oid[] =
  3758. {43, 206, 15, 6, 8, 3};
  3759. /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
  3760. static const byte keySphincsFast_Level5Oid[] =
  3761. {43, 206, 15, 6, 9, 3};
  3762. /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
  3763. static const byte keySphincsSmall_Level1Oid[] =
  3764. {43, 206, 15, 6, 7, 10};
  3765. /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
  3766. static const byte keySphincsSmall_Level3Oid[] =
  3767. {43, 206, 15, 6, 8, 7};
  3768. /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
  3769. static const byte keySphincsSmall_Level5Oid[] =
  3770. {43, 206, 15, 6, 9, 7};
  3771. #endif /* HAVE_SPHINCS */
  3772. #endif /* HAVE_PQC */
  3773. /* curveType */
  3774. #ifdef HAVE_ECC
  3775. /* See "ecc_sets" table in ecc.c */
  3776. #endif /* HAVE_ECC */
  3777. #ifdef HAVE_AES_CBC
  3778. /* blkType */
  3779. #ifdef WOLFSSL_AES_128
  3780. static const byte blkAes128CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 2};
  3781. #endif
  3782. #ifdef WOLFSSL_AES_192
  3783. static const byte blkAes192CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 22};
  3784. #endif
  3785. #ifdef WOLFSSL_AES_256
  3786. static const byte blkAes256CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 42};
  3787. #endif
  3788. #endif /* HAVE_AES_CBC */
  3789. #ifdef HAVE_AESGCM
  3790. #ifdef WOLFSSL_AES_128
  3791. static const byte blkAes128GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 6};
  3792. #endif
  3793. #ifdef WOLFSSL_AES_192
  3794. static const byte blkAes192GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 26};
  3795. #endif
  3796. #ifdef WOLFSSL_AES_256
  3797. static const byte blkAes256GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 46};
  3798. #endif
  3799. #endif /* HAVE_AESGCM */
  3800. #ifdef HAVE_AESCCM
  3801. #ifdef WOLFSSL_AES_128
  3802. static const byte blkAes128CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 7};
  3803. #endif
  3804. #ifdef WOLFSSL_AES_192
  3805. static const byte blkAes192CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 27};
  3806. #endif
  3807. #ifdef WOLFSSL_AES_256
  3808. static const byte blkAes256CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 47};
  3809. #endif
  3810. #endif /* HAVE_AESCCM */
  3811. #ifndef NO_DES3
  3812. static const byte blkDesCbcOid[] = {43, 14, 3, 2, 7};
  3813. static const byte blkDes3CbcOid[] = {42, 134, 72, 134, 247, 13, 3, 7};
  3814. #endif
  3815. /* keyWrapType */
  3816. #ifdef WOLFSSL_AES_128
  3817. static const byte wrapAes128Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 5};
  3818. #endif
  3819. #ifdef WOLFSSL_AES_192
  3820. static const byte wrapAes192Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 25};
  3821. #endif
  3822. #ifdef WOLFSSL_AES_256
  3823. static const byte wrapAes256Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 45};
  3824. #endif
  3825. #ifdef HAVE_PKCS7
  3826. /* From RFC 3211 */
  3827. static const byte wrapPwriKekOid[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3,9};
  3828. #endif
  3829. /* cmsKeyAgreeType */
  3830. #ifndef NO_SHA
  3831. static const byte dhSinglePass_stdDH_sha1kdf_Oid[] =
  3832. {43, 129, 5, 16, 134, 72, 63, 0, 2};
  3833. #endif
  3834. #ifdef WOLFSSL_SHA224
  3835. static const byte dhSinglePass_stdDH_sha224kdf_Oid[] = {43, 129, 4, 1, 11, 0};
  3836. #endif
  3837. #ifndef NO_SHA256
  3838. static const byte dhSinglePass_stdDH_sha256kdf_Oid[] = {43, 129, 4, 1, 11, 1};
  3839. #endif
  3840. #ifdef WOLFSSL_SHA384
  3841. static const byte dhSinglePass_stdDH_sha384kdf_Oid[] = {43, 129, 4, 1, 11, 2};
  3842. #endif
  3843. #ifdef WOLFSSL_SHA512
  3844. static const byte dhSinglePass_stdDH_sha512kdf_Oid[] = {43, 129, 4, 1, 11, 3};
  3845. #endif
  3846. /* ocspType */
  3847. #ifdef HAVE_OCSP
  3848. static const byte ocspBasicOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 1};
  3849. static const byte ocspNonceOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 2};
  3850. static const byte ocspNoCheckOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 5};
  3851. #endif /* HAVE_OCSP */
  3852. /* certExtType */
  3853. static const byte extBasicCaOid[] = {85, 29, 19};
  3854. static const byte extAltNamesOid[] = {85, 29, 17};
  3855. static const byte extCrlDistOid[] = {85, 29, 31};
  3856. static const byte extAuthInfoOid[] = {43, 6, 1, 5, 5, 7, 1, 1};
  3857. static const byte extAuthKeyOid[] = {85, 29, 35};
  3858. static const byte extSubjKeyOid[] = {85, 29, 14};
  3859. static const byte extCertPolicyOid[] = {85, 29, 32};
  3860. static const byte extKeyUsageOid[] = {85, 29, 15};
  3861. static const byte extInhibitAnyOid[] = {85, 29, 54};
  3862. static const byte extExtKeyUsageOid[] = {85, 29, 37};
  3863. #ifndef IGNORE_NAME_CONSTRAINTS
  3864. static const byte extNameConsOid[] = {85, 29, 30};
  3865. #endif
  3866. #ifdef HAVE_CRL
  3867. static const byte extCrlNumberOid[] = {85, 29, 20};
  3868. #endif
  3869. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  3870. static const byte extSubjDirAttrOid[] = {85, 29, 9};
  3871. #endif
  3872. #ifdef WOLFSSL_SUBJ_INFO_ACC
  3873. static const byte extSubjInfoAccessOid[] = {43, 6, 1, 5, 5, 7, 1, 11};
  3874. #endif
  3875. /* certAuthInfoType */
  3876. static const byte extAuthInfoOcspOid[] = {43, 6, 1, 5, 5, 7, 48, 1};
  3877. static const byte extAuthInfoCaIssuerOid[] = {43, 6, 1, 5, 5, 7, 48, 2};
  3878. #ifdef WOLFSSL_SUBJ_INFO_ACC
  3879. static const byte extAuthInfoCaRespOid[] = {43, 6, 1, 5, 5, 7, 48, 5};
  3880. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  3881. /* certPolicyType */
  3882. static const byte extCertPolicyAnyOid[] = {85, 29, 32, 0};
  3883. #ifdef WOLFSSL_FPKI
  3884. #define CERT_POLICY_TYPE_OID_BASE(num) {96, 134, 72, 1, 101, 3, 2, 1, 3, num}
  3885. static const byte extCertPolicyFpkiCommonAuthOid[] =
  3886. CERT_POLICY_TYPE_OID_BASE(13);
  3887. static const byte extCertPolicyFpkiPivAuthOid[] =
  3888. CERT_POLICY_TYPE_OID_BASE(40);
  3889. static const byte extCertPolicyFpkiPivAuthHwOid[] =
  3890. CERT_POLICY_TYPE_OID_BASE(41);
  3891. static const byte extCertPolicyFpkiPiviAuthOid[] =
  3892. CERT_POLICY_TYPE_OID_BASE(45);
  3893. #endif /* WOLFSSL_FPKI */
  3894. /* certAltNameType */
  3895. static const byte extAltNamesHwNameOid[] = {43, 6, 1, 5, 5, 7, 8, 4};
  3896. /* certKeyUseType */
  3897. static const byte extExtKeyUsageAnyOid[] = {85, 29, 37, 0};
  3898. static const byte extExtKeyUsageServerAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 1};
  3899. static const byte extExtKeyUsageClientAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 2};
  3900. static const byte extExtKeyUsageCodeSigningOid[] = {43, 6, 1, 5, 5, 7, 3, 3};
  3901. static const byte extExtKeyUsageEmailProtectOid[] = {43, 6, 1, 5, 5, 7, 3, 4};
  3902. static const byte extExtKeyUsageTimestampOid[] = {43, 6, 1, 5, 5, 7, 3, 8};
  3903. static const byte extExtKeyUsageOcspSignOid[] = {43, 6, 1, 5, 5, 7, 3, 9};
  3904. #ifdef WOLFSSL_WOLFSSH
  3905. #define EXT_KEY_USAGE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 3, num}
  3906. static const byte extExtKeyUsageSshClientAuthOid[] =
  3907. EXT_KEY_USAGE_OID_BASE(21);
  3908. static const byte extExtKeyUsageSshMSCLOid[] =
  3909. {43, 6, 1, 4, 1, 130, 55, 20, 2, 2};
  3910. static const byte extExtKeyUsageSshKpClientAuthOid[] =
  3911. {43, 6, 1, 5, 2, 3, 4};
  3912. #endif /* WOLFSSL_WOLFSSH */
  3913. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  3914. #define SUBJ_DIR_ATTR_TYPE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 9, num}
  3915. static const byte extSubjDirAttrDobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(1);
  3916. static const byte extSubjDirAttrPobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(2);
  3917. static const byte extSubjDirAttrGenderOid[] =
  3918. SUBJ_DIR_ATTR_TYPE_OID_BASE(3);
  3919. static const byte extSubjDirAttrCocOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(4);
  3920. static const byte extSubjDirAttrCorOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(5);
  3921. #endif
  3922. #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3923. defined(WOLFSSL_ASN_TEMPLATE) || defined(OPENSSL_EXTRA) || \
  3924. defined(OPENSSL_EXTRA_X509_SMALL)
  3925. /* csrAttrType */
  3926. #define CSR_ATTR_TYPE_OID_BASE(num) {42, 134, 72, 134, 247, 13, 1, 9, num}
  3927. #if !defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3928. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  3929. defined(WOLFSSL_ASN_TEMPLATE)
  3930. static const byte attrEmailOid[] = CSR_ATTR_TYPE_OID_BASE(1);
  3931. #endif
  3932. #ifdef WOLFSSL_CERT_REQ
  3933. static const byte attrUnstructuredNameOid[] = CSR_ATTR_TYPE_OID_BASE(2);
  3934. static const byte attrPkcs9ContentTypeOid[] = CSR_ATTR_TYPE_OID_BASE(3);
  3935. static const byte attrChallengePasswordOid[] = CSR_ATTR_TYPE_OID_BASE(7);
  3936. static const byte attrExtensionRequestOid[] = CSR_ATTR_TYPE_OID_BASE(14);
  3937. static const byte attrSerialNumberOid[] = {85, 4, 5};
  3938. static const byte attrDnQualifier[] = {85, 4, 46};
  3939. static const byte attrInitals[] = {85, 4, 43};
  3940. static const byte attrSurname[] = {85, 4, 4};
  3941. static const byte attrGivenName[] = {85, 4, 42};
  3942. #endif
  3943. #endif
  3944. /* kdfType */
  3945. static const byte pbkdf2Oid[] = {42, 134, 72, 134, 247, 13, 1, 5, 12};
  3946. /* PKCS5 */
  3947. #if !defined(NO_DES3) && !defined(NO_MD5)
  3948. static const byte pbeMd5Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 3};
  3949. #endif
  3950. #if !defined(NO_DES3) && !defined(NO_SHA)
  3951. static const byte pbeSha1Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 10};
  3952. #endif
  3953. static const byte pbes2[] = {42, 134, 72, 134, 247, 13, 1, 5, 13};
  3954. /* PKCS12 */
  3955. #if !defined(NO_RC4) && !defined(NO_SHA)
  3956. static const byte pbeSha1RC4128[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 1};
  3957. #endif
  3958. #if !defined(NO_DES3) && !defined(NO_SHA)
  3959. static const byte pbeSha1Des3[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 3};
  3960. #endif
  3961. #ifdef HAVE_LIBZ
  3962. /* zlib compression */
  3963. static const byte zlibCompress[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3, 8};
  3964. #endif
  3965. #ifdef WOLFSSL_APACHE_HTTPD
  3966. /* tlsExtType */
  3967. static const byte tlsFeatureOid[] = {43, 6, 1, 5, 5, 7, 1, 24};
  3968. /* certNameType */
  3969. static const byte dnsSRVOid[] = {43, 6, 1, 5, 5, 7, 8, 7};
  3970. #endif
  3971. #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3972. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  3973. defined(WOLFSSL_ASN_TEMPLATE)
  3974. /* Pilot attribute types (0.9.2342.19200300.100.1.*) */
  3975. #define PLT_ATTR_TYPE_OID_BASE(num) {9, 146, 38, 137, 147, 242, 44, 100, 1, num}
  3976. static const byte uidOid[] = PLT_ATTR_TYPE_OID_BASE(1); /* user id */
  3977. static const byte fvrtDrk[] = PLT_ATTR_TYPE_OID_BASE(5);/* favourite drink*/
  3978. #endif
  3979. #if defined(WOLFSSL_CERT_GEN) || \
  3980. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  3981. defined(WOLFSSL_ASN_TEMPLATE)
  3982. static const byte dcOid[] = {9, 146, 38, 137, 147, 242, 44, 100, 1, 25}; /* domain component */
  3983. #endif
  3984. /* Looks up the ID/type of an OID.
  3985. *
  3986. * When known returns the OID as a byte array and its length.
  3987. * ID-type are unique.
  3988. *
  3989. * Use oidIgnoreType to autofail.
  3990. *
  3991. * @param [in] id OID id.
  3992. * @param [in] type Type of OID (enum Oid_Types).
  3993. * @param [out] oidSz Length of OID byte array returned.
  3994. * @return Array of bytes for the OID.
  3995. * @return NULL when ID/type not recognized.
  3996. */
  3997. const byte* OidFromId(word32 id, word32 type, word32* oidSz)
  3998. {
  3999. const byte* oid = NULL;
  4000. *oidSz = 0;
  4001. switch (type) {
  4002. case oidHashType:
  4003. switch (id) {
  4004. #ifdef WOLFSSL_MD2
  4005. case MD2h:
  4006. oid = hashMd2hOid;
  4007. *oidSz = sizeof(hashMd2hOid);
  4008. break;
  4009. #endif
  4010. #ifndef NO_MD5
  4011. case MD5h:
  4012. oid = hashMd5hOid;
  4013. *oidSz = sizeof(hashMd5hOid);
  4014. break;
  4015. #endif
  4016. #ifndef NO_SHA
  4017. case SHAh:
  4018. oid = hashSha1hOid;
  4019. *oidSz = sizeof(hashSha1hOid);
  4020. break;
  4021. #endif
  4022. #ifdef WOLFSSL_SHA224
  4023. case SHA224h:
  4024. oid = hashSha224hOid;
  4025. *oidSz = sizeof(hashSha224hOid);
  4026. break;
  4027. #endif
  4028. #ifndef NO_SHA256
  4029. case SHA256h:
  4030. oid = hashSha256hOid;
  4031. *oidSz = sizeof(hashSha256hOid);
  4032. break;
  4033. #endif
  4034. #ifdef WOLFSSL_SHA384
  4035. case SHA384h:
  4036. oid = hashSha384hOid;
  4037. *oidSz = sizeof(hashSha384hOid);
  4038. break;
  4039. #endif
  4040. #ifdef WOLFSSL_SHA512
  4041. #ifndef WOLFSSL_NOSHA512_224
  4042. case SHA512_224h:
  4043. oid = hashSha512_224hOid;
  4044. *oidSz = sizeof(hashSha512_224hOid);
  4045. break;
  4046. #endif
  4047. #ifndef WOLFSSL_NOSHA512_256
  4048. case SHA512_256h:
  4049. oid = hashSha512_256hOid;
  4050. *oidSz = sizeof(hashSha512_256hOid);
  4051. break;
  4052. #endif
  4053. case SHA512h:
  4054. oid = hashSha512hOid;
  4055. *oidSz = sizeof(hashSha512hOid);
  4056. break;
  4057. #endif
  4058. #ifdef WOLFSSL_SHA3
  4059. #ifndef WOLFSSL_NOSHA3_224
  4060. case SHA3_224h:
  4061. oid = hashSha3_224hOid;
  4062. *oidSz = sizeof(hashSha3_224hOid);
  4063. break;
  4064. #endif /* WOLFSSL_NOSHA3_224 */
  4065. #ifndef WOLFSSL_NOSHA3_256
  4066. case SHA3_256h:
  4067. oid = hashSha3_256hOid;
  4068. *oidSz = sizeof(hashSha3_256hOid);
  4069. break;
  4070. #endif /* WOLFSSL_NOSHA3_256 */
  4071. #ifndef WOLFSSL_NOSHA3_384
  4072. case SHA3_384h:
  4073. oid = hashSha3_384hOid;
  4074. *oidSz = sizeof(hashSha3_384hOid);
  4075. break;
  4076. #endif /* WOLFSSL_NOSHA3_384 */
  4077. #ifndef WOLFSSL_NOSHA3_512
  4078. case SHA3_512h:
  4079. oid = hashSha3_512hOid;
  4080. *oidSz = sizeof(hashSha3_512hOid);
  4081. break;
  4082. #endif /* WOLFSSL_NOSHA3_512 */
  4083. #endif /* WOLFSSL_SHA3 */
  4084. default:
  4085. break;
  4086. }
  4087. break;
  4088. case oidSigType:
  4089. switch (id) {
  4090. #if !defined(NO_DSA) && !defined(NO_SHA)
  4091. case CTC_SHAwDSA:
  4092. oid = sigSha1wDsaOid;
  4093. *oidSz = sizeof(sigSha1wDsaOid);
  4094. break;
  4095. case CTC_SHA256wDSA:
  4096. oid = sigSha256wDsaOid;
  4097. *oidSz = sizeof(sigSha256wDsaOid);
  4098. break;
  4099. #endif /* NO_DSA */
  4100. #ifndef NO_RSA
  4101. #ifdef WOLFSSL_MD2
  4102. case CTC_MD2wRSA:
  4103. oid = sigMd2wRsaOid;
  4104. *oidSz = sizeof(sigMd2wRsaOid);
  4105. break;
  4106. #endif
  4107. #ifndef NO_MD5
  4108. case CTC_MD5wRSA:
  4109. oid = sigMd5wRsaOid;
  4110. *oidSz = sizeof(sigMd5wRsaOid);
  4111. break;
  4112. #endif
  4113. #ifndef NO_SHA
  4114. case CTC_SHAwRSA:
  4115. oid = sigSha1wRsaOid;
  4116. *oidSz = sizeof(sigSha1wRsaOid);
  4117. break;
  4118. #endif
  4119. #ifdef WOLFSSL_SHA224
  4120. case CTC_SHA224wRSA:
  4121. oid = sigSha224wRsaOid;
  4122. *oidSz = sizeof(sigSha224wRsaOid);
  4123. break;
  4124. #endif
  4125. #ifndef NO_SHA256
  4126. case CTC_SHA256wRSA:
  4127. oid = sigSha256wRsaOid;
  4128. *oidSz = sizeof(sigSha256wRsaOid);
  4129. break;
  4130. #endif
  4131. #ifdef WOLFSSL_SHA384
  4132. case CTC_SHA384wRSA:
  4133. oid = sigSha384wRsaOid;
  4134. *oidSz = sizeof(sigSha384wRsaOid);
  4135. break;
  4136. #endif
  4137. #ifdef WOLFSSL_SHA512
  4138. case CTC_SHA512wRSA:
  4139. oid = sigSha512wRsaOid;
  4140. *oidSz = sizeof(sigSha512wRsaOid);
  4141. break;
  4142. #endif /* WOLFSSL_SHA512 */
  4143. #ifdef WOLFSSL_SHA3
  4144. #ifndef WOLFSSL_NOSHA3_224
  4145. case CTC_SHA3_224wRSA:
  4146. oid = sigSha3_224wRsaOid;
  4147. *oidSz = sizeof(sigSha3_224wRsaOid);
  4148. break;
  4149. #endif
  4150. #ifndef WOLFSSL_NOSHA3_256
  4151. case CTC_SHA3_256wRSA:
  4152. oid = sigSha3_256wRsaOid;
  4153. *oidSz = sizeof(sigSha3_256wRsaOid);
  4154. break;
  4155. #endif
  4156. #ifndef WOLFSSL_NOSHA3_384
  4157. case CTC_SHA3_384wRSA:
  4158. oid = sigSha3_384wRsaOid;
  4159. *oidSz = sizeof(sigSha3_384wRsaOid);
  4160. break;
  4161. #endif
  4162. #ifndef WOLFSSL_NOSHA3_512
  4163. case CTC_SHA3_512wRSA:
  4164. oid = sigSha3_512wRsaOid;
  4165. *oidSz = sizeof(sigSha3_512wRsaOid);
  4166. break;
  4167. #endif
  4168. #endif
  4169. #ifdef WC_RSA_PSS
  4170. case CTC_RSASSAPSS:
  4171. oid = sigRsaSsaPssOid;
  4172. *oidSz = sizeof(sigRsaSsaPssOid);
  4173. break;
  4174. #endif
  4175. #endif /* NO_RSA */
  4176. #ifdef HAVE_ECC
  4177. #ifndef NO_SHA
  4178. case CTC_SHAwECDSA:
  4179. oid = sigSha1wEcdsaOid;
  4180. *oidSz = sizeof(sigSha1wEcdsaOid);
  4181. break;
  4182. #endif
  4183. #ifdef WOLFSSL_SHA224
  4184. case CTC_SHA224wECDSA:
  4185. oid = sigSha224wEcdsaOid;
  4186. *oidSz = sizeof(sigSha224wEcdsaOid);
  4187. break;
  4188. #endif
  4189. #ifndef NO_SHA256
  4190. case CTC_SHA256wECDSA:
  4191. oid = sigSha256wEcdsaOid;
  4192. *oidSz = sizeof(sigSha256wEcdsaOid);
  4193. break;
  4194. #endif
  4195. #ifdef WOLFSSL_SHA384
  4196. case CTC_SHA384wECDSA:
  4197. oid = sigSha384wEcdsaOid;
  4198. *oidSz = sizeof(sigSha384wEcdsaOid);
  4199. break;
  4200. #endif
  4201. #ifdef WOLFSSL_SHA512
  4202. case CTC_SHA512wECDSA:
  4203. oid = sigSha512wEcdsaOid;
  4204. *oidSz = sizeof(sigSha512wEcdsaOid);
  4205. break;
  4206. #endif
  4207. #ifdef WOLFSSL_SHA3
  4208. #ifndef WOLFSSL_NOSHA3_224
  4209. case CTC_SHA3_224wECDSA:
  4210. oid = sigSha3_224wEcdsaOid;
  4211. *oidSz = sizeof(sigSha3_224wEcdsaOid);
  4212. break;
  4213. #endif
  4214. #ifndef WOLFSSL_NOSHA3_256
  4215. case CTC_SHA3_256wECDSA:
  4216. oid = sigSha3_256wEcdsaOid;
  4217. *oidSz = sizeof(sigSha3_256wEcdsaOid);
  4218. break;
  4219. #endif
  4220. #ifndef WOLFSSL_NOSHA3_384
  4221. case CTC_SHA3_384wECDSA:
  4222. oid = sigSha3_384wEcdsaOid;
  4223. *oidSz = sizeof(sigSha3_384wEcdsaOid);
  4224. break;
  4225. #endif
  4226. #ifndef WOLFSSL_NOSHA3_512
  4227. case CTC_SHA3_512wECDSA:
  4228. oid = sigSha3_512wEcdsaOid;
  4229. *oidSz = sizeof(sigSha3_512wEcdsaOid);
  4230. break;
  4231. #endif
  4232. #endif
  4233. #endif /* HAVE_ECC */
  4234. #ifdef HAVE_ED25519
  4235. case CTC_ED25519:
  4236. oid = sigEd25519Oid;
  4237. *oidSz = sizeof(sigEd25519Oid);
  4238. break;
  4239. #endif
  4240. #ifdef HAVE_ED448
  4241. case CTC_ED448:
  4242. oid = sigEd448Oid;
  4243. *oidSz = sizeof(sigEd448Oid);
  4244. break;
  4245. #endif
  4246. #ifdef HAVE_PQC
  4247. #ifdef HAVE_FALCON
  4248. case CTC_FALCON_LEVEL1:
  4249. oid = sigFalcon_Level1Oid;
  4250. *oidSz = sizeof(sigFalcon_Level1Oid);
  4251. break;
  4252. case CTC_FALCON_LEVEL5:
  4253. oid = sigFalcon_Level5Oid;
  4254. *oidSz = sizeof(sigFalcon_Level5Oid);
  4255. break;
  4256. #endif /* HAVE_FALCON */
  4257. #ifdef HAVE_DILITHIUM
  4258. case CTC_DILITHIUM_LEVEL2:
  4259. oid = sigDilithium_Level2Oid;
  4260. *oidSz = sizeof(sigDilithium_Level2Oid);
  4261. break;
  4262. case CTC_DILITHIUM_LEVEL3:
  4263. oid = sigDilithium_Level3Oid;
  4264. *oidSz = sizeof(sigDilithium_Level3Oid);
  4265. break;
  4266. case CTC_DILITHIUM_LEVEL5:
  4267. oid = sigDilithium_Level5Oid;
  4268. *oidSz = sizeof(sigDilithium_Level5Oid);
  4269. break;
  4270. #endif /* HAVE_DILITHIUM */
  4271. #ifdef HAVE_SPHINCS
  4272. case CTC_SPHINCS_FAST_LEVEL1:
  4273. oid = sigSphincsFast_Level1Oid;
  4274. *oidSz = sizeof(sigSphincsFast_Level1Oid);
  4275. break;
  4276. case CTC_SPHINCS_FAST_LEVEL3:
  4277. oid = sigSphincsFast_Level3Oid;
  4278. *oidSz = sizeof(sigSphincsFast_Level3Oid);
  4279. break;
  4280. case CTC_SPHINCS_FAST_LEVEL5:
  4281. oid = sigSphincsFast_Level5Oid;
  4282. *oidSz = sizeof(sigSphincsFast_Level5Oid);
  4283. break;
  4284. case CTC_SPHINCS_SMALL_LEVEL1:
  4285. oid = sigSphincsSmall_Level1Oid;
  4286. *oidSz = sizeof(sigSphincsSmall_Level1Oid);
  4287. break;
  4288. case CTC_SPHINCS_SMALL_LEVEL3:
  4289. oid = sigSphincsSmall_Level3Oid;
  4290. *oidSz = sizeof(sigSphincsSmall_Level3Oid);
  4291. break;
  4292. case CTC_SPHINCS_SMALL_LEVEL5:
  4293. oid = sigSphincsSmall_Level5Oid;
  4294. *oidSz = sizeof(sigSphincsSmall_Level5Oid);
  4295. break;
  4296. #endif /* HAVE_SPHINCS */
  4297. #endif /* HAVE_PQC */
  4298. default:
  4299. break;
  4300. }
  4301. break;
  4302. case oidKeyType:
  4303. switch (id) {
  4304. #ifndef NO_DSA
  4305. case DSAk:
  4306. oid = keyDsaOid;
  4307. *oidSz = sizeof(keyDsaOid);
  4308. break;
  4309. #endif /* NO_DSA */
  4310. #ifndef NO_RSA
  4311. case RSAk:
  4312. oid = keyRsaOid;
  4313. *oidSz = sizeof(keyRsaOid);
  4314. break;
  4315. #ifdef WC_RSA_PSS
  4316. case RSAPSSk:
  4317. oid = keyRsaPssOid;
  4318. *oidSz = sizeof(keyRsaPssOid);
  4319. break;
  4320. #endif
  4321. #endif /* NO_RSA */
  4322. #ifdef HAVE_ECC
  4323. case ECDSAk:
  4324. oid = keyEcdsaOid;
  4325. *oidSz = sizeof(keyEcdsaOid);
  4326. break;
  4327. #endif /* HAVE_ECC */
  4328. #ifdef HAVE_ED25519
  4329. case ED25519k:
  4330. oid = keyEd25519Oid;
  4331. *oidSz = sizeof(keyEd25519Oid);
  4332. break;
  4333. #endif /* HAVE_ED25519 */
  4334. #ifdef HAVE_CURVE25519
  4335. case X25519k:
  4336. oid = keyCurve25519Oid;
  4337. *oidSz = sizeof(keyCurve25519Oid);
  4338. break;
  4339. #endif /* HAVE_CURVE25519 */
  4340. #ifdef HAVE_ED448
  4341. case ED448k:
  4342. oid = keyEd448Oid;
  4343. *oidSz = sizeof(keyEd448Oid);
  4344. break;
  4345. #endif /* HAVE_ED448 */
  4346. #ifdef HAVE_CURVE448
  4347. case X448k:
  4348. oid = keyCurve448Oid;
  4349. *oidSz = sizeof(keyCurve448Oid);
  4350. break;
  4351. #endif /* HAVE_CURVE448 */
  4352. #ifndef NO_DH
  4353. case DHk:
  4354. oid = keyDhOid;
  4355. *oidSz = sizeof(keyDhOid);
  4356. break;
  4357. #endif /* !NO_DH */
  4358. #ifdef HAVE_PQC
  4359. #ifdef HAVE_FALCON
  4360. case FALCON_LEVEL1k:
  4361. oid = keyFalcon_Level1Oid;
  4362. *oidSz = sizeof(keyFalcon_Level1Oid);
  4363. break;
  4364. case FALCON_LEVEL5k:
  4365. oid = keyFalcon_Level5Oid;
  4366. *oidSz = sizeof(keyFalcon_Level5Oid);
  4367. break;
  4368. #endif /* HAVE_FALCON */
  4369. #ifdef HAVE_DILITHIUM
  4370. case DILITHIUM_LEVEL2k:
  4371. oid = keyDilithium_Level2Oid;
  4372. *oidSz = sizeof(keyDilithium_Level2Oid);
  4373. break;
  4374. case DILITHIUM_LEVEL3k:
  4375. oid = keyDilithium_Level3Oid;
  4376. *oidSz = sizeof(keyDilithium_Level3Oid);
  4377. break;
  4378. case DILITHIUM_LEVEL5k:
  4379. oid = keyDilithium_Level5Oid;
  4380. *oidSz = sizeof(keyDilithium_Level5Oid);
  4381. break;
  4382. #endif /* HAVE_DILITHIUM */
  4383. #ifdef HAVE_SPHINCS
  4384. case SPHINCS_FAST_LEVEL1k:
  4385. oid = keySphincsFast_Level1Oid;
  4386. *oidSz = sizeof(keySphincsFast_Level1Oid);
  4387. break;
  4388. case SPHINCS_FAST_LEVEL3k:
  4389. oid = keySphincsFast_Level3Oid;
  4390. *oidSz = sizeof(keySphincsFast_Level3Oid);
  4391. break;
  4392. case SPHINCS_FAST_LEVEL5k:
  4393. oid = keySphincsFast_Level5Oid;
  4394. *oidSz = sizeof(keySphincsFast_Level5Oid);
  4395. break;
  4396. case SPHINCS_SMALL_LEVEL1k:
  4397. oid = keySphincsSmall_Level1Oid;
  4398. *oidSz = sizeof(keySphincsSmall_Level1Oid);
  4399. break;
  4400. case SPHINCS_SMALL_LEVEL3k:
  4401. oid = keySphincsSmall_Level3Oid;
  4402. *oidSz = sizeof(keySphincsSmall_Level3Oid);
  4403. break;
  4404. case SPHINCS_SMALL_LEVEL5k:
  4405. oid = keySphincsSmall_Level5Oid;
  4406. *oidSz = sizeof(keySphincsSmall_Level5Oid);
  4407. break;
  4408. #endif /* HAVE_SPHINCS */
  4409. #endif /* HAVE_PQC */
  4410. default:
  4411. break;
  4412. }
  4413. break;
  4414. #ifdef HAVE_ECC
  4415. case oidCurveType:
  4416. if (wc_ecc_get_oid(id, &oid, oidSz) < 0) {
  4417. WOLFSSL_MSG("ECC OID not found");
  4418. }
  4419. break;
  4420. #endif /* HAVE_ECC */
  4421. case oidBlkType:
  4422. switch (id) {
  4423. #ifdef HAVE_AES_CBC
  4424. #ifdef WOLFSSL_AES_128
  4425. case AES128CBCb:
  4426. oid = blkAes128CbcOid;
  4427. *oidSz = sizeof(blkAes128CbcOid);
  4428. break;
  4429. #endif
  4430. #ifdef WOLFSSL_AES_192
  4431. case AES192CBCb:
  4432. oid = blkAes192CbcOid;
  4433. *oidSz = sizeof(blkAes192CbcOid);
  4434. break;
  4435. #endif
  4436. #ifdef WOLFSSL_AES_256
  4437. case AES256CBCb:
  4438. oid = blkAes256CbcOid;
  4439. *oidSz = sizeof(blkAes256CbcOid);
  4440. break;
  4441. #endif
  4442. #endif /* HAVE_AES_CBC */
  4443. #ifdef HAVE_AESGCM
  4444. #ifdef WOLFSSL_AES_128
  4445. case AES128GCMb:
  4446. oid = blkAes128GcmOid;
  4447. *oidSz = sizeof(blkAes128GcmOid);
  4448. break;
  4449. #endif
  4450. #ifdef WOLFSSL_AES_192
  4451. case AES192GCMb:
  4452. oid = blkAes192GcmOid;
  4453. *oidSz = sizeof(blkAes192GcmOid);
  4454. break;
  4455. #endif
  4456. #ifdef WOLFSSL_AES_256
  4457. case AES256GCMb:
  4458. oid = blkAes256GcmOid;
  4459. *oidSz = sizeof(blkAes256GcmOid);
  4460. break;
  4461. #endif
  4462. #endif /* HAVE_AESGCM */
  4463. #ifdef HAVE_AESCCM
  4464. #ifdef WOLFSSL_AES_128
  4465. case AES128CCMb:
  4466. oid = blkAes128CcmOid;
  4467. *oidSz = sizeof(blkAes128CcmOid);
  4468. break;
  4469. #endif
  4470. #ifdef WOLFSSL_AES_192
  4471. case AES192CCMb:
  4472. oid = blkAes192CcmOid;
  4473. *oidSz = sizeof(blkAes192CcmOid);
  4474. break;
  4475. #endif
  4476. #ifdef WOLFSSL_AES_256
  4477. case AES256CCMb:
  4478. oid = blkAes256CcmOid;
  4479. *oidSz = sizeof(blkAes256CcmOid);
  4480. break;
  4481. #endif
  4482. #endif /* HAVE_AESCCM */
  4483. #ifndef NO_DES3
  4484. case DESb:
  4485. oid = blkDesCbcOid;
  4486. *oidSz = sizeof(blkDesCbcOid);
  4487. break;
  4488. case DES3b:
  4489. oid = blkDes3CbcOid;
  4490. *oidSz = sizeof(blkDes3CbcOid);
  4491. break;
  4492. #endif /* !NO_DES3 */
  4493. default:
  4494. break;
  4495. }
  4496. break;
  4497. #ifdef HAVE_OCSP
  4498. case oidOcspType:
  4499. switch (id) {
  4500. case OCSP_BASIC_OID:
  4501. oid = ocspBasicOid;
  4502. *oidSz = sizeof(ocspBasicOid);
  4503. break;
  4504. case OCSP_NONCE_OID:
  4505. oid = ocspNonceOid;
  4506. *oidSz = sizeof(ocspNonceOid);
  4507. break;
  4508. default:
  4509. break;
  4510. }
  4511. break;
  4512. #endif /* HAVE_OCSP */
  4513. case oidCertExtType:
  4514. switch (id) {
  4515. case BASIC_CA_OID:
  4516. oid = extBasicCaOid;
  4517. *oidSz = sizeof(extBasicCaOid);
  4518. break;
  4519. case ALT_NAMES_OID:
  4520. oid = extAltNamesOid;
  4521. *oidSz = sizeof(extAltNamesOid);
  4522. break;
  4523. case CRL_DIST_OID:
  4524. oid = extCrlDistOid;
  4525. *oidSz = sizeof(extCrlDistOid);
  4526. break;
  4527. case AUTH_INFO_OID:
  4528. oid = extAuthInfoOid;
  4529. *oidSz = sizeof(extAuthInfoOid);
  4530. break;
  4531. case AUTH_KEY_OID:
  4532. oid = extAuthKeyOid;
  4533. *oidSz = sizeof(extAuthKeyOid);
  4534. break;
  4535. case SUBJ_KEY_OID:
  4536. oid = extSubjKeyOid;
  4537. *oidSz = sizeof(extSubjKeyOid);
  4538. break;
  4539. case CERT_POLICY_OID:
  4540. oid = extCertPolicyOid;
  4541. *oidSz = sizeof(extCertPolicyOid);
  4542. break;
  4543. case KEY_USAGE_OID:
  4544. oid = extKeyUsageOid;
  4545. *oidSz = sizeof(extKeyUsageOid);
  4546. break;
  4547. case INHIBIT_ANY_OID:
  4548. oid = extInhibitAnyOid;
  4549. *oidSz = sizeof(extInhibitAnyOid);
  4550. break;
  4551. case EXT_KEY_USAGE_OID:
  4552. oid = extExtKeyUsageOid;
  4553. *oidSz = sizeof(extExtKeyUsageOid);
  4554. break;
  4555. #ifndef IGNORE_NAME_CONSTRAINTS
  4556. case NAME_CONS_OID:
  4557. oid = extNameConsOid;
  4558. *oidSz = sizeof(extNameConsOid);
  4559. break;
  4560. #endif
  4561. #ifdef HAVE_OCSP
  4562. case OCSP_NOCHECK_OID:
  4563. oid = ocspNoCheckOid;
  4564. *oidSz = sizeof(ocspNoCheckOid);
  4565. break;
  4566. #endif
  4567. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  4568. case SUBJ_DIR_ATTR_OID:
  4569. oid = extSubjDirAttrOid;
  4570. *oidSz = sizeof(extSubjDirAttrOid);
  4571. break;
  4572. #endif
  4573. #ifdef WOLFSSL_SUBJ_INFO_ACC
  4574. case SUBJ_INFO_ACC_OID:
  4575. oid = extSubjInfoAccessOid;
  4576. *oidSz = sizeof(extSubjInfoAccessOid);
  4577. break;
  4578. #endif
  4579. default:
  4580. break;
  4581. }
  4582. break;
  4583. case oidCrlExtType:
  4584. #ifdef HAVE_CRL
  4585. switch (id) {
  4586. case AUTH_KEY_OID:
  4587. oid = extAuthKeyOid;
  4588. *oidSz = sizeof(extAuthKeyOid);
  4589. break;
  4590. case CRL_NUMBER_OID:
  4591. oid = extCrlNumberOid;
  4592. *oidSz = sizeof(extCrlNumberOid);
  4593. break;
  4594. default:
  4595. break;
  4596. }
  4597. #endif
  4598. break;
  4599. case oidCertAuthInfoType:
  4600. switch (id) {
  4601. case AIA_OCSP_OID:
  4602. oid = extAuthInfoOcspOid;
  4603. *oidSz = sizeof(extAuthInfoOcspOid);
  4604. break;
  4605. case AIA_CA_ISSUER_OID:
  4606. oid = extAuthInfoCaIssuerOid;
  4607. *oidSz = sizeof(extAuthInfoCaIssuerOid);
  4608. break;
  4609. #ifdef WOLFSSL_SUBJ_INFO_ACC
  4610. case AIA_CA_REPO_OID:
  4611. oid = extAuthInfoCaRespOid;
  4612. *oidSz = sizeof(extAuthInfoCaRespOid);
  4613. break;
  4614. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  4615. default:
  4616. break;
  4617. }
  4618. break;
  4619. case oidCertPolicyType:
  4620. switch (id) {
  4621. case CP_ANY_OID:
  4622. oid = extCertPolicyAnyOid;
  4623. *oidSz = sizeof(extCertPolicyAnyOid);
  4624. break;
  4625. #if defined(WOLFSSL_FPKI)
  4626. case CP_FPKI_COMMON_AUTH_OID:
  4627. oid = extCertPolicyFpkiCommonAuthOid;
  4628. *oidSz = sizeof(extCertPolicyFpkiCommonAuthOid);
  4629. break;
  4630. case CP_FPKI_PIV_AUTH_OID:
  4631. oid = extCertPolicyFpkiPivAuthOid;
  4632. *oidSz = sizeof(extCertPolicyFpkiPivAuthOid);
  4633. break;
  4634. case CP_FPKI_PIV_AUTH_HW_OID: /* collision with AES256CBCb */
  4635. oid = extCertPolicyFpkiPivAuthHwOid;
  4636. *oidSz = sizeof(extCertPolicyFpkiPivAuthHwOid);
  4637. break;
  4638. case CP_FPKI_PIVI_AUTH_OID:
  4639. oid = extCertPolicyFpkiPiviAuthOid;
  4640. *oidSz = sizeof(extCertPolicyFpkiPiviAuthOid);
  4641. break;
  4642. #endif /* WOLFSSL_FPKI */
  4643. default:
  4644. break;
  4645. }
  4646. break;
  4647. case oidCertAltNameType:
  4648. switch (id) {
  4649. case HW_NAME_OID:
  4650. oid = extAltNamesHwNameOid;
  4651. *oidSz = sizeof(extAltNamesHwNameOid);
  4652. break;
  4653. default:
  4654. break;
  4655. }
  4656. break;
  4657. case oidCertKeyUseType:
  4658. switch (id) {
  4659. case EKU_ANY_OID:
  4660. oid = extExtKeyUsageAnyOid;
  4661. *oidSz = sizeof(extExtKeyUsageAnyOid);
  4662. break;
  4663. case EKU_SERVER_AUTH_OID:
  4664. oid = extExtKeyUsageServerAuthOid;
  4665. *oidSz = sizeof(extExtKeyUsageServerAuthOid);
  4666. break;
  4667. case EKU_CLIENT_AUTH_OID:
  4668. oid = extExtKeyUsageClientAuthOid;
  4669. *oidSz = sizeof(extExtKeyUsageClientAuthOid);
  4670. break;
  4671. case EKU_CODESIGNING_OID:
  4672. oid = extExtKeyUsageCodeSigningOid;
  4673. *oidSz = sizeof(extExtKeyUsageCodeSigningOid);
  4674. break;
  4675. case EKU_EMAILPROTECT_OID:
  4676. oid = extExtKeyUsageEmailProtectOid;
  4677. *oidSz = sizeof(extExtKeyUsageEmailProtectOid);
  4678. break;
  4679. case EKU_TIMESTAMP_OID:
  4680. oid = extExtKeyUsageTimestampOid;
  4681. *oidSz = sizeof(extExtKeyUsageTimestampOid);
  4682. break;
  4683. case EKU_OCSP_SIGN_OID:
  4684. oid = extExtKeyUsageOcspSignOid;
  4685. *oidSz = sizeof(extExtKeyUsageOcspSignOid);
  4686. break;
  4687. #ifdef WOLFSSL_WOLFSSH
  4688. case EKU_SSH_CLIENT_AUTH_OID:
  4689. oid = extExtKeyUsageSshClientAuthOid;
  4690. *oidSz = sizeof(extExtKeyUsageSshClientAuthOid);
  4691. break;
  4692. case EKU_SSH_MSCL_OID:
  4693. oid = extExtKeyUsageSshMSCLOid;
  4694. *oidSz = sizeof(extExtKeyUsageSshMSCLOid);
  4695. break;
  4696. case EKU_SSH_KP_CLIENT_AUTH_OID:
  4697. oid = extExtKeyUsageSshKpClientAuthOid;
  4698. *oidSz = sizeof(extExtKeyUsageSshKpClientAuthOid);
  4699. break;
  4700. #endif /* WOLFSSL_WOLFSSH */
  4701. default:
  4702. break;
  4703. }
  4704. break;
  4705. case oidKdfType:
  4706. switch (id) {
  4707. case PBKDF2_OID:
  4708. oid = pbkdf2Oid;
  4709. *oidSz = sizeof(pbkdf2Oid);
  4710. break;
  4711. default:
  4712. break;
  4713. }
  4714. break;
  4715. case oidPBEType:
  4716. switch (id) {
  4717. #if !defined(NO_SHA) && !defined(NO_RC4)
  4718. case PBE_SHA1_RC4_128_SUM:
  4719. case PBE_SHA1_RC4_128:
  4720. oid = pbeSha1RC4128;
  4721. *oidSz = sizeof(pbeSha1RC4128);
  4722. break;
  4723. #endif
  4724. #if !defined(NO_MD5) && !defined(NO_DES3)
  4725. case PBE_MD5_DES_SUM:
  4726. case PBE_MD5_DES:
  4727. oid = pbeMd5Des;
  4728. *oidSz = sizeof(pbeMd5Des);
  4729. break;
  4730. #endif
  4731. #if !defined(NO_SHA) && !defined(NO_DES3)
  4732. case PBE_SHA1_DES_SUM:
  4733. case PBE_SHA1_DES:
  4734. oid = pbeSha1Des;
  4735. *oidSz = sizeof(pbeSha1Des);
  4736. break;
  4737. #endif
  4738. #if !defined(NO_SHA) && !defined(NO_DES3)
  4739. case PBE_SHA1_DES3_SUM:
  4740. case PBE_SHA1_DES3:
  4741. oid = pbeSha1Des3;
  4742. *oidSz = sizeof(pbeSha1Des3);
  4743. break;
  4744. #endif
  4745. case PBES2_SUM:
  4746. case PBES2:
  4747. oid = pbes2;
  4748. *oidSz = sizeof(pbes2);
  4749. break;
  4750. default:
  4751. break;
  4752. }
  4753. break;
  4754. case oidKeyWrapType:
  4755. switch (id) {
  4756. #ifdef WOLFSSL_AES_128
  4757. case AES128_WRAP:
  4758. oid = wrapAes128Oid;
  4759. *oidSz = sizeof(wrapAes128Oid);
  4760. break;
  4761. #endif
  4762. #ifdef WOLFSSL_AES_192
  4763. case AES192_WRAP:
  4764. oid = wrapAes192Oid;
  4765. *oidSz = sizeof(wrapAes192Oid);
  4766. break;
  4767. #endif
  4768. #ifdef WOLFSSL_AES_256
  4769. case AES256_WRAP:
  4770. oid = wrapAes256Oid;
  4771. *oidSz = sizeof(wrapAes256Oid);
  4772. break;
  4773. #endif
  4774. #ifdef HAVE_PKCS7
  4775. case PWRI_KEK_WRAP:
  4776. oid = wrapPwriKekOid;
  4777. *oidSz = sizeof(wrapPwriKekOid);
  4778. break;
  4779. #endif
  4780. default:
  4781. break;
  4782. }
  4783. break;
  4784. case oidCmsKeyAgreeType:
  4785. switch (id) {
  4786. #ifndef NO_SHA
  4787. case dhSinglePass_stdDH_sha1kdf_scheme:
  4788. oid = dhSinglePass_stdDH_sha1kdf_Oid;
  4789. *oidSz = sizeof(dhSinglePass_stdDH_sha1kdf_Oid);
  4790. break;
  4791. #endif
  4792. #ifdef WOLFSSL_SHA224
  4793. case dhSinglePass_stdDH_sha224kdf_scheme:
  4794. oid = dhSinglePass_stdDH_sha224kdf_Oid;
  4795. *oidSz = sizeof(dhSinglePass_stdDH_sha224kdf_Oid);
  4796. break;
  4797. #endif
  4798. #ifndef NO_SHA256
  4799. case dhSinglePass_stdDH_sha256kdf_scheme:
  4800. oid = dhSinglePass_stdDH_sha256kdf_Oid;
  4801. *oidSz = sizeof(dhSinglePass_stdDH_sha256kdf_Oid);
  4802. break;
  4803. #endif
  4804. #ifdef WOLFSSL_SHA384
  4805. case dhSinglePass_stdDH_sha384kdf_scheme:
  4806. oid = dhSinglePass_stdDH_sha384kdf_Oid;
  4807. *oidSz = sizeof(dhSinglePass_stdDH_sha384kdf_Oid);
  4808. break;
  4809. #endif
  4810. #ifdef WOLFSSL_SHA512
  4811. case dhSinglePass_stdDH_sha512kdf_scheme:
  4812. oid = dhSinglePass_stdDH_sha512kdf_Oid;
  4813. *oidSz = sizeof(dhSinglePass_stdDH_sha512kdf_Oid);
  4814. break;
  4815. #endif
  4816. default:
  4817. break;
  4818. }
  4819. break;
  4820. #ifndef NO_HMAC
  4821. case oidHmacType:
  4822. switch (id) {
  4823. #ifdef WOLFSSL_SHA224
  4824. case HMAC_SHA224_OID:
  4825. oid = hmacSha224Oid;
  4826. *oidSz = sizeof(hmacSha224Oid);
  4827. break;
  4828. #endif
  4829. #ifndef NO_SHA256
  4830. case HMAC_SHA256_OID:
  4831. oid = hmacSha256Oid;
  4832. *oidSz = sizeof(hmacSha256Oid);
  4833. break;
  4834. #endif
  4835. #ifdef WOLFSSL_SHA384
  4836. case HMAC_SHA384_OID:
  4837. oid = hmacSha384Oid;
  4838. *oidSz = sizeof(hmacSha384Oid);
  4839. break;
  4840. #endif
  4841. #ifdef WOLFSSL_SHA512
  4842. case HMAC_SHA512_OID:
  4843. oid = hmacSha512Oid;
  4844. *oidSz = sizeof(hmacSha512Oid);
  4845. break;
  4846. #endif
  4847. default:
  4848. break;
  4849. }
  4850. break;
  4851. #endif /* !NO_HMAC */
  4852. #ifdef HAVE_LIBZ
  4853. case oidCompressType:
  4854. switch (id) {
  4855. case ZLIBc:
  4856. oid = zlibCompress;
  4857. *oidSz = sizeof(zlibCompress);
  4858. break;
  4859. default:
  4860. break;
  4861. }
  4862. break;
  4863. #endif /* HAVE_LIBZ */
  4864. #ifdef WOLFSSL_APACHE_HTTPD
  4865. case oidCertNameType:
  4866. switch (id) {
  4867. case NID_id_on_dnsSRV:
  4868. oid = dnsSRVOid;
  4869. *oidSz = sizeof(dnsSRVOid);
  4870. break;
  4871. default:
  4872. break;
  4873. }
  4874. break;
  4875. case oidTlsExtType:
  4876. switch (id) {
  4877. case TLS_FEATURE_OID:
  4878. oid = tlsFeatureOid;
  4879. *oidSz = sizeof(tlsFeatureOid);
  4880. break;
  4881. default:
  4882. break;
  4883. }
  4884. break;
  4885. #endif /* WOLFSSL_APACHE_HTTPD */
  4886. #ifdef WOLFSSL_CERT_REQ
  4887. case oidCsrAttrType:
  4888. switch (id) {
  4889. case GIVEN_NAME_OID:
  4890. oid = attrGivenName;
  4891. *oidSz = sizeof(attrGivenName);
  4892. break;
  4893. case SURNAME_OID:
  4894. oid = attrSurname;
  4895. *oidSz = sizeof(attrSurname);
  4896. break;
  4897. case INITIALS_OID:
  4898. oid = attrInitals;
  4899. *oidSz = sizeof(attrInitals);
  4900. break;
  4901. case DNQUALIFIER_OID:
  4902. oid = attrDnQualifier;
  4903. *oidSz = sizeof(attrDnQualifier);
  4904. break;
  4905. case UNSTRUCTURED_NAME_OID:
  4906. oid = attrUnstructuredNameOid;
  4907. *oidSz = sizeof(attrUnstructuredNameOid);
  4908. break;
  4909. case PKCS9_CONTENT_TYPE_OID:
  4910. oid = attrPkcs9ContentTypeOid;
  4911. *oidSz = sizeof(attrPkcs9ContentTypeOid);
  4912. break;
  4913. case CHALLENGE_PASSWORD_OID:
  4914. oid = attrChallengePasswordOid;
  4915. *oidSz = sizeof(attrChallengePasswordOid);
  4916. break;
  4917. case SERIAL_NUMBER_OID:
  4918. oid = attrSerialNumberOid;
  4919. *oidSz = sizeof(attrSerialNumberOid);
  4920. break;
  4921. case USER_ID_OID:
  4922. oid = uidOid;
  4923. *oidSz = sizeof(uidOid);
  4924. break;
  4925. case EXTENSION_REQUEST_OID:
  4926. oid = attrExtensionRequestOid;
  4927. *oidSz = sizeof(attrExtensionRequestOid);
  4928. break;
  4929. default:
  4930. break;
  4931. }
  4932. break;
  4933. #endif
  4934. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  4935. case oidSubjDirAttrType:
  4936. switch (id) {
  4937. case SDA_DOB_OID:
  4938. oid = extSubjDirAttrDobOid;
  4939. *oidSz = sizeof(extSubjDirAttrDobOid);
  4940. break;
  4941. case SDA_POB_OID:
  4942. oid = extSubjDirAttrPobOid;
  4943. *oidSz = sizeof(extSubjDirAttrPobOid);
  4944. break;
  4945. case SDA_GENDER_OID:
  4946. oid = extSubjDirAttrGenderOid;
  4947. *oidSz = sizeof(extSubjDirAttrGenderOid);
  4948. break;
  4949. case SDA_COC_OID:
  4950. oid = extSubjDirAttrCocOid;
  4951. *oidSz = sizeof(extSubjDirAttrCocOid);
  4952. break;
  4953. case SDA_COR_OID:
  4954. oid = extSubjDirAttrCorOid;
  4955. *oidSz = sizeof(extSubjDirAttrCorOid);
  4956. break;
  4957. default:
  4958. break;
  4959. }
  4960. break;
  4961. #endif /* WOLFSSL_SUBJ_DIR_ATTR */
  4962. case oidIgnoreType:
  4963. default:
  4964. break;
  4965. }
  4966. return oid;
  4967. }
  4968. #ifdef HAVE_ECC
  4969. /* Check the OID id is for a known elliptic curve.
  4970. *
  4971. * @param [in] oid OID id.
  4972. * @return ECC set id on success.
  4973. * @return ECC_CURVE_OID_E when OID id is 0 or not supported.
  4974. */
  4975. static int CheckCurve(word32 oid)
  4976. {
  4977. int ret;
  4978. word32 oidSz;
  4979. /* Lookup OID id. */
  4980. ret = wc_ecc_get_oid(oid, NULL, &oidSz);
  4981. /* Check for error or zero length OID size (can't get OID for encoding). */
  4982. if ((ret < 0) || (oidSz == 0)) {
  4983. WOLFSSL_MSG("CheckCurve not found");
  4984. WOLFSSL_ERROR_VERBOSE(ECC_CURVE_OID_E);
  4985. ret = ECC_CURVE_OID_E;
  4986. }
  4987. /* Return ECC set id or error code. */
  4988. return ret;
  4989. }
  4990. #endif
  4991. #ifdef HAVE_OID_ENCODING
  4992. /* Encode dotted form of OID into byte array version.
  4993. *
  4994. * @param [in] in Dotted form of OID.
  4995. * @param [in] inSz Count of numbers in dotted form.
  4996. * @param [in] out Buffer to hold OID.
  4997. * @param [in, out] outSz On in, size of buffer.
  4998. * On out, number of bytes in buffer.
  4999. * @return 0 on success
  5000. * @return BAD_FUNC_ARG when in or outSz is NULL.
  5001. * @return BUFFER_E when buffer too small.
  5002. */
  5003. int EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz)
  5004. {
  5005. int i, x, len;
  5006. word32 d, t;
  5007. /* check args */
  5008. if (in == NULL || outSz == NULL) {
  5009. return BAD_FUNC_ARG;
  5010. }
  5011. /* compute length of encoded OID */
  5012. d = (in[0] * 40) + in[1];
  5013. len = 0;
  5014. for (i = 1; i < (int)inSz; i++) {
  5015. x = 0;
  5016. t = d;
  5017. while (t) {
  5018. x++;
  5019. t >>= 1;
  5020. }
  5021. len += (x / 7) + ((x % 7) ? 1 : 0) + (d == 0 ? 1 : 0);
  5022. if (i < (int)inSz - 1) {
  5023. d = in[i + 1];
  5024. }
  5025. }
  5026. if (out) {
  5027. /* verify length */
  5028. if ((int)*outSz < len) {
  5029. return BUFFER_E; /* buffer provided is not large enough */
  5030. }
  5031. /* calc first byte */
  5032. d = (in[0] * 40) + in[1];
  5033. /* encode bytes */
  5034. x = 0;
  5035. for (i = 1; i < (int)inSz; i++) {
  5036. if (d) {
  5037. int y = x, z;
  5038. byte mask = 0;
  5039. while (d) {
  5040. out[x++] = (byte)((d & 0x7F) | mask);
  5041. d >>= 7;
  5042. mask |= 0x80; /* upper bit is set on all but the last byte */
  5043. }
  5044. /* now swap bytes y...x-1 */
  5045. z = x - 1;
  5046. while (y < z) {
  5047. mask = out[y];
  5048. out[y] = out[z];
  5049. out[z] = mask;
  5050. ++y;
  5051. --z;
  5052. }
  5053. }
  5054. else {
  5055. out[x++] = 0x00; /* zero value */
  5056. }
  5057. /* next word */
  5058. if (i < (int)inSz - 1) {
  5059. d = in[i + 1];
  5060. }
  5061. }
  5062. }
  5063. /* return length */
  5064. *outSz = len;
  5065. return 0;
  5066. }
  5067. #endif /* HAVE_OID_ENCODING */
  5068. #if defined(HAVE_OID_DECODING) || defined(WOLFSSL_ASN_PRINT)
  5069. /* Encode dotted form of OID into byte array version.
  5070. *
  5071. * @param [in] in Byte array containing OID.
  5072. * @param [in] inSz Size of OID in bytes.
  5073. * @param [in] out Array to hold dotted form of OID.
  5074. * @param [in, out] outSz On in, number of elements in array.
  5075. * On out, count of numbers in dotted form.
  5076. * @return 0 on success
  5077. * @return BAD_FUNC_ARG when in or outSz is NULL.
  5078. * @return BUFFER_E when dotted form buffer too small.
  5079. */
  5080. int DecodeObjectId(const byte* in, word32 inSz, word16* out, word32* outSz)
  5081. {
  5082. int x = 0, y = 0;
  5083. word32 t = 0;
  5084. /* check args */
  5085. if (in == NULL || outSz == NULL) {
  5086. return BAD_FUNC_ARG;
  5087. }
  5088. /* decode bytes */
  5089. while (inSz--) {
  5090. t = (t << 7) | (in[x] & 0x7F);
  5091. if (!(in[x] & 0x80)) {
  5092. if (y >= (int)*outSz) {
  5093. return BUFFER_E;
  5094. }
  5095. if (y == 0) {
  5096. out[0] = (word16)(t / 40);
  5097. out[1] = (word16)(t % 40);
  5098. y = 2;
  5099. }
  5100. else {
  5101. out[y++] = (word16)t;
  5102. }
  5103. t = 0; /* reset tmp */
  5104. }
  5105. x++;
  5106. }
  5107. /* return length */
  5108. *outSz = (word32)y;
  5109. return 0;
  5110. }
  5111. #endif /* HAVE_OID_DECODING */
  5112. /* Decode the header of a BER/DER encoded OBJECT ID.
  5113. *
  5114. * @param [in] input Buffer holding DER/BER encoded data.
  5115. * @param [in, out] inOutIdx On in, starting index of header.
  5116. * On out, end of parsed header.
  5117. * @param [out] len Number of bytes in the ASN.1 data.
  5118. * @param [in] maxIdx Length of data in buffer.
  5119. * @return 0 on success.
  5120. * @return BUFFER_E when there is not enough data to parse.
  5121. * @return ASN_PARSE_E when the tag is not a OBJECT ID or length is invalid.
  5122. */
  5123. int GetASNObjectId(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  5124. {
  5125. int ret = GetASNHeader(input, ASN_OBJECT_ID, inOutIdx, len, maxIdx);
  5126. if (ret > 0) {
  5127. /* Only return 0 on success. */
  5128. ret = 0;
  5129. }
  5130. return ret;
  5131. }
  5132. /* Set the DER/BER encoding of the ASN.1 OBJECT ID header.
  5133. *
  5134. * When output is NULL, calculate the header length only.
  5135. *
  5136. * @param [in] len Length of OBJECT ID data in bytes.
  5137. * @param [out] output Buffer to write into.
  5138. * @return Number of bytes added to the buffer.
  5139. */
  5140. int SetObjectId(int len, byte* output)
  5141. {
  5142. int idx = 0;
  5143. if (output) {
  5144. /* Write out tag. */
  5145. output[idx] = ASN_OBJECT_ID;
  5146. }
  5147. /* Skip tag. */
  5148. idx += ASN_TAG_SZ;
  5149. /* Encode length - passing NULL for output will not encode. */
  5150. idx += (int)SetLength((word32)len, output ? output + idx : NULL);
  5151. /* Return index after header. */
  5152. return idx;
  5153. }
  5154. #ifdef ASN_DUMP_OID
  5155. /* Dump the OID information.
  5156. *
  5157. * Decode the OID too if function available.
  5158. *
  5159. * @param [in] oidData OID data from buffer.
  5160. * @param [in] oidSz Size of OID data in buffer.
  5161. * @param [in] oid OID id.
  5162. * @param [in] oidType Type of OID.
  5163. * @return 0 on success.
  5164. * @return BUFFER_E when not enough bytes for proper decode.
  5165. * (HAVE_OID_DECODING)
  5166. */
  5167. static int DumpOID(const byte* oidData, word32 oidSz, word32 oid,
  5168. word32 oidType)
  5169. {
  5170. int ret = 0;
  5171. word32 i;
  5172. /* support for dumping OID information */
  5173. printf("OID (Type %d, Sz %d, Sum %d): ", oidType, oidSz, oid);
  5174. /* Dump bytes in decimal. */
  5175. for (i = 0; i < oidSz; i++) {
  5176. printf("%d, ", oidData[i]);
  5177. }
  5178. printf("\n");
  5179. /* Dump bytes in hexadecimal. */
  5180. for (i = 0; i < oidSz; i++) {
  5181. printf("%02x, ", oidData[i]);
  5182. }
  5183. printf("\n");
  5184. #ifdef HAVE_OID_DECODING
  5185. {
  5186. word16 decOid[MAX_OID_SZ];
  5187. word32 decOidSz = sizeof(decOid);
  5188. /* Decode the OID into dotted form. */
  5189. ret = DecodeObjectId(oidData, oidSz, decOid, &decOidSz);
  5190. if (ret == 0) {
  5191. printf(" Decoded (Sz %d): ", decOidSz);
  5192. for (i=0; i<decOidSz; i++) {
  5193. printf("%d.", decOid[i]);
  5194. }
  5195. printf("\n");
  5196. }
  5197. else {
  5198. printf("DecodeObjectId failed: %d\n", ret);
  5199. }
  5200. }
  5201. #endif /* HAVE_OID_DECODING */
  5202. return ret;
  5203. }
  5204. #endif /* ASN_DUMP_OID */
  5205. /* Get the OID data and verify it is of the type specified when compiled in.
  5206. *
  5207. * @param [in] input Buffer holding OID.
  5208. * @param [in, out] inOutIdx On in, starting index of OID.
  5209. * On out, end of parsed OID.
  5210. * @param [out] oid OID id.
  5211. * @param [in] oidType Expected type of OID. Define NO_VERIFY_OID to
  5212. * not compile in check.
  5213. * @param [in] length Length of OID data in buffer.
  5214. * @return 0 on success.
  5215. * @return ASN_UNKNOWN_OID_E when OID is not recognized.
  5216. * @return BUFFER_E when not enough bytes for proper decode. (ASN_DUMP_OID and
  5217. * HAVE_OID_DECODING)
  5218. */
  5219. static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
  5220. word32 oidType, int length)
  5221. {
  5222. int ret = 0;
  5223. word32 idx = *inOutIdx;
  5224. #ifndef NO_VERIFY_OID
  5225. word32 actualOidSz;
  5226. const byte* actualOid;
  5227. const byte* checkOid = NULL;
  5228. word32 checkOidSz;
  5229. #endif /* NO_VERIFY_OID */
  5230. #ifdef HAVE_PQC
  5231. word32 found_collision = 0;
  5232. #endif
  5233. (void)oidType;
  5234. *oid = 0;
  5235. #ifndef NO_VERIFY_OID
  5236. /* Keep references to OID data and length for check. */
  5237. actualOid = &input[idx];
  5238. actualOidSz = (word32)length;
  5239. #endif /* NO_VERIFY_OID */
  5240. #if defined(HAVE_PQC) && defined(HAVE_LIBOQS)
  5241. /* Since we are summing it up, there could be collisions...and indeed there
  5242. * are: SPHINCS_FAST_LEVEL1 and SPHINCS_FAST_LEVEL3.
  5243. *
  5244. * We will look for the special case of SPHINCS_FAST_LEVEL3 and set *oid to
  5245. * 283 instead of 281; 282 is taken.
  5246. *
  5247. * These hacks will hopefully disappear when new standardized OIDs appear.
  5248. */
  5249. if (memcmp(&input[idx], sigSphincsFast_Level3Oid,
  5250. sizeof(sigSphincsFast_Level3Oid)) == 0) {
  5251. found_collision = SPHINCS_FAST_LEVEL3k;
  5252. }
  5253. #endif /* HAVE_PQC */
  5254. /* Sum it up for now. */
  5255. while (length--) {
  5256. /* odd HC08 compiler behavior here when input[idx++] */
  5257. *oid += (word32)input[idx];
  5258. idx++;
  5259. }
  5260. #ifdef HAVE_PQC
  5261. if (found_collision) {
  5262. *oid = found_collision;
  5263. }
  5264. #endif /* HAVE_PQC */
  5265. /* Return the index after the OID data. */
  5266. *inOutIdx = idx;
  5267. #ifndef NO_VERIFY_OID
  5268. /* 'Ignore' type means we don't care which OID it is. */
  5269. if (oidType != oidIgnoreType) {
  5270. /* Get the OID data for the id-type. */
  5271. checkOid = OidFromId(*oid, oidType, &checkOidSz);
  5272. #if defined(WOLFSSL_FPKI)
  5273. /* Handle OID sum collision of
  5274. AES256CBCb (454) 2.16.840.1.101.3.4.1.42
  5275. CP_FPKI_PIV_AUTH_HW_OID (454) 2.16.840.1.101.3.2.1.3.41
  5276. */
  5277. #if defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  5278. if ((actualOidSz == (word32)sizeof(blkAes256CbcOid)) &&
  5279. (XMEMCMP(actualOid, blkAes256CbcOid,
  5280. sizeof(blkAes256CbcOid)) == 0)) {
  5281. checkOid = blkAes256CbcOid;
  5282. checkOidSz = sizeof(blkAes256CbcOid);
  5283. }
  5284. #endif /* HAVE_AES_CBC */
  5285. #endif /* WOLFSSL_FPKI */
  5286. #ifdef ASN_DUMP_OID
  5287. /* Dump out the data for debug. */
  5288. ret = DumpOID(actualOid, actualOidSz, *oid, oidType);
  5289. #endif
  5290. /* TODO: Want to fail when checkOid is NULL.
  5291. * Can't as too many situations where unknown OID is to be
  5292. * supported. Extra parameter for must not be NULL?
  5293. */
  5294. /* Check that the OID data matches what we found for the OID id. */
  5295. if ((ret == 0) && (checkOid != NULL) && ((checkOidSz != actualOidSz) ||
  5296. (XMEMCMP(actualOid, checkOid, checkOidSz) != 0))) {
  5297. WOLFSSL_MSG("OID Check Failed");
  5298. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  5299. ret = ASN_UNKNOWN_OID_E;
  5300. }
  5301. }
  5302. #endif /* NO_VERIFY_OID */
  5303. return ret;
  5304. }
  5305. #ifdef WOLFSSL_ASN_TEMPLATE
  5306. /* ASN.1 template for an OBJECT_ID. */
  5307. static const ASNItem objectIdASN[] = {
  5308. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 }
  5309. };
  5310. enum {
  5311. OBJECTIDASN_IDX_OID = 0
  5312. };
  5313. /* Number of items in ASN.1 template for an OBJECT_ID. */
  5314. #define objectIdASN_Length (sizeof(objectIdASN) / sizeof(ASNItem))
  5315. #endif
  5316. /* Get the OID id/sum from the BER encoded OBJECT_ID.
  5317. *
  5318. * @param [in] input Buffer holding BER encoded data.
  5319. * @param [in, out] inOutIdx On in, start of OBJECT_ID.
  5320. * On out, start of ASN.1 item after OBJECT_ID.
  5321. * @param [out] oid Id of OID in OBJECT_ID data.
  5322. * @param [in] oidType Type of OID to expect.
  5323. * @param [in] maxIdx Maximum index of data in buffer.
  5324. * @return 0 on success.
  5325. * @return ASN_PARSE_E when encoding is invalid.
  5326. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  5327. */
  5328. int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
  5329. word32 oidType, word32 maxIdx)
  5330. {
  5331. #ifndef WOLFSSL_ASN_TEMPLATE
  5332. int ret, length;
  5333. WOLFSSL_ENTER("GetObjectId");
  5334. ret = GetASNObjectId(input, inOutIdx, &length, maxIdx);
  5335. if (ret != 0)
  5336. return ret;
  5337. return GetOID(input, inOutIdx, oid, oidType, length);
  5338. #else
  5339. ASNGetData dataASN[objectIdASN_Length];
  5340. int ret;
  5341. WOLFSSL_ENTER("GetObjectId");
  5342. /* Clear dynamic data and set OID type expected. */
  5343. XMEMSET(dataASN, 0, sizeof(dataASN));
  5344. GetASN_OID(&dataASN[OBJECTIDASN_IDX_OID], oidType);
  5345. /* Decode OBJECT_ID. */
  5346. ret = GetASN_Items(objectIdASN, dataASN, objectIdASN_Length, 0, input,
  5347. inOutIdx, maxIdx);
  5348. if (ret == 0) {
  5349. /* Return the id/sum. */
  5350. *oid = dataASN[OBJECTIDASN_IDX_OID].data.oid.sum;
  5351. }
  5352. return ret;
  5353. #endif /* WOLFSSL_ASN_TEMPLATE */
  5354. }
  5355. #ifndef WOLFSSL_ASN_TEMPLATE
  5356. static int SkipObjectId(const byte* input, word32* inOutIdx, word32 maxIdx)
  5357. {
  5358. word32 idx = *inOutIdx;
  5359. int length;
  5360. int ret;
  5361. ret = GetASNObjectId(input, &idx, &length, maxIdx);
  5362. if (ret != 0)
  5363. return ret;
  5364. idx += (word32)length;
  5365. *inOutIdx = idx;
  5366. return 0;
  5367. }
  5368. #endif
  5369. #ifdef WOLFSSL_ASN_TEMPLATE
  5370. /* ASN.1 template for an algorithm identifier. */
  5371. static const ASNItem algoIdASN[] = {
  5372. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5373. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  5374. /* NULL */ { 1, ASN_TAG_NULL, 0, 0, 1 },
  5375. };
  5376. enum {
  5377. ALGOIDASN_IDX_SEQ = 0,
  5378. ALGOIDASN_IDX_OID,
  5379. ALGOIDASN_IDX_NULL
  5380. };
  5381. /* Number of items in ASN.1 template for an algorithm identifier. */
  5382. #define algoIdASN_Length (sizeof(algoIdASN) / sizeof(ASNItem))
  5383. #endif
  5384. /* Get the OID id/sum from the BER encoding of an algorithm identifier.
  5385. *
  5386. * NULL tag is skipped if present.
  5387. *
  5388. * @param [in] input Buffer holding BER encoded data.
  5389. * @param [in, out] inOutIdx On in, start of algorithm identifier.
  5390. * On out, start of ASN.1 item after algorithm id.
  5391. * @param [out] oid Id of OID in algorithm identifier data.
  5392. * @param [in] oidType Type of OID to expect.
  5393. * @param [in] maxIdx Maximum index of data in buffer.
  5394. * @return 0 on success.
  5395. * @return ASN_PARSE_E when encoding is invalid.
  5396. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  5397. */
  5398. int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
  5399. word32 oidType, word32 maxIdx)
  5400. {
  5401. #ifndef WOLFSSL_ASN_TEMPLATE
  5402. int length;
  5403. word32 idx = *inOutIdx;
  5404. int ret;
  5405. *oid = 0;
  5406. WOLFSSL_ENTER("GetAlgoId");
  5407. if (GetSequence(input, &idx, &length, maxIdx) < 0)
  5408. return ASN_PARSE_E;
  5409. if (GetObjectId(input, &idx, oid, oidType, maxIdx) < 0)
  5410. return ASN_OBJECT_ID_E;
  5411. /* could have NULL tag and 0 terminator, but may not */
  5412. if (idx < maxIdx) {
  5413. word32 localIdx = idx; /*use localIdx to not advance when checking tag*/
  5414. byte tag;
  5415. if (GetASNTag(input, &localIdx, &tag, maxIdx) == 0) {
  5416. if (tag == ASN_TAG_NULL) {
  5417. ret = GetASNNull(input, &idx, maxIdx);
  5418. if (ret != 0)
  5419. return ret;
  5420. }
  5421. }
  5422. }
  5423. *inOutIdx = idx;
  5424. return 0;
  5425. #else
  5426. DECL_ASNGETDATA(dataASN, algoIdASN_Length);
  5427. int ret = 0;
  5428. WOLFSSL_ENTER("GetAlgoId");
  5429. CALLOC_ASNGETDATA(dataASN, algoIdASN_Length, ret, NULL);
  5430. if (ret == 0) {
  5431. /* Set OID type expected. */
  5432. GetASN_OID(&dataASN[ALGOIDASN_IDX_OID], oidType);
  5433. /* Decode the algorithm identifier. */
  5434. ret = GetASN_Items(algoIdASN, dataASN, algoIdASN_Length, 0, input,
  5435. inOutIdx, maxIdx);
  5436. }
  5437. if (ret == 0) {
  5438. /* Return the OID id/sum. */
  5439. *oid = dataASN[ALGOIDASN_IDX_OID].data.oid.sum;
  5440. }
  5441. FREE_ASNGETDATA(dataASN, NULL);
  5442. return ret;
  5443. #endif /* WOLFSSL_ASN_TEMPLATE */
  5444. }
  5445. #ifndef NO_RSA
  5446. #ifdef WC_RSA_PSS
  5447. /* RFC 8017 - PKCS #1 has RSA PSS parameter ASN definition. */
  5448. /* Convert a hash OID to a hash type.
  5449. *
  5450. * @param [in] oid Hash OID.
  5451. * @param [out] type Hash type.
  5452. * @return 0 on success.
  5453. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5454. */
  5455. static int RsaPssHashOidToType(word32 oid, enum wc_HashType* type)
  5456. {
  5457. int ret = 0;
  5458. switch (oid) {
  5459. /* SHA-1 is missing as it is the default is not allowed to appear. */
  5460. #ifdef WOLFSSL_SHA224
  5461. case SHA224h:
  5462. *type = WC_HASH_TYPE_SHA224;
  5463. break;
  5464. #endif
  5465. #ifndef NO_SHA256
  5466. case SHA256h:
  5467. *type = WC_HASH_TYPE_SHA256;
  5468. break;
  5469. #endif
  5470. #ifdef WOLFSSL_SHA384
  5471. case SHA384h:
  5472. *type = WC_HASH_TYPE_SHA384;
  5473. break;
  5474. #endif
  5475. #ifdef WOLFSSL_SHA512
  5476. case SHA512h:
  5477. *type = WC_HASH_TYPE_SHA512;
  5478. break;
  5479. /* TODO: SHA512_224h */
  5480. /* TODO: SHA512_256h */
  5481. #endif
  5482. default:
  5483. ret = ASN_PARSE_E;
  5484. break;
  5485. }
  5486. return ret;
  5487. }
  5488. /* Convert a hash OID to a MGF1 type.
  5489. *
  5490. * @param [in] oid Hash OID.
  5491. * @param [out] mgf MGF type.
  5492. * @return 0 on success.
  5493. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5494. */
  5495. static int RsaPssHashOidToMgf1(word32 oid, int* mgf)
  5496. {
  5497. int ret = 0;
  5498. switch (oid) {
  5499. /* SHA-1 is missing as it is the default is not allowed to appear. */
  5500. #ifdef WOLFSSL_SHA224
  5501. case SHA224h:
  5502. *mgf = WC_MGF1SHA224;
  5503. break;
  5504. #endif
  5505. #ifndef NO_SHA256
  5506. case SHA256h:
  5507. *mgf = WC_MGF1SHA256;
  5508. break;
  5509. #endif
  5510. #ifdef WOLFSSL_SHA384
  5511. case SHA384h:
  5512. *mgf = WC_MGF1SHA384;
  5513. break;
  5514. #endif
  5515. #ifdef WOLFSSL_SHA512
  5516. case SHA512h:
  5517. *mgf = WC_MGF1SHA512;
  5518. break;
  5519. /* TODO: SHA512_224h */
  5520. /* TODO: SHA512_256h */
  5521. #endif
  5522. default:
  5523. ret = ASN_PARSE_E;
  5524. break;
  5525. }
  5526. return ret;
  5527. }
  5528. /* Convert a hash OID to a fake signature OID.
  5529. *
  5530. * @param [in] oid Hash OID.
  5531. * @param [out] sigOid Signature OID to pass wto HashForSignature().
  5532. * @return 0 on success.
  5533. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5534. */
  5535. static int RsaPssHashOidToSigOid(word32 oid, word32* sigOid)
  5536. {
  5537. int ret = 0;
  5538. switch (oid) {
  5539. #ifndef NO_SHA
  5540. case WC_HASH_TYPE_SHA:
  5541. *sigOid = CTC_SHAwRSA;
  5542. break;
  5543. #endif
  5544. #ifdef WOLFSSL_SHA224
  5545. case WC_HASH_TYPE_SHA224:
  5546. *sigOid = CTC_SHA224wRSA;
  5547. break;
  5548. #endif
  5549. #ifndef NO_SHA256
  5550. case WC_HASH_TYPE_SHA256:
  5551. *sigOid = CTC_SHA256wRSA;
  5552. break;
  5553. #endif
  5554. #ifdef WOLFSSL_SHA384
  5555. case WC_HASH_TYPE_SHA384:
  5556. *sigOid = CTC_SHA384wRSA;
  5557. break;
  5558. #endif
  5559. #ifdef WOLFSSL_SHA512
  5560. case WC_HASH_TYPE_SHA512:
  5561. *sigOid = CTC_SHA512wRSA;
  5562. break;
  5563. #endif
  5564. /* TODO: SHA512_224h */
  5565. /* TODO: SHA512_256h */
  5566. /* Not supported by HashForSignature() */
  5567. default:
  5568. ret = ASN_PARSE_E;
  5569. break;
  5570. }
  5571. return ret;
  5572. }
  5573. #ifdef WOLFSSL_ASN_TEMPLATE
  5574. /* ASN tag for hashAlgorigthm. */
  5575. #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | 0)
  5576. /* ASN tag for maskGenAlgorithm. */
  5577. #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | 1)
  5578. /* ASN tag for saltLength. */
  5579. #define ASN_TAG_RSA_PSS_SALTLEN (ASN_CONTEXT_SPECIFIC | 2)
  5580. /* ASN tag for trailerField. */
  5581. #define ASN_TAG_RSA_PSS_TRAILER (ASN_CONTEXT_SPECIFIC | 3)
  5582. /* ASN.1 template for RSA PSS parameters. */
  5583. static const ASNItem rsaPssParamsASN[] = {
  5584. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5585. /* HASH */ { 1, ASN_TAG_RSA_PSS_HASH, 1, 1, 1 },
  5586. /* HASHSEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  5587. /* HASHOID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  5588. /* HASHNULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  5589. /* MGF */ { 1, ASN_TAG_RSA_PSS_MGF, 1, 1, 1 },
  5590. /* MGFSEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  5591. /* MGFOID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  5592. /* MGFPARAM */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  5593. /* MGFHOID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  5594. /* MGFHNULL */ { 4, ASN_TAG_NULL, 0, 0, 1 },
  5595. /* SALTLEN */ { 1, ASN_TAG_RSA_PSS_SALTLEN, 1, 1, 1 },
  5596. /* SALTLENINT */ { 2, ASN_INTEGER, 0, 0, 0 },
  5597. /* TRAILER */ { 1, ASN_TAG_RSA_PSS_TRAILER, 1, 1, 1 },
  5598. /* TRAILERINT */ { 2, ASN_INTEGER, 0, 0, 0 },
  5599. };
  5600. enum {
  5601. RSAPSSPARAMSASN_IDX_SEQ = 0,
  5602. RSAPSSPARAMSASN_IDX_HASH,
  5603. RSAPSSPARAMSASN_IDX_HASHSEQ,
  5604. RSAPSSPARAMSASN_IDX_HASHOID,
  5605. RSAPSSPARAMSASN_IDX_HASHNULL,
  5606. RSAPSSPARAMSASN_IDX_MGF,
  5607. RSAPSSPARAMSASN_IDX_MGFSEQ,
  5608. RSAPSSPARAMSASN_IDX_MGFOID,
  5609. RSAPSSPARAMSASN_IDX_MGFPARAM,
  5610. RSAPSSPARAMSASN_IDX_MGFHOID,
  5611. RSAPSSPARAMSASN_IDX_MGFHNULL,
  5612. RSAPSSPARAMSASN_IDX_SALTLEN,
  5613. RSAPSSPARAMSASN_IDX_SALTLENINT,
  5614. RSAPSSPARAMSASN_IDX_TRAILER,
  5615. RSAPSSPARAMSASN_IDX_TRAILERINT,
  5616. };
  5617. /* Number of items in ASN.1 template for an algorithm identifier. */
  5618. #define rsaPssParamsASN_Length (sizeof(rsaPssParamsASN) / sizeof(ASNItem))
  5619. #else
  5620. /* ASN tag for hashAlgorigthm. */
  5621. #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0)
  5622. /* ASN tag for maskGenAlgorithm. */
  5623. #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)
  5624. /* ASN tag for saltLength. */
  5625. #define ASN_TAG_RSA_PSS_SALTLEN (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)
  5626. /* ASN tag for trailerField. */
  5627. #define ASN_TAG_RSA_PSS_TRAILER (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)
  5628. #endif
  5629. /* Decode the RSA PSS parameters.
  5630. *
  5631. * @param [in] params Buffer holding BER encoded RSA PSS parameters.
  5632. * @param [in] sz Size of data in buffer in bytes.
  5633. * @param [out] hash Hash algorithm to use on message.
  5634. * @param [out] mgf MGF algorithm to use with PSS padding.
  5635. * @param [out] saltLen Length of salt in PSS padding.
  5636. * @return ASN_PARSE_E when the decoding fails.
  5637. * @return 0 on success.
  5638. */
  5639. static int DecodeRsaPssParams(const byte* params, word32 sz,
  5640. enum wc_HashType* hash, int* mgf, int* saltLen)
  5641. {
  5642. #ifndef WOLFSSL_ASN_TEMPLATE
  5643. int ret = 0;
  5644. word32 idx = 0;
  5645. int len = 0;
  5646. word32 oid = 0;
  5647. byte tag;
  5648. int length;
  5649. if (GetSequence_ex(params, &idx, &len, sz, 1) < 0) {
  5650. ret = ASN_PARSE_E;
  5651. }
  5652. if (ret == 0) {
  5653. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_HASH)) {
  5654. /* Hash algorithm to use on message. */
  5655. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5656. ret = ASN_PARSE_E;
  5657. }
  5658. if (ret == 0) {
  5659. if (GetAlgoId(params, &idx, &oid, oidHashType, sz) < 0) {
  5660. ret = ASN_PARSE_E;
  5661. }
  5662. }
  5663. if (ret == 0) {
  5664. ret = RsaPssHashOidToType(oid, hash);
  5665. }
  5666. }
  5667. else {
  5668. /* Default hash algorithm. */
  5669. *hash = WC_HASH_TYPE_SHA;
  5670. }
  5671. }
  5672. if (ret == 0) {
  5673. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_MGF)) {
  5674. /* MGF and hash algorithm to use with padding. */
  5675. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5676. ret = ASN_PARSE_E;
  5677. }
  5678. if (ret == 0) {
  5679. if (GetAlgoId(params, &idx, &oid, oidIgnoreType, sz) < 0) {
  5680. ret = ASN_PARSE_E;
  5681. }
  5682. }
  5683. if ((ret == 0) && (oid != MGF1_OID)) {
  5684. ret = ASN_PARSE_E;
  5685. }
  5686. if (ret == 0) {
  5687. ret = GetAlgoId(params, &idx, &oid, oidHashType, sz);
  5688. if (ret == 0) {
  5689. ret = RsaPssHashOidToMgf1(oid, mgf);
  5690. }
  5691. }
  5692. }
  5693. else {
  5694. /* Default MGF/Hash algorithm. */
  5695. *mgf = WC_MGF1SHA1;
  5696. }
  5697. }
  5698. if (ret == 0) {
  5699. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_SALTLEN)) {
  5700. /* Salt length to use with padding. */
  5701. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5702. ret = ASN_PARSE_E;
  5703. }
  5704. if (ret == 0) {
  5705. ret = GetInteger16Bit(params, &idx, sz);
  5706. if (ret >= 0) {
  5707. *saltLen = ret;
  5708. ret = 0;
  5709. }
  5710. }
  5711. }
  5712. else {
  5713. /* Default salt length. */
  5714. *saltLen = 20;
  5715. }
  5716. }
  5717. if (ret == 0) {
  5718. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_TRAILER)) {
  5719. /* Unused - trialerField. */
  5720. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5721. ret = ASN_PARSE_E;
  5722. }
  5723. if (ret == 0) {
  5724. ret = GetInteger16Bit(params, &idx, sz);
  5725. if (ret > 0) {
  5726. ret = 0;
  5727. }
  5728. }
  5729. }
  5730. }
  5731. if ((ret == 0) && (idx != sz)) {
  5732. ret = ASN_PARSE_E;
  5733. }
  5734. return ret;
  5735. #else
  5736. DECL_ASNGETDATA(dataASN, rsaPssParamsASN_Length);
  5737. int ret = 0;
  5738. word16 sLen = 20;
  5739. CALLOC_ASNGETDATA(dataASN, rsaPssParamsASN_Length, ret, NULL);
  5740. if (ret == 0) {
  5741. word32 inOutIdx = 0;
  5742. /* Default values. */
  5743. *hash = WC_HASH_TYPE_SHA;
  5744. *mgf = WC_MGF1SHA1;
  5745. /* Set OID type expected. */
  5746. GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_HASHOID], oidHashType);
  5747. GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_MGFHOID], oidHashType);
  5748. /* Place the salt length into 16-bit var sLen. */
  5749. GetASN_Int16Bit(&dataASN[RSAPSSPARAMSASN_IDX_SALTLENINT], &sLen);
  5750. /* Decode the algorithm identifier. */
  5751. ret = GetASN_Items(rsaPssParamsASN, dataASN, rsaPssParamsASN_Length, 1,
  5752. params, &inOutIdx, sz);
  5753. }
  5754. if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_HASHOID].tag != 0)) {
  5755. word32 oid = dataASN[RSAPSSPARAMSASN_IDX_HASHOID].data.oid.sum;
  5756. ret = RsaPssHashOidToType(oid, hash);
  5757. }
  5758. if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].tag != 0)) {
  5759. word32 oid = dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].data.oid.sum;
  5760. ret = RsaPssHashOidToMgf1(oid, mgf);
  5761. }
  5762. if (ret == 0) {
  5763. *saltLen = sLen;
  5764. }
  5765. FREE_ASNGETDATA(dataASN, NULL);
  5766. return ret;
  5767. #endif /* WOLFSSL_ASN_TEMPLATE */
  5768. }
  5769. #endif /* WC_RSA_PSS */
  5770. #ifndef HAVE_USER_RSA
  5771. #if defined(WOLFSSL_ASN_TEMPLATE) || (!defined(NO_CERTS) && \
  5772. (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  5773. defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)))
  5774. /* Byte offset of numbers in RSA key. */
  5775. size_t rsaIntOffset[] = {
  5776. OFFSETOF(RsaKey, n),
  5777. OFFSETOF(RsaKey, e),
  5778. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  5779. OFFSETOF(RsaKey, d),
  5780. OFFSETOF(RsaKey, p),
  5781. OFFSETOF(RsaKey, q),
  5782. #if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
  5783. OFFSETOF(RsaKey, dP),
  5784. OFFSETOF(RsaKey, dQ),
  5785. OFFSETOF(RsaKey, u)
  5786. #endif
  5787. #endif
  5788. };
  5789. /* Get a number from the RSA key based on an index.
  5790. *
  5791. * Order: { n, e, d, p, q, dP, dQ, u }
  5792. *
  5793. * Caller must ensure index is not invalid!
  5794. *
  5795. * @param [in] key RSA key object.
  5796. * @param [in] idx Index of number.
  5797. * @return A pointer to an mp_int when valid index.
  5798. * @return NULL when invalid index.
  5799. */
  5800. static mp_int* GetRsaInt(RsaKey* key, int idx)
  5801. {
  5802. /* Cast key to byte array to and use offset to get to mp_int field. */
  5803. return (mp_int*)(((byte*)key) + rsaIntOffset[idx]);
  5804. }
  5805. #endif
  5806. #ifdef WOLFSSL_ASN_TEMPLATE
  5807. /* ASN.1 template for an RSA private key.
  5808. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  5809. */
  5810. static const ASNItem rsaKeyASN[] = {
  5811. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5812. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  5813. /* Integers need to be in this specific order
  5814. * as asn code depends on this. */
  5815. /* N */ { 1, ASN_INTEGER, 0, 0, 0 },
  5816. /* E */ { 1, ASN_INTEGER, 0, 0, 0 },
  5817. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  5818. /* D */ { 1, ASN_INTEGER, 0, 0, 0 },
  5819. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  5820. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  5821. /* DP */ { 1, ASN_INTEGER, 0, 0, 0 },
  5822. /* DQ */ { 1, ASN_INTEGER, 0, 0, 0 },
  5823. /* U */ { 1, ASN_INTEGER, 0, 0, 0 },
  5824. /* otherPrimeInfos OtherPrimeInfos OPTIONAL
  5825. * v2 - multiprime */
  5826. #endif
  5827. };
  5828. enum {
  5829. RSAKEYASN_IDX_SEQ = 0,
  5830. RSAKEYASN_IDX_VER,
  5831. /* Integers need to be in this specific order
  5832. * as asn code depends on this. */
  5833. RSAKEYASN_IDX_N,
  5834. RSAKEYASN_IDX_E,
  5835. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  5836. RSAKEYASN_IDX_D,
  5837. RSAKEYASN_IDX_P,
  5838. RSAKEYASN_IDX_Q,
  5839. RSAKEYASN_IDX_DP,
  5840. RSAKEYASN_IDX_DQ,
  5841. RSAKEYASN_IDX_U,
  5842. #endif
  5843. WOLF_ENUM_DUMMY_LAST_ELEMENT(RSAKEYASN_IDX)
  5844. };
  5845. /* Number of items in ASN.1 template for an RSA private key. */
  5846. #define rsaKeyASN_Length (sizeof(rsaKeyASN) / sizeof(ASNItem))
  5847. #endif
  5848. /* Decode RSA private key.
  5849. *
  5850. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  5851. *
  5852. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  5853. * being extracted.
  5854. *
  5855. * @param [in] input Buffer holding BER encoded data.
  5856. * @param [in, out] inOutIdx On in, start of RSA private key.
  5857. * On out, start of ASN.1 item after RSA private key.
  5858. * @param [in, out] key RSA key object. May be NULL.
  5859. * @param [out] keySz Size of key in bytes. May be NULL.
  5860. * @param [in] inSz Number of bytes in buffer.
  5861. * @return 0 on success.
  5862. * @return BAD_FUNC_ARG when input or inOutIdx is NULL.
  5863. * @return BAD_FUNC_ARG when key and keySz are NULL.
  5864. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  5865. * is invalid.
  5866. * @return BUFFER_E when data in buffer is too small.
  5867. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  5868. * non-zero length.
  5869. * @return MP_INIT_E when the unable to initialize an mp_int.
  5870. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  5871. */
  5872. static int _RsaPrivateKeyDecode(const byte* input, word32* inOutIdx,
  5873. RsaKey* key, int* keySz, word32 inSz)
  5874. {
  5875. #ifndef WOLFSSL_ASN_TEMPLATE
  5876. int version, length;
  5877. word32 algId = 0;
  5878. if (inOutIdx == NULL || input == NULL || (key == NULL && keySz == NULL)) {
  5879. return BAD_FUNC_ARG;
  5880. }
  5881. /* if has pkcs8 header skip it */
  5882. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  5883. /* ignore error, did not have pkcs8 header */
  5884. }
  5885. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  5886. return ASN_PARSE_E;
  5887. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  5888. return ASN_PARSE_E;
  5889. if (key == NULL) {
  5890. int i;
  5891. /* Modulus */
  5892. if (GetASNInt(input, inOutIdx, keySz, inSz) < 0) {
  5893. return ASN_PARSE_E;
  5894. }
  5895. *inOutIdx += (word32)*keySz;
  5896. for (i = 1; i < RSA_INTS; i++) {
  5897. if (SkipInt(input, inOutIdx, inSz) < 0) {
  5898. return ASN_RSA_KEY_E;
  5899. }
  5900. }
  5901. }
  5902. else {
  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. }
  5945. return 0;
  5946. #else
  5947. DECL_ASNGETDATA(dataASN, rsaKeyASN_Length);
  5948. int ret = 0;
  5949. byte version = (byte)-1;
  5950. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  5951. word32 algId = 0;
  5952. #endif
  5953. void* heap = NULL;
  5954. /* Check validity of parameters. */
  5955. if ((inOutIdx == NULL) || (input == NULL) || ((key == NULL) &&
  5956. (keySz == NULL))) {
  5957. ret = BAD_FUNC_ARG;
  5958. }
  5959. if ((ret == 0) && (key != NULL)) {
  5960. heap = key->heap;
  5961. }
  5962. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  5963. if (ret == 0) {
  5964. /* if has pkcs8 header skip it */
  5965. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  5966. /* ignore error, did not have pkcs8 header */
  5967. }
  5968. }
  5969. #endif
  5970. (void)heap;
  5971. CALLOC_ASNGETDATA(dataASN, rsaKeyASN_Length, ret, heap);
  5972. if (ret == 0) {
  5973. int i;
  5974. /* Register variable to hold version field. */
  5975. GetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], &version);
  5976. /* Setup data to store INTEGER data in mp_int's in RSA object. */
  5977. #if defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5978. #define RSA_ASN_INTS RSA_PUB_INTS
  5979. /* Not extracting all data from BER encoding. */
  5980. #define RSA_ASN_COMPLETE 0
  5981. #else
  5982. #define RSA_ASN_INTS RSA_INTS
  5983. /* Extracting all data from BER encoding. */
  5984. #define RSA_ASN_COMPLETE 1
  5985. #endif
  5986. if (key != NULL) {
  5987. /* Extract all public fields. */
  5988. for (i = 0; i < RSA_ASN_INTS; i++) {
  5989. GetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i],
  5990. GetRsaInt(key, i));
  5991. }
  5992. }
  5993. /* Parse BER encoding for RSA private key. */
  5994. ret = GetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length,
  5995. RSA_ASN_COMPLETE, input, inOutIdx, inSz);
  5996. }
  5997. /* Check version: 0 - two prime, 1 - multi-prime
  5998. * Multi-prime has optional sequence after coefficient for extra primes.
  5999. * If extra primes, parsing will fail as not all the buffer was used.
  6000. */
  6001. if ((ret == 0) && (version > PKCS1v1)) {
  6002. ret = ASN_PARSE_E;
  6003. }
  6004. if ((ret == 0) && (key != NULL)) {
  6005. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  6006. /* RSA key object has all private key values. */
  6007. key->type = RSA_PRIVATE;
  6008. #else
  6009. /* RSA key object has all public key values. */
  6010. key->type = RSA_PUBLIC;
  6011. #endif
  6012. #ifdef WOLFSSL_XILINX_CRYPT
  6013. if (wc_InitRsaHw(key) != 0)
  6014. ret = BAD_STATE_E;
  6015. #endif
  6016. }
  6017. else if (ret == 0) {
  6018. /* Not filling in key but do want key size. */
  6019. *keySz = (int)dataASN[(byte)RSAKEYASN_IDX_N].length;
  6020. /* Check whether first byte of data is 0x00 and drop it. */
  6021. if (input[(int)dataASN[RSAKEYASN_IDX_E].offset - *keySz] == 0) {
  6022. (*keySz)--;
  6023. }
  6024. }
  6025. FREE_ASNGETDATA(dataASN, heap);
  6026. return ret;
  6027. #endif /* WOLFSSL_ASN_TEMPLATE */
  6028. }
  6029. /* Decode RSA private key.
  6030. *
  6031. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  6032. *
  6033. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  6034. * being extracted.
  6035. *
  6036. * @param [in] input Buffer holding BER encoded data.
  6037. * @param [in, out] inOutIdx On in, start of RSA private key.
  6038. * On out, start of ASN.1 item after RSA private key.
  6039. * @param [in, out] key RSA key object.
  6040. * @param [in] inSz Number of bytes in buffer.
  6041. * @return 0 on success.
  6042. * @return BAD_FUNC_ARG when input, inOutIdx or key is NULL.
  6043. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6044. * is invalid.
  6045. * @return BUFFER_E when data in buffer is too small.
  6046. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6047. * non-zero length.
  6048. * @return MP_INIT_E when the unable to initialize an mp_int.
  6049. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  6050. */
  6051. int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  6052. word32 inSz)
  6053. {
  6054. if (key == NULL) {
  6055. return BAD_FUNC_ARG;
  6056. }
  6057. return _RsaPrivateKeyDecode(input, inOutIdx, key, NULL, inSz);
  6058. }
  6059. /* Valdidate RSA private key ASN.1 encoding.
  6060. *
  6061. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  6062. *
  6063. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  6064. * being extracted.
  6065. *
  6066. * @param [in] input Buffer holding BER encoded data.
  6067. * @param [in, out] inOutIdx On in, start of RSA private key.
  6068. * On out, start of ASN.1 item after RSA private key.
  6069. * @param [in] inSz Number of bytes in buffer.
  6070. * @return 0 on success.
  6071. * @return BAD_FUNC_ARG when input, inOutIdx or keySz is NULL.
  6072. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6073. * is invalid.
  6074. * @return BUFFER_E when data in buffer is too small.
  6075. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6076. * non-zero length.
  6077. * @return MP_INIT_E when the unable to initialize an mp_int.
  6078. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  6079. */
  6080. int wc_RsaPrivateKeyValidate(const byte* input, word32* inOutIdx, int* keySz,
  6081. word32 inSz)
  6082. {
  6083. return _RsaPrivateKeyDecode(input, inOutIdx, NULL, keySz, inSz);
  6084. }
  6085. #endif /* HAVE_USER_RSA */
  6086. #endif /* NO_RSA */
  6087. #ifdef WOLFSSL_ASN_TEMPLATE
  6088. /* ASN.1 template for a PKCS #8 key.
  6089. * Ignoring optional attributes and public key.
  6090. * PKCS #8: RFC 5958, 2 - PrivateKeyInfo
  6091. */
  6092. static const ASNItem pkcs8KeyASN[] = {
  6093. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  6094. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  6095. /* PKEY_ALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  6096. /* PKEY_ALGO_OID_KEY */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  6097. /* PKEY_ALGO_OID_CURVE */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  6098. /* PKEY_ALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  6099. #ifdef WC_RSA_PSS
  6100. /* PKEY_ALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  6101. #endif
  6102. /* PKEY_DATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  6103. /* attributes [0] Attributes OPTIONAL */
  6104. /* [[2: publicKey [1] PublicKey OPTIONAL ]] */
  6105. };
  6106. enum {
  6107. PKCS8KEYASN_IDX_SEQ = 0,
  6108. PKCS8KEYASN_IDX_VER,
  6109. PKCS8KEYASN_IDX_PKEY_ALGO_SEQ,
  6110. PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY,
  6111. PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE,
  6112. PKCS8KEYASN_IDX_PKEY_ALGO_NULL,
  6113. #ifdef WC_RSA_PSS
  6114. PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ,
  6115. #endif
  6116. PKCS8KEYASN_IDX_PKEY_DATA,
  6117. WOLF_ENUM_DUMMY_LAST_ELEMENT(PKCS8KEYASN_IDX)
  6118. };
  6119. /* Number of items in ASN.1 template for a PKCS #8 key. */
  6120. #define pkcs8KeyASN_Length (sizeof(pkcs8KeyASN) / sizeof(ASNItem))
  6121. #endif
  6122. /* Remove PKCS #8 header around an RSA, ECDSA, Ed25519, or Ed448.
  6123. *
  6124. * @param [in] input Buffer holding BER data.
  6125. * @param [in, out] inOutIdx On in, start of PKCS #8 encoding.
  6126. * On out, start of encoded key.
  6127. * @param [in] sz Size of data in buffer.
  6128. * @param [out] algId Key's algorithm id from PKCS #8 header.
  6129. * @return Length of key data on success.
  6130. * @return BAD_FUNC_ARG when input or inOutIdx is NULL.
  6131. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6132. * is invalid.
  6133. * @return BUFFER_E when data in buffer is too small.
  6134. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  6135. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6136. * non-zero length.
  6137. */
  6138. int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz,
  6139. word32* algId)
  6140. {
  6141. #ifndef WOLFSSL_ASN_TEMPLATE
  6142. word32 idx;
  6143. int version, length;
  6144. int ret;
  6145. byte tag;
  6146. if (input == NULL || inOutIdx == NULL)
  6147. return BAD_FUNC_ARG;
  6148. idx = *inOutIdx;
  6149. if (GetSequence(input, &idx, &length, sz) < 0)
  6150. return ASN_PARSE_E;
  6151. if (GetMyVersion(input, &idx, &version, sz) < 0)
  6152. return ASN_PARSE_E;
  6153. if (GetAlgoId(input, &idx, algId, oidKeyType, sz) < 0)
  6154. return ASN_PARSE_E;
  6155. if (GetASNTag(input, &idx, &tag, sz) < 0)
  6156. return ASN_PARSE_E;
  6157. idx = idx - 1; /* reset idx after finding tag */
  6158. #if defined(WC_RSA_PSS) && !defined(NO_RSA)
  6159. if (*algId == RSAPSSk && tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  6160. word32 seqIdx = idx;
  6161. int seqLen;
  6162. /* Not set when -1. */
  6163. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  6164. int mgf = -1;
  6165. int saltLen = 0;
  6166. if (GetSequence(input, &idx, &seqLen, sz) < 0) {
  6167. return ASN_PARSE_E;
  6168. }
  6169. /* Get the private key parameters. */
  6170. ret = DecodeRsaPssParams(input + seqIdx,
  6171. seqLen + idx - seqIdx, &hash, &mgf, &saltLen);
  6172. if (ret != 0) {
  6173. return ASN_PARSE_E;
  6174. }
  6175. /* TODO: store parameters so that usage can be checked. */
  6176. idx += seqLen;
  6177. }
  6178. #endif /* WC_RSA_PSS && !NO_RSA */
  6179. if (tag == ASN_OBJECT_ID) {
  6180. if (SkipObjectId(input, &idx, sz) < 0)
  6181. return ASN_PARSE_E;
  6182. }
  6183. ret = GetOctetString(input, &idx, &length, sz);
  6184. if (ret < 0) {
  6185. if (ret == BUFFER_E)
  6186. return ASN_PARSE_E;
  6187. /* Some private keys don't expect an octet string */
  6188. WOLFSSL_MSG("Couldn't find Octet string");
  6189. }
  6190. *inOutIdx = idx;
  6191. return length;
  6192. #else
  6193. DECL_ASNGETDATA(dataASN, pkcs8KeyASN_Length);
  6194. int ret = 0;
  6195. word32 oid = 9;
  6196. byte version;
  6197. word32 idx;
  6198. /* Check validity of parameters. */
  6199. if (input == NULL || inOutIdx == NULL) {
  6200. return BAD_FUNC_ARG;
  6201. }
  6202. idx = *inOutIdx;
  6203. CALLOC_ASNGETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  6204. if (ret == 0) {
  6205. /* Get version, check key type and curve type. */
  6206. GetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], &version);
  6207. GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], oidKeyType);
  6208. GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE], oidCurveType);
  6209. /* Parse data. */
  6210. ret = GetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, 1, input,
  6211. &idx, sz);
  6212. }
  6213. if (ret == 0) {
  6214. /* Key type OID. */
  6215. oid = dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY].data.oid.sum;
  6216. /* Version 1 includes an optional public key.
  6217. * If public key is included then the parsing will fail as it did not
  6218. * use all the data.
  6219. */
  6220. if (version > PKCS8v1) {
  6221. ret = ASN_PARSE_E;
  6222. }
  6223. }
  6224. if (ret == 0) {
  6225. switch (oid) {
  6226. #ifndef NO_RSA
  6227. case RSAk:
  6228. /* Must have NULL item but not OBJECT_ID item. */
  6229. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag == 0) ||
  6230. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6231. ret = ASN_PARSE_E;
  6232. }
  6233. break;
  6234. #ifdef WC_RSA_PSS
  6235. case RSAPSSk:
  6236. /* Must not have NULL item. */
  6237. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
  6238. ret = ASN_PARSE_E;
  6239. }
  6240. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].tag != 0) {
  6241. enum wc_HashType hash;
  6242. int mgf;
  6243. int saltLen;
  6244. const byte* params = GetASNItem_Addr(
  6245. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
  6246. word32 paramsSz = GetASNItem_Length(
  6247. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
  6248. /* Validate the private key parameters. */
  6249. ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf,
  6250. &saltLen);
  6251. if (ret != 0) {
  6252. return ASN_PARSE_E;
  6253. }
  6254. /* TODO: store parameters so that usage can be checked. */
  6255. }
  6256. break;
  6257. #endif
  6258. #endif
  6259. #ifdef HAVE_ECC
  6260. case ECDSAk:
  6261. /* Must not have NULL item. */
  6262. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
  6263. ret = ASN_PARSE_E;
  6264. }
  6265. break;
  6266. #endif
  6267. #ifdef HAVE_ED25519
  6268. case ED25519k:
  6269. /* Neither NULL item nor OBJECT_ID item allowed. */
  6270. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6271. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6272. ret = ASN_PARSE_E;
  6273. }
  6274. break;
  6275. #endif
  6276. #ifdef HAVE_CURVE25519
  6277. case X25519k:
  6278. /* Neither NULL item nor OBJECT_ID item allowed. */
  6279. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6280. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6281. ret = ASN_PARSE_E;
  6282. }
  6283. break;
  6284. #endif
  6285. #ifdef HAVE_ED448
  6286. case ED448k:
  6287. /* Neither NULL item nor OBJECT_ID item allowed. */
  6288. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6289. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6290. ret = ASN_PARSE_E;
  6291. }
  6292. break;
  6293. #endif
  6294. #ifdef HAVE_CURVE448
  6295. case X448k:
  6296. /* Neither NULL item nor OBJECT_ID item allowed. */
  6297. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6298. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6299. ret = ASN_PARSE_E;
  6300. }
  6301. break;
  6302. #endif
  6303. /* DSAk not supported. */
  6304. /* Falcon, Dilithium and Sphincs not supported. */
  6305. /* Ignore OID lookup failures. */
  6306. default:
  6307. break;
  6308. }
  6309. }
  6310. if (ret == 0) {
  6311. /* Return algorithm id of internal key. */
  6312. *algId = oid;
  6313. /* Return index to start of internal key. */
  6314. *inOutIdx = GetASNItem_DataIdx(dataASN[PKCS8KEYASN_IDX_PKEY_DATA], input);
  6315. /* Return value is length of internal key. */
  6316. ret = (int)dataASN[PKCS8KEYASN_IDX_PKEY_DATA].data.ref.length;
  6317. }
  6318. FREE_ASNGETDATA(dataASN, NULL);
  6319. return ret;
  6320. #endif
  6321. }
  6322. /* TODO: test case */
  6323. int ToTraditionalInline(const byte* input, word32* inOutIdx, word32 sz)
  6324. {
  6325. word32 oid;
  6326. return ToTraditionalInline_ex(input, inOutIdx, sz, &oid);
  6327. }
  6328. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6329. /* Remove PKCS8 header, move beginning of traditional to beginning of input */
  6330. int ToTraditional_ex(byte* input, word32 sz, word32* algId)
  6331. {
  6332. word32 inOutIdx = 0;
  6333. int length;
  6334. if (input == NULL)
  6335. return BAD_FUNC_ARG;
  6336. length = ToTraditionalInline_ex(input, &inOutIdx, sz, algId);
  6337. if (length < 0)
  6338. return length;
  6339. if ((word32)length + inOutIdx > sz)
  6340. return BUFFER_E;
  6341. XMEMMOVE(input, input + inOutIdx, (size_t)length);
  6342. return length;
  6343. }
  6344. int ToTraditional(byte* input, word32 sz)
  6345. {
  6346. word32 oid;
  6347. return ToTraditional_ex(input, sz, &oid);
  6348. }
  6349. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  6350. #if defined(HAVE_PKCS8) && !defined(NO_CERTS)
  6351. int wc_GetPkcs8TraditionalOffset(byte* input, word32* inOutIdx, word32 sz)
  6352. {
  6353. int length;
  6354. word32 algId;
  6355. if (input == NULL || inOutIdx == NULL || (*inOutIdx > sz))
  6356. return BAD_FUNC_ARG;
  6357. length = ToTraditionalInline_ex(input, inOutIdx, sz, &algId);
  6358. return length;
  6359. }
  6360. int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz,
  6361. int algoID, const byte* curveOID, word32 oidSz)
  6362. {
  6363. #ifndef WOLFSSL_ASN_TEMPLATE
  6364. word32 keyIdx = 0;
  6365. word32 tmpSz = 0;
  6366. word32 sz;
  6367. word32 tmpAlgId = 0;
  6368. /* If out is NULL then return the max size needed
  6369. * + 2 for ASN_OBJECT_ID and ASN_OCTET_STRING tags */
  6370. if (out == NULL && outSz != NULL) {
  6371. *outSz = keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6372. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2;
  6373. if (curveOID != NULL)
  6374. *outSz += oidSz + MAX_LENGTH_SZ + 1;
  6375. WOLFSSL_MSG("Checking size of PKCS8");
  6376. return LENGTH_ONLY_E;
  6377. }
  6378. WOLFSSL_ENTER("wc_CreatePKCS8Key");
  6379. if (key == NULL || out == NULL || outSz == NULL) {
  6380. return BAD_FUNC_ARG;
  6381. }
  6382. /* check the buffer has enough room for largest possible size */
  6383. if (curveOID != NULL) {
  6384. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6385. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 3 + oidSz + MAX_LENGTH_SZ))
  6386. return BUFFER_E;
  6387. }
  6388. else {
  6389. oidSz = 0; /* with no curveOID oid size must be 0 */
  6390. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6391. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2))
  6392. return BUFFER_E;
  6393. }
  6394. /* sanity check: make sure the key doesn't already have a PKCS 8 header */
  6395. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  6396. (void)tmpAlgId;
  6397. return ASN_PARSE_E;
  6398. }
  6399. /* PrivateKeyInfo ::= SEQUENCE */
  6400. keyIdx = MAX_SEQ_SZ; /* save room for sequence */
  6401. /* version Version
  6402. * no header information just INTEGER */
  6403. sz = (word32)SetMyVersion(PKCS8v0, out + keyIdx, 0);
  6404. tmpSz += sz; keyIdx += sz;
  6405. /* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier */
  6406. sz = 0; /* set sz to 0 and get privateKey oid buffer size needed */
  6407. if (curveOID != NULL && oidSz > 0) {
  6408. byte buf[MAX_LENGTH_SZ];
  6409. sz = SetLength(oidSz, buf);
  6410. sz += 1; /* plus one for ASN object id */
  6411. }
  6412. sz = (word32)SetAlgoID(algoID, out + keyIdx, oidKeyType, (int)(oidSz + sz));
  6413. tmpSz += sz; keyIdx += sz;
  6414. /* privateKey PrivateKey *
  6415. * pkcs8 ecc uses slightly different format. Places curve oid in
  6416. * buffer */
  6417. if (curveOID != NULL && oidSz > 0) {
  6418. sz = (word32)SetObjectId((int)oidSz, out + keyIdx);
  6419. keyIdx += sz; tmpSz += sz;
  6420. XMEMCPY(out + keyIdx, curveOID, oidSz);
  6421. keyIdx += oidSz; tmpSz += oidSz;
  6422. }
  6423. sz = (word32)SetOctetString(keySz, out + keyIdx);
  6424. keyIdx += sz; tmpSz += sz;
  6425. XMEMCPY(out + keyIdx, key, keySz);
  6426. tmpSz += keySz;
  6427. /* attributes optional
  6428. * No attributes currently added */
  6429. /* rewind and add sequence */
  6430. sz = SetSequence(tmpSz, out);
  6431. XMEMMOVE(out + sz, out + MAX_SEQ_SZ, tmpSz);
  6432. *outSz = tmpSz + sz;
  6433. return (int)(tmpSz + sz);
  6434. #else
  6435. DECL_ASNSETDATA(dataASN, pkcs8KeyASN_Length);
  6436. int sz;
  6437. int ret = 0;
  6438. word32 keyIdx = 0;
  6439. word32 tmpAlgId = 0;
  6440. WOLFSSL_ENTER("wc_CreatePKCS8Key");
  6441. /* Check validity of parameters. */
  6442. if (out == NULL && outSz != NULL) {
  6443. }
  6444. else if (key == NULL || out == NULL || outSz == NULL) {
  6445. ret = BAD_FUNC_ARG;
  6446. }
  6447. /* Sanity check: make sure key doesn't have PKCS #8 header. */
  6448. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  6449. (void)tmpAlgId;
  6450. ret = ASN_PARSE_E;
  6451. }
  6452. CALLOC_ASNSETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  6453. if (ret == 0) {
  6454. /* Only support default PKCS #8 format - v0. */
  6455. SetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], PKCS8v0);
  6456. /* Set key OID that corresponds to key data. */
  6457. SetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], (word32)algoID,
  6458. oidKeyType);
  6459. if (curveOID != NULL && oidSz > 0) {
  6460. /* ECC key and curveOID set to write. */
  6461. SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE], curveOID, oidSz);
  6462. }
  6463. else {
  6464. /* EC curve OID to encode. */
  6465. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].noOut = 1;
  6466. }
  6467. /* Only RSA keys have NULL tagged item after OID. */
  6468. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].noOut = (algoID != RSAk);
  6469. #ifdef WC_RSA_PSS
  6470. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].noOut = 1;
  6471. #endif
  6472. /* Set key data to encode. */
  6473. SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_DATA], key, keySz);
  6474. /* Get the size of the DER encoding. */
  6475. ret = SizeASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, &sz);
  6476. }
  6477. if (ret == 0) {
  6478. /* Always return the calculated size. */
  6479. *outSz = (word32)sz;
  6480. }
  6481. /* Check for buffer to encoded into. */
  6482. if ((ret == 0) && (out == NULL)) {
  6483. WOLFSSL_MSG("Checking size of PKCS8");
  6484. ret = LENGTH_ONLY_E;
  6485. }
  6486. if (ret == 0) {
  6487. /* Encode PKCS #8 key into buffer. */
  6488. SetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, out);
  6489. ret = sz;
  6490. }
  6491. FREE_ASNSETDATA(dataASN, NULL);
  6492. return ret;
  6493. #endif /* WOLFSSL_ASN_TEMPLATE */
  6494. }
  6495. #endif /* HAVE_PKCS8 && !NO_CERTS */
  6496. #if defined(HAVE_PKCS12) || !defined(NO_CHECK_PRIVATE_KEY)
  6497. /* check that the private key is a pair for the public key
  6498. * return 1 (true) on match
  6499. * return 0 or negative value on failure/error
  6500. *
  6501. * privKey : buffer holding DER format private key
  6502. * privKeySz : size of private key buffer
  6503. * pubKey : buffer holding DER format public key
  6504. * pubKeySz : size of public key buffer
  6505. * ks : type of key */
  6506. int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz,
  6507. const byte* pubKey, word32 pubKeySz, enum Key_Sum ks)
  6508. {
  6509. int ret;
  6510. (void)privKeySz;
  6511. (void)pubKeySz;
  6512. (void)ks;
  6513. if (privKey == NULL || pubKey == NULL) {
  6514. return BAD_FUNC_ARG;
  6515. }
  6516. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  6517. /* test if RSA key */
  6518. if (ks == RSAk
  6519. #ifdef WC_RSA_PSS
  6520. || ks == RSAPSSk
  6521. #endif
  6522. ) {
  6523. #ifdef WOLFSSL_SMALL_STACK
  6524. RsaKey* a;
  6525. RsaKey* b = NULL;
  6526. #else
  6527. RsaKey a[1], b[1];
  6528. #endif
  6529. word32 keyIdx = 0;
  6530. #ifdef WOLFSSL_SMALL_STACK
  6531. a = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  6532. if (a == NULL)
  6533. return MEMORY_E;
  6534. b = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  6535. if (b == NULL) {
  6536. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6537. return MEMORY_E;
  6538. }
  6539. #endif
  6540. if ((ret = wc_InitRsaKey(a, NULL)) < 0) {
  6541. #ifdef WOLFSSL_SMALL_STACK
  6542. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6543. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6544. #endif
  6545. return ret;
  6546. }
  6547. if ((ret = wc_InitRsaKey(b, NULL)) < 0) {
  6548. wc_FreeRsaKey(a);
  6549. #ifdef WOLFSSL_SMALL_STACK
  6550. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6551. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6552. #endif
  6553. return ret;
  6554. }
  6555. if ((ret = wc_RsaPrivateKeyDecode(privKey, &keyIdx, a, privKeySz)) == 0) {
  6556. WOLFSSL_MSG("Checking RSA key pair");
  6557. keyIdx = 0; /* reset to 0 for parsing public key */
  6558. if ((ret = wc_RsaPublicKeyDecode(pubKey, &keyIdx, b,
  6559. pubKeySz)) == 0) {
  6560. /* limit for user RSA crypto because of RsaKey
  6561. * dereference. */
  6562. #if defined(HAVE_USER_RSA)
  6563. WOLFSSL_MSG("Cannot verify RSA pair with user RSA");
  6564. ret = 1; /* return first RSA cert as match */
  6565. #else
  6566. /* both keys extracted successfully now check n and e
  6567. * values are the same. This is dereferencing RsaKey */
  6568. if (mp_cmp(&(a->n), &(b->n)) != MP_EQ ||
  6569. mp_cmp(&(a->e), &(b->e)) != MP_EQ) {
  6570. ret = MP_CMP_E;
  6571. WOLFSSL_ERROR_VERBOSE(ret);
  6572. }
  6573. else
  6574. ret = 1;
  6575. #endif
  6576. }
  6577. else {
  6578. WOLFSSL_ERROR_VERBOSE(ret);
  6579. }
  6580. }
  6581. wc_FreeRsaKey(b);
  6582. wc_FreeRsaKey(a);
  6583. #ifdef WOLFSSL_SMALL_STACK
  6584. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6585. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6586. #endif
  6587. }
  6588. else
  6589. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  6590. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  6591. if (ks == ECDSAk) {
  6592. #ifdef WOLFSSL_SMALL_STACK
  6593. ecc_key* key_pair;
  6594. byte* privDer;
  6595. #else
  6596. ecc_key key_pair[1];
  6597. byte privDer[MAX_ECC_BYTES];
  6598. #endif
  6599. word32 privSz = MAX_ECC_BYTES;
  6600. word32 keyIdx = 0;
  6601. #ifdef WOLFSSL_SMALL_STACK
  6602. key_pair = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL, DYNAMIC_TYPE_ECC);
  6603. if (key_pair == NULL)
  6604. return MEMORY_E;
  6605. privDer = (byte*)XMALLOC(MAX_ECC_BYTES, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6606. if (privDer == NULL) {
  6607. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6608. return MEMORY_E;
  6609. }
  6610. #endif
  6611. if ((ret = wc_ecc_init(key_pair)) < 0) {
  6612. #ifdef WOLFSSL_SMALL_STACK
  6613. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6614. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6615. #endif
  6616. return ret;
  6617. }
  6618. if ((ret = wc_EccPrivateKeyDecode(privKey, &keyIdx, key_pair,
  6619. privKeySz)) == 0) {
  6620. WOLFSSL_MSG("Checking ECC key pair");
  6621. if ((ret = wc_ecc_export_private_only(key_pair, privDer, &privSz))
  6622. == 0) {
  6623. #ifdef WOLFSSL_CHECK_MEM_ZERO
  6624. wc_MemZero_Add("wc_CheckPrivateKey privDer", privDer, privSz);
  6625. #endif
  6626. wc_ecc_free(key_pair);
  6627. ret = wc_ecc_init(key_pair);
  6628. if (ret == 0) {
  6629. ret = wc_ecc_import_private_key(privDer,
  6630. privSz, pubKey,
  6631. pubKeySz, key_pair);
  6632. }
  6633. /* public and private extracted successfully now check if is
  6634. * a pair and also do sanity checks on key. wc_ecc_check_key
  6635. * checks that private * base generator equals pubkey */
  6636. if (ret == 0) {
  6637. if ((ret = wc_ecc_check_key(key_pair)) == 0) {
  6638. ret = 1;
  6639. }
  6640. else {
  6641. WOLFSSL_ERROR_VERBOSE(ret);
  6642. }
  6643. }
  6644. ForceZero(privDer, privSz);
  6645. }
  6646. }
  6647. else {
  6648. WOLFSSL_ERROR_VERBOSE(ret);
  6649. }
  6650. wc_ecc_free(key_pair);
  6651. #ifdef WOLFSSL_SMALL_STACK
  6652. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6653. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6654. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  6655. wc_MemZero_Check(privDer, MAX_ECC_BYTES);
  6656. #endif
  6657. }
  6658. else
  6659. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  6660. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  6661. if (ks == ED25519k) {
  6662. #ifdef WOLFSSL_SMALL_STACK
  6663. ed25519_key* key_pair;
  6664. #else
  6665. ed25519_key key_pair[1];
  6666. #endif
  6667. word32 keyIdx = 0;
  6668. #ifdef WOLFSSL_SMALL_STACK
  6669. key_pair = (ed25519_key*)XMALLOC(sizeof(ed25519_key), NULL,
  6670. DYNAMIC_TYPE_ED25519);
  6671. if (key_pair == NULL)
  6672. return MEMORY_E;
  6673. #endif
  6674. if ((ret = wc_ed25519_init(key_pair)) < 0) {
  6675. #ifdef WOLFSSL_SMALL_STACK
  6676. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  6677. #endif
  6678. return ret;
  6679. }
  6680. if ((ret = wc_Ed25519PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6681. privKeySz)) == 0) {
  6682. WOLFSSL_MSG("Checking ED25519 key pair");
  6683. keyIdx = 0;
  6684. if ((ret = wc_ed25519_import_public(pubKey, pubKeySz,
  6685. key_pair)) == 0) {
  6686. /* public and private extracted successfully no check if is
  6687. * a pair and also do sanity checks on key. wc_ecc_check_key
  6688. * checks that private * base generator equals pubkey */
  6689. if ((ret = wc_ed25519_check_key(key_pair)) == 0) {
  6690. ret = 1;
  6691. }
  6692. else {
  6693. WOLFSSL_ERROR_VERBOSE(ret);
  6694. }
  6695. }
  6696. }
  6697. else {
  6698. WOLFSSL_ERROR_VERBOSE(ret);
  6699. }
  6700. wc_ed25519_free(key_pair);
  6701. #ifdef WOLFSSL_SMALL_STACK
  6702. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  6703. #endif
  6704. }
  6705. else
  6706. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  6707. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  6708. if (ks == ED448k) {
  6709. #ifdef WOLFSSL_SMALL_STACK
  6710. ed448_key* key_pair = NULL;
  6711. #else
  6712. ed448_key key_pair[1];
  6713. #endif
  6714. word32 keyIdx = 0;
  6715. #ifdef WOLFSSL_SMALL_STACK
  6716. key_pair = (ed448_key*)XMALLOC(sizeof(ed448_key), NULL,
  6717. DYNAMIC_TYPE_ED448);
  6718. if (key_pair == NULL)
  6719. return MEMORY_E;
  6720. #endif
  6721. if ((ret = wc_ed448_init(key_pair)) < 0) {
  6722. #ifdef WOLFSSL_SMALL_STACK
  6723. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  6724. #endif
  6725. return ret;
  6726. }
  6727. if ((ret = wc_Ed448PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6728. privKeySz)) == 0) {
  6729. WOLFSSL_MSG("Checking ED448 key pair");
  6730. keyIdx = 0;
  6731. if ((ret = wc_ed448_import_public(pubKey, pubKeySz,
  6732. key_pair)) == 0) {
  6733. /* public and private extracted successfully no check if is
  6734. * a pair and also do sanity checks on key. wc_ecc_check_key
  6735. * checks that private * base generator equals pubkey */
  6736. if ((ret = wc_ed448_check_key(key_pair)) == 0) {
  6737. ret = 1;
  6738. }
  6739. else {
  6740. WOLFSSL_ERROR_VERBOSE(ret);
  6741. }
  6742. }
  6743. }
  6744. else {
  6745. WOLFSSL_ERROR_VERBOSE(ret);
  6746. }
  6747. wc_ed448_free(key_pair);
  6748. #ifdef WOLFSSL_SMALL_STACK
  6749. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  6750. #endif
  6751. }
  6752. else
  6753. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  6754. #if defined(HAVE_PQC)
  6755. #if defined(HAVE_FALCON)
  6756. if ((ks == FALCON_LEVEL1k) || (ks == FALCON_LEVEL5k)) {
  6757. #ifdef WOLFSSL_SMALL_STACK
  6758. falcon_key* key_pair = NULL;
  6759. #else
  6760. falcon_key key_pair[1];
  6761. #endif
  6762. word32 keyIdx = 0;
  6763. #ifdef WOLFSSL_SMALL_STACK
  6764. key_pair = (falcon_key*)XMALLOC(sizeof(falcon_key), NULL,
  6765. DYNAMIC_TYPE_FALCON);
  6766. if (key_pair == NULL)
  6767. return MEMORY_E;
  6768. #endif
  6769. ret = wc_falcon_init(key_pair);
  6770. if (ret < 0) {
  6771. #ifdef WOLFSSL_SMALL_STACK
  6772. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6773. #endif
  6774. return ret;
  6775. }
  6776. if (ks == FALCON_LEVEL1k) {
  6777. ret = wc_falcon_set_level(key_pair, 1);
  6778. }
  6779. else if (ks == FALCON_LEVEL5k) {
  6780. ret = wc_falcon_set_level(key_pair, 5);
  6781. }
  6782. if (ret < 0) {
  6783. #ifdef WOLFSSL_SMALL_STACK
  6784. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6785. #endif
  6786. return ret;
  6787. }
  6788. if ((ret = wc_Falcon_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6789. privKeySz)) == 0) {
  6790. WOLFSSL_MSG("Checking Falcon key pair");
  6791. keyIdx = 0;
  6792. if ((ret = wc_falcon_import_public(pubKey, pubKeySz,
  6793. key_pair)) == 0) {
  6794. /* Public and private extracted successfully. Sanity check. */
  6795. if ((ret = wc_falcon_check_key(key_pair)) == 0) {
  6796. ret = 1;
  6797. }
  6798. else {
  6799. WOLFSSL_ERROR_VERBOSE(ret);
  6800. }
  6801. }
  6802. }
  6803. else {
  6804. WOLFSSL_ERROR_VERBOSE(ret);
  6805. }
  6806. wc_falcon_free(key_pair);
  6807. #ifdef WOLFSSL_SMALL_STACK
  6808. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6809. #endif
  6810. }
  6811. else
  6812. #endif /* HAVE_FALCON */
  6813. #if defined(HAVE_DILITHIUM)
  6814. if ((ks == DILITHIUM_LEVEL2k) ||
  6815. (ks == DILITHIUM_LEVEL3k) ||
  6816. (ks == DILITHIUM_LEVEL5k)) {
  6817. #ifdef WOLFSSL_SMALL_STACK
  6818. dilithium_key* key_pair = NULL;
  6819. #else
  6820. dilithium_key key_pair[1];
  6821. #endif
  6822. word32 keyIdx = 0;
  6823. #ifdef WOLFSSL_SMALL_STACK
  6824. key_pair = (dilithium_key*)XMALLOC(sizeof(dilithium_key), NULL,
  6825. DYNAMIC_TYPE_DILITHIUM);
  6826. if (key_pair == NULL)
  6827. return MEMORY_E;
  6828. #endif
  6829. ret = wc_dilithium_init(key_pair);
  6830. if (ret < 0) {
  6831. #ifdef WOLFSSL_SMALL_STACK
  6832. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6833. #endif
  6834. return ret;
  6835. }
  6836. if (ks == DILITHIUM_LEVEL2k) {
  6837. ret = wc_dilithium_set_level(key_pair, 2);
  6838. }
  6839. else if (ks == DILITHIUM_LEVEL3k) {
  6840. ret = wc_dilithium_set_level(key_pair, 3);
  6841. }
  6842. else if (ks == DILITHIUM_LEVEL5k) {
  6843. ret = wc_dilithium_set_level(key_pair, 5);
  6844. }
  6845. if (ret < 0) {
  6846. #ifdef WOLFSSL_SMALL_STACK
  6847. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6848. #endif
  6849. return ret;
  6850. }
  6851. if ((ret = wc_Dilithium_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6852. privKeySz)) == 0) {
  6853. WOLFSSL_MSG("Checking Dilithium key pair");
  6854. keyIdx = 0;
  6855. if ((ret = wc_dilithium_import_public(pubKey, pubKeySz,
  6856. key_pair)) == 0) {
  6857. /* Public and private extracted successfully. Sanity check. */
  6858. if ((ret = wc_dilithium_check_key(key_pair)) == 0)
  6859. ret = 1;
  6860. }
  6861. }
  6862. wc_dilithium_free(key_pair);
  6863. #ifdef WOLFSSL_SMALL_STACK
  6864. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6865. #endif
  6866. }
  6867. else
  6868. #endif /* HAVE_DILITHIUM */
  6869. #if defined(HAVE_SPHINCS)
  6870. if ((ks == SPHINCS_FAST_LEVEL1k) ||
  6871. (ks == SPHINCS_FAST_LEVEL3k) ||
  6872. (ks == SPHINCS_FAST_LEVEL5k) ||
  6873. (ks == SPHINCS_SMALL_LEVEL1k) ||
  6874. (ks == SPHINCS_SMALL_LEVEL3k) ||
  6875. (ks == SPHINCS_SMALL_LEVEL5k)) {
  6876. #ifdef WOLFSSL_SMALL_STACK
  6877. sphincs_key* key_pair = NULL;
  6878. #else
  6879. sphincs_key key_pair[1];
  6880. #endif
  6881. word32 keyIdx = 0;
  6882. #ifdef WOLFSSL_SMALL_STACK
  6883. key_pair = (sphincs_key*)XMALLOC(sizeof(sphincs_key), NULL,
  6884. DYNAMIC_TYPE_SPHINCS);
  6885. if (key_pair == NULL)
  6886. return MEMORY_E;
  6887. #endif
  6888. ret = wc_sphincs_init(key_pair);
  6889. if (ret < 0) {
  6890. #ifdef WOLFSSL_SMALL_STACK
  6891. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6892. #endif
  6893. return ret;
  6894. }
  6895. if (ks == SPHINCS_FAST_LEVEL1k) {
  6896. ret = wc_sphincs_set_level_and_optim(key_pair, 1, FAST_VARIANT);
  6897. }
  6898. else if (ks == SPHINCS_FAST_LEVEL3k) {
  6899. ret = wc_sphincs_set_level_and_optim(key_pair, 3, FAST_VARIANT);
  6900. }
  6901. else if (ks == SPHINCS_FAST_LEVEL5k) {
  6902. ret = wc_sphincs_set_level_and_optim(key_pair, 5, FAST_VARIANT);
  6903. }
  6904. else if (ks == SPHINCS_SMALL_LEVEL1k) {
  6905. ret = wc_sphincs_set_level_and_optim(key_pair, 1, SMALL_VARIANT);
  6906. }
  6907. else if (ks == SPHINCS_SMALL_LEVEL3k) {
  6908. ret = wc_sphincs_set_level_and_optim(key_pair, 3, SMALL_VARIANT);
  6909. }
  6910. else if (ks == SPHINCS_SMALL_LEVEL5k) {
  6911. ret = wc_sphincs_set_level_and_optim(key_pair, 5, SMALL_VARIANT);
  6912. }
  6913. if (ret < 0) {
  6914. #ifdef WOLFSSL_SMALL_STACK
  6915. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6916. #endif
  6917. return ret;
  6918. }
  6919. if ((ret = wc_Sphincs_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6920. privKeySz)) == 0) {
  6921. WOLFSSL_MSG("Checking Sphincs key pair");
  6922. keyIdx = 0;
  6923. if ((ret = wc_sphincs_import_public(pubKey, pubKeySz,
  6924. key_pair)) == 0) {
  6925. /* Public and private extracted successfully. Sanity check. */
  6926. if ((ret = wc_sphincs_check_key(key_pair)) == 0)
  6927. ret = 1;
  6928. }
  6929. }
  6930. wc_sphincs_free(key_pair);
  6931. #ifdef WOLFSSL_SMALL_STACK
  6932. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6933. #endif
  6934. }
  6935. else
  6936. #endif /* HAVE_SPHINCS */
  6937. #endif /* HAVE_PQC */
  6938. {
  6939. ret = 0;
  6940. }
  6941. (void)ks;
  6942. return ret;
  6943. }
  6944. /* check that the private key is a pair for the public key in certificate
  6945. * return 1 (true) on match
  6946. * return 0 or negative value on failure/error
  6947. *
  6948. * key : buffer holding DER format key
  6949. * keySz : size of key buffer
  6950. * der : a initialized and parsed DecodedCert holding a certificate */
  6951. int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der)
  6952. {
  6953. if (key == NULL || der == NULL) {
  6954. return BAD_FUNC_ARG;
  6955. }
  6956. return wc_CheckPrivateKey(key, keySz, der->publicKey,
  6957. der->pubKeySize, (enum Key_Sum) der->keyOID);
  6958. }
  6959. #endif /* HAVE_PKCS12 || !NO_CHECK_PRIVATE_KEY */
  6960. #ifndef NO_PWDBASED
  6961. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6962. /* Check the PBE algorithm is supported and return wolfSSL id, version and block
  6963. * size of encryption algorithm.
  6964. *
  6965. * When PBES2, version is PKCS5v2, CheckAlgoV2() must be called to get id and
  6966. * blockSz based on encryption algorithm.
  6967. *
  6968. * @param [in] first First byte of OID to use in check.
  6969. * @param [in] second Second byte of OID to use in check.
  6970. * @param [out] id wolfSSL id for PBE algorithm.
  6971. * @param [out] version Version of PBE OID:
  6972. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  6973. * @param [out] blockSz Block size of encryption algorithm.
  6974. * @return 0 on success.
  6975. * @return ALGO_ID_E when OID not supported.
  6976. * @return ASN_INPUT_E when first byte is invalid.
  6977. */
  6978. static int CheckAlgo(int first, int second, int* id, int* version, int* blockSz)
  6979. {
  6980. int ret = 0;
  6981. (void)id;
  6982. (void)blockSz;
  6983. *version = -1;
  6984. /* pkcs-12 1 = pkcs-12PbeIds */
  6985. if (first == 1) {
  6986. /* PKCS #12: Appendix C */
  6987. switch (second) {
  6988. #if !defined(NO_SHA)
  6989. #ifndef NO_RC4
  6990. case PBE_SHA1_RC4_128:
  6991. *id = PBE_SHA1_RC4_128;
  6992. *version = PKCS12v1;
  6993. if (blockSz != NULL) {
  6994. *blockSz = 1;
  6995. }
  6996. break;
  6997. #endif
  6998. #ifndef NO_DES3
  6999. case PBE_SHA1_DES3:
  7000. *id = PBE_SHA1_DES3;
  7001. *version = PKCS12v1;
  7002. if (blockSz != NULL) {
  7003. *blockSz = DES_BLOCK_SIZE;
  7004. }
  7005. break;
  7006. #endif
  7007. #ifdef WC_RC2
  7008. case PBE_SHA1_40RC2_CBC:
  7009. *id = PBE_SHA1_40RC2_CBC;
  7010. *version = PKCS12v1;
  7011. if (blockSz != NULL) {
  7012. *blockSz = RC2_BLOCK_SIZE;
  7013. }
  7014. break;
  7015. #endif
  7016. #endif /* !NO_SHA */
  7017. default:
  7018. ret = ALGO_ID_E;
  7019. break;
  7020. }
  7021. }
  7022. else if (first != PKCS5) {
  7023. /* Bad OID. */
  7024. ret = ASN_INPUT_E;
  7025. }
  7026. /* PKCS #5 PBES2: Appendix A.4
  7027. * pkcs-5 13 = id-PBES2 */
  7028. else if (second == PBES2) {
  7029. *version = PKCS5v2;
  7030. /* Id and block size come from CheckAlgoV2() */
  7031. }
  7032. else {
  7033. /* PKCS #5 PBES1: Appendix A.3 */
  7034. /* see RFC 2898 for ids */
  7035. switch (second) {
  7036. #ifndef NO_DES3
  7037. #ifndef NO_MD5
  7038. case PBES1_MD5_DES:
  7039. *id = PBE_MD5_DES;
  7040. *version = PKCS5;
  7041. if (blockSz != NULL) {
  7042. *blockSz = DES_BLOCK_SIZE;
  7043. }
  7044. break;
  7045. #endif
  7046. #ifndef NO_SHA
  7047. case PBES1_SHA1_DES:
  7048. *id = PBE_SHA1_DES;
  7049. *version = PKCS5;
  7050. if (blockSz != NULL) {
  7051. *blockSz = DES_BLOCK_SIZE;
  7052. }
  7053. break;
  7054. #endif
  7055. #endif /* !NO_DES3 */
  7056. default:
  7057. ret = ALGO_ID_E;
  7058. break;
  7059. }
  7060. }
  7061. /* Return error code. */
  7062. return ret;
  7063. }
  7064. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7065. #ifdef HAVE_PKCS8
  7066. /* Check the encryption algorithm with PBES2 is supported and return block size
  7067. * and wolfSSL id for the PBE.
  7068. *
  7069. * @param [in] oid Encryption algorithm OID id.
  7070. * @param [out] id wolfSSL id for PBE algorithm.
  7071. * @param [out] version Version of PBE OID:
  7072. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  7073. * @return 0 on success.
  7074. * @return ALGO_ID_E when encryption algorithm is not supported with PBES2.
  7075. */
  7076. static int CheckAlgoV2(int oid, int* id, int* blockSz)
  7077. {
  7078. int ret = 0;
  7079. (void)id;
  7080. (void)blockSz;
  7081. switch (oid) {
  7082. #if !defined(NO_DES3) && !defined(NO_SHA)
  7083. case DESb:
  7084. *id = PBE_SHA1_DES;
  7085. if (blockSz != NULL) {
  7086. *blockSz = DES_BLOCK_SIZE;
  7087. }
  7088. break;
  7089. case DES3b:
  7090. *id = PBE_SHA1_DES3;
  7091. if (blockSz != NULL) {
  7092. *blockSz = DES_BLOCK_SIZE;
  7093. }
  7094. break;
  7095. #endif
  7096. #ifdef WOLFSSL_AES_256
  7097. case AES256CBCb:
  7098. *id = PBE_AES256_CBC;
  7099. if (blockSz != NULL) {
  7100. *blockSz = AES_BLOCK_SIZE;
  7101. }
  7102. break;
  7103. #endif
  7104. #ifdef WOLFSSL_AES_128
  7105. case AES128CBCb:
  7106. *id = PBE_AES128_CBC;
  7107. if (blockSz != NULL) {
  7108. *blockSz = AES_BLOCK_SIZE;
  7109. }
  7110. break;
  7111. #endif
  7112. default:
  7113. WOLFSSL_MSG("No PKCS v2 algo found");
  7114. ret = ALGO_ID_E;
  7115. break;
  7116. }
  7117. /* Return error code. */
  7118. return ret;
  7119. }
  7120. #endif /* HAVE_PKCS8 */
  7121. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7122. int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz,
  7123. int* algoID, void* heap)
  7124. {
  7125. word32 tmpIdx = 0;
  7126. if (key == NULL || algoID == NULL)
  7127. return BAD_FUNC_ARG;
  7128. *algoID = 0;
  7129. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  7130. {
  7131. RsaKey *rsa = (RsaKey *)XMALLOC(sizeof *rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7132. if (rsa == NULL)
  7133. return MEMORY_E;
  7134. wc_InitRsaKey(rsa, heap);
  7135. if (wc_RsaPrivateKeyDecode(key, &tmpIdx, rsa, keySz) == 0) {
  7136. *algoID = RSAk;
  7137. }
  7138. else {
  7139. WOLFSSL_MSG("Not RSA DER key");
  7140. }
  7141. wc_FreeRsaKey(rsa);
  7142. XFREE(rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7143. }
  7144. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  7145. #if defined(HAVE_ECC) && !defined(NO_ASN_CRYPT)
  7146. if (*algoID == 0) {
  7147. ecc_key *ecc = (ecc_key *)XMALLOC(sizeof *ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7148. if (ecc == NULL)
  7149. return MEMORY_E;
  7150. tmpIdx = 0;
  7151. wc_ecc_init_ex(ecc, heap, INVALID_DEVID);
  7152. if (wc_EccPrivateKeyDecode(key, &tmpIdx, ecc, keySz) == 0) {
  7153. *algoID = ECDSAk;
  7154. /* now find oid */
  7155. if (wc_ecc_get_oid(ecc->dp->oidSum, curveOID, oidSz) < 0) {
  7156. WOLFSSL_MSG("Error getting ECC curve OID");
  7157. wc_ecc_free(ecc);
  7158. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7159. return BAD_FUNC_ARG;
  7160. }
  7161. }
  7162. else {
  7163. WOLFSSL_MSG("Not ECC DER key either");
  7164. }
  7165. wc_ecc_free(ecc);
  7166. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7167. }
  7168. #endif /* HAVE_ECC && !NO_ASN_CRYPT */
  7169. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  7170. if (*algoID == 0) {
  7171. ed25519_key *ed25519 = (ed25519_key *)XMALLOC(sizeof *ed25519, heap,
  7172. DYNAMIC_TYPE_TMP_BUFFER);
  7173. if (ed25519 == NULL)
  7174. return MEMORY_E;
  7175. tmpIdx = 0;
  7176. if (wc_ed25519_init_ex(ed25519, heap, INVALID_DEVID) == 0) {
  7177. if (wc_Ed25519PrivateKeyDecode(key, &tmpIdx, ed25519, keySz) == 0) {
  7178. *algoID = ED25519k;
  7179. }
  7180. else {
  7181. WOLFSSL_MSG("Not ED25519 DER key");
  7182. }
  7183. wc_ed25519_free(ed25519);
  7184. }
  7185. else {
  7186. WOLFSSL_MSG("GetKeyOID wc_ed25519_init failed");
  7187. }
  7188. XFREE(ed25519, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7189. }
  7190. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  7191. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  7192. if (*algoID == 0) {
  7193. ed448_key *ed448 = (ed448_key *)XMALLOC(sizeof *ed448, heap,
  7194. DYNAMIC_TYPE_TMP_BUFFER);
  7195. if (ed448 == NULL)
  7196. return MEMORY_E;
  7197. tmpIdx = 0;
  7198. if (wc_ed448_init(ed448) == 0) {
  7199. if (wc_Ed448PrivateKeyDecode(key, &tmpIdx, ed448, keySz) == 0) {
  7200. *algoID = ED448k;
  7201. }
  7202. else {
  7203. WOLFSSL_MSG("Not ED448 DER key");
  7204. }
  7205. wc_ed448_free(ed448);
  7206. }
  7207. else {
  7208. WOLFSSL_MSG("GetKeyOID wc_ed448_init failed");
  7209. }
  7210. XFREE(ed448, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7211. }
  7212. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  7213. #if defined(HAVE_PQC)
  7214. #if defined(HAVE_FALCON)
  7215. if (*algoID == 0) {
  7216. falcon_key *falcon = (falcon_key *)XMALLOC(sizeof(*falcon), heap,
  7217. DYNAMIC_TYPE_TMP_BUFFER);
  7218. if (falcon == NULL)
  7219. return MEMORY_E;
  7220. if (wc_falcon_init(falcon) != 0) {
  7221. tmpIdx = 0;
  7222. if (wc_falcon_set_level(falcon, 1) == 0) {
  7223. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  7224. == 0) {
  7225. *algoID = FALCON_LEVEL1k;
  7226. }
  7227. else {
  7228. WOLFSSL_MSG("Not Falcon Level 1 DER key");
  7229. }
  7230. }
  7231. else if (wc_falcon_set_level(falcon, 5) == 0) {
  7232. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  7233. == 0) {
  7234. *algoID = FALCON_LEVEL5k;
  7235. }
  7236. else {
  7237. WOLFSSL_MSG("Not Falcon Level 5 DER key");
  7238. }
  7239. }
  7240. else {
  7241. WOLFSSL_MSG("GetKeyOID falcon initialization failed");
  7242. }
  7243. wc_falcon_free(falcon);
  7244. }
  7245. XFREE(falcon, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7246. }
  7247. #endif /* HAVE_FALCON */
  7248. #if defined(HAVE_DILITHIUM)
  7249. if (*algoID == 0) {
  7250. dilithium_key *dilithium = (dilithium_key *)XMALLOC(sizeof(*dilithium),
  7251. heap, DYNAMIC_TYPE_TMP_BUFFER);
  7252. if (dilithium == NULL)
  7253. return MEMORY_E;
  7254. if (wc_dilithium_init(dilithium) != 0) {
  7255. tmpIdx = 0;
  7256. if (wc_dilithium_set_level(dilithium, 2)
  7257. == 0) {
  7258. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7259. keySz) == 0) {
  7260. *algoID = DILITHIUM_LEVEL2k;
  7261. }
  7262. else {
  7263. WOLFSSL_MSG("Not Dilithium Level 2 DER key");
  7264. }
  7265. }
  7266. else if (wc_dilithium_set_level(dilithium, 3)
  7267. == 0) {
  7268. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7269. keySz) == 0) {
  7270. *algoID = DILITHIUM_LEVEL3k;
  7271. }
  7272. else {
  7273. WOLFSSL_MSG("Not Dilithium Level 3 DER key");
  7274. }
  7275. }
  7276. else if (wc_dilithium_set_level(dilithium, 5)
  7277. == 0) {
  7278. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7279. keySz) == 0) {
  7280. *algoID = DILITHIUM_LEVEL5k;
  7281. }
  7282. else {
  7283. WOLFSSL_MSG("Not Dilithium Level 5 DER key");
  7284. }
  7285. }
  7286. else {
  7287. WOLFSSL_MSG("GetKeyOID dilithium initialization failed");
  7288. }
  7289. wc_dilithium_free(dilithium);
  7290. }
  7291. XFREE(dilithium, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7292. }
  7293. #endif /* HAVE_DILITHIUM */
  7294. #if defined(HAVE_SPHINCS)
  7295. if (*algoID == 0) {
  7296. sphincs_key *sphincs = (sphincs_key *)XMALLOC(sizeof(*sphincs),
  7297. heap, DYNAMIC_TYPE_TMP_BUFFER);
  7298. if (sphincs == NULL)
  7299. return MEMORY_E;
  7300. if (wc_sphincs_init(sphincs) != 0) {
  7301. tmpIdx = 0;
  7302. if (wc_sphincs_set_level_and_optim(sphincs, 1, FAST_VARIANT)
  7303. == 0) {
  7304. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7305. keySz) == 0) {
  7306. *algoID = SPHINCS_FAST_LEVEL1k;
  7307. }
  7308. else {
  7309. WOLFSSL_MSG("Not Sphincs-fast Level 1 DER key");
  7310. }
  7311. }
  7312. else if (wc_sphincs_set_level_and_optim(sphincs, 3, FAST_VARIANT)
  7313. == 0) {
  7314. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7315. keySz) == 0) {
  7316. *algoID = SPHINCS_FAST_LEVEL3k;
  7317. }
  7318. else {
  7319. WOLFSSL_MSG("Not Sphincs-fast Level 3 DER key");
  7320. }
  7321. }
  7322. else if (wc_sphincs_set_level_and_optim(sphincs, 5, FAST_VARIANT)
  7323. == 0) {
  7324. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7325. keySz) == 0) {
  7326. *algoID = SPHINCS_FAST_LEVEL5k;
  7327. }
  7328. else {
  7329. WOLFSSL_MSG("Not Sphincs-fast Level 5 DER key");
  7330. }
  7331. }
  7332. else if (wc_sphincs_set_level_and_optim(sphincs, 1, SMALL_VARIANT)
  7333. == 0) {
  7334. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7335. keySz) == 0) {
  7336. *algoID = SPHINCS_SMALL_LEVEL1k;
  7337. }
  7338. else {
  7339. WOLFSSL_MSG("Not Sphincs-small Level 1 DER key");
  7340. }
  7341. }
  7342. else if (wc_sphincs_set_level_and_optim(sphincs, 3, SMALL_VARIANT)
  7343. == 0) {
  7344. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7345. keySz) == 0) {
  7346. *algoID = SPHINCS_SMALL_LEVEL3k;
  7347. }
  7348. else {
  7349. WOLFSSL_MSG("Not Sphincs-small Level 3 DER key");
  7350. }
  7351. }
  7352. else if (wc_sphincs_set_level_and_optim(sphincs, 5, SMALL_VARIANT)
  7353. == 0) {
  7354. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7355. keySz) == 0) {
  7356. *algoID = SPHINCS_SMALL_LEVEL5k;
  7357. }
  7358. else {
  7359. WOLFSSL_MSG("Not Sphincs-small Level 5 DER key");
  7360. }
  7361. }
  7362. else {
  7363. WOLFSSL_MSG("GetKeyOID sphincs initialization failed");
  7364. }
  7365. wc_sphincs_free(sphincs);
  7366. }
  7367. XFREE(sphincs, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7368. }
  7369. #endif /* HAVE_SPHINCS */
  7370. #endif /* HAVE_PQC */
  7371. /* if flag is not set then this is not a key that we understand. */
  7372. if (*algoID == 0) {
  7373. WOLFSSL_MSG("Bad key DER or compile options");
  7374. return BAD_FUNC_ARG;
  7375. }
  7376. (void)tmpIdx;
  7377. (void)curveOID;
  7378. (void)oidSz;
  7379. (void)keySz;
  7380. (void)heap;
  7381. return 1;
  7382. }
  7383. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7384. #ifdef WOLFSSL_ASN_TEMPLATE
  7385. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7386. /* ASN.1 template for PBES2 parameters.
  7387. * PKCS #5: RFC 8018, A.4 - PBES2-params without outer SEQUENCE
  7388. * A.2 - PBKDF2-params
  7389. * B.2 - Encryption schemes
  7390. * C - AlgorithmIdentifier
  7391. */
  7392. static const ASNItem pbes2ParamsASN[] = {
  7393. /* KDF_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7394. /* PBKDF2 */
  7395. /* KDF_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  7396. /* PBKDF2_PARAMS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7397. /* Salt */
  7398. /* PBKDF2_PARAMS_SALT */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  7399. /* Iteration count */
  7400. /* PBKDF2_PARAMS_ITER */ { 2, ASN_INTEGER, 0, 0, 0 },
  7401. /* Key length */
  7402. /* PBKDF2_PARAMS_KEYLEN */ { 2, ASN_INTEGER, 0, 0, 1 },
  7403. /* PRF - default is HMAC-SHA1 */
  7404. /* PBKDF2_PARAMS_PRF */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  7405. /* PBKDF2_PARAMS_PRF_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  7406. /* PBKDF2_PARAMS_PRF_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  7407. /* ENCS_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7408. /* Encryption algorithm */
  7409. /* ENCS_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  7410. /* IV for CBC */
  7411. /* ENCS_PARAMS */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  7412. };
  7413. enum {
  7414. PBES2PARAMSASN_IDX_KDF_SEQ = 0,
  7415. PBES2PARAMSASN_IDX_KDF_OID,
  7416. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SEQ,
  7417. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT,
  7418. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER,
  7419. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_KEYLEN,
  7420. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF,
  7421. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID,
  7422. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_NULL,
  7423. PBES2PARAMSASN_IDX_ENCS_SEQ,
  7424. PBES2PARAMSASN_IDX_ENCS_OID,
  7425. PBES2PARAMSASN_IDX_ENCS_PARAMS
  7426. };
  7427. /* Number of items in ASN.1 template for PBES2 parameters. */
  7428. #define pbes2ParamsASN_Length (sizeof(pbes2ParamsASN) / sizeof(ASNItem))
  7429. /* ASN.1 template for PBES1 parameters.
  7430. * PKCS #5: RFC 8018, A.3. - PBEParameter without outer SEQUENCE
  7431. */
  7432. static const ASNItem pbes1ParamsASN[] = {
  7433. /* Salt */
  7434. /* SALT */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  7435. /* Iteration count */
  7436. /* ITER */ { 0, ASN_INTEGER, 0, 0, 0 },
  7437. };
  7438. enum {
  7439. PBES1PARAMSASN_IDX_SALT = 0,
  7440. PBES1PARAMSASN_IDX_ITER
  7441. };
  7442. /* Number of items in ASN.1 template for PBES1 parameters. */
  7443. #define pbes1ParamsASN_Length (sizeof(pbes1ParamsASN) / sizeof(ASNItem))
  7444. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7445. #endif /* WOLFSSL_ASN_TEMPLATE */
  7446. #ifdef HAVE_PKCS8
  7447. /*
  7448. * Equivalent to calling TraditionalEnc with the same parameters but with
  7449. * encAlgId set to 0. This function must be kept alive because it's sometimes
  7450. * part of the API (WOLFSSL_ASN_API).
  7451. */
  7452. int UnTraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  7453. const char* password, int passwordSz, int vPKCS, int vAlgo,
  7454. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  7455. {
  7456. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz,
  7457. vPKCS, vAlgo, 0, salt, saltSz, itt, rng, heap);
  7458. }
  7459. static int GetAlgoV2(int encAlgId, const byte** oid, int *len, int* id,
  7460. int *blkSz)
  7461. {
  7462. int ret = 0;
  7463. switch (encAlgId) {
  7464. #if !defined(NO_DES3) && !defined(NO_SHA)
  7465. case DESb:
  7466. *len = sizeof(blkDesCbcOid);
  7467. *oid = blkDesCbcOid;
  7468. *id = PBE_SHA1_DES;
  7469. *blkSz = 8;
  7470. break;
  7471. case DES3b:
  7472. *len = sizeof(blkDes3CbcOid);
  7473. *oid = blkDes3CbcOid;
  7474. *id = PBE_SHA1_DES3;
  7475. *blkSz = 8;
  7476. break;
  7477. #endif
  7478. #if defined(WOLFSSL_AES_256) && defined(HAVE_AES_CBC)
  7479. case AES256CBCb:
  7480. *len = sizeof(blkAes256CbcOid);
  7481. *oid = blkAes256CbcOid;
  7482. *id = PBE_AES256_CBC;
  7483. *blkSz = 16;
  7484. break;
  7485. #endif
  7486. default:
  7487. (void)len;
  7488. (void)oid;
  7489. (void)id;
  7490. (void)blkSz;
  7491. ret = ALGO_ID_E;
  7492. }
  7493. return ret;
  7494. }
  7495. int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz,
  7496. const char* password, int passwordSz, int vPKCS, int pbeOid,
  7497. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  7498. void* heap)
  7499. {
  7500. #ifdef WOLFSSL_SMALL_STACK
  7501. byte* saltTmp = NULL;
  7502. #else
  7503. byte saltTmp[MAX_SALT_SIZE];
  7504. #endif
  7505. int genSalt = 0;
  7506. int ret = 0;
  7507. int version = 0;
  7508. int pbeId = 0;
  7509. int blockSz = 0;
  7510. const byte* encOid = NULL;
  7511. int encOidSz = 0;
  7512. word32 padSz = 0;
  7513. word32 innerLen = 0;
  7514. const byte* pbeOidBuf = NULL;
  7515. word32 pbeOidBufSz = 0;
  7516. word32 pbeLen = 0;
  7517. word32 kdfLen = 0;
  7518. word32 encLen = 0;
  7519. byte cbcIv[MAX_IV_SIZE];
  7520. word32 idx = 0;
  7521. word32 encIdx = 0;
  7522. (void)heap;
  7523. WOLFSSL_ENTER("wc_EncryptPKCS8Key");
  7524. if (key == NULL || outSz == NULL || password == NULL) {
  7525. ret = BAD_FUNC_ARG;
  7526. }
  7527. if (ret == 0) {
  7528. ret = CheckAlgo(vPKCS, pbeOid, &pbeId, &version, &blockSz);
  7529. }
  7530. if (ret == 0 && (salt == NULL || saltSz == 0)) {
  7531. genSalt = 1;
  7532. saltSz = 8;
  7533. }
  7534. if (ret == 0 && version == PKCS5v2) {
  7535. ret = GetAlgoV2(encAlgId, &encOid, &encOidSz, &pbeId, &blockSz);
  7536. }
  7537. if (ret == 0) {
  7538. padSz = (word32)((blockSz - ((int)keySz & (blockSz - 1))) &
  7539. (blockSz - 1));
  7540. /* inner = OCT salt INT itt */
  7541. innerLen = 2 + saltSz + 2 + (itt < 256 ? 1 : 2);
  7542. if (version != PKCS5v2) {
  7543. pbeOidBuf = OidFromId((word32)pbeId, oidPBEType, &pbeOidBufSz);
  7544. /* pbe = OBJ pbse1 SEQ [ inner ] */
  7545. pbeLen = 2 + pbeOidBufSz + 2 + innerLen;
  7546. }
  7547. else {
  7548. pbeOidBuf = pbes2;
  7549. pbeOidBufSz = sizeof(pbes2);
  7550. /* kdf = OBJ pbkdf2 [ SEQ innerLen ] */
  7551. kdfLen = 2 + sizeof(pbkdf2Oid) + 2 + innerLen;
  7552. /* enc = OBJ enc_alg OCT iv */
  7553. encLen = 2 + (word32)encOidSz + 2 + (word32)blockSz;
  7554. /* pbe = OBJ pbse2 SEQ [ SEQ [ kdf ] SEQ [ enc ] ] */
  7555. pbeLen = (word32)(2 + sizeof(pbes2) + 2 + 2 + (size_t)kdfLen + 2 +
  7556. (size_t)encLen);
  7557. ret = wc_RNG_GenerateBlock(rng, cbcIv, (word32)blockSz);
  7558. }
  7559. }
  7560. if (ret == 0) {
  7561. /* outerLen = length of PBE encoding + octet string data */
  7562. /* Plus 2 for tag and length for pbe */
  7563. word32 outerLen = 2 + pbeLen;
  7564. /* Octet string tag, length */
  7565. outerLen += 1 + SetLength(keySz + padSz, NULL);
  7566. /* Octet string bytes */
  7567. outerLen += keySz + padSz;
  7568. if (out == NULL) {
  7569. /* Sequence tag, length */
  7570. *outSz = 1 + SetLength(outerLen, NULL) + outerLen;
  7571. return LENGTH_ONLY_E;
  7572. }
  7573. SetOctetString(keySz + padSz, out);
  7574. idx += SetSequence(outerLen, out + idx);
  7575. encIdx = idx + outerLen - keySz - padSz;
  7576. /* Put Encrypted content in place. */
  7577. XMEMCPY(out + encIdx, key, keySz);
  7578. if (padSz > 0) {
  7579. XMEMSET(out + encIdx + keySz, (int)padSz, padSz);
  7580. keySz += padSz;
  7581. }
  7582. if (genSalt == 1) {
  7583. #ifdef WOLFSSL_SMALL_STACK
  7584. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7585. if (saltTmp == NULL) {
  7586. ret = MEMORY_E;
  7587. }
  7588. else
  7589. #endif
  7590. {
  7591. salt = saltTmp;
  7592. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  7593. WOLFSSL_MSG("Error generating random salt");
  7594. }
  7595. }
  7596. }
  7597. }
  7598. if (ret == 0) {
  7599. ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, pbeId,
  7600. out + encIdx, (int)keySz, version, cbcIv, 1, 0);
  7601. }
  7602. if (ret == 0) {
  7603. if (version != PKCS5v2) {
  7604. /* PBE algorithm */
  7605. idx += SetSequence(pbeLen, out + idx);
  7606. idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
  7607. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  7608. idx += pbeOidBufSz;
  7609. }
  7610. else {
  7611. /* PBES2 algorithm identifier */
  7612. idx += SetSequence(pbeLen, out + idx);
  7613. idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
  7614. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  7615. idx += pbeOidBufSz;
  7616. /* PBES2 Parameters: SEQ [ kdf ] SEQ [ enc ] */
  7617. idx += SetSequence(2 + kdfLen + 2 + encLen, out + idx);
  7618. /* KDF Algorithm Identifier */
  7619. idx += SetSequence(kdfLen, out + idx);
  7620. idx += (word32)SetObjectId((int)sizeof(pbkdf2Oid), out + idx);
  7621. XMEMCPY(out + idx, pbkdf2Oid, sizeof(pbkdf2Oid));
  7622. idx += sizeof(pbkdf2Oid);
  7623. }
  7624. idx += SetSequence(innerLen, out + idx);
  7625. idx += SetOctetString(saltSz, out + idx);
  7626. XMEMCPY(out + idx, salt, saltSz); idx += saltSz;
  7627. ret = SetShortInt(out, &idx, (word32)itt, *outSz);
  7628. if (ret > 0)
  7629. ret = 0;
  7630. }
  7631. if (ret == 0) {
  7632. if (version == PKCS5v2) {
  7633. /* Encryption Algorithm Identifier */
  7634. idx += SetSequence(encLen, out + idx);
  7635. idx += (word32)SetObjectId(encOidSz, out + idx);
  7636. XMEMCPY(out + idx, encOid, (size_t)encOidSz);
  7637. idx += (word32)encOidSz;
  7638. /* Encryption Algorithm Parameter: CBC IV */
  7639. idx += SetOctetString((word32)blockSz, out + idx);
  7640. XMEMCPY(out + idx, cbcIv, (size_t)blockSz);
  7641. idx += (word32)blockSz;
  7642. }
  7643. idx += SetOctetString(keySz, out + idx);
  7644. /* Default PRF - no need to write out OID */
  7645. idx += keySz;
  7646. ret = (int)idx;
  7647. }
  7648. #ifdef WOLFSSL_SMALL_STACK
  7649. if (saltTmp != NULL) {
  7650. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7651. }
  7652. #endif
  7653. WOLFSSL_LEAVE("wc_EncryptPKCS8Key", ret);
  7654. return ret;
  7655. }
  7656. int wc_DecryptPKCS8Key(byte* input, word32 sz, const char* password,
  7657. int passwordSz)
  7658. {
  7659. int ret;
  7660. int length;
  7661. word32 inOutIdx = 0;
  7662. if (input == NULL || password == NULL) {
  7663. return BAD_FUNC_ARG;
  7664. }
  7665. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  7666. ret = ASN_PARSE_E;
  7667. }
  7668. else {
  7669. ret = DecryptContent(input + inOutIdx, sz - inOutIdx, password,
  7670. passwordSz);
  7671. if (ret > 0) {
  7672. XMEMMOVE(input, input + inOutIdx, (size_t)ret);
  7673. }
  7674. }
  7675. if (ret > 0) {
  7676. /* DecryptContent will decrypt the data, but it will leave any padding
  7677. * bytes intact. This code calculates the length without the padding
  7678. * and we return that to the user. */
  7679. inOutIdx = 0;
  7680. if (GetSequence(input, &inOutIdx, &length, (word32)ret) < 0) {
  7681. ret = ASN_PARSE_E;
  7682. }
  7683. else {
  7684. ret = (int)inOutIdx + length;
  7685. }
  7686. }
  7687. return ret;
  7688. }
  7689. /* Takes an unencrypted, traditional DER-encoded key and converts it to a PKCS#8
  7690. * encrypted key. If out is not NULL, it will hold the encrypted key. If it's
  7691. * NULL, LENGTH_ONLY_E will be returned and outSz will have the required out
  7692. * buffer size. */
  7693. int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  7694. const char* password, int passwordSz, int vPKCS, int vAlgo,
  7695. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  7696. void* heap)
  7697. {
  7698. int ret = 0;
  7699. byte *pkcs8Key = NULL;
  7700. word32 pkcs8KeySz = 0;
  7701. int algId = 0;
  7702. const byte* curveOid = NULL;
  7703. word32 curveOidSz = 0;
  7704. if (ret == 0) {
  7705. /* check key type and get OID if ECC */
  7706. ret = wc_GetKeyOID(key, keySz, &curveOid, &curveOidSz, &algId, heap);
  7707. if (ret == 1)
  7708. ret = 0;
  7709. }
  7710. if (ret == 0) {
  7711. ret = wc_CreatePKCS8Key(NULL, &pkcs8KeySz, key, keySz, algId, curveOid,
  7712. curveOidSz);
  7713. if (ret == LENGTH_ONLY_E)
  7714. ret = 0;
  7715. }
  7716. if (ret == 0) {
  7717. pkcs8Key = (byte*)XMALLOC(pkcs8KeySz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7718. if (pkcs8Key == NULL)
  7719. ret = MEMORY_E;
  7720. }
  7721. if (ret == 0) {
  7722. ret = wc_CreatePKCS8Key(pkcs8Key, &pkcs8KeySz, key, keySz, algId,
  7723. curveOid, curveOidSz);
  7724. if (ret >= 0) {
  7725. pkcs8KeySz = (word32)ret;
  7726. ret = 0;
  7727. }
  7728. }
  7729. #ifdef WOLFSSL_CHECK_MEM_ZERO
  7730. if (ret == 0) {
  7731. wc_MemZero_Add("TraditionalEnc pkcs8Key", pkcs8Key, pkcs8KeySz);
  7732. }
  7733. #endif
  7734. if (ret == 0) {
  7735. ret = wc_EncryptPKCS8Key(pkcs8Key, pkcs8KeySz, out, outSz, password,
  7736. passwordSz, vPKCS, vAlgo, encAlgId, salt, saltSz, itt, rng, heap);
  7737. }
  7738. if (pkcs8Key != NULL) {
  7739. ForceZero(pkcs8Key, pkcs8KeySz);
  7740. XFREE(pkcs8Key, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7741. }
  7742. (void)rng;
  7743. return ret;
  7744. }
  7745. /* Same as TraditionalEnc, but in the public API. */
  7746. int wc_CreateEncryptedPKCS8Key(byte* key, word32 keySz, byte* out,
  7747. word32* outSz, const char* password, int passwordSz, int vPKCS,
  7748. int pbeOid, int encAlgId, byte* salt, word32 saltSz, int itt,
  7749. WC_RNG* rng, void* heap)
  7750. {
  7751. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz, vPKCS,
  7752. pbeOid, encAlgId, salt, saltSz, itt, rng, heap);
  7753. }
  7754. #ifdef WOLFSSL_ASN_TEMPLATE
  7755. /* ASN.1 template for PKCS #8/#7 encrypted key for decrypting
  7756. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  7757. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  7758. */
  7759. static const ASNItem pkcs8DecASN[] = {
  7760. /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7761. /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  7762. /* ENCALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  7763. /* PKCS #7 */
  7764. /* ENCCONTENT */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ENC_CONTENT,
  7765. 0, 0, 2 },
  7766. /* PKCS #8 */
  7767. /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
  7768. };
  7769. enum {
  7770. PKCS8DECASN_IDX_ENCALGO_SEQ = 0,
  7771. PKCS8DECASN_IDX_ENCALGO_OID,
  7772. PKCS8DECASN_IDX_ENCALGO_PARAMS,
  7773. PKCS8DECASN_IDX_ENCCONTENT,
  7774. PKCS8DECASN_IDX_ENCDATA
  7775. };
  7776. /* Number of items in ASN.1 template for PKCS #8/#7 encrypted key. */
  7777. #define pkcs8DecASN_Length (sizeof(pkcs8DecASN) / sizeof(ASNItem))
  7778. #endif
  7779. /* Decrypt data using PBE algorithm.
  7780. *
  7781. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  7782. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  7783. *
  7784. * Note: input buffer is overwritten with decrypted data!
  7785. *
  7786. * Salt is in KDF parameters and IV is PBE parameters when needed.
  7787. *
  7788. * @param [in] input Data to decrypt and unwrap.
  7789. * @param [in] sz Size of encrypted data.
  7790. * @param [in] password Password to derive encryption key with.
  7791. * @param [in] passwordSz Size of password in bytes.
  7792. * @return Length of decrypted data on success.
  7793. * @return MEMORY_E when dynamic memory allocation fails.
  7794. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  7795. * is invalid.
  7796. * @return BUFFER_E when data in buffer is too small.
  7797. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  7798. * @return Other when decryption fails.
  7799. */
  7800. int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz)
  7801. {
  7802. #ifndef WOLFSSL_ASN_TEMPLATE
  7803. word32 inOutIdx = 0, seqEnd, oid, shaOid = 0;
  7804. int ret = 0, first, second, length = 0, version, saltSz, id = 0;
  7805. int iterations = 0, keySz = 0;
  7806. #ifdef WOLFSSL_SMALL_STACK
  7807. byte* salt = NULL;
  7808. byte* cbcIv = NULL;
  7809. #else
  7810. byte salt[MAX_SALT_SIZE];
  7811. byte cbcIv[MAX_IV_SIZE];
  7812. #endif
  7813. byte tag;
  7814. if (passwordSz < 0) {
  7815. WOLFSSL_MSG("Bad password size");
  7816. return BAD_FUNC_ARG;
  7817. }
  7818. if (GetAlgoId(input, &inOutIdx, &oid, oidIgnoreType, sz) < 0) {
  7819. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7820. }
  7821. first = input[inOutIdx - 2]; /* PKCS version always 2nd to last byte */
  7822. second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
  7823. if (CheckAlgo(first, second, &id, &version, NULL) < 0) {
  7824. ERROR_OUT(ASN_INPUT_E, exit_dc); /* Algo ID error */
  7825. }
  7826. if (version == PKCS5v2) {
  7827. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  7828. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7829. }
  7830. if (GetAlgoId(input, &inOutIdx, &oid, oidKdfType, sz) < 0) {
  7831. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7832. }
  7833. if (oid != PBKDF2_OID) {
  7834. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7835. }
  7836. }
  7837. if (GetSequence(input, &inOutIdx, &length, sz) <= 0) {
  7838. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7839. }
  7840. /* Find the end of this SEQUENCE so we can check for the OPTIONAL and
  7841. * DEFAULT items. */
  7842. seqEnd = inOutIdx + (word32)length;
  7843. ret = GetOctetString(input, &inOutIdx, &saltSz, sz);
  7844. if (ret < 0)
  7845. goto exit_dc;
  7846. if (saltSz > MAX_SALT_SIZE) {
  7847. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7848. }
  7849. #ifdef WOLFSSL_SMALL_STACK
  7850. salt = (byte*)XMALLOC(MAX_SALT_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7851. if (salt == NULL) {
  7852. ERROR_OUT(MEMORY_E, exit_dc);
  7853. }
  7854. #endif
  7855. XMEMCPY(salt, &input[inOutIdx], (size_t)saltSz);
  7856. inOutIdx += (word32)saltSz;
  7857. if (GetShortInt(input, &inOutIdx, &iterations, sz) < 0) {
  7858. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7859. }
  7860. /* OPTIONAL key length */
  7861. if (seqEnd > inOutIdx) {
  7862. word32 localIdx = inOutIdx;
  7863. if (GetASNTag(input, &localIdx, &tag, sz) < 0) {
  7864. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7865. }
  7866. if (tag == ASN_INTEGER &&
  7867. GetShortInt(input, &inOutIdx, &keySz, sz) < 0) {
  7868. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7869. }
  7870. }
  7871. /* DEFAULT HMAC is SHA-1 */
  7872. if (seqEnd > inOutIdx) {
  7873. if (GetAlgoId(input, &inOutIdx, &oid, oidHmacType, sz) < 0) {
  7874. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7875. }
  7876. shaOid = oid;
  7877. }
  7878. #ifdef WOLFSSL_SMALL_STACK
  7879. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7880. if (cbcIv == NULL) {
  7881. ERROR_OUT(MEMORY_E, exit_dc);
  7882. }
  7883. #endif
  7884. if (version == PKCS5v2) {
  7885. /* get encryption algo */
  7886. if (GetAlgoId(input, &inOutIdx, &oid, oidBlkType, sz) < 0) {
  7887. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7888. }
  7889. if (CheckAlgoV2((int)oid, &id, NULL) < 0) {
  7890. ERROR_OUT(ASN_PARSE_E, exit_dc); /* PKCS v2 algo id error */
  7891. }
  7892. if (shaOid == 0)
  7893. shaOid = oid;
  7894. ret = GetOctetString(input, &inOutIdx, &length, sz);
  7895. if (ret < 0)
  7896. goto exit_dc;
  7897. if (length > MAX_IV_SIZE) {
  7898. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7899. }
  7900. XMEMCPY(cbcIv, &input[inOutIdx], (size_t)length);
  7901. inOutIdx += (word32)length;
  7902. }
  7903. if (GetASNTag(input, &inOutIdx, &tag, sz) < 0) {
  7904. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7905. }
  7906. if (tag != (ASN_CONTEXT_SPECIFIC | 0) && tag != ASN_OCTET_STRING) {
  7907. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7908. }
  7909. if (GetLength(input, &inOutIdx, &length, sz) < 0) {
  7910. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7911. }
  7912. ret = wc_CryptKey(password, passwordSz, salt, saltSz, iterations, id,
  7913. input + inOutIdx, length, version, cbcIv, 0, (int)shaOid);
  7914. exit_dc:
  7915. #ifdef WOLFSSL_SMALL_STACK
  7916. XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7917. XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7918. #endif
  7919. if (ret == 0) {
  7920. XMEMMOVE(input, input + inOutIdx, (size_t)length);
  7921. ret = length;
  7922. }
  7923. return ret;
  7924. #else
  7925. /* pbes2ParamsASN longer than pkcs8DecASN_Length/pbes1ParamsASN_Length. */
  7926. DECL_ASNGETDATA(dataASN, pbes2ParamsASN_Length);
  7927. int ret = 0;
  7928. int id = 0;
  7929. int version;
  7930. word32 idx = 0;
  7931. word32 pIdx = 0;
  7932. word32 iterations;
  7933. word32 keySz = 0;
  7934. word32 saltSz = 0;
  7935. word32 shaOid = 0;
  7936. byte* salt = NULL;
  7937. byte* key = NULL;
  7938. byte cbcIv[MAX_IV_SIZE];
  7939. byte* params = NULL;
  7940. WOLFSSL_ENTER("DecryptContent");
  7941. CALLOC_ASNGETDATA(dataASN, pbes2ParamsASN_Length, ret, NULL);
  7942. if (ret == 0) {
  7943. /* Check OID is a PBE Type */
  7944. GetASN_OID(&dataASN[PKCS8DECASN_IDX_ENCALGO_OID], oidPBEType);
  7945. ret = GetASN_Items(pkcs8DecASN, dataASN, pkcs8DecASN_Length, 0, input,
  7946. &idx, sz);
  7947. }
  7948. if (ret == 0) {
  7949. /* Check the PBE algorithm and get the version and id. */
  7950. idx = dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.length;
  7951. /* Second last byte: 1 (PKCS #12 PBE Id) or 5 (PKCS #5)
  7952. * Last byte: Alg or PBES2 */
  7953. ret = CheckAlgo(dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 2],
  7954. dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 1],
  7955. &id, &version, NULL);
  7956. }
  7957. if (ret == 0) {
  7958. /* Get the parameters data. */
  7959. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCALGO_PARAMS], &params, &sz);
  7960. /* Having a numbered choice means none or both will have errored out. */
  7961. if (dataASN[PKCS8DECASN_IDX_ENCCONTENT].tag != 0)
  7962. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCCONTENT], &key, &keySz);
  7963. else if (dataASN[PKCS8DECASN_IDX_ENCDATA].tag != 0)
  7964. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCDATA], &key, &keySz);
  7965. else
  7966. ret = ASN_RSA_KEY_E;
  7967. }
  7968. if (ret == 0) {
  7969. if (version != PKCS5v2) {
  7970. /* Initialize for PBES1 parameters and put iterations in var. */
  7971. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes1ParamsASN_Length);
  7972. GetASN_Int32Bit(&dataASN[PBES1PARAMSASN_IDX_ITER], &iterations);
  7973. /* Parse the PBES1 parameters. */
  7974. ret = GetASN_Items(pbes1ParamsASN, dataASN, pbes1ParamsASN_Length,
  7975. 0, params, &pIdx, sz);
  7976. if (ret == 0) {
  7977. /* Get the salt data. */
  7978. GetASN_GetRef(&dataASN[PBES1PARAMSASN_IDX_SALT], &salt, &saltSz);
  7979. }
  7980. }
  7981. else {
  7982. word32 ivSz = MAX_IV_SIZE;
  7983. /* Initialize for PBES2 parameters. Put iterations in var; match
  7984. * KDF, HMAC and cipher, and copy CBC into buffer. */
  7985. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes2ParamsASN_Length);
  7986. GetASN_ExpBuffer(&dataASN[PBES2PARAMSASN_IDX_KDF_OID], pbkdf2Oid, sizeof(pbkdf2Oid));
  7987. GetASN_Int32Bit(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER], &iterations);
  7988. GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID], oidHmacType);
  7989. GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_ENCS_OID], oidBlkType);
  7990. GetASN_Buffer(&dataASN[PBES2PARAMSASN_IDX_ENCS_PARAMS], cbcIv, &ivSz);
  7991. /* Parse the PBES2 parameters */
  7992. ret = GetASN_Items(pbes2ParamsASN, dataASN, pbes2ParamsASN_Length,
  7993. 0, params, &pIdx, sz);
  7994. if (ret == 0) {
  7995. /* Get the salt data. */
  7996. GetASN_GetRef(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT], &salt, &saltSz);
  7997. /* Get the digest and encryption algorithm id. */
  7998. shaOid = dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID].data.oid.sum; /* Default HMAC-SHA1 */
  7999. id = (int)dataASN[PBES2PARAMSASN_IDX_ENCS_OID].data.oid.sum;
  8000. /* Convert encryption algorithm to a PBE algorithm if needed. */
  8001. CheckAlgoV2(id, &id, NULL);
  8002. }
  8003. }
  8004. }
  8005. if (ret == 0) {
  8006. /* Decrypt the key. */
  8007. ret = wc_CryptKey(
  8008. password, passwordSz, salt, (int)saltSz, (int)iterations, id, key,
  8009. (int)keySz, version, cbcIv, 0, (int)shaOid);
  8010. }
  8011. if (ret == 0) {
  8012. /* Copy the decrypted key into the input (inline). */
  8013. XMEMMOVE(input, key, keySz);
  8014. ret = (int)keySz;
  8015. }
  8016. FREE_ASNGETDATA(dataASN, NULL);
  8017. return ret;
  8018. #endif
  8019. }
  8020. /* Decrypt data using PBE algorithm and get key from PKCS#8 wrapping.
  8021. *
  8022. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  8023. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo
  8024. *
  8025. * Note: input buffer is overwritten with decrypted key!
  8026. *
  8027. * Salt is in KDF parameters and IV is PBE parameters when needed.
  8028. *
  8029. * @param [in] input Data to decrypt and unwrap.
  8030. * @param [in] sz Size of encrypted data.
  8031. * @param [in] password Password to derive encryption key with.
  8032. * @param [in] passwordSz Size of password in bytes.
  8033. * @param [out] algId Key algorithm from PKCS#8 wrapper.
  8034. * @return Length of decrypted data on success.
  8035. * @return MEMORY_E when dynamic memory allocation fails.
  8036. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8037. * is invalid.
  8038. * @return BUFFER_E when data in buffer is too small.
  8039. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8040. * @return Other when decryption fails.
  8041. */
  8042. int ToTraditionalEnc(byte* input, word32 sz, const char* password,
  8043. int passwordSz, word32* algId)
  8044. {
  8045. int ret;
  8046. ret = wc_DecryptPKCS8Key(input, sz, password, passwordSz);
  8047. if (ret > 0) {
  8048. ret = ToTraditional_ex(input, (word32)ret, algId);
  8049. }
  8050. return ret;
  8051. }
  8052. #endif /* HAVE_PKCS8 */
  8053. #ifdef HAVE_PKCS12
  8054. #define PKCS8_MIN_BLOCK_SIZE 8
  8055. static int Pkcs8Pad(byte* buf, int sz, int blockSz)
  8056. {
  8057. int padSz;
  8058. /* calculate pad size */
  8059. padSz = blockSz - (sz & (blockSz - 1));
  8060. /* pad with padSz value */
  8061. if (buf) {
  8062. int i;
  8063. for (i = 0; i < padSz; i++) {
  8064. buf[sz+i] = (byte)(padSz & 0xFF);
  8065. }
  8066. }
  8067. /* return adjusted length */
  8068. return sz + padSz;
  8069. }
  8070. #ifdef WOLFSSL_ASN_TEMPLATE
  8071. /* ASN.1 template for PKCS #8 encrypted key with PBES1 parameters.
  8072. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  8073. * PKCS #5: RFC 8018, A.3 - PBEParameter
  8074. */
  8075. static const ASNItem p8EncPbes1ASN[] = {
  8076. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8077. /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8078. /* PBE algorithm */
  8079. /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8080. /* ENCALGO_PBEPARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8081. /* Salt */
  8082. /* ENCALGO_PBEPARAM_SALT */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  8083. /* Iteration Count */
  8084. /* ENCALGO_PBEPARAM_ITER */ { 3, ASN_INTEGER, 0, 0, 0 },
  8085. /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  8086. };
  8087. enum {
  8088. P8ENCPBES1ASN_IDX_SEQ = 0,
  8089. P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8090. P8ENCPBES1ASN_IDX_ENCALGO_OID,
  8091. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SEQ,
  8092. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT,
  8093. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER,
  8094. P8ENCPBES1ASN_IDX_ENCDATA
  8095. };
  8096. #define p8EncPbes1ASN_Length (sizeof(p8EncPbes1ASN) / sizeof(ASNItem))
  8097. #endif
  8098. /* Wrap a private key in PKCS#8 and encrypt.
  8099. *
  8100. * Used for PKCS#12 and PKCS#7.
  8101. * vPKCS is the version of PKCS to use.
  8102. * vAlgo is the algorithm version to use.
  8103. *
  8104. * When salt is NULL, a random number is generated.
  8105. *
  8106. * data returned is :
  8107. * [ seq - obj [ seq -salt,itt]] , construct with encrypted data
  8108. *
  8109. * @param [in] input Data to encrypt.
  8110. * @param [in] inputSz Length of data in bytes.
  8111. * @param [out] out Buffer to write wrapped encrypted data into.
  8112. * @param [out] outSz Length of encrypted data in bytes.
  8113. * @param [in] password Password used to create encryption key.
  8114. * @param [in] passwordSz Length of password in bytes.
  8115. * @param [in] vPKCS First byte used to determine PBE algorithm.
  8116. * @param [in] vAlgo Second byte used to determine PBE algorithm.
  8117. * @param [in] salt Salt to use with KDF.
  8118. * @param [in] saltSz Length of salt in bytes.
  8119. * @param [in] itt Number of iterations to use in KDF.
  8120. * @param [in] rng Random number generator to use to generate salt.
  8121. * @param [in] heap Dynamic memory allocator hint.
  8122. * @return The size of encrypted data on success
  8123. * @return LENGTH_ONLY_E when out is NULL and able to encode.
  8124. * @return ASN_PARSE_E when the salt size is too large.
  8125. * @return ASN_VERSION_E when attempting to use a PBES2 algorithm (use
  8126. * TraditionalEnc).
  8127. * @return MEMORY_E when dynamic memory allocation fails.
  8128. * @return Other when encryption or random number generation fails.
  8129. */
  8130. int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz,
  8131. const char* password, int passwordSz, int vPKCS, int vAlgo,
  8132. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  8133. {
  8134. #ifndef WOLFSSL_ASN_TEMPLATE
  8135. word32 sz;
  8136. word32 inOutIdx = 0;
  8137. word32 tmpIdx = 0;
  8138. word32 totalSz = 0;
  8139. word32 seqSz;
  8140. word32 innerSz;
  8141. int ret;
  8142. int version, id, blockSz = 0;
  8143. #ifdef WOLFSSL_SMALL_STACK
  8144. byte* saltTmp = NULL;
  8145. byte* cbcIv = NULL;
  8146. #else
  8147. byte saltTmp[MAX_SALT_SIZE];
  8148. byte cbcIv[MAX_IV_SIZE];
  8149. #endif
  8150. byte seq[MAX_SEQ_SZ];
  8151. byte shr[MAX_SHORT_SZ];
  8152. word32 maxShr = MAX_SHORT_SZ;
  8153. word32 algoSz;
  8154. const byte* algoName;
  8155. (void)heap;
  8156. WOLFSSL_ENTER("EncryptContent");
  8157. if (CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0)
  8158. return ASN_INPUT_E; /* Algo ID error */
  8159. if (version == PKCS5v2) {
  8160. WOLFSSL_MSG("PKCS#5 version 2 not supported yet");
  8161. return BAD_FUNC_ARG;
  8162. }
  8163. if (saltSz > MAX_SALT_SIZE)
  8164. return ASN_PARSE_E;
  8165. if (outSz == NULL) {
  8166. return BAD_FUNC_ARG;
  8167. }
  8168. /* calculate size */
  8169. /* size of constructed string at end */
  8170. sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8171. totalSz = ASN_TAG_SZ;
  8172. totalSz += SetLength(sz, seq);
  8173. totalSz += sz;
  8174. /* size of sequence holding object id and sub sequence of salt and itt */
  8175. algoName = OidFromId((word32)id, oidPBEType, &algoSz);
  8176. if (algoName == NULL) {
  8177. WOLFSSL_MSG("Unknown Algorithm");
  8178. return 0;
  8179. }
  8180. innerSz = (word32)SetObjectId((int)algoSz, seq);
  8181. innerSz += algoSz;
  8182. /* get subsequence of salt and itt */
  8183. if (salt == NULL || saltSz == 0) {
  8184. sz = 8;
  8185. }
  8186. else {
  8187. sz = saltSz;
  8188. }
  8189. seqSz = SetOctetString(sz, seq);
  8190. seqSz += sz;
  8191. tmpIdx = 0;
  8192. ret = SetShortInt(shr, &tmpIdx, (word32)itt, maxShr);
  8193. if (ret >= 0) {
  8194. seqSz += (word32)ret;
  8195. }
  8196. else {
  8197. return ret;
  8198. }
  8199. innerSz += seqSz + SetSequence(seqSz, seq);
  8200. totalSz += innerSz + SetSequence(innerSz, seq);
  8201. if (out == NULL) {
  8202. *outSz = totalSz;
  8203. return LENGTH_ONLY_E;
  8204. }
  8205. inOutIdx = 0;
  8206. if (totalSz > *outSz)
  8207. return BUFFER_E;
  8208. inOutIdx += SetSequence(innerSz, out + inOutIdx);
  8209. inOutIdx += (word32)SetObjectId((int)algoSz, out + inOutIdx);
  8210. XMEMCPY(out + inOutIdx, algoName, algoSz);
  8211. inOutIdx += algoSz;
  8212. inOutIdx += SetSequence(seqSz, out + inOutIdx);
  8213. /* create random salt if one not provided */
  8214. if (salt == NULL || saltSz == 0) {
  8215. saltSz = 8;
  8216. #ifdef WOLFSSL_SMALL_STACK
  8217. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8218. if (saltTmp == NULL)
  8219. return MEMORY_E;
  8220. #endif
  8221. salt = saltTmp;
  8222. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  8223. WOLFSSL_MSG("Error generating random salt");
  8224. #ifdef WOLFSSL_SMALL_STACK
  8225. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8226. #endif
  8227. return ret;
  8228. }
  8229. }
  8230. inOutIdx += SetOctetString(saltSz, out + inOutIdx);
  8231. if (saltSz + inOutIdx > *outSz) {
  8232. #ifdef WOLFSSL_SMALL_STACK
  8233. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8234. #endif
  8235. return BUFFER_E;
  8236. }
  8237. XMEMCPY(out + inOutIdx, salt, saltSz);
  8238. inOutIdx += saltSz;
  8239. /* place iteration setting in buffer */
  8240. ret = SetShortInt(out, &inOutIdx, (word32)itt, *outSz);
  8241. if (ret < 0) {
  8242. #ifdef WOLFSSL_SMALL_STACK
  8243. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8244. #endif
  8245. return ret;
  8246. }
  8247. if (inOutIdx + 1 > *outSz) {
  8248. #ifdef WOLFSSL_SMALL_STACK
  8249. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8250. #endif
  8251. return BUFFER_E;
  8252. }
  8253. out[inOutIdx++] = ASN_CONTEXT_SPECIFIC | 0;
  8254. /* get pad size and verify buffer room */
  8255. sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8256. if (sz + inOutIdx > *outSz) {
  8257. #ifdef WOLFSSL_SMALL_STACK
  8258. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8259. #endif
  8260. return BUFFER_E;
  8261. }
  8262. inOutIdx += SetLength(sz, out + inOutIdx);
  8263. /* copy input to output buffer and pad end */
  8264. XMEMCPY(out + inOutIdx, input, inputSz);
  8265. sz = (word32)Pkcs8Pad(out + inOutIdx, (int)inputSz, blockSz);
  8266. #ifdef WOLFSSL_SMALL_STACK
  8267. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8268. if (cbcIv == NULL) {
  8269. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8270. return MEMORY_E;
  8271. }
  8272. #endif
  8273. /* encrypt */
  8274. if ((ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
  8275. out + inOutIdx, (int)sz, version, cbcIv, 1, 0)) < 0) {
  8276. #ifdef WOLFSSL_SMALL_STACK
  8277. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8278. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8279. #endif
  8280. return ret; /* encrypt failure */
  8281. }
  8282. #ifdef WOLFSSL_SMALL_STACK
  8283. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8284. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8285. #endif
  8286. (void)rng;
  8287. return (int)(inOutIdx + sz);
  8288. #else
  8289. DECL_ASNSETDATA(dataASN, p8EncPbes1ASN_Length);
  8290. int ret = 0;
  8291. int sz = 0;
  8292. int version;
  8293. int id = -1;
  8294. int blockSz = 0;
  8295. word32 pkcs8Sz = 0;
  8296. (void)heap;
  8297. WOLFSSL_ENTER("EncryptContent");
  8298. /* Must have a output size to return or check. */
  8299. if (outSz == NULL) {
  8300. ret = BAD_FUNC_ARG;
  8301. }
  8302. /* Check salt size is valid. */
  8303. if ((ret == 0) && (saltSz > MAX_SALT_SIZE)) {
  8304. ret = ASN_PARSE_E;
  8305. }
  8306. /* Get algorithm parameters for algorithm identifier. */
  8307. if ((ret == 0) && CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0) {
  8308. ret = ASN_INPUT_E;
  8309. }
  8310. /* Check PKCS #5 version - only PBSE1 parameters supported. */
  8311. if ((ret == 0) && (version == PKCS5v2)) {
  8312. ret = BAD_FUNC_ARG;
  8313. }
  8314. CALLOC_ASNSETDATA(dataASN, p8EncPbes1ASN_Length, ret, heap);
  8315. if (ret == 0) {
  8316. /* Setup data to go into encoding including PBE algorithm, salt,
  8317. * iteration count, and padded key length. */
  8318. SetASN_OID(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_OID], (word32)id,
  8319. oidPBEType);
  8320. if (salt == NULL || saltSz == 0) {
  8321. salt = NULL;
  8322. saltSz = PKCS5_SALT_SZ;
  8323. /* Salt generated into encoding below. */
  8324. }
  8325. SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT],
  8326. salt, saltSz);
  8327. SetASN_Int16Bit(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER],
  8328. (word16)itt);
  8329. pkcs8Sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8330. SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCDATA], NULL, pkcs8Sz);
  8331. /* Calculate size of encoding. */
  8332. ret = SizeASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8333. dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8334. (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
  8335. &sz);
  8336. }
  8337. /* Return size when no output buffer. */
  8338. if ((ret == 0) && (out == NULL)) {
  8339. *outSz = (word32)sz;
  8340. ret = LENGTH_ONLY_E;
  8341. }
  8342. /* Check output buffer is big enough for encoded data. */
  8343. if ((ret == 0) && (sz > (int)*outSz)) {
  8344. ret = BAD_FUNC_ARG;
  8345. }
  8346. if (ret == 0) {
  8347. /* Encode PKCS#8 key. */
  8348. SetASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8349. dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8350. (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
  8351. out);
  8352. if (salt == NULL) {
  8353. /* Generate salt into encoding. */
  8354. salt = (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT].
  8355. data.buffer.data;
  8356. ret = wc_RNG_GenerateBlock(rng, salt, saltSz);
  8357. }
  8358. }
  8359. if (ret == 0) {
  8360. byte cbcIv[MAX_IV_SIZE];
  8361. /* Store PKCS#8 key in output buffer. */
  8362. byte* pkcs8 =
  8363. (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCDATA].data.buffer.data;
  8364. XMEMCPY(pkcs8, input, inputSz);
  8365. Pkcs8Pad(pkcs8, (int)inputSz, blockSz);
  8366. /* Encrypt PKCS#8 key inline. */
  8367. ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
  8368. pkcs8, (int)pkcs8Sz, version, cbcIv, 1, 0);
  8369. }
  8370. if (ret == 0) {
  8371. /* Returning size on success. */
  8372. ret = sz;
  8373. }
  8374. FREE_ASNSETDATA(dataASN, heap);
  8375. return ret;
  8376. #endif /* WOLFSSL_ASN_TEMPLATE */
  8377. }
  8378. #endif /* HAVE_PKCS12 */
  8379. #endif /* NO_PWDBASED */
  8380. #ifndef NO_RSA
  8381. #ifndef HAVE_USER_RSA
  8382. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  8383. /* This function is to retrieve key position information in a cert.*
  8384. * The information will be used to call TSIP TLS-linked API for *
  8385. * certificate verification. */
  8386. static int RsaPublicKeyDecodeRawIndex(const byte* input, word32* inOutIdx,
  8387. word32 inSz, word32* key_n,
  8388. word32* key_n_len, word32* key_e,
  8389. word32* key_e_len)
  8390. {
  8391. int ret = 0;
  8392. int length = 0;
  8393. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8394. byte b;
  8395. #endif
  8396. if (input == NULL || inOutIdx == NULL)
  8397. return BAD_FUNC_ARG;
  8398. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8399. return ASN_PARSE_E;
  8400. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8401. if ((*inOutIdx + 1) > inSz)
  8402. return BUFFER_E;
  8403. b = input[*inOutIdx];
  8404. if (b != ASN_INTEGER) {
  8405. /* not from decoded cert, will have algo id, skip past */
  8406. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8407. return ASN_PARSE_E;
  8408. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  8409. return ASN_PARSE_E;
  8410. /* Option NULL ASN.1 tag */
  8411. if (*inOutIdx >= inSz) {
  8412. return BUFFER_E;
  8413. }
  8414. if (input[*inOutIdx] == ASN_TAG_NULL) {
  8415. ret = GetASNNull(input, inOutIdx, inSz);
  8416. if (ret != 0)
  8417. return ret;
  8418. }
  8419. /* TODO: support RSA PSS */
  8420. /* should have bit tag length and seq next */
  8421. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  8422. if (ret != 0)
  8423. return ret;
  8424. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8425. return ASN_PARSE_E;
  8426. }
  8427. #endif /* OPENSSL_EXTRA */
  8428. /* Get modulus */
  8429. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8430. *key_n += *inOutIdx;
  8431. if (ret < 0) {
  8432. return ASN_RSA_KEY_E;
  8433. }
  8434. if (key_n_len)
  8435. *key_n_len = length;
  8436. *inOutIdx += length;
  8437. /* Get exponent */
  8438. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8439. *key_e += *inOutIdx;
  8440. if (ret < 0) {
  8441. return ASN_RSA_KEY_E;
  8442. }
  8443. if (key_e_len)
  8444. *key_e_len = length;
  8445. return ret;
  8446. }
  8447. #endif /* WOLFSSL_RENESAS_TSIP */
  8448. #ifdef WOLFSSL_ASN_TEMPLATE
  8449. /* ASN.1 template for an RSA public key.
  8450. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8451. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8452. */
  8453. static const ASNItem rsaPublicKeyASN[] = {
  8454. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8455. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8456. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8457. /* ALGOID_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  8458. #ifdef WC_RSA_PSS
  8459. /* ALGOID_P_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  8460. #endif
  8461. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 1, 0 },
  8462. /* RSAPublicKey */
  8463. /* PUBKEY_RSA_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8464. /* PUBKEY_RSA_N */ { 3, ASN_INTEGER, 0, 0, 0 },
  8465. /* PUBKEY_RSA_E */ { 3, ASN_INTEGER, 0, 0, 0 },
  8466. };
  8467. enum {
  8468. RSAPUBLICKEYASN_IDX_SEQ = 0,
  8469. RSAPUBLICKEYASN_IDX_ALGOID_SEQ,
  8470. RSAPUBLICKEYASN_IDX_ALGOID_OID,
  8471. RSAPUBLICKEYASN_IDX_ALGOID_NULL,
  8472. #ifdef WC_RSA_PSS
  8473. RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ,
  8474. #endif
  8475. RSAPUBLICKEYASN_IDX_PUBKEY,
  8476. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ,
  8477. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N,
  8478. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E
  8479. };
  8480. /* Number of items in ASN.1 template for an RSA public key. */
  8481. #define rsaPublicKeyASN_Length (sizeof(rsaPublicKeyASN) / sizeof(ASNItem))
  8482. #endif
  8483. /* Decode RSA public key.
  8484. *
  8485. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8486. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8487. *
  8488. * @param [in] input Buffer holding BER encoded data.
  8489. * @param [in, out] inOutIdx On in, start of RSA public key.
  8490. * On out, start of ASN.1 item after RSA public key.
  8491. * @param [in] inSz Number of bytes in buffer.
  8492. * @param [out] n Pointer to modulus in buffer.
  8493. * @param [out] nSz Size of modulus in bytes.
  8494. * @param [out] e Pointer to exponent in buffer.
  8495. * @param [out] eSz Size of exponent in bytes.
  8496. * @return 0 on success.
  8497. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8498. * is invalid.
  8499. * @return BUFFER_E when data in buffer is too small.
  8500. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8501. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8502. * non-zero length.
  8503. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8504. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8505. */
  8506. int wc_RsaPublicKeyDecode_ex(const byte* input, word32* inOutIdx, word32 inSz,
  8507. const byte** n, word32* nSz, const byte** e, word32* eSz)
  8508. {
  8509. #ifndef WOLFSSL_ASN_TEMPLATE
  8510. int ret = 0;
  8511. int length = 0;
  8512. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8513. word32 localIdx;
  8514. byte tag;
  8515. #endif
  8516. if (input == NULL || inOutIdx == NULL)
  8517. return BAD_FUNC_ARG;
  8518. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8519. return ASN_PARSE_E;
  8520. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8521. localIdx = *inOutIdx;
  8522. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  8523. return BUFFER_E;
  8524. if (tag != ASN_INTEGER) {
  8525. /* not from decoded cert, will have algo id, skip past */
  8526. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8527. return ASN_PARSE_E;
  8528. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  8529. return ASN_PARSE_E;
  8530. /* Option NULL ASN.1 tag */
  8531. if (*inOutIdx >= inSz) {
  8532. return BUFFER_E;
  8533. }
  8534. localIdx = *inOutIdx;
  8535. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  8536. return ASN_PARSE_E;
  8537. if (tag == ASN_TAG_NULL) {
  8538. ret = GetASNNull(input, inOutIdx, inSz);
  8539. if (ret != 0)
  8540. return ret;
  8541. }
  8542. #ifdef WC_RSA_PSS
  8543. /* Skip RSA PSS parameters. */
  8544. else if (tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  8545. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8546. return ASN_PARSE_E;
  8547. *inOutIdx += length;
  8548. }
  8549. #endif
  8550. /* should have bit tag length and seq next */
  8551. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  8552. if (ret != 0)
  8553. return ret;
  8554. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8555. return ASN_PARSE_E;
  8556. }
  8557. #endif /* OPENSSL_EXTRA */
  8558. /* Get modulus */
  8559. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8560. if (ret < 0) {
  8561. return ASN_RSA_KEY_E;
  8562. }
  8563. if (nSz)
  8564. *nSz = (word32)length;
  8565. if (n)
  8566. *n = &input[*inOutIdx];
  8567. *inOutIdx += (word32)length;
  8568. /* Get exponent */
  8569. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8570. if (ret < 0) {
  8571. return ASN_RSA_KEY_E;
  8572. }
  8573. if (eSz)
  8574. *eSz = (word32)length;
  8575. if (e)
  8576. *e = &input[*inOutIdx];
  8577. *inOutIdx += (word32)length;
  8578. return ret;
  8579. #else
  8580. DECL_ASNGETDATA(dataASN, rsaPublicKeyASN_Length);
  8581. int ret = 0;
  8582. #ifdef WC_RSA_PSS
  8583. word32 oid = RSAk;
  8584. #endif
  8585. /* Check validity of parameters. */
  8586. if (input == NULL || inOutIdx == NULL) {
  8587. ret = BAD_FUNC_ARG;
  8588. }
  8589. CALLOC_ASNGETDATA(dataASN, rsaPublicKeyASN_Length, ret, NULL);
  8590. if (ret == 0) {
  8591. /* Try decoding PKCS #1 public key by ignoring rest of ASN.1. */
  8592. ret = GetASN_Items(&rsaPublicKeyASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8593. &dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8594. (int)(rsaPublicKeyASN_Length - RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ),
  8595. 0, input, inOutIdx, inSz);
  8596. if (ret != 0) {
  8597. /* Didn't work - try whole SubjectKeyInfo instead. */
  8598. #ifdef WC_RSA_PSS
  8599. /* Could be RSA or RSA PSS key. */
  8600. GetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], oidKeyType);
  8601. #else
  8602. /* Set the OID to expect. */
  8603. GetASN_ExpBuffer(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID],
  8604. keyRsaOid, sizeof(keyRsaOid));
  8605. #endif
  8606. /* Decode SubjectKeyInfo. */
  8607. ret = GetASN_Items(rsaPublicKeyASN, dataASN,
  8608. rsaPublicKeyASN_Length, 1, input, inOutIdx,
  8609. inSz);
  8610. }
  8611. }
  8612. #ifdef WC_RSA_PSS
  8613. if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].tag != 0)) {
  8614. /* Two possible OIDs supported - RSA and RSA PSS. */
  8615. oid = dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].data.oid.sum;
  8616. if ((oid != RSAk) && (oid != RSAPSSk)) {
  8617. ret = ASN_PARSE_E;
  8618. }
  8619. }
  8620. if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].tag != 0)) {
  8621. /* Can't have NULL and SEQ. */
  8622. if (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_NULL].tag != 0) {
  8623. ret = ASN_PARSE_E;
  8624. }
  8625. /* SEQ present only with RSA PSS. */
  8626. if ((ret == 0) && (oid != RSAPSSk)) {
  8627. ret = ASN_PARSE_E;
  8628. }
  8629. if (ret == 0) {
  8630. enum wc_HashType hash;
  8631. int mgf;
  8632. int saltLen;
  8633. const byte* params = GetASNItem_Addr(
  8634. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
  8635. word32 paramsSz = GetASNItem_Length(
  8636. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
  8637. /* Validate the private key parameters. */
  8638. ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf, &saltLen);
  8639. /* TODO: store parameters so that usage can be checked. */
  8640. }
  8641. }
  8642. #endif
  8643. if (ret == 0) {
  8644. /* Return the buffers and lengths asked for. */
  8645. if (n != NULL) {
  8646. *n = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.data;
  8647. }
  8648. if (nSz != NULL) {
  8649. *nSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.length;
  8650. }
  8651. if (e != NULL) {
  8652. *e = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.data;
  8653. }
  8654. if (eSz != NULL) {
  8655. *eSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.length;
  8656. }
  8657. }
  8658. FREE_ASNGETDATA(dataASN, NULL);
  8659. return ret;
  8660. #endif /* WOLFSSL_ASN_TEMPLATE */
  8661. }
  8662. /* Decode RSA public key.
  8663. *
  8664. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8665. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8666. *
  8667. * @param [in] input Buffer holding BER encoded data.
  8668. * @param [in, out] inOutIdx On in, start of RSA public key.
  8669. * On out, start of ASN.1 item after RSA public key.
  8670. * @param [in, out] key RSA key object.
  8671. * @param [in] inSz Number of bytes in buffer.
  8672. * @return 0 on success.
  8673. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8674. * is invalid.
  8675. * @return BUFFER_E when data in buffer is too small.
  8676. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8677. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8678. * non-zero length.
  8679. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8680. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8681. */
  8682. int wc_RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  8683. word32 inSz)
  8684. {
  8685. int ret;
  8686. const byte *n = NULL, *e = NULL;
  8687. word32 nSz = 0, eSz = 0;
  8688. if (key == NULL)
  8689. return BAD_FUNC_ARG;
  8690. ret = wc_RsaPublicKeyDecode_ex(input, inOutIdx, inSz, &n, &nSz, &e, &eSz);
  8691. if (ret == 0) {
  8692. ret = wc_RsaPublicKeyDecodeRaw(n, nSz, e, eSz, key);
  8693. }
  8694. return ret;
  8695. }
  8696. #endif /* HAVE_USER_RSA */
  8697. #endif /* !NO_RSA */
  8698. #ifndef NO_DH
  8699. #if defined(WOLFSSL_DH_EXTRA)
  8700. /*
  8701. * Decodes DH public key to fill specified DhKey.
  8702. *
  8703. * return 0 on success, negative on failure
  8704. */
  8705. int wc_DhPublicKeyDecode(const byte* input, word32* inOutIdx,
  8706. DhKey* key, word32 inSz)
  8707. {
  8708. int ret = 0;
  8709. int length;
  8710. word32 oid = 0;
  8711. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  8712. return BAD_FUNC_ARG;
  8713. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8714. return ASN_PARSE_E;
  8715. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8716. return ASN_PARSE_E;
  8717. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  8718. if (oid != DHk || ret < 0)
  8719. return ASN_DH_KEY_E;
  8720. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8721. return ASN_PARSE_E;
  8722. if (GetInt(&key->p, input, inOutIdx, inSz) < 0)
  8723. return ASN_DH_KEY_E;
  8724. if (GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8725. mp_clear(&key->p);
  8726. return ASN_DH_KEY_E;
  8727. }
  8728. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  8729. if (ret > 0) {
  8730. /* Found Bit String WOLFSSL_DH_EXTRA is required to access DhKey.pub */
  8731. if (GetInt(&key->pub, input, inOutIdx, inSz) < 0) {
  8732. mp_clear(&key->p);
  8733. mp_clear(&key->g);
  8734. return ASN_DH_KEY_E;
  8735. }
  8736. }
  8737. else {
  8738. mp_clear(&key->p);
  8739. mp_clear(&key->g);
  8740. return ASN_DH_KEY_E;
  8741. }
  8742. return 0;
  8743. }
  8744. #endif /* WOLFSSL_DH_EXTRA */
  8745. #ifdef WOLFSSL_ASN_TEMPLATE
  8746. /* ASN.1 template for DH key.
  8747. * PKCS #3, 9 - DHParameter.
  8748. * (Also in: RFC 2786, 3)
  8749. */
  8750. static const ASNItem dhParamASN[] = {
  8751. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8752. /* prime */
  8753. /* PRIME */ { 1, ASN_INTEGER, 0, 0, 0 },
  8754. /* base */
  8755. /* BASE */ { 1, ASN_INTEGER, 0, 0, 0 },
  8756. /* privateValueLength */
  8757. /* PRIVLEN */ { 1, ASN_INTEGER, 0, 0, 1 },
  8758. };
  8759. enum {
  8760. DHPARAMASN_IDX_SEQ = 0,
  8761. DHPARAMASN_IDX_PRIME,
  8762. DHPARAMASN_IDX_BASE,
  8763. DHPARAMASN_IDX_PRIVLEN
  8764. };
  8765. /* Number of items in ASN.1 template for DH key. */
  8766. #define dhParamASN_Length (sizeof(dhParamASN) / sizeof(ASNItem))
  8767. #ifdef WOLFSSL_DH_EXTRA
  8768. /* ASN.1 template for DH key wrapped in PKCS #8 or SubjectPublicKeyInfo.
  8769. * PKCS #8: RFC 5208, 5 - PrivateKeyInfo
  8770. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8771. * RFC 3279, 2.3.3 - DH in SubjectPublicKeyInfo
  8772. */
  8773. static const ASNItem dhKeyPkcs8ASN[] = {
  8774. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8775. /* VER */ { 1, ASN_INTEGER, 0, 0, 1 },
  8776. /* PKEYALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8777. /* PKEYALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8778. /* DHParameter */
  8779. /* PKEYALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8780. /* p */
  8781. /* PKEYALGO_PARAM_P */ { 3, ASN_INTEGER, 0, 0, 0 },
  8782. /* g */
  8783. /* PKEYALGO_PARAM_G */ { 3, ASN_INTEGER, 0, 0, 0 },
  8784. /* q - factor of p-1 */
  8785. /* PKEYALGO_PARAM_Q */ { 3, ASN_INTEGER, 0, 0, 1 },
  8786. /* j - subgroup factor */
  8787. /* PKEYALGO_PARAM_J */ { 3, ASN_INTEGER, 0, 0, 1 },
  8788. /* ValidationParms */
  8789. /* PKEYALGO_PARAM_VALID */ { 3, ASN_SEQUENCE, 0, 0, 1 },
  8790. /* PrivateKey - PKCS #8 */
  8791. /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 2 },
  8792. /* PKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
  8793. /* PublicKey - SubjectPublicKeyInfo. */
  8794. /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 2 },
  8795. /* PUBKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
  8796. };
  8797. enum {
  8798. DHKEYPKCS8ASN_IDX_SEQ = 0,
  8799. DHKEYPKCS8ASN_IDX_VER,
  8800. DHKEYPKCS8ASN_IDX_PKEYALGO_SEQ,
  8801. DHKEYPKCS8ASN_IDX_PKEYALGO_OID,
  8802. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_SEQ,
  8803. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P,
  8804. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G,
  8805. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q,
  8806. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J,
  8807. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID,
  8808. DHKEYPKCS8ASN_IDX_PKEY_STR,
  8809. DHKEYPKCS8ASN_IDX_PKEY_INT,
  8810. DHKEYPKCS8ASN_IDX_PUBKEY_STR,
  8811. DHKEYPKCS8ASN_IDX_PUBKEY_INT
  8812. };
  8813. #define dhKeyPkcs8ASN_Length (sizeof(dhKeyPkcs8ASN) / sizeof(ASNItem))
  8814. #endif
  8815. #endif
  8816. /* Decodes either PKCS#3 DH parameters or PKCS#8 DH key file (WOLFSSL_DH_EXTRA).
  8817. *
  8818. * See also wc_DhParamsLoad(). Loads directly into buffers rather than key
  8819. * object.
  8820. *
  8821. * @param [in] input BER/DER encoded data.
  8822. * @param [in, out] inOutIdx On in, start of DH key data.
  8823. * On out, end of DH key data.
  8824. * @param [in, out] key DH key object.
  8825. * @param [in] inSz Size of data in bytes.
  8826. * @return 0 on success.
  8827. * @return BAD_FUNC_ARG when input, inOutIDx or key is NULL.
  8828. * @return MEMORY_E when dynamic memory allocation fails.
  8829. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8830. * is invalid.
  8831. * @return BUFFER_E when data in buffer is too small.
  8832. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8833. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8834. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8835. * non-zero length.
  8836. * @return MP_INIT_E when the unable to initialize an mp_int.
  8837. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  8838. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8839. */
  8840. int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
  8841. {
  8842. #ifndef WOLFSSL_ASN_TEMPLATE
  8843. int ret = 0;
  8844. int length;
  8845. #ifdef WOLFSSL_DH_EXTRA
  8846. #if !defined(HAVE_FIPS) || \
  8847. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8848. word32 oid = 0, temp = 0;
  8849. #endif
  8850. #endif
  8851. WOLFSSL_ENTER("wc_DhKeyDecode");
  8852. if (inOutIdx == NULL)
  8853. return BAD_FUNC_ARG;
  8854. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8855. return ASN_PARSE_E;
  8856. #ifdef WOLFSSL_DH_EXTRA
  8857. #if !defined(HAVE_FIPS) || \
  8858. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8859. temp = *inOutIdx;
  8860. #endif
  8861. #endif
  8862. /* Assume input started after 1.2.840.113549.1.3.1 dhKeyAgreement */
  8863. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  8864. ret = ASN_DH_KEY_E;
  8865. }
  8866. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8867. mp_clear(&key->p);
  8868. ret = ASN_DH_KEY_E;
  8869. }
  8870. #ifdef WOLFSSL_DH_EXTRA
  8871. #if !defined(HAVE_FIPS) || \
  8872. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8873. /* If ASN_DH_KEY_E: Check if input started at beginning of key */
  8874. if (ret == ASN_DH_KEY_E) {
  8875. *inOutIdx = temp;
  8876. /* the version (0) - private only (for public skip) */
  8877. if (GetASNInt(input, inOutIdx, &length, inSz) == 0) {
  8878. *inOutIdx += (word32)length;
  8879. }
  8880. /* Size of dhKeyAgreement section */
  8881. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8882. return ASN_PARSE_E;
  8883. /* Check for dhKeyAgreement */
  8884. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  8885. if (oid != DHk || ret < 0)
  8886. return ASN_DH_KEY_E;
  8887. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8888. return ASN_PARSE_E;
  8889. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  8890. return ASN_DH_KEY_E;
  8891. }
  8892. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8893. mp_clear(&key->p);
  8894. return ASN_DH_KEY_E;
  8895. }
  8896. }
  8897. temp = *inOutIdx;
  8898. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  8899. if (ret > 0) {
  8900. /* Found Bit String */
  8901. if (GetInt(&key->pub, input, inOutIdx, inSz) == 0) {
  8902. WOLFSSL_MSG("Found Public Key");
  8903. ret = 0;
  8904. }
  8905. } else {
  8906. *inOutIdx = temp;
  8907. ret = (GetOctetString(input, inOutIdx, &length, inSz) >= 0);
  8908. if (ret > 0) {
  8909. /* Found Octet String */
  8910. if (GetInt(&key->priv, input, inOutIdx, inSz) == 0) {
  8911. WOLFSSL_MSG("Found Private Key");
  8912. /* Compute public */
  8913. ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
  8914. }
  8915. } else {
  8916. /* Don't use length from failed CheckBitString/GetOctetString */
  8917. *inOutIdx = temp;
  8918. ret = 0;
  8919. }
  8920. }
  8921. #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
  8922. #endif /* WOLFSSL_DH_EXTRA */
  8923. WOLFSSL_LEAVE("wc_DhKeyDecode", ret);
  8924. return ret;
  8925. #else
  8926. #ifdef WOLFSSL_DH_EXTRA
  8927. DECL_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length);
  8928. #else
  8929. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  8930. #endif
  8931. int ret = 0;
  8932. /* Check input parameters are valid. */
  8933. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  8934. ret = BAD_FUNC_ARG;
  8935. }
  8936. #ifdef WOLFSSL_DH_EXTRA
  8937. ALLOC_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length, ret, key->heap);
  8938. #else
  8939. ALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, key->heap);
  8940. #endif
  8941. if (ret == 0) {
  8942. /* Initialize data and set mp_ints to hold p and g. */
  8943. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhParamASN_Length);
  8944. GetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
  8945. GetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
  8946. /* Try simple PKCS #3 template. */
  8947. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  8948. inOutIdx, inSz);
  8949. #ifdef WOLFSSL_DH_EXTRA
  8950. if (ret != 0) {
  8951. mp_free(&key->p);
  8952. mp_free(&key->g);
  8953. /* Initialize data and set mp_ints to hold p, g, q, priv and pub. */
  8954. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhKeyPkcs8ASN_Length);
  8955. GetASN_ExpBuffer(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID],
  8956. keyDhOid, sizeof(keyDhOid));
  8957. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
  8958. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
  8959. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q], &key->q);
  8960. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
  8961. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
  8962. /* Try PKCS #8 wrapped template. */
  8963. ret = GetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, 1,
  8964. input, inOutIdx, inSz);
  8965. if (ret == 0) {
  8966. /* VERSION only present in PKCS #8 private key structure */
  8967. if ((dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].length != 0) &&
  8968. (dataASN[DHKEYPKCS8ASN_IDX_VER].length == 0)) {
  8969. ret = ASN_PARSE_E;
  8970. }
  8971. else if ((dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].length != 0) &&
  8972. (dataASN[DHKEYPKCS8ASN_IDX_VER].length != 0)) {
  8973. ret = ASN_PARSE_E;
  8974. }
  8975. }
  8976. if ((ret == 0) && mp_iszero(&key->pub)) {
  8977. ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
  8978. }
  8979. }
  8980. #endif
  8981. }
  8982. FREE_ASNGETDATA(dataASN, key->heap);
  8983. return ret;
  8984. #endif /* WOLFSSL_ASN_TEMPLATE */
  8985. }
  8986. #ifdef WOLFSSL_DH_EXTRA
  8987. /* Export DH Key (private or public) */
  8988. int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv)
  8989. {
  8990. #ifndef WOLFSSL_ASN_TEMPLATE
  8991. int ret, privSz = 0, pubSz = 0;
  8992. word32 keySz, idx, len, total;
  8993. if (key == NULL || outSz == NULL) {
  8994. return BAD_FUNC_ARG;
  8995. }
  8996. /* determine size */
  8997. if (exportPriv) {
  8998. /* octect string: priv */
  8999. privSz = SetASNIntMP(&key->priv, -1, NULL);
  9000. if (privSz < 0)
  9001. return privSz;
  9002. idx = 1 + SetLength((word32)privSz, NULL) +
  9003. (word32)privSz; /* +1 for ASN_OCTET_STRING */
  9004. }
  9005. else {
  9006. /* bit string: public */
  9007. pubSz = SetASNIntMP(&key->pub, -1, NULL);
  9008. if (pubSz < 0)
  9009. return pubSz;
  9010. idx = SetBitString((word32)pubSz, 0, NULL) + (word32)pubSz;
  9011. }
  9012. keySz = idx;
  9013. /* DH Parameters sequence with P and G */
  9014. total = 0;
  9015. ret = wc_DhParamsToDer(key, NULL, &total);
  9016. if (ret != LENGTH_ONLY_E)
  9017. return ret;
  9018. idx += total;
  9019. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  9020. idx += (word32)SetObjectId(sizeof(keyDhOid), NULL);
  9021. idx += (word32)sizeof(keyDhOid);
  9022. len = idx - keySz;
  9023. /* sequence - all but pub/priv */
  9024. idx += SetSequence(len, NULL);
  9025. if (exportPriv) {
  9026. /* version: 0 (ASN_INTEGER, 0x01, 0x00) */
  9027. idx += 3;
  9028. }
  9029. /* sequence */
  9030. total = idx + SetSequence(idx, NULL);
  9031. /* if no output, then just getting size */
  9032. if (output == NULL) {
  9033. *outSz = total;
  9034. return LENGTH_ONLY_E;
  9035. }
  9036. /* make sure output fits in buffer */
  9037. if (total > *outSz) {
  9038. return BUFFER_E;
  9039. }
  9040. total = idx;
  9041. /* sequence */
  9042. idx = SetSequence(total, output);
  9043. if (exportPriv) {
  9044. /* version: 0 */
  9045. idx += (word32)SetMyVersion(0, output + idx, 0);
  9046. }
  9047. /* sequence - all but pub/priv */
  9048. idx += SetSequence(len, output + idx);
  9049. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  9050. idx += (word32)SetObjectId(sizeof(keyDhOid), output + idx);
  9051. XMEMCPY(output + idx, keyDhOid, sizeof(keyDhOid));
  9052. idx += sizeof(keyDhOid);
  9053. /* DH Parameters sequence with P and G */
  9054. total = *outSz - idx;
  9055. ret = wc_DhParamsToDer(key, output + idx, &total);
  9056. if (ret < 0)
  9057. return ret;
  9058. idx += total;
  9059. /* octect string: priv */
  9060. if (exportPriv) {
  9061. idx += (word32)SetOctetString((word32)privSz, output + idx);
  9062. idx += (word32)SetASNIntMP(&key->priv, -1, output + idx);
  9063. }
  9064. else {
  9065. /* bit string: public */
  9066. idx += (word32)SetBitString((word32)pubSz, 0, output + idx);
  9067. idx += (word32)SetASNIntMP(&key->pub, -1, output + idx);
  9068. }
  9069. *outSz = idx;
  9070. return (int)idx;
  9071. #else
  9072. ASNSetData dataASN[dhKeyPkcs8ASN_Length];
  9073. int ret = 0;
  9074. int sz;
  9075. WOLFSSL_ENTER("wc_DhKeyToDer");
  9076. XMEMSET(dataASN, 0, sizeof(dataASN));
  9077. SetASN_Int8Bit(&dataASN[DHKEYPKCS8ASN_IDX_VER], 0);
  9078. SetASN_OID(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID], DHk, oidKeyType);
  9079. /* Set mp_int containing p and g. */
  9080. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
  9081. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
  9082. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q].noOut = 1;
  9083. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J].noOut = 1;
  9084. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID].noOut = 1;
  9085. if (exportPriv) {
  9086. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
  9087. dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_STR].noOut = 1;
  9088. dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].noOut = 1;
  9089. }
  9090. else {
  9091. dataASN[DHKEYPKCS8ASN_IDX_VER].noOut = 1;
  9092. dataASN[DHKEYPKCS8ASN_IDX_PKEY_STR].noOut = 1;
  9093. dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].noOut = 1;
  9094. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
  9095. }
  9096. /* Calculate the size of the DH parameters. */
  9097. ret = SizeASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, &sz);
  9098. if (output == NULL) {
  9099. *outSz = (word32)sz;
  9100. ret = LENGTH_ONLY_E;
  9101. }
  9102. /* Check buffer is big enough for encoding. */
  9103. if ((ret == 0) && ((int)*outSz < sz)) {
  9104. ret = BUFFER_E;
  9105. }
  9106. if (ret == 0) {
  9107. /* Encode the DH parameters into buffer. */
  9108. SetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, output);
  9109. /* Set the actual encoding size. */
  9110. *outSz = (word32)sz;
  9111. /* Return the actual encoding size. */
  9112. ret = sz;
  9113. }
  9114. return ret;
  9115. #endif
  9116. }
  9117. int wc_DhPubKeyToDer(DhKey* key, byte* out, word32* outSz)
  9118. {
  9119. return wc_DhKeyToDer(key, out, outSz, 0);
  9120. }
  9121. int wc_DhPrivKeyToDer(DhKey* key, byte* out, word32* outSz)
  9122. {
  9123. return wc_DhKeyToDer(key, out, outSz, 1);
  9124. }
  9125. /* Convert DH key parameters to DER format, write to output (outSz)
  9126. * If output is NULL then max expected size is set to outSz and LENGTH_ONLY_E is
  9127. * returned.
  9128. *
  9129. * Note : static function due to redefinition complications with DhKey and FIPS
  9130. * version 2 build.
  9131. *
  9132. * return bytes written on success */
  9133. int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz)
  9134. {
  9135. #ifndef WOLFSSL_ASN_TEMPLATE
  9136. int ret;
  9137. word32 idx, total;
  9138. if (key == NULL || outSz == NULL) {
  9139. return BAD_FUNC_ARG;
  9140. }
  9141. /* determine size */
  9142. /* integer - g */
  9143. ret = SetASNIntMP(&key->g, -1, NULL);
  9144. if (ret < 0)
  9145. return ret;
  9146. idx = (word32)ret;
  9147. /* integer - p */
  9148. ret = SetASNIntMP(&key->p, -1, NULL);
  9149. if (ret < 0)
  9150. return ret;
  9151. idx += (word32)ret;
  9152. total = idx;
  9153. /* sequence */
  9154. idx += SetSequence(idx, NULL);
  9155. if (output == NULL) {
  9156. *outSz = idx;
  9157. return LENGTH_ONLY_E;
  9158. }
  9159. /* make sure output fits in buffer */
  9160. if (idx > *outSz) {
  9161. return BUFFER_E;
  9162. }
  9163. /* write DH parameters */
  9164. /* sequence - for P and G only */
  9165. idx = SetSequence(total, output);
  9166. /* integer - p */
  9167. ret = SetASNIntMP(&key->p, -1, output + idx);
  9168. if (ret < 0)
  9169. return ret;
  9170. idx += (word32)ret;
  9171. /* integer - g */
  9172. ret = SetASNIntMP(&key->g, -1, output + idx);
  9173. if (ret < 0)
  9174. return ret;
  9175. idx += (word32)ret;
  9176. *outSz = idx;
  9177. return (int)idx;
  9178. #else
  9179. ASNSetData dataASN[dhParamASN_Length];
  9180. int ret = 0;
  9181. int sz = 0;
  9182. WOLFSSL_ENTER("wc_DhParamsToDer");
  9183. if (key == NULL || outSz == NULL) {
  9184. ret = BAD_FUNC_ARG;
  9185. }
  9186. if (ret == 0) {
  9187. XMEMSET(dataASN, 0, sizeof(dataASN));
  9188. /* Set mp_int containing p and g. */
  9189. SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
  9190. SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
  9191. /* privateValueLength not encoded. */
  9192. dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
  9193. /* Calculate the size of the DH parameters. */
  9194. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  9195. }
  9196. if ((ret == 0) && (output == NULL)) {
  9197. *outSz = (word32)sz;
  9198. ret = LENGTH_ONLY_E;
  9199. }
  9200. /* Check buffer is big enough for encoding. */
  9201. if ((ret == 0) && (*outSz < (word32)sz)) {
  9202. ret = BUFFER_E;
  9203. }
  9204. if (ret == 0) {
  9205. /* Encode the DH parameters into buffer. */
  9206. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, output);
  9207. /* Set the actual encoding size. */
  9208. *outSz = (word32)sz;
  9209. /* Return count of bytes written. */
  9210. ret = sz;
  9211. }
  9212. return ret;
  9213. #endif
  9214. }
  9215. #endif /* WOLFSSL_DH_EXTRA */
  9216. /* Decode DH parameters.
  9217. *
  9218. * PKCS #3, 9 - DHParameter.
  9219. * (Also in: RFC 2786, 3)
  9220. *
  9221. * @param [in] input Buffer holding BER encoded data.
  9222. * @param [in, out] inOutIdx On in, start of RSA public key.
  9223. * On out, start of ASN.1 item after RSA public key.
  9224. * @param [in] inSz Number of bytes in buffer.
  9225. * @param [in, out] p Buffer to hold prime.
  9226. * @param [out] pInOutSz On in, size of buffer to hold prime in bytes.
  9227. * On out, size of prime in bytes.
  9228. * @param [in, out] g Buffer to hold base.
  9229. * @param [out] gInOutSz On in, size of buffer to hold base in bytes.
  9230. * On out, size of base in bytes.
  9231. * @return 0 on success.
  9232. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9233. * is invalid.
  9234. * @return BUFFER_E when data in buffer is too small.
  9235. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  9236. */
  9237. int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
  9238. byte* g, word32* gInOutSz)
  9239. {
  9240. #ifndef WOLFSSL_ASN_TEMPLATE
  9241. word32 idx = 0;
  9242. int ret;
  9243. int length;
  9244. if (GetSequence(input, &idx, &length, inSz) <= 0)
  9245. return ASN_PARSE_E;
  9246. ret = GetASNInt(input, &idx, &length, inSz);
  9247. if (ret != 0)
  9248. return ret;
  9249. if (length <= (int)*pInOutSz) {
  9250. XMEMCPY(p, &input[idx], (size_t)length);
  9251. *pInOutSz = (word32)length;
  9252. }
  9253. else {
  9254. return BUFFER_E;
  9255. }
  9256. idx += (word32)length;
  9257. ret = GetASNInt(input, &idx, &length, inSz);
  9258. if (ret != 0)
  9259. return ret;
  9260. if (length <= (int)*gInOutSz) {
  9261. XMEMCPY(g, &input[idx], (size_t)length);
  9262. *gInOutSz = (word32)length;
  9263. }
  9264. else {
  9265. return BUFFER_E;
  9266. }
  9267. return 0;
  9268. #else
  9269. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  9270. word32 idx = 0;
  9271. int ret = 0;
  9272. /* Make sure pointers are valid before use. */
  9273. if ((input == NULL) || (p == NULL) || (pInOutSz == NULL) || (g == NULL) ||
  9274. (gInOutSz == NULL)) {
  9275. ret = BAD_FUNC_ARG;
  9276. }
  9277. CALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, NULL);
  9278. if (ret == 0) {
  9279. /* Set the buffers to copy p and g into. */
  9280. GetASN_Buffer(&dataASN[DHPARAMASN_IDX_PRIME], p, pInOutSz);
  9281. GetASN_Buffer(&dataASN[DHPARAMASN_IDX_BASE], g, gInOutSz);
  9282. /* Decode the DH Parameters. */
  9283. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  9284. &idx, inSz);
  9285. }
  9286. FREE_ASNGETDATA(dataASN, NULL);
  9287. return ret;
  9288. #endif /* WOLFSSL_ASN_TEMPLATE */
  9289. }
  9290. #endif /* !NO_DH */
  9291. #ifndef NO_DSA
  9292. static mp_int* GetDsaInt(DsaKey* key, int idx)
  9293. {
  9294. if (idx == 0)
  9295. return &key->p;
  9296. if (idx == 1)
  9297. return &key->q;
  9298. if (idx == 2)
  9299. return &key->g;
  9300. if (idx == 3)
  9301. return &key->y;
  9302. if (idx == 4)
  9303. return &key->x;
  9304. return NULL;
  9305. }
  9306. #ifdef WOLFSSL_ASN_TEMPLATE
  9307. /* ASN.1 template for DSA public and private keys.
  9308. * Public key: seq, p, q, g, y
  9309. * Private key: seq, version, p, q, g, y, x
  9310. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9311. */
  9312. static const ASNItem dsaKeyASN[] = {
  9313. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9314. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  9315. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  9316. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  9317. /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
  9318. /* Y */ { 1, ASN_INTEGER, 0, 0, 0 },
  9319. /* X */ { 1, ASN_INTEGER, 0, 0, 0 },
  9320. };
  9321. enum {
  9322. DSAKEYASN_IDX_SEQ = 0,
  9323. DSAKEYASN_IDX_VER,
  9324. DSAKEYASN_IDX_P,
  9325. DSAKEYASN_IDX_Q,
  9326. DSAKEYASN_IDX_G,
  9327. DSAKEYASN_IDX_Y,
  9328. DSAKEYASN_IDX_X
  9329. };
  9330. /* Number of items in ASN.1 template for DSA private key. */
  9331. #define dsaKeyASN_Length (sizeof(dsaKeyASN) / sizeof(ASNItem))
  9332. /* Number of items in ASN.1 template for DSA public key. */
  9333. #define dsaPublicKeyASN_Length ((sizeof(dsaKeyASN) / sizeof(ASNItem)) - 2)
  9334. /* ASN.1 template for PublicKeyInfo with DSA.
  9335. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  9336. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9337. */
  9338. static const ASNItem dsaPubKeyASN[] = {
  9339. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9340. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  9341. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  9342. /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  9343. /* p */
  9344. /* ALGOID_PARAMS_P */ { 3, ASN_INTEGER, 0, 0, 0 },
  9345. /* q */
  9346. /* ALGOID_PARAMS_Q */ { 3, ASN_INTEGER, 0, 0, 0 },
  9347. /* g */
  9348. /* ALGOID_PARAMS_G */ { 3, ASN_INTEGER, 0, 0, 0 },
  9349. /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 1 },
  9350. /* y */
  9351. /* PUBKEY_Y */ { 2, ASN_INTEGER, 0, 0, 0 },
  9352. };
  9353. enum {
  9354. DSAPUBKEYASN_IDX_SEQ = 0,
  9355. DSAPUBKEYASN_IDX_ALGOID_SEQ,
  9356. DSAPUBKEYASN_IDX_ALGOID_OID,
  9357. DSAPUBKEYASN_IDX_ALGOID_PARAMS,
  9358. DSAPUBKEYASN_IDX_ALGOID_PARAMS_P,
  9359. DSAPUBKEYASN_IDX_ALGOID_PARAMS_Q,
  9360. DSAPUBKEYASN_IDX_ALGOID_PARAMS_G,
  9361. DSAPUBKEYASN_IDX_PUBKEY_STR,
  9362. DSAPUBKEYASN_IDX_PUBKEY_Y
  9363. };
  9364. /* Number of items in ASN.1 template for PublicKeyInfo with DSA. */
  9365. #define dsaPubKeyASN_Length (sizeof(dsaPubKeyASN) / sizeof(ASNItem))
  9366. #endif /* WOLFSSL_ASN_TEMPLATE */
  9367. /* Decode DSA public key.
  9368. *
  9369. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  9370. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9371. *
  9372. * @param [in] input Buffer holding BER encoded data.
  9373. * @param [in, out] inOutIdx On in, start of DSA public key.
  9374. * On out, start of ASN.1 item after DSA public key.
  9375. * @param [in, out] key DSA key object.
  9376. * @param [in] inSz Number of bytes in buffer.
  9377. * @return 0 on success.
  9378. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9379. * is invalid.
  9380. * @return BUFFER_E when data in buffer is too small.
  9381. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  9382. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  9383. * non-zero length.
  9384. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  9385. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  9386. */
  9387. int wc_DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9388. word32 inSz)
  9389. {
  9390. #ifndef WOLFSSL_ASN_TEMPLATE
  9391. int length;
  9392. int ret = 0;
  9393. word32 oid;
  9394. word32 maxIdx;
  9395. if (input == NULL || inOutIdx == NULL || key == NULL)
  9396. return BAD_FUNC_ARG;
  9397. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9398. return ASN_PARSE_E;
  9399. maxIdx = (word32)(*inOutIdx + (word32)length);
  9400. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  9401. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  9402. GetInt(&key->g, input, inOutIdx, maxIdx) < 0 ||
  9403. GetInt(&key->y, input, inOutIdx, maxIdx) < 0 )
  9404. ret = ASN_DH_KEY_E;
  9405. if (ret != 0) {
  9406. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9407. return ASN_PARSE_E;
  9408. ret = GetObjectId(input, inOutIdx, &oid, oidIgnoreType, inSz);
  9409. if (ret != 0)
  9410. return ret;
  9411. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9412. return ASN_PARSE_E;
  9413. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  9414. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  9415. GetInt(&key->g, input, inOutIdx, inSz) < 0)
  9416. return ASN_DH_KEY_E;
  9417. if (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) < 0)
  9418. return ASN_PARSE_E;
  9419. if (GetInt(&key->y, input, inOutIdx, inSz) < 0 )
  9420. return ASN_DH_KEY_E;
  9421. ret = 0;
  9422. }
  9423. key->type = DSA_PUBLIC;
  9424. return ret;
  9425. #else
  9426. /* dsaPubKeyASN is longer than dsaPublicKeyASN. */
  9427. DECL_ASNGETDATA(dataASN, dsaPubKeyASN_Length);
  9428. int ret = 0;
  9429. /* Validated parameters. */
  9430. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  9431. ret = BAD_FUNC_ARG;
  9432. }
  9433. ALLOC_ASNGETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  9434. if (ret == 0) {
  9435. int i;
  9436. /* Clear dynamic data items. */
  9437. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPublicKeyASN_Length);
  9438. /* seq
  9439. * p, q, g, y
  9440. * Start DSA ints from DSAKEYASN_IDX_VER instead of DSAKEYASN_IDX_P */
  9441. for (i = 0; i < DSA_INTS - 1; i++)
  9442. GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i], GetDsaInt(key, i));
  9443. /* Parse as simple form. */
  9444. ret = GetASN_Items(dsaKeyASN, dataASN, dsaPublicKeyASN_Length, 0, input,
  9445. inOutIdx, inSz);
  9446. if (ret != 0) {
  9447. /* Clear dynamic data items. */
  9448. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPubKeyASN_Length);
  9449. /* Set DSA OID to expect. */
  9450. GetASN_ExpBuffer(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID],
  9451. keyDsaOid, sizeof(keyDsaOid));
  9452. /* p, q, g */
  9453. for (i = 0; i < DSA_INTS - 2; i++)
  9454. GetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
  9455. GetDsaInt(key, i));
  9456. /* y */
  9457. GetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
  9458. /* Parse as SubjectPublicKeyInfo. */
  9459. ret = GetASN_Items(dsaPubKeyASN, dataASN, dsaPubKeyASN_Length, 1,
  9460. input, inOutIdx, inSz);
  9461. }
  9462. }
  9463. if (ret == 0) {
  9464. /* Data parsed - set type of key parsed. */
  9465. key->type = DSA_PUBLIC;
  9466. }
  9467. FREE_ASNGETDATA(dataASN, key->heap);
  9468. return ret;
  9469. #endif
  9470. }
  9471. int wc_DsaParamsDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9472. word32 inSz)
  9473. {
  9474. int length;
  9475. word32 maxIdx;
  9476. if (input == NULL || inOutIdx == NULL || key == NULL)
  9477. return BAD_FUNC_ARG;
  9478. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9479. return ASN_PARSE_E;
  9480. maxIdx = (word32)(*inOutIdx + (word32)length);
  9481. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  9482. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  9483. GetInt(&key->g, input, inOutIdx, maxIdx) < 0)
  9484. return ASN_DH_KEY_E;
  9485. return 0;
  9486. }
  9487. #ifdef WOLFSSL_ASN_TEMPLATE
  9488. /* ASN.1 template for a DSA key holding private key in an OCTET_STRING. */
  9489. static const ASNItem dsaKeyOctASN[] = {
  9490. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9491. /* p */
  9492. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  9493. /* q */
  9494. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  9495. /* g */
  9496. /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
  9497. /* Private key */
  9498. /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  9499. /* x */
  9500. /* X */ { 2, ASN_INTEGER, 0, 0, 0 },
  9501. };
  9502. enum {
  9503. DSAKEYOCTASN_IDX_SEQ = 0,
  9504. DSAKEYOCTASN_IDX_P,
  9505. DSAKEYOCTASN_IDX_Q,
  9506. DSAKEYOCTASN_IDX_G,
  9507. DSAKEYOCTASN_IDX_PKEY_STR,
  9508. DSAKEYOCTASN_IDX_X
  9509. };
  9510. /* Number of items in ASN.1 template for a DSA key (OCTET_STRING version). */
  9511. #define dsaKeyOctASN_Length (sizeof(dsaKeyOctASN) / sizeof(ASNItem))
  9512. #endif
  9513. /* Decode DSA private key.
  9514. *
  9515. * @param [in] input Buffer holding BER encoded data.
  9516. * @param [in, out] inOutIdx On in, start of DSA public key.
  9517. * On out, start of ASN.1 item after DSA public key.
  9518. * @param [in, out] key DSA key object.
  9519. * @param [in] inSz Number of bytes in buffer.
  9520. * @return 0 on success.
  9521. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9522. * is invalid.
  9523. * @return BUFFER_E when data in buffer is too small.
  9524. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  9525. * non-zero length.
  9526. */
  9527. int wc_DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9528. word32 inSz)
  9529. {
  9530. #ifndef WOLFSSL_ASN_TEMPLATE
  9531. int length, version, ret = 0, temp = 0;
  9532. word32 algId = 0;
  9533. /* Sanity checks on input */
  9534. if (input == NULL || inOutIdx == NULL || key == NULL) {
  9535. return BAD_FUNC_ARG;
  9536. }
  9537. /* if has pkcs8 header skip it */
  9538. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  9539. /* ignore error, did not have pkcs8 header */
  9540. }
  9541. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9542. return ASN_PARSE_E;
  9543. temp = (int)*inOutIdx;
  9544. /* Default case expects a certificate with OctetString but no version ID */
  9545. ret = GetInt(&key->p, input, inOutIdx, inSz);
  9546. if (ret < 0) {
  9547. mp_clear(&key->p);
  9548. ret = ASN_PARSE_E;
  9549. }
  9550. else {
  9551. ret = GetInt(&key->q, input, inOutIdx, inSz);
  9552. if (ret < 0) {
  9553. mp_clear(&key->p);
  9554. mp_clear(&key->q);
  9555. ret = ASN_PARSE_E;
  9556. }
  9557. else {
  9558. ret = GetInt(&key->g, input, inOutIdx, inSz);
  9559. if (ret < 0) {
  9560. mp_clear(&key->p);
  9561. mp_clear(&key->q);
  9562. mp_clear(&key->g);
  9563. ret = ASN_PARSE_E;
  9564. }
  9565. else {
  9566. ret = GetOctetString(input, inOutIdx, &length, inSz);
  9567. if (ret < 0) {
  9568. mp_clear(&key->p);
  9569. mp_clear(&key->q);
  9570. mp_clear(&key->g);
  9571. ret = ASN_PARSE_E;
  9572. }
  9573. else {
  9574. ret = GetInt(&key->y, input, inOutIdx, inSz);
  9575. if (ret < 0) {
  9576. mp_clear(&key->p);
  9577. mp_clear(&key->q);
  9578. mp_clear(&key->g);
  9579. mp_clear(&key->y);
  9580. ret = ASN_PARSE_E;
  9581. }
  9582. }
  9583. }
  9584. }
  9585. }
  9586. /* An alternate pass if default certificate fails parsing */
  9587. if (ret == ASN_PARSE_E) {
  9588. *inOutIdx = (word32)temp;
  9589. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  9590. return ASN_PARSE_E;
  9591. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  9592. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  9593. GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
  9594. GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
  9595. GetInt(&key->x, input, inOutIdx, inSz) < 0 )
  9596. return ASN_DH_KEY_E;
  9597. }
  9598. key->type = DSA_PRIVATE;
  9599. return 0;
  9600. #else
  9601. /* dsaKeyASN is longer than dsaKeyOctASN. */
  9602. DECL_ASNGETDATA(dataASN, dsaKeyASN_Length);
  9603. int ret = 0;
  9604. byte version = 0;
  9605. /* Sanity checks on input */
  9606. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  9607. ret = BAD_FUNC_ARG;
  9608. }
  9609. CALLOC_ASNGETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  9610. if (ret == 0) {
  9611. int i;
  9612. /* Try dsaKeyOctASN */
  9613. /* Initialize key data and set mp_ints for params */
  9614. for (i = 0; i < DSA_INTS - 2; i++) {
  9615. GetASN_MP(&dataASN[(int)DSAKEYOCTASN_IDX_P + i], GetDsaInt(key, i));
  9616. }
  9617. /* and priv */
  9618. GetASN_MP(&dataASN[DSAKEYOCTASN_IDX_X], GetDsaInt(key, i));
  9619. /* Try simple form. */
  9620. ret = GetASN_Items(dsaKeyOctASN, dataASN, dsaKeyOctASN_Length, 1, input,
  9621. inOutIdx, inSz);
  9622. if (ret != 0) {
  9623. /* Try dsaKeyASN */
  9624. XMEMSET(dataASN, 0, sizeof(*dataASN) * dsaKeyASN_Length);
  9625. GetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], &version);
  9626. for (i = 0; i < DSA_INTS; i++) {
  9627. mp_int* n = GetDsaInt(key, i);
  9628. mp_clear(n);
  9629. GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], n);
  9630. }
  9631. /* Try simple OCTET_STRING form. */
  9632. ret = GetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, 1, input,
  9633. inOutIdx, inSz);
  9634. }
  9635. }
  9636. if (ret == 0) {
  9637. /* Set the contents to be a private key. */
  9638. key->type = DSA_PRIVATE;
  9639. }
  9640. FREE_ASNGETDATA(dataASN, key->heap);
  9641. return ret;
  9642. #endif
  9643. }
  9644. #ifndef WOLFSSL_ASN_TEMPLATE
  9645. /* Release Tmp DSA resources */
  9646. static WC_INLINE void FreeTmpDsas(byte** tmps, void* heap, int ints)
  9647. {
  9648. int i;
  9649. for (i = 0; i < ints; i++)
  9650. XFREE(tmps[i], heap, DYNAMIC_TYPE_DSA);
  9651. (void)heap;
  9652. }
  9653. #endif /* !WOLFSSL_ASN_TEMPLATE */
  9654. #if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \
  9655. defined(WOLFSSL_CERT_GEN))
  9656. /* Encode a DSA public key into buffer.
  9657. *
  9658. * @param [out] output Buffer to hold encoded data.
  9659. * @param [in] key DSA key object.
  9660. * @param [out] outLen Length of buffer.
  9661. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  9662. * @return Size of encoded data in bytes on success.
  9663. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  9664. * than a minimal size (5 bytes), or buffer size is smaller than
  9665. * encoding size.
  9666. * @return MEMORY_E when dynamic memory allocation fails.
  9667. */
  9668. int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header)
  9669. {
  9670. #ifndef WOLFSSL_ASN_TEMPLATE
  9671. /* p, g, q = DSA params, y = public exponent */
  9672. #ifdef WOLFSSL_SMALL_STACK
  9673. byte* p = NULL;
  9674. byte* g = NULL;
  9675. byte* q = NULL;
  9676. byte* y = NULL;
  9677. #else
  9678. byte p[MAX_DSA_INT_SZ];
  9679. byte g[MAX_DSA_INT_SZ];
  9680. byte q[MAX_DSA_INT_SZ];
  9681. byte y[MAX_DSA_INT_SZ];
  9682. #endif
  9683. byte innerSeq[MAX_SEQ_SZ];
  9684. byte outerSeq[MAX_SEQ_SZ];
  9685. byte bitString[1 + MAX_LENGTH_SZ + 1];
  9686. int pSz, gSz, qSz, ySz;
  9687. word32 idx, innerSeqSz, outerSeqSz, bitStringSz = 0;
  9688. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  9689. if (output == NULL || key == NULL || outLen < MAX_SEQ_SZ) {
  9690. return BAD_FUNC_ARG;
  9691. }
  9692. /* p */
  9693. #ifdef WOLFSSL_SMALL_STACK
  9694. p = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9695. if (p == NULL)
  9696. return MEMORY_E;
  9697. #endif
  9698. if ((pSz = SetASNIntMP(&key->p, MAX_DSA_INT_SZ, p)) < 0) {
  9699. WOLFSSL_MSG("SetASNIntMP Error with p");
  9700. #ifdef WOLFSSL_SMALL_STACK
  9701. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9702. #endif
  9703. return pSz;
  9704. }
  9705. /* q */
  9706. #ifdef WOLFSSL_SMALL_STACK
  9707. q = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9708. if (q == NULL)
  9709. return MEMORY_E;
  9710. #endif
  9711. if ((qSz = SetASNIntMP(&key->q, MAX_DSA_INT_SZ, q)) < 0) {
  9712. WOLFSSL_MSG("SetASNIntMP Error with q");
  9713. #ifdef WOLFSSL_SMALL_STACK
  9714. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9715. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9716. #endif
  9717. return qSz;
  9718. }
  9719. /* g */
  9720. #ifdef WOLFSSL_SMALL_STACK
  9721. g = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9722. if (g == NULL)
  9723. return MEMORY_E;
  9724. #endif
  9725. if ((gSz = SetASNIntMP(&key->g, MAX_DSA_INT_SZ, g)) < 0) {
  9726. WOLFSSL_MSG("SetASNIntMP Error with g");
  9727. #ifdef WOLFSSL_SMALL_STACK
  9728. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9729. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9730. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9731. #endif
  9732. return gSz;
  9733. }
  9734. /* y */
  9735. #ifdef WOLFSSL_SMALL_STACK
  9736. y = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9737. if (y == NULL)
  9738. return MEMORY_E;
  9739. #endif
  9740. if ((ySz = SetASNIntMP(&key->y, MAX_DSA_INT_SZ, y)) < 0) {
  9741. WOLFSSL_MSG("SetASNIntMP Error with y");
  9742. #ifdef WOLFSSL_SMALL_STACK
  9743. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9744. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9745. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9746. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9747. #endif
  9748. return ySz;
  9749. }
  9750. if (with_header) {
  9751. word32 algoSz;
  9752. #ifdef WOLFSSL_SMALL_STACK
  9753. byte* algo = NULL;
  9754. algo = (byte*)XMALLOC(MAX_ALGO_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9755. if (algo == NULL) {
  9756. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9757. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9758. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9759. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9760. return MEMORY_E;
  9761. }
  9762. #else
  9763. byte algo[MAX_ALGO_SZ];
  9764. #endif
  9765. innerSeqSz = SetSequence((word32)(pSz + qSz + gSz), innerSeq);
  9766. algoSz = SetAlgoID(DSAk, algo, oidKeyType, 0);
  9767. bitStringSz = SetBitString((word32)ySz, 0, bitString);
  9768. outerSeqSz = SetSequence(algoSz + innerSeqSz +
  9769. (word32)(pSz + qSz + gSz), outerSeq);
  9770. idx = SetSequence(algoSz + innerSeqSz + (word32)(pSz + qSz + gSz) +
  9771. bitStringSz + (word32)ySz + outerSeqSz, output);
  9772. /* check output size */
  9773. if ((idx + algoSz + bitStringSz + innerSeqSz +
  9774. (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen)
  9775. {
  9776. #ifdef WOLFSSL_SMALL_STACK
  9777. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9778. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9779. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9780. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9781. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9782. #endif
  9783. WOLFSSL_MSG("Error, output size smaller than outlen");
  9784. return BUFFER_E;
  9785. }
  9786. /* outerSeq */
  9787. XMEMCPY(output + idx, outerSeq, outerSeqSz);
  9788. idx += outerSeqSz;
  9789. /* algo */
  9790. XMEMCPY(output + idx, algo, algoSz);
  9791. idx += algoSz;
  9792. #ifdef WOLFSSL_SMALL_STACK
  9793. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9794. #endif
  9795. } else {
  9796. innerSeqSz = SetSequence((word32)(pSz + qSz + gSz + ySz), innerSeq);
  9797. /* check output size */
  9798. if ((innerSeqSz + (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen) {
  9799. #ifdef WOLFSSL_SMALL_STACK
  9800. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9801. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9802. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9803. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9804. #endif
  9805. WOLFSSL_MSG("Error, output size smaller than outlen");
  9806. return BUFFER_E;
  9807. }
  9808. idx = 0;
  9809. }
  9810. /* innerSeq */
  9811. XMEMCPY(output + idx, innerSeq, innerSeqSz);
  9812. idx += innerSeqSz;
  9813. /* p */
  9814. XMEMCPY(output + idx, p, (size_t)pSz);
  9815. idx += (word32)pSz;
  9816. /* q */
  9817. XMEMCPY(output + idx, q, (size_t)qSz);
  9818. idx += (word32)qSz;
  9819. /* g */
  9820. XMEMCPY(output + idx, g, (size_t)gSz);
  9821. idx += (word32)gSz;
  9822. /* bit string */
  9823. if (bitStringSz > 0) {
  9824. XMEMCPY(output + idx, bitString, bitStringSz);
  9825. idx += bitStringSz;
  9826. }
  9827. /* y */
  9828. XMEMCPY(output + idx, y, (size_t)ySz);
  9829. idx += (word32)ySz;
  9830. #ifdef WOLFSSL_SMALL_STACK
  9831. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9832. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9833. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9834. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9835. #endif
  9836. return (int)idx;
  9837. #else
  9838. DECL_ASNSETDATA(dataASN, dsaPubKeyASN_Length);
  9839. int ret = 0;
  9840. int i;
  9841. int sz = 0;
  9842. const ASNItem *data = NULL;
  9843. int count = 0;
  9844. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  9845. if ((output == NULL) || (key == NULL) || (outLen < MAX_SEQ_SZ)) {
  9846. ret = BAD_FUNC_ARG;
  9847. }
  9848. CALLOC_ASNSETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  9849. if (ret == 0) {
  9850. if (with_header) {
  9851. /* Using dsaPubKeyASN */
  9852. data = dsaPubKeyASN;
  9853. count = dsaPubKeyASN_Length;
  9854. /* Set the algorithm OID to write out. */
  9855. SetASN_OID(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID], DSAk, oidKeyType);
  9856. /* Set the mp_ints to encode - parameters and public value. */
  9857. for (i = 0; i < DSA_INTS - 2; i++) {
  9858. SetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
  9859. GetDsaInt(key, i));
  9860. }
  9861. SetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
  9862. }
  9863. else {
  9864. /* Using dsaKeyASN */
  9865. data = dsaKeyASN;
  9866. count = dsaPublicKeyASN_Length;
  9867. /* Set the mp_ints to encode - parameters and public value. */
  9868. for (i = 0; i < DSA_INTS - 1; i++) {
  9869. /* Move all DSA ints up one slot (ignore VERSION so now
  9870. * it means P) */
  9871. SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i],
  9872. GetDsaInt(key, i));
  9873. }
  9874. }
  9875. ret = SizeASN_Items(data, dataASN, count, &sz);
  9876. }
  9877. /* Check buffer is big enough for encoding. */
  9878. if ((ret == 0) && (sz > (int)outLen)) {
  9879. ret = BAD_FUNC_ARG;
  9880. }
  9881. /* Encode the DSA public key into output buffer. */
  9882. if (ret == 0) {
  9883. ret = SetASN_Items(data, dataASN, count, output);
  9884. }
  9885. FREE_ASNSETDATA(dataASN, key->heap);
  9886. return ret;
  9887. #endif /* WOLFSSL_ASN_TEMPLATE */
  9888. }
  9889. /* Encode a DSA public key into buffer.
  9890. *
  9891. * @param [out] output Buffer to hold encoded data.
  9892. * @param [in] key DSA key object.
  9893. * @param [out] outLen Length of buffer.
  9894. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  9895. * @return Size of encoded data in bytes on success.
  9896. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  9897. * than a minimal size (5 bytes), or buffer size is smaller than
  9898. * encoding size.
  9899. * @return MEMORY_E when dynamic memory allocation fails.
  9900. */
  9901. int wc_DsaKeyToPublicDer(DsaKey* key, byte* output, word32 inLen)
  9902. {
  9903. return wc_SetDsaPublicKey(output, key, (int)inLen, 1);
  9904. }
  9905. #endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */
  9906. static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen,
  9907. int ints, int includeVersion)
  9908. {
  9909. #ifndef WOLFSSL_ASN_TEMPLATE
  9910. word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen, j;
  9911. word32 sizes[DSA_INTS];
  9912. int i, ret = 0;
  9913. byte seq[MAX_SEQ_SZ];
  9914. byte ver[MAX_VERSION_SZ];
  9915. byte* tmps[DSA_INTS];
  9916. if (ints > DSA_INTS || inLen == NULL)
  9917. return BAD_FUNC_ARG;
  9918. XMEMSET(sizes, 0, sizeof(sizes));
  9919. for (i = 0; i < ints; i++)
  9920. tmps[i] = NULL;
  9921. /* write all big ints from key to DER tmps */
  9922. for (i = 0; i < ints; i++) {
  9923. int mpSz;
  9924. mp_int* keyInt = GetDsaInt(key, i);
  9925. word32 rawLen = (word32)mp_unsigned_bin_size(keyInt) + 1;
  9926. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  9927. DYNAMIC_TYPE_DSA);
  9928. if (tmps[i] == NULL) {
  9929. ret = MEMORY_E;
  9930. break;
  9931. }
  9932. mpSz = SetASNIntMP(keyInt, -1, tmps[i]);
  9933. if (mpSz < 0) {
  9934. ret = mpSz;
  9935. break;
  9936. }
  9937. sizes[i] = (word32)mpSz;
  9938. intTotalLen += (word32)mpSz;
  9939. }
  9940. if (ret != 0) {
  9941. FreeTmpDsas(tmps, key->heap, ints);
  9942. return ret;
  9943. }
  9944. /* make headers */
  9945. if (includeVersion)
  9946. verSz = (word32)SetMyVersion(0, ver, FALSE);
  9947. seqSz = SetSequence(verSz + intTotalLen, seq);
  9948. outLen = seqSz + verSz + intTotalLen;
  9949. *inLen = outLen;
  9950. if (output == NULL) {
  9951. FreeTmpDsas(tmps, key->heap, ints);
  9952. return LENGTH_ONLY_E;
  9953. }
  9954. if (outLen > *inLen) {
  9955. FreeTmpDsas(tmps, key->heap, ints);
  9956. return BAD_FUNC_ARG;
  9957. }
  9958. /* write to output */
  9959. XMEMCPY(output, seq, seqSz);
  9960. j = seqSz;
  9961. if (includeVersion) {
  9962. XMEMCPY(output + j, ver, verSz);
  9963. j += verSz;
  9964. }
  9965. for (i = 0; i < ints; i++) {
  9966. XMEMCPY(output + j, tmps[i], sizes[i]);
  9967. j += sizes[i];
  9968. }
  9969. FreeTmpDsas(tmps, key->heap, ints);
  9970. return (int)outLen;
  9971. #else
  9972. DECL_ASNSETDATA(dataASN, dsaKeyASN_Length);
  9973. int ret = 0;
  9974. int sz = 0;
  9975. (void)ints;
  9976. if ((key == NULL) || (inLen == NULL)) {
  9977. ret = BAD_FUNC_ARG;
  9978. }
  9979. if ((ret == 0) && (ints > DSA_INTS)) {
  9980. ret = BAD_FUNC_ARG;
  9981. }
  9982. CALLOC_ASNSETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  9983. if (ret == 0) {
  9984. int i;
  9985. if (includeVersion) {
  9986. /* Set the version. */
  9987. SetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], 0);
  9988. }
  9989. else {
  9990. dataASN[DSAKEYASN_IDX_VER].noOut = 1;
  9991. }
  9992. dataASN[DSAKEYASN_IDX_Y].noOut = mp_iszero(&key->y);
  9993. dataASN[DSAKEYASN_IDX_X].noOut = mp_iszero(&key->x);
  9994. /* Set the mp_ints to encode - params, public and private value. */
  9995. for (i = 0; i < DSA_INTS; i++) {
  9996. if (i < ints)
  9997. SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], GetDsaInt(key, i));
  9998. else
  9999. dataASN[(int)DSAKEYASN_IDX_P + i].noOut = 1;
  10000. }
  10001. /* Calculate size of the encoding. */
  10002. ret = SizeASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, &sz);
  10003. }
  10004. if ((ret == 0) && (output == NULL)) {
  10005. *inLen = (word32)sz;
  10006. ret = LENGTH_ONLY_E;
  10007. }
  10008. /* Check buffer is big enough for encoding. */
  10009. if ((ret == 0) && (sz > (int)*inLen)) {
  10010. ret = BAD_FUNC_ARG;
  10011. }
  10012. if (ret == 0) {
  10013. /* Encode the DSA private key into output buffer. */
  10014. SetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, output);
  10015. /* Return the size of the encoding. */
  10016. ret = sz;
  10017. }
  10018. FREE_ASNSETDATA(dataASN, key->heap);
  10019. return ret;
  10020. #endif /* WOLFSSL_ASN_TEMPLATE */
  10021. }
  10022. /* Encode a DSA private key into buffer.
  10023. *
  10024. * @param [in] key DSA key object.
  10025. * @param [out] output Buffer to hold encoded data.
  10026. * @param [out] inLen Length of buffer.
  10027. * @return Size of encoded data in bytes on success.
  10028. * @return BAD_FUNC_ARG when key or output is NULL, or key is not a private key
  10029. * or, buffer size is smaller than encoding size.
  10030. * @return MEMORY_E when dynamic memory allocation fails.
  10031. */
  10032. int wc_DsaKeyToDer(DsaKey* key, byte* output, word32 inLen)
  10033. {
  10034. if (!key || !output)
  10035. return BAD_FUNC_ARG;
  10036. if (key->type != DSA_PRIVATE)
  10037. return BAD_FUNC_ARG;
  10038. return DsaKeyIntsToDer(key, output, &inLen, DSA_INTS, 1);
  10039. }
  10040. /* Convert DsaKey parameters to DER format, write to output (inLen),
  10041. return bytes written. Version is excluded to be compatible with
  10042. OpenSSL d2i_DSAparams */
  10043. int wc_DsaKeyToParamsDer(DsaKey* key, byte* output, word32 inLen)
  10044. {
  10045. if (!key || !output)
  10046. return BAD_FUNC_ARG;
  10047. return DsaKeyIntsToDer(key, output, &inLen, DSA_PARAM_INTS, 0);
  10048. }
  10049. /* This version of the function allows output to be NULL. In that case, the
  10050. DsaKeyIntsToDer will return LENGTH_ONLY_E and the required output buffer
  10051. size will be pointed to by inLen. */
  10052. int wc_DsaKeyToParamsDer_ex(DsaKey* key, byte* output, word32* inLen)
  10053. {
  10054. if (!key || !inLen)
  10055. return BAD_FUNC_ARG;
  10056. return DsaKeyIntsToDer(key, output, inLen, DSA_PARAM_INTS, 0);
  10057. }
  10058. #endif /* NO_DSA */
  10059. /* Initialize decoded certificate object with buffer of DER encoding.
  10060. *
  10061. * @param [in, out] cert Decoded certificate object.
  10062. * @param [in] source Buffer containing DER encoded certificate.
  10063. * @param [in] inSz Size of DER data in buffer in bytes.
  10064. * @param [in] heap Dynamic memory hint.
  10065. */
  10066. void InitDecodedCert(DecodedCert* cert,
  10067. const byte* source, word32 inSz, void* heap)
  10068. {
  10069. InitDecodedCert_ex(cert, source, inSz, heap, INVALID_DEVID);
  10070. }
  10071. /* Initialize decoded certificate object with buffer of DER encoding.
  10072. *
  10073. * @param [in, out] cert Decoded certificate object.
  10074. * @param [in] source Buffer containing DER encoded certificate.
  10075. * @param [in] inSz Size of DER data in buffer in bytes.
  10076. * @param [in] heap Dynamic memory hint.
  10077. * @param [in] devId Crypto callback ID to use.
  10078. */
  10079. void InitDecodedCert_ex(DecodedCert* cert,
  10080. const byte* source, word32 inSz, void* heap, int devId)
  10081. {
  10082. if (cert != NULL) {
  10083. XMEMSET(cert, 0, sizeof(DecodedCert));
  10084. cert->subjectCNEnc = CTC_UTF8;
  10085. cert->issuer[0] = '\0';
  10086. cert->subject[0] = '\0';
  10087. cert->source = source; /* don't own */
  10088. cert->maxIdx = inSz; /* can't go over this index */
  10089. cert->heap = heap;
  10090. cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
  10091. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10092. #ifdef WOLFSSL_CERT_NAME_ALL
  10093. cert->subjectNEnc = CTC_UTF8;
  10094. cert->subjectIEnc = CTC_UTF8;
  10095. cert->subjectDNQEnc = CTC_UTF8;
  10096. cert->subjectGNEnc = CTC_UTF8;
  10097. #endif
  10098. cert->subjectSNEnc = CTC_UTF8;
  10099. cert->subjectCEnc = CTC_PRINTABLE;
  10100. cert->subjectLEnc = CTC_UTF8;
  10101. cert->subjectSTEnc = CTC_UTF8;
  10102. cert->subjectOEnc = CTC_UTF8;
  10103. cert->subjectOUEnc = CTC_UTF8;
  10104. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  10105. cert->issuerSNEnc = CTC_UTF8;
  10106. cert->issuerCEnc = CTC_PRINTABLE;
  10107. cert->issuerLEnc = CTC_UTF8;
  10108. cert->issuerSTEnc = CTC_UTF8;
  10109. cert->issuerOEnc = CTC_UTF8;
  10110. cert->issuerOUEnc = CTC_UTF8;
  10111. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  10112. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  10113. #ifndef NO_CERTS
  10114. InitSignatureCtx(&cert->sigCtx, heap, devId);
  10115. #endif
  10116. }
  10117. }
  10118. void wc_InitDecodedCert(DecodedCert* cert, const byte* source, word32 inSz,
  10119. void* heap)
  10120. {
  10121. InitDecodedCert(cert, source, inSz, heap);
  10122. }
  10123. /* Free the alternative names object.
  10124. *
  10125. * Frees each linked list items and its name.
  10126. *
  10127. * @param [in, out] altNames Alternative names.
  10128. * @param [in] heap Dynamic memory hint.
  10129. */
  10130. void FreeAltNames(DNS_entry* altNames, void* heap)
  10131. {
  10132. (void)heap;
  10133. while (altNames) {
  10134. DNS_entry* tmp = altNames->next;
  10135. XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
  10136. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  10137. XFREE(altNames->ipString, heap, DYNAMIC_TYPE_ALTNAME);
  10138. #endif
  10139. XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME);
  10140. altNames = tmp;
  10141. }
  10142. }
  10143. /* malloc and initialize a new alt name structure */
  10144. DNS_entry* AltNameNew(void* heap)
  10145. {
  10146. DNS_entry* ret;
  10147. ret = (DNS_entry*)XMALLOC(sizeof(DNS_entry), heap, DYNAMIC_TYPE_ALTNAME);
  10148. if (ret != NULL) {
  10149. XMEMSET(ret, 0, sizeof(DNS_entry));
  10150. }
  10151. (void)heap;
  10152. return ret;
  10153. }
  10154. #ifndef IGNORE_NAME_CONSTRAINTS
  10155. /* Free the subtree names object.
  10156. *
  10157. * Frees each linked list items and its name.
  10158. *
  10159. * @param [in, out] names Subtree names.
  10160. * @param [in] heap Dynamic memory hint.
  10161. */
  10162. void FreeNameSubtrees(Base_entry* names, void* heap)
  10163. {
  10164. (void)heap;
  10165. while (names) {
  10166. Base_entry* tmp = names->next;
  10167. XFREE(names->name, heap, DYNAMIC_TYPE_ALTNAME);
  10168. XFREE(names, heap, DYNAMIC_TYPE_ALTNAME);
  10169. names = tmp;
  10170. }
  10171. }
  10172. #endif /* IGNORE_NAME_CONSTRAINTS */
  10173. /* Free the decoded cert object's dynamic data.
  10174. *
  10175. * @param [in, out] cert Decoded certificate object.
  10176. */
  10177. void FreeDecodedCert(DecodedCert* cert)
  10178. {
  10179. if (cert == NULL)
  10180. return;
  10181. if (cert->subjectCNStored == 1) {
  10182. XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
  10183. }
  10184. if (cert->pubKeyStored == 1) {
  10185. XFREE((void*)cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  10186. }
  10187. if (cert->weOwnAltNames && cert->altNames)
  10188. FreeAltNames(cert->altNames, cert->heap);
  10189. #ifndef IGNORE_NAME_CONSTRAINTS
  10190. if (cert->altEmailNames)
  10191. FreeAltNames(cert->altEmailNames, cert->heap);
  10192. if (cert->altDirNames)
  10193. FreeAltNames(cert->altDirNames, cert->heap);
  10194. if (cert->permittedNames)
  10195. FreeNameSubtrees(cert->permittedNames, cert->heap);
  10196. if (cert->excludedNames)
  10197. FreeNameSubtrees(cert->excludedNames, cert->heap);
  10198. #endif /* IGNORE_NAME_CONSTRAINTS */
  10199. #ifdef WOLFSSL_SEP
  10200. XFREE(cert->deviceType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10201. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10202. XFREE(cert->hwSerialNum, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10203. #endif /* WOLFSSL_SEP */
  10204. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10205. if (cert->issuerName != NULL)
  10206. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->issuerName);
  10207. if (cert->subjectName != NULL)
  10208. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->subjectName);
  10209. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  10210. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10211. if (cert->sce_tsip_encRsaKeyIdx != NULL)
  10212. XFREE(cert->sce_tsip_encRsaKeyIdx, cert->heap, DYNAMIC_TYPE_RSA);
  10213. #endif
  10214. #ifndef NO_CERTS
  10215. FreeSignatureCtx(&cert->sigCtx);
  10216. #endif
  10217. }
  10218. void wc_FreeDecodedCert(DecodedCert* cert)
  10219. {
  10220. FreeDecodedCert(cert);
  10221. }
  10222. #ifndef WOLFSSL_ASN_TEMPLATE
  10223. static int GetCertHeader(DecodedCert* cert)
  10224. {
  10225. int ret = 0, len;
  10226. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  10227. return ASN_PARSE_E;
  10228. /* Reset the max index for the size indicated in the outer wrapper. */
  10229. cert->maxIdx = (word32)len + cert->srcIdx;
  10230. cert->certBegin = cert->srcIdx;
  10231. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  10232. return ASN_PARSE_E;
  10233. cert->sigIndex = (word32)len + cert->srcIdx;
  10234. if (cert->sigIndex > cert->maxIdx)
  10235. return ASN_PARSE_E;
  10236. if (GetExplicitVersion(cert->source, &cert->srcIdx, &cert->version,
  10237. cert->sigIndex) < 0)
  10238. return ASN_PARSE_E;
  10239. if (wc_GetSerialNumber(cert->source, &cert->srcIdx, cert->serial,
  10240. &cert->serialSz, cert->sigIndex) < 0)
  10241. return ASN_PARSE_E;
  10242. return ret;
  10243. }
  10244. #endif
  10245. #if defined(HAVE_ED25519) || defined(HAVE_ED448) || (defined(HAVE_PQC) && \
  10246. defined(HAVE_LIBOQS))
  10247. /* Store the key data under the BIT_STRING in dynamicly allocated data.
  10248. *
  10249. * @param [in, out] cert Certificate object.
  10250. * @param [in] source Buffer containing encoded key.
  10251. * @param [in, out] srcIdx On in, start of key data.
  10252. * On out, start of element after key data.
  10253. * @param [in] maxIdx Maximum index of certificate data.
  10254. */
  10255. static int StoreKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10256. word32 maxIdx)
  10257. {
  10258. int ret;
  10259. int length;
  10260. byte* publicKey;
  10261. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10262. if (ret == 0) {
  10263. #ifdef HAVE_OCSP
  10264. ret = CalcHashId(source + *srcIdx, (word32)length,
  10265. cert->subjectKeyHash);
  10266. }
  10267. if (ret == 0) {
  10268. #endif
  10269. publicKey = (byte*)XMALLOC((size_t)length, cert->heap,
  10270. DYNAMIC_TYPE_PUBLIC_KEY);
  10271. if (publicKey == NULL) {
  10272. ret = MEMORY_E;
  10273. }
  10274. else {
  10275. XMEMCPY(publicKey, &source[*srcIdx], (size_t)length);
  10276. cert->publicKey = publicKey;
  10277. cert->pubKeyStored = 1;
  10278. cert->pubKeySize = (word32)length;
  10279. *srcIdx += (word32)length;
  10280. }
  10281. }
  10282. return ret;
  10283. }
  10284. #endif /* HAVE_ED25519 || HAVE_ED448 */
  10285. #if !defined(NO_RSA)
  10286. #ifdef WOLFSSL_ASN_TEMPLATE
  10287. /* ASN.1 template for header before RSA key in certificate. */
  10288. static const ASNItem rsaCertKeyASN[] = {
  10289. /* STR */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  10290. /* SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  10291. };
  10292. enum {
  10293. RSACERTKEYASN_IDX_STR = 0,
  10294. RSACERTKEYASN_IDX_SEQ
  10295. };
  10296. /* Number of items in ASN.1 template for header before RSA key in cert. */
  10297. #define rsaCertKeyASN_Length (sizeof(rsaCertKeyASN) / sizeof(ASNItem))
  10298. #endif
  10299. /* Store RSA key pointer and length in certificate object.
  10300. *
  10301. * @param [in, out] cert Certificate object.
  10302. * @param [in] source Buffer containing encoded key.
  10303. * @param [in, out] srcIdx On in, start of RSA key data.
  10304. * On out, start of element after RSA key data.
  10305. * @param [in] maxIdx Maximum index of key data.
  10306. * @return 0 on success.
  10307. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10308. * is invalid.
  10309. * @return BUFFER_E when data in buffer is too small.
  10310. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10311. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10312. * non-zero length.
  10313. */
  10314. static int StoreRsaKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10315. word32 maxIdx)
  10316. {
  10317. #ifndef WOLFSSL_ASN_TEMPLATE
  10318. int length;
  10319. int pubLen;
  10320. word32 pubIdx;
  10321. if (CheckBitString(source, srcIdx, &pubLen, maxIdx, 1, NULL) != 0)
  10322. return ASN_PARSE_E;
  10323. pubIdx = *srcIdx;
  10324. if (GetSequence(source, srcIdx, &length, pubIdx + (word32)pubLen) < 0)
  10325. return ASN_PARSE_E;
  10326. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10327. cert->sigCtx.CertAtt.pubkey_n_start =
  10328. cert->sigCtx.CertAtt.pubkey_e_start = pubIdx;
  10329. #endif
  10330. cert->pubKeySize = (word32)pubLen;
  10331. cert->publicKey = source + pubIdx;
  10332. #ifdef WOLFSSL_MAXQ10XX_TLS
  10333. cert->publicKeyIndex = pubIdx;
  10334. #endif
  10335. *srcIdx += (word32)length;
  10336. #ifdef HAVE_OCSP
  10337. return CalcHashId(cert->publicKey, cert->pubKeySize, cert->subjectKeyHash);
  10338. #else
  10339. return 0;
  10340. #endif
  10341. #else
  10342. ASNGetData dataASN[rsaCertKeyASN_Length];
  10343. int ret;
  10344. /* No dynamic data. */
  10345. XMEMSET(dataASN, 0, sizeof(dataASN));
  10346. /* Decode the header before the key data. */
  10347. ret = GetASN_Items(rsaCertKeyASN, dataASN, rsaCertKeyASN_Length, 1, source,
  10348. srcIdx, maxIdx);
  10349. if (ret == 0) {
  10350. /* Store the pointer and length in certificate object starting at
  10351. * SEQUENCE. */
  10352. GetASN_GetConstRef(&dataASN[RSACERTKEYASN_IDX_STR],
  10353. &cert->publicKey, &cert->pubKeySize);
  10354. #ifdef WOLFSSL_MAXQ10XX_TLS
  10355. cert->publicKeyIndex = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
  10356. #endif
  10357. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10358. /* Start of SEQUENCE. */
  10359. cert->sigCtx.CertAtt.pubkey_n_start =
  10360. cert->sigCtx.CertAtt.pubkey_e_start = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
  10361. #endif
  10362. #ifdef HAVE_OCSP
  10363. /* Calculate the hash of the public key for OCSP. */
  10364. ret = CalcHashId(cert->publicKey, cert->pubKeySize,
  10365. cert->subjectKeyHash);
  10366. #endif
  10367. }
  10368. return ret;
  10369. #endif /* WOLFSSL_ASN_TEMPLATE */
  10370. }
  10371. #endif /* !NO_RSA */
  10372. #ifdef HAVE_ECC
  10373. #ifdef WOLFSSL_ASN_TEMPLATE
  10374. /* ASN.1 template for header before ECC key in certificate. */
  10375. static const ASNItem eccCertKeyASN[] = {
  10376. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 2 },
  10377. /* Algo parameters */
  10378. /* PARAMS */ { 1, ASN_SEQUENCE, 1, 0, 2 },
  10379. /* Subject public key */
  10380. /* SUBJPUBKEY */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  10381. };
  10382. enum {
  10383. ECCCERTKEYASN_IDX_OID = 0,
  10384. ECCCERTKEYASN_IDX_PARAMS,
  10385. ECCCERTKEYASN_IDX_SUBJPUBKEY
  10386. };
  10387. /* Number of items in ASN.1 template for header before ECC key in cert. */
  10388. #define eccCertKeyASN_Length (sizeof(eccCertKeyASN) / sizeof(ASNItem))
  10389. #endif /* WOLFSSL_ASN_TEMPLATE */
  10390. /* Store public ECC key in certificate object.
  10391. *
  10392. * Parse parameters and store public key data.
  10393. *
  10394. * @param [in, out] cert Certificate object.
  10395. * @param [in] source Buffer containing encoded key.
  10396. * @param [in, out] srcIdx On in, start of ECC key data.
  10397. * On out, start of element after ECC key data.
  10398. * @param [in] maxIdx Maximum index of key data.
  10399. * @param [in] pubKey Buffer holding encoded public key.
  10400. * @param [in] pubKeyLen Length of encoded public key in bytes.
  10401. * @return 0 on success.
  10402. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10403. * is invalid.
  10404. * @return BUFFER_E when data in buffer is too small.
  10405. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  10406. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10407. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10408. * non-zero length.
  10409. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  10410. */
  10411. static int StoreEccKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10412. word32 maxIdx, const byte* pubKey, word32 pubKeyLen)
  10413. {
  10414. #ifndef WOLFSSL_ASN_TEMPLATE
  10415. int ret;
  10416. word32 localIdx;
  10417. byte* publicKey;
  10418. byte tag;
  10419. int length;
  10420. localIdx = *srcIdx;
  10421. if (GetASNTag(source, &localIdx, &tag, maxIdx) < 0)
  10422. return ASN_PARSE_E;
  10423. if (tag != (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  10424. if (GetObjectId(source, srcIdx, &cert->pkCurveOID, oidCurveType,
  10425. maxIdx) < 0)
  10426. return ASN_PARSE_E;
  10427. if ((ret = CheckCurve(cert->pkCurveOID)) < 0)
  10428. return ECC_CURVE_OID_E;
  10429. #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  10430. cert->sigCtx.CertAtt.curve_id = ret;
  10431. #else
  10432. (void)ret;
  10433. #endif
  10434. /* key header */
  10435. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10436. if (ret != 0)
  10437. return ret;
  10438. #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  10439. cert->sigCtx.CertAtt.pubkey_n_start =
  10440. cert->sigCtx.CertAtt.pubkey_e_start = (*srcIdx + 1);
  10441. cert->sigCtx.CertAtt.pubkey_n_len = ((length - 1) >> 1);
  10442. cert->sigCtx.CertAtt.pubkey_e_start +=
  10443. cert->sigCtx.CertAtt.pubkey_n_len;
  10444. cert->sigCtx.CertAtt.pubkey_e_len =
  10445. cert->sigCtx.CertAtt.pubkey_n_len;
  10446. #endif
  10447. #ifdef WOLFSSL_MAXQ10XX_TLS
  10448. cert->publicKeyIndex = *srcIdx + 1;
  10449. #endif
  10450. #ifdef HAVE_OCSP
  10451. ret = CalcHashId(source + *srcIdx, (word32)length,
  10452. cert->subjectKeyHash);
  10453. if (ret != 0)
  10454. return ret;
  10455. #endif
  10456. *srcIdx += (word32)length;
  10457. }
  10458. publicKey = (byte*)XMALLOC(pubKeyLen, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  10459. if (publicKey == NULL)
  10460. return MEMORY_E;
  10461. XMEMCPY(publicKey, pubKey, pubKeyLen);
  10462. cert->publicKey = publicKey;
  10463. cert->pubKeyStored = 1;
  10464. cert->pubKeySize = pubKeyLen;
  10465. return 0;
  10466. #else
  10467. int ret = 0;
  10468. DECL_ASNGETDATA(dataASN, eccCertKeyASN_Length);
  10469. byte* publicKey;
  10470. /* Clear dynamic data and check OID is a curve. */
  10471. CALLOC_ASNGETDATA(dataASN, eccCertKeyASN_Length, ret, cert->heap);
  10472. if (ret == 0) {
  10473. GetASN_OID(&dataASN[ECCCERTKEYASN_IDX_OID], oidCurveType);
  10474. /* Parse ECC public key header. */
  10475. ret = GetASN_Items(eccCertKeyASN, dataASN, eccCertKeyASN_Length, 1,
  10476. source, srcIdx, maxIdx);
  10477. }
  10478. if (ret == 0) {
  10479. if (dataASN[ECCCERTKEYASN_IDX_OID].tag != 0) {
  10480. /* Store curve OID. */
  10481. cert->pkCurveOID = dataASN[ECCCERTKEYASN_IDX_OID].data.oid.sum;
  10482. }
  10483. /* Ignore explicit parameters. */
  10484. #ifdef WOLFSSL_MAXQ10XX_TLS
  10485. cert->publicKeyIndex =
  10486. GetASNItem_DataIdx(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY], source)
  10487. + 1;
  10488. #endif
  10489. #ifdef HAVE_OCSP
  10490. /* Calculate the hash of the subject public key for OCSP. */
  10491. ret = CalcHashId(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.data,
  10492. dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.length,
  10493. cert->subjectKeyHash);
  10494. }
  10495. if (ret == 0) {
  10496. #endif
  10497. /* Store public key data length. */
  10498. cert->pubKeySize = pubKeyLen;
  10499. /* Must allocated space for key.
  10500. * Don't memcpy into constant pointer so use temp. */
  10501. publicKey = (byte*)XMALLOC(cert->pubKeySize, cert->heap,
  10502. DYNAMIC_TYPE_PUBLIC_KEY);
  10503. if (publicKey == NULL) {
  10504. ret = MEMORY_E;
  10505. }
  10506. else {
  10507. /* Copy in whole public key and store pointer. */
  10508. XMEMCPY(publicKey, pubKey, cert->pubKeySize);
  10509. cert->publicKey = publicKey;
  10510. /* Indicate publicKey needs to be freed. */
  10511. cert->pubKeyStored = 1;
  10512. }
  10513. }
  10514. FREE_ASNGETDATA(dataASN, cert->heap);
  10515. return ret;
  10516. #endif /* WOLFSSL_ASN_TEMPLATE */
  10517. }
  10518. #endif /* HAVE_ECC */
  10519. #if !defined(NO_DSA)
  10520. #ifdef WOLFSSL_ASN_TEMPLATE
  10521. /* ASN.1 template for DSA key in certificate.
  10522. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  10523. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  10524. */
  10525. static const ASNItem dsaCertKeyASN[] = {
  10526. /* 0 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  10527. /* 1 */ { 2, ASN_INTEGER, 0, 0, 0 },
  10528. /* 2 */ { 2, ASN_INTEGER, 0, 0, 0 },
  10529. /* 3 */ { 2, ASN_INTEGER, 0, 0, 0 },
  10530. /* 4 */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  10531. /* 5 */ { 1, ASN_INTEGER, 0, 0, 0 },
  10532. };
  10533. /* Number of items in ASN.1 template for DSA key in certificate. */
  10534. #define dsaCertKeyASN_Length (sizeof(dsaCertKeyASN) / sizeof(ASNItem))
  10535. #endif /* WOLFSSL_ASN_TEMPLATE */
  10536. /* Parse DSA parameters to ensure valid.
  10537. *
  10538. * @param [in] source Buffer containing encoded key.
  10539. * @param [in, out] srcIdx On in, start of DSA key data.
  10540. * On out, start of element after DSA key data.
  10541. * @param [in] maxIdx Maximum index of key data.
  10542. * @param [in] heap Dynamic memory hint.
  10543. * @return 0 on success.
  10544. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10545. * is invalid.
  10546. * @return BUFFER_E when data in buffer is too small.
  10547. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10548. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10549. * non-zero length.
  10550. */
  10551. static int ParseDsaKey(const byte* source, word32* srcIdx, word32 maxIdx,
  10552. void* heap)
  10553. {
  10554. #ifndef WOLFSSL_ASN_TEMPLATE
  10555. int ret;
  10556. int length;
  10557. (void)heap;
  10558. ret = GetSequence(source, srcIdx, &length, maxIdx);
  10559. if (ret < 0)
  10560. return ret;
  10561. ret = SkipInt(source, srcIdx, maxIdx);
  10562. if (ret != 0)
  10563. return ret;
  10564. ret = SkipInt(source, srcIdx, maxIdx);
  10565. if (ret != 0)
  10566. return ret;
  10567. ret = SkipInt(source, srcIdx, maxIdx);
  10568. if (ret != 0)
  10569. return ret;
  10570. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10571. if (ret != 0)
  10572. return ret;
  10573. ret = GetASNInt(source, srcIdx, &length, maxIdx);
  10574. if (ret != 0)
  10575. return ASN_PARSE_E;
  10576. *srcIdx += (word32)length;
  10577. return 0;
  10578. #else
  10579. DECL_ASNGETDATA(dataASN, dsaCertKeyASN_Length);
  10580. int ret = 0;
  10581. (void)heap;
  10582. CALLOC_ASNGETDATA(dataASN, dsaCertKeyASN_Length, ret, heap);
  10583. if (ret == 0) {
  10584. /* Parse the DSA key data to ensure valid. */
  10585. ret = GetASN_Items(dsaCertKeyASN, dataASN, dsaCertKeyASN_Length, 1,
  10586. source, srcIdx, maxIdx);
  10587. }
  10588. FREE_ASNGETDATA(dataASN, heap);
  10589. return ret;
  10590. #endif /* WOLFSSL_ASN_TEMPLATE */
  10591. }
  10592. #endif /* !NO_DSA */
  10593. /* Decode the SubjectPublicKeyInfo block in a certificate.
  10594. *
  10595. * Stores the public key in fields of the certificate object.
  10596. * Validates the BER/DER items and does not store in a key object.
  10597. *
  10598. * @param [in, out] cert Decoded certificate oject.
  10599. * @param [in] source BER/DER encoded SubjectPublicKeyInfo block.
  10600. * @param [in, out] inOutIdx On in, start of public key.
  10601. * On out, start of ASN.1 item after public key.
  10602. * @param [in] maxIdx Maximum index of key data.
  10603. * @return 0 on success.
  10604. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10605. * is invalid.
  10606. * @return BUFFER_E when data in buffer is too small.
  10607. */
  10608. static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx,
  10609. word32 maxIdx)
  10610. {
  10611. word32 srcIdx = *inOutIdx;
  10612. #if defined(HAVE_ECC) || !defined(NO_DSA)
  10613. int pubLen;
  10614. #endif
  10615. #if defined(HAVE_ECC) || !defined(NO_DSA)
  10616. int pubIdx = (int)srcIdx;
  10617. #endif
  10618. int ret = 0;
  10619. int length;
  10620. #ifndef WOLFSSL_ASN_TEMPLATE
  10621. if (GetSequence(source, &srcIdx, &length, maxIdx) < 0)
  10622. #else
  10623. /* Get SEQUENCE and expect all data to be accounted for. */
  10624. if (GetASN_Sequence(source, &srcIdx, &length, maxIdx, 1) != 0)
  10625. #endif
  10626. {
  10627. return ASN_PARSE_E;
  10628. }
  10629. #if defined(HAVE_ECC) || !defined(NO_DSA)
  10630. pubLen = (int)srcIdx - pubIdx + length;
  10631. #endif
  10632. maxIdx = srcIdx + (word32)length;
  10633. /* Decode the algorithm identifier for the key. */
  10634. if (GetAlgoId(source, &srcIdx, &cert->keyOID, oidKeyType, maxIdx) < 0) {
  10635. return ASN_PARSE_E;
  10636. }
  10637. (void)length;
  10638. /* Parse each type of public key. */
  10639. switch (cert->keyOID) {
  10640. #ifndef NO_RSA
  10641. #ifdef WC_RSA_PSS
  10642. case RSAPSSk:
  10643. if (srcIdx != maxIdx &&
  10644. source[srcIdx] == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  10645. word32 seqIdx = srcIdx;
  10646. int seqLen;
  10647. /* Not set when -1. */
  10648. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  10649. int mgf = -1;
  10650. int saltLen = 0;
  10651. /* Defaults for sig algorithm parameters. */
  10652. enum wc_HashType sigHash = WC_HASH_TYPE_SHA;
  10653. int sigMgf = WC_MGF1SHA1;
  10654. int sigSaltLen = 20;
  10655. if (GetSequence(source, &srcIdx, &seqLen, maxIdx) < 0) {
  10656. return ASN_PARSE_E;
  10657. }
  10658. /* Get the pubic key parameters. */
  10659. ret = DecodeRsaPssParams(source + seqIdx,
  10660. (word32)seqLen + srcIdx - seqIdx, &hash, &mgf, &saltLen);
  10661. if (ret != 0) {
  10662. return ASN_PARSE_E;
  10663. }
  10664. /* Get the signature parameters. */
  10665. ret = DecodeRsaPssParams(source + cert->sigParamsIndex,
  10666. cert->sigParamsLength, &sigHash, &sigMgf, &sigSaltLen);
  10667. if (ret != 0) {
  10668. return ASN_PARSE_E;
  10669. }
  10670. /* Validated signature params match public key params. */
  10671. if (hash != WC_HASH_TYPE_NONE && hash != sigHash) {
  10672. WOLFSSL_MSG("RSA PSS: hash not matching signature hash");
  10673. return ASN_PARSE_E;
  10674. }
  10675. if (mgf != -1 && mgf != sigMgf) {
  10676. WOLFSSL_MSG("RSA PSS: MGF not matching signature MGF");
  10677. return ASN_PARSE_E;
  10678. }
  10679. if (saltLen > sigSaltLen) {
  10680. WOLFSSL_MSG("RSA PSS: sig salt length too small");
  10681. return ASN_PARSE_E;
  10682. }
  10683. srcIdx += (word32)seqLen;
  10684. }
  10685. FALL_THROUGH;
  10686. #endif /* WC_RSA_PSS */
  10687. case RSAk:
  10688. ret = StoreRsaKey(cert, source, &srcIdx, maxIdx);
  10689. break;
  10690. #endif /* NO_RSA */
  10691. #ifdef HAVE_ECC
  10692. case ECDSAk:
  10693. ret = StoreEccKey(cert, source, &srcIdx, maxIdx, source + pubIdx,
  10694. (word32)pubLen);
  10695. break;
  10696. #endif /* HAVE_ECC */
  10697. #ifdef HAVE_ED25519
  10698. case ED25519k:
  10699. cert->pkCurveOID = ED25519k;
  10700. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10701. break;
  10702. #endif /* HAVE_ED25519 */
  10703. #ifdef HAVE_ED448
  10704. case ED448k:
  10705. cert->pkCurveOID = ED448k;
  10706. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10707. break;
  10708. #endif /* HAVE_ED448 */
  10709. #if defined(HAVE_PQC) && defined(HAVE_LIBOQS)
  10710. #ifdef HAVE_FALCON
  10711. case FALCON_LEVEL1k:
  10712. cert->pkCurveOID = FALCON_LEVEL1k;
  10713. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10714. break;
  10715. case FALCON_LEVEL5k:
  10716. cert->pkCurveOID = FALCON_LEVEL5k;
  10717. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10718. break;
  10719. #endif /* HAVE_FALCON */
  10720. #ifdef HAVE_DILITHIUM
  10721. case DILITHIUM_LEVEL2k:
  10722. cert->pkCurveOID = DILITHIUM_LEVEL2k;
  10723. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10724. break;
  10725. case DILITHIUM_LEVEL3k:
  10726. cert->pkCurveOID = DILITHIUM_LEVEL3k;
  10727. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10728. break;
  10729. case DILITHIUM_LEVEL5k:
  10730. cert->pkCurveOID = DILITHIUM_LEVEL5k;
  10731. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10732. break;
  10733. #endif /* HAVE_DILITHIUM */
  10734. #ifdef HAVE_SPHINCS
  10735. case SPHINCS_FAST_LEVEL1k:
  10736. cert->pkCurveOID = SPHINCS_FAST_LEVEL1k;
  10737. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10738. break;
  10739. case SPHINCS_FAST_LEVEL3k:
  10740. cert->pkCurveOID = SPHINCS_FAST_LEVEL3k;
  10741. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10742. break;
  10743. case SPHINCS_FAST_LEVEL5k:
  10744. cert->pkCurveOID = SPHINCS_FAST_LEVEL5k;
  10745. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10746. break;
  10747. case SPHINCS_SMALL_LEVEL1k:
  10748. cert->pkCurveOID = SPHINCS_SMALL_LEVEL1k;
  10749. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10750. break;
  10751. case SPHINCS_SMALL_LEVEL3k:
  10752. cert->pkCurveOID = SPHINCS_SMALL_LEVEL3k;
  10753. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10754. break;
  10755. case SPHINCS_SMALL_LEVEL5k:
  10756. cert->pkCurveOID = SPHINCS_SMALL_LEVEL5k;
  10757. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10758. break;
  10759. #endif /* HAVE_SPHINCS */
  10760. #endif /* HAVE_PQC */
  10761. #ifndef NO_DSA
  10762. case DSAk:
  10763. cert->publicKey = source + pubIdx;
  10764. cert->pubKeySize = (word32)pubLen;
  10765. ret = ParseDsaKey(source, &srcIdx, maxIdx, cert->heap);
  10766. break;
  10767. #endif /* NO_DSA */
  10768. default:
  10769. WOLFSSL_MSG("Unknown or not compiled in key OID");
  10770. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  10771. ret = ASN_UNKNOWN_OID_E;
  10772. }
  10773. /* Return index after public key. */
  10774. *inOutIdx = srcIdx;
  10775. /* Return error code. */
  10776. return ret;
  10777. }
  10778. /* Calculate hash of the id using the SHA-1 or SHA-256.
  10779. *
  10780. * @param [in] data Data to hash.
  10781. * @param [in] len Length of data to hash.
  10782. * @param [out] hash Buffer to hold hash.
  10783. * @return 0 on success.
  10784. * @return MEMORY_E when dynamic memory allocation fails.
  10785. */
  10786. int CalcHashId(const byte* data, word32 len, byte* hash)
  10787. {
  10788. int ret;
  10789. #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
  10790. ret = wc_Sha256Hash(data, len, hash);
  10791. #elif !defined(NO_SHA)
  10792. ret = wc_ShaHash(data, len, hash);
  10793. #else
  10794. ret = NOT_COMPILED_IN;
  10795. (void)data;
  10796. (void)len;
  10797. (void)hash;
  10798. #endif
  10799. return ret;
  10800. }
  10801. #ifndef NO_CERTS
  10802. /* Get the hash of the id using the SHA-1 or SHA-256.
  10803. *
  10804. * If the id is not the length of the hash, then hash it.
  10805. *
  10806. * @param [in] id Id to get hash for.
  10807. * @param [in] len Length of id in bytes.
  10808. * @param [out] hash Buffer to hold hash.
  10809. * @return 0 on success.
  10810. * @return MEMORY_E when dynamic memory allocation fails.
  10811. */
  10812. static int GetHashId(const byte* id, int length, byte* hash)
  10813. {
  10814. int ret;
  10815. if (length == KEYID_SIZE) {
  10816. XMEMCPY(hash, id, (size_t)length);
  10817. ret = 0;
  10818. }
  10819. else {
  10820. ret = CalcHashId(id, (word32)length, hash);
  10821. }
  10822. return ret;
  10823. }
  10824. #endif /* !NO_CERTS */
  10825. #ifdef WOLFSSL_ASN_TEMPLATE
  10826. /* Id for email address. */
  10827. #define ASN_EMAIL 0x100
  10828. /* Id for domain component. */
  10829. #define ASN_DC 0x102
  10830. /* Id for jurisdiction country. */
  10831. #define ASN_JURIS_C 0x203
  10832. /* Id for jurisdiction state. */
  10833. #define ASN_JURIS_ST 0x202
  10834. /* Set the string for a name component into the subject name. */
  10835. #define SetCertNameSubject(cert, id, val) \
  10836. *((char**)(((byte *)(cert)) + certNameSubject[(id) - 3].data)) = (val)
  10837. /* Set the string length for a name component into the subject name. */
  10838. #define SetCertNameSubjectLen(cert, id, val) \
  10839. *((int*)(((byte *)(cert)) + certNameSubject[(id) - 3].len)) = (int)(val)
  10840. /* Set the encoding for a name component into the subject name. */
  10841. #define SetCertNameSubjectEnc(cert, id, val) \
  10842. *((byte*)(((byte *)(cert)) + certNameSubject[(id) - 3].enc)) = (val)
  10843. /* Get the string of a name component from the subject name. */
  10844. #define GetCertNameSubjectStr(id) \
  10845. (certNameSubject[(id) - 3].str)
  10846. /* Get the string length of a name component from the subject name. */
  10847. #define GetCertNameSubjectStrLen(id) \
  10848. (certNameSubject[(id) - 3].strLen)
  10849. /* Get the NID of a name component from the subject name. */
  10850. #define GetCertNameSubjectNID(id) \
  10851. (certNameSubject[(id) - 3].nid)
  10852. #define ValidCertNameSubject(id) \
  10853. (((id) - 3) >= 0 && ((id) - 3) < certNameSubjectSz && \
  10854. (certNameSubject[(id) - 3].strLen > 0))
  10855. /* Mapping of certificate name component to useful information. */
  10856. typedef struct CertNameData {
  10857. /* Type string of name component. */
  10858. const char* str;
  10859. /* Length of type string of name component. */
  10860. byte strLen;
  10861. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10862. /* Offset of data in subject name component. */
  10863. size_t data;
  10864. /* Offset of length in subject name component. */
  10865. size_t len;
  10866. /* Offset of encoding in subject name component. */
  10867. size_t enc;
  10868. #endif
  10869. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10870. /* NID of type for subject name component. */
  10871. int nid;
  10872. #endif
  10873. } CertNameData;
  10874. /* List of data for common name components. */
  10875. static const CertNameData certNameSubject[] = {
  10876. /* Common Name */
  10877. {
  10878. "/CN=", 4,
  10879. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10880. OFFSETOF(DecodedCert, subjectCN),
  10881. OFFSETOF(DecodedCert, subjectCNLen),
  10882. OFFSETOF(DecodedCert, subjectCNEnc),
  10883. #endif
  10884. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10885. NID_commonName
  10886. #endif
  10887. },
  10888. /* Surname */
  10889. {
  10890. "/SN=", 4,
  10891. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10892. OFFSETOF(DecodedCert, subjectSN),
  10893. OFFSETOF(DecodedCert, subjectSNLen),
  10894. OFFSETOF(DecodedCert, subjectSNEnc),
  10895. #endif
  10896. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10897. NID_surname
  10898. #endif
  10899. },
  10900. /* Serial Number */
  10901. {
  10902. "/serialNumber=", 14,
  10903. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10904. OFFSETOF(DecodedCert, subjectSND),
  10905. OFFSETOF(DecodedCert, subjectSNDLen),
  10906. OFFSETOF(DecodedCert, subjectSNDEnc),
  10907. #endif
  10908. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10909. NID_serialNumber
  10910. #endif
  10911. },
  10912. /* Country Name */
  10913. {
  10914. "/C=", 3,
  10915. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10916. OFFSETOF(DecodedCert, subjectC),
  10917. OFFSETOF(DecodedCert, subjectCLen),
  10918. OFFSETOF(DecodedCert, subjectCEnc),
  10919. #endif
  10920. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10921. NID_countryName
  10922. #endif
  10923. },
  10924. /* Locality Name */
  10925. {
  10926. "/L=", 3,
  10927. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10928. OFFSETOF(DecodedCert, subjectL),
  10929. OFFSETOF(DecodedCert, subjectLLen),
  10930. OFFSETOF(DecodedCert, subjectLEnc),
  10931. #endif
  10932. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10933. NID_localityName
  10934. #endif
  10935. },
  10936. /* State Name */
  10937. {
  10938. "/ST=", 4,
  10939. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10940. OFFSETOF(DecodedCert, subjectST),
  10941. OFFSETOF(DecodedCert, subjectSTLen),
  10942. OFFSETOF(DecodedCert, subjectSTEnc),
  10943. #endif
  10944. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10945. NID_stateOrProvinceName
  10946. #endif
  10947. },
  10948. /* Street Address */
  10949. {
  10950. "/street=", 8,
  10951. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10952. OFFSETOF(DecodedCert, subjectStreet),
  10953. OFFSETOF(DecodedCert, subjectStreetLen),
  10954. OFFSETOF(DecodedCert, subjectStreetEnc),
  10955. #endif
  10956. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10957. NID_streetAddress
  10958. #endif
  10959. },
  10960. /* Organization Name */
  10961. {
  10962. "/O=", 3,
  10963. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10964. OFFSETOF(DecodedCert, subjectO),
  10965. OFFSETOF(DecodedCert, subjectOLen),
  10966. OFFSETOF(DecodedCert, subjectOEnc),
  10967. #endif
  10968. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10969. NID_organizationName
  10970. #endif
  10971. },
  10972. /* Organization Unit Name */
  10973. {
  10974. "/OU=", 4,
  10975. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10976. OFFSETOF(DecodedCert, subjectOU),
  10977. OFFSETOF(DecodedCert, subjectOULen),
  10978. OFFSETOF(DecodedCert, subjectOUEnc),
  10979. #endif
  10980. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10981. NID_organizationalUnitName
  10982. #endif
  10983. },
  10984. /* Title */
  10985. {
  10986. NULL, 0,
  10987. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10988. 0,
  10989. 0,
  10990. 0,
  10991. #endif
  10992. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10993. 0,
  10994. #endif
  10995. },
  10996. /* Undefined */
  10997. {
  10998. NULL, 0,
  10999. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11000. 0,
  11001. 0,
  11002. 0,
  11003. #endif
  11004. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11005. 0,
  11006. #endif
  11007. },
  11008. /* Undefined */
  11009. {
  11010. NULL, 0,
  11011. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11012. 0,
  11013. 0,
  11014. 0,
  11015. #endif
  11016. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11017. 0,
  11018. #endif
  11019. },
  11020. /* Business Category */
  11021. {
  11022. "/businessCategory=", 18,
  11023. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11024. OFFSETOF(DecodedCert, subjectBC),
  11025. OFFSETOF(DecodedCert, subjectBCLen),
  11026. OFFSETOF(DecodedCert, subjectBCEnc),
  11027. #endif
  11028. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11029. NID_businessCategory
  11030. #endif
  11031. },
  11032. /* Undefined */
  11033. {
  11034. NULL, 0,
  11035. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11036. 0,
  11037. 0,
  11038. 0,
  11039. #endif
  11040. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11041. 0,
  11042. #endif
  11043. },
  11044. /* Postal Code */
  11045. {
  11046. "/postalCode=", 12,
  11047. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11048. OFFSETOF(DecodedCert, subjectPC),
  11049. OFFSETOF(DecodedCert, subjectPCLen),
  11050. OFFSETOF(DecodedCert, subjectPCEnc),
  11051. #endif
  11052. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11053. NID_postalCode
  11054. #endif
  11055. },
  11056. /* User Id */
  11057. {
  11058. "/userid=", 8,
  11059. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11060. OFFSETOF(DecodedCert, subjectUID),
  11061. OFFSETOF(DecodedCert, subjectUIDLen),
  11062. OFFSETOF(DecodedCert, subjectUIDEnc),
  11063. #endif
  11064. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11065. NID_userId
  11066. #endif
  11067. },
  11068. #ifdef WOLFSSL_CERT_NAME_ALL
  11069. /* Name, id 41 */
  11070. {
  11071. "/N=", 3,
  11072. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11073. OFFSETOF(DecodedCert, subjectN),
  11074. OFFSETOF(DecodedCert, subjectNLen),
  11075. OFFSETOF(DecodedCert, subjectNEnc),
  11076. #endif
  11077. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11078. NID_name
  11079. #endif
  11080. },
  11081. /* Given Name, id 42 */
  11082. {
  11083. "/GN=", 4,
  11084. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11085. OFFSETOF(DecodedCert, subjectGN),
  11086. OFFSETOF(DecodedCert, subjectGNLen),
  11087. OFFSETOF(DecodedCert, subjectGNEnc),
  11088. #endif
  11089. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11090. NID_givenName
  11091. #endif
  11092. },
  11093. /* initials, id 43 */
  11094. {
  11095. "/initials=", 10,
  11096. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11097. OFFSETOF(DecodedCert, subjectI),
  11098. OFFSETOF(DecodedCert, subjectILen),
  11099. OFFSETOF(DecodedCert, subjectIEnc),
  11100. #endif
  11101. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11102. NID_initials
  11103. #endif
  11104. },
  11105. /* DN Qualifier Name, id 46 */
  11106. {
  11107. "/dnQualifier=", 13,
  11108. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11109. OFFSETOF(DecodedCert, subjectDNQ),
  11110. OFFSETOF(DecodedCert, subjectDNQLen),
  11111. OFFSETOF(DecodedCert, subjectDNQEnc),
  11112. #endif
  11113. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11114. NID_dnQualifier
  11115. #endif
  11116. },
  11117. #endif /* WOLFSSL_CERT_NAME_ALL */
  11118. };
  11119. static const int certNameSubjectSz =
  11120. (int) (sizeof(certNameSubject) / sizeof(CertNameData));
  11121. /* ASN.1 template for an RDN.
  11122. * X.509: RFC 5280, 4.1.2.4 - RelativeDistinguishedName
  11123. */
  11124. static const ASNItem rdnASN[] = {
  11125. /* SET */ { 1, ASN_SET, 1, 1, 0 },
  11126. /* AttributeTypeAndValue */
  11127. /* ATTR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  11128. /* AttributeType */
  11129. /* ATTR_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  11130. /* AttributeValue: Choice of tags - rdnChoice. */
  11131. /* ATTR_VAL */ { 3, 0, 0, 0, 0 },
  11132. };
  11133. enum {
  11134. RDNASN_IDX_SET = 0,
  11135. RDNASN_IDX_ATTR_SEQ,
  11136. RDNASN_IDX_ATTR_TYPE,
  11137. RDNASN_IDX_ATTR_VAL
  11138. };
  11139. /* Number of items in ASN.1 template for an RDN. */
  11140. #define rdnASN_Length (sizeof(rdnASN) / sizeof(ASNItem))
  11141. /* Supported types of encodings (tags) for RDN strings.
  11142. * X.509: RFC 5280, 4.1.2.4 - DirectoryString
  11143. * (IA5 String not listed in RFC but required for alternative types)
  11144. */
  11145. static const byte rdnChoice[] = {
  11146. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, ASN_T61STRING,
  11147. ASN_UNIVERSALSTRING, ASN_BMPSTRING, 0
  11148. };
  11149. #endif
  11150. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  11151. /* used to set the human readable string for the IP address with a ASN_IP_TYPE
  11152. * DNS entry
  11153. * return 0 on success
  11154. */
  11155. static int GenerateDNSEntryIPString(DNS_entry* entry, void* heap)
  11156. {
  11157. int ret = 0;
  11158. int nameSz;
  11159. char tmpName[WOLFSSL_MAX_IPSTR] = {0};
  11160. char* ip;
  11161. if (entry == NULL || entry->type != ASN_IP_TYPE) {
  11162. return BAD_FUNC_ARG;
  11163. }
  11164. if (entry->len != WOLFSSL_IP4_ADDR_LEN &&
  11165. entry->len != WOLFSSL_IP6_ADDR_LEN) {
  11166. WOLFSSL_MSG("Unexpected IP size");
  11167. return BAD_FUNC_ARG;
  11168. }
  11169. ip = entry->name;
  11170. /* store IP addresses as a string */
  11171. if (entry->len == WOLFSSL_IP4_ADDR_LEN) {
  11172. if (XSNPRINTF(tmpName, sizeof(tmpName), "%u.%u.%u.%u", 0xFFU & ip[0],
  11173. 0xFFU & ip[1], 0xFFU & ip[2], 0xFFU & ip[3])
  11174. >= (int)sizeof(tmpName))
  11175. {
  11176. WOLFSSL_MSG("IP buffer overrun");
  11177. return BUFFER_E;
  11178. }
  11179. }
  11180. if (entry->len == WOLFSSL_IP6_ADDR_LEN) {
  11181. int i;
  11182. for (i = 0; i < 8; i++) {
  11183. if (XSNPRINTF(tmpName + i * 5, sizeof(tmpName) - i * 5,
  11184. "%02X%02X%s", 0xFF & ip[2 * i], 0xFF & ip[2 * i + 1],
  11185. (i < 7) ? ":" : "")
  11186. >= (int)sizeof(tmpName))
  11187. {
  11188. WOLFSSL_MSG("IPv6 buffer overrun");
  11189. return BUFFER_E;
  11190. }
  11191. }
  11192. }
  11193. nameSz = (int)XSTRLEN(tmpName);
  11194. entry->ipString = (char*)XMALLOC(nameSz + 1, heap, DYNAMIC_TYPE_ALTNAME);
  11195. if (entry->ipString == NULL) {
  11196. ret = MEMORY_E;
  11197. }
  11198. if (ret == 0) {
  11199. XMEMCPY(entry->ipString, tmpName, nameSz);
  11200. entry->ipString[nameSz] = '\0';
  11201. }
  11202. (void)heap;
  11203. return ret;
  11204. }
  11205. #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  11206. #ifdef WOLFSSL_ASN_TEMPLATE
  11207. #if defined(WOLFSSL_CERT_GEN) || !defined(NO_CERTS)
  11208. /* Adds a DNS entry to a list of DNS entries
  11209. *
  11210. * @param [in, out] lst Linked list of DNS name entries.
  11211. * @param [in] entry Entry to add to the list
  11212. * @return 0 on success.
  11213. */
  11214. static int AddDNSEntryToList(DNS_entry** lst, DNS_entry* entry)
  11215. {
  11216. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  11217. entry->next = NULL;
  11218. if (*lst == NULL) {
  11219. /* First on list */
  11220. *lst = entry;
  11221. }
  11222. else {
  11223. DNS_entry* temp = *lst;
  11224. /* Find end */
  11225. for (; (temp->next != NULL); temp = temp->next);
  11226. /* Add to end */
  11227. temp->next = entry;
  11228. }
  11229. #else
  11230. /* Prepend entry to linked list. */
  11231. entry->next = *lst;
  11232. *lst = entry;
  11233. #endif
  11234. return 0;
  11235. }
  11236. /* Allocate a DNS entry and set the fields.
  11237. *
  11238. * @param [in] cert Certificate object.
  11239. * @param [in] str DNS name string.
  11240. * @param [in] strLen Length of DNS name string.
  11241. * @param [in] type Type of DNS name string.
  11242. * @param [in, out] entries Linked list of DNS name entries.
  11243. * @return 0 on success.
  11244. * @return MEMORY_E when dynamic memory allocation fails.
  11245. */
  11246. static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen,
  11247. int type, DNS_entry** entries)
  11248. {
  11249. DNS_entry* dnsEntry;
  11250. int ret = 0;
  11251. /* Only used for heap. */
  11252. (void)cert;
  11253. /* TODO: consider one malloc. */
  11254. /* Allocate DNS Entry object. */
  11255. dnsEntry = AltNameNew(cert->heap);
  11256. if (dnsEntry == NULL) {
  11257. ret = MEMORY_E;
  11258. }
  11259. if (ret == 0) {
  11260. /* Allocate DNS Entry name - length of string plus 1 for NUL. */
  11261. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  11262. DYNAMIC_TYPE_ALTNAME);
  11263. if (dnsEntry->name == NULL) {
  11264. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11265. ret = MEMORY_E;
  11266. }
  11267. }
  11268. if (ret == 0) {
  11269. /* Set tag type, name length, name and NUL terminate name. */
  11270. dnsEntry->type = type;
  11271. dnsEntry->len = strLen;
  11272. XMEMCPY(dnsEntry->name, str, (size_t)strLen);
  11273. dnsEntry->name[strLen] = '\0';
  11274. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  11275. /* store IP addresses as a string */
  11276. if (type == ASN_IP_TYPE) {
  11277. if ((ret = GenerateDNSEntryIPString(dnsEntry, cert->heap)) != 0) {
  11278. XFREE(dnsEntry->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11279. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11280. }
  11281. }
  11282. #endif
  11283. }
  11284. if (ret == 0) {
  11285. ret = AddDNSEntryToList(entries, dnsEntry);
  11286. }
  11287. return ret;
  11288. }
  11289. #endif
  11290. /* Set the details of a subject name component into a certificate.
  11291. *
  11292. * @param [in, out] cert Certificate object.
  11293. * @param [in] id Id of component.
  11294. * @param [in] str String for component.
  11295. * @param [in] strLen Length of string.
  11296. * @param [in] tag BER tag representing encoding of string.
  11297. * @return 0 on success, negative values on failure.
  11298. */
  11299. static int SetSubject(DecodedCert* cert, int id, byte* str, int strLen,
  11300. byte tag)
  11301. {
  11302. int ret = 0;
  11303. /* Put string and encoding into certificate. */
  11304. if (id == ASN_COMMON_NAME) {
  11305. cert->subjectCN = (char *)str;
  11306. cert->subjectCNLen = (int)strLen;
  11307. cert->subjectCNEnc = (char)tag;
  11308. }
  11309. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11310. else if (id > ASN_COMMON_NAME && id <= ASN_USER_ID) {
  11311. /* Use table and offsets to put data into appropriate fields. */
  11312. SetCertNameSubject(cert, id, (char*)str);
  11313. SetCertNameSubjectLen(cert, id, strLen);
  11314. SetCertNameSubjectEnc(cert, id, tag);
  11315. }
  11316. #endif
  11317. #if !defined(IGNORE_NAME_CONSTRAINTS) || \
  11318. defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11319. else if (id == ASN_EMAIL) {
  11320. cert->subjectEmail = (char*)str;
  11321. cert->subjectEmailLen = strLen;
  11322. }
  11323. #endif
  11324. #ifdef WOLFSSL_CERT_EXT
  11325. /* TODO: consider mapping id to an index and using SetCertNameSubect*(). */
  11326. else if (id == ASN_JURIS_C) {
  11327. cert->subjectJC = (char*)str;
  11328. cert->subjectJCLen = strLen;
  11329. cert->subjectJCEnc = (char)tag;
  11330. }
  11331. else if (id == ASN_JURIS_ST) {
  11332. cert->subjectJS = (char*)str;
  11333. cert->subjectJSLen = strLen;
  11334. cert->subjectJSEnc = (char)tag;
  11335. }
  11336. #endif
  11337. return ret;
  11338. }
  11339. /* Get a RelativeDistinguishedName from the encoding and put in certificate.
  11340. *
  11341. * @param [in, out] cert Certificate object.
  11342. * @param [in, out] full Full name string. ([/<type>=<value>]*)
  11343. * @param [in, out] idx Index int full name to place next component.
  11344. * @param [in, out] nid NID of component type.
  11345. * @param [in] isSubject Whether this data is for a subject name.
  11346. * @param [in] dataASN Decoded data of RDN. Expected rdnASN type.
  11347. * @return 0 on success.
  11348. * @return MEMORY_E when dynamic memory allocation fails.
  11349. * @return ASN_PARSE_E when type not supported.
  11350. */
  11351. static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid,
  11352. int isSubject, ASNGetData* dataASN)
  11353. {
  11354. int ret = 0;
  11355. const char* typeStr = NULL;
  11356. byte typeStrLen = 0;
  11357. byte* oid;
  11358. word32 oidSz;
  11359. int id = 0;
  11360. (void)nid;
  11361. /* Get name type OID from data items. */
  11362. GetASN_OIDData(&dataASN[RDNASN_IDX_ATTR_TYPE], &oid, &oidSz);
  11363. /* v1 name types */
  11364. if ((oidSz == 3) && (oid[0] == 0x55) && (oid[1] == 0x04)) {
  11365. id = oid[2];
  11366. /* Check range of supported ids in table. */
  11367. if (ValidCertNameSubject(id)) {
  11368. /* Get the type string, length and NID from table. */
  11369. typeStr = GetCertNameSubjectStr(id);
  11370. typeStrLen = GetCertNameSubjectStrLen(id);
  11371. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11372. *nid = GetCertNameSubjectNID(id);
  11373. #endif
  11374. }
  11375. }
  11376. else if (oidSz == sizeof(attrEmailOid) && XMEMCMP(oid, attrEmailOid, oidSz) == 0) {
  11377. /* Set the email id, type string, length and NID. */
  11378. id = ASN_EMAIL;
  11379. typeStr = WOLFSSL_EMAIL_ADDR;
  11380. typeStrLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  11381. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11382. *nid = NID_emailAddress;
  11383. #endif
  11384. }
  11385. else if (oidSz == sizeof(uidOid) && XMEMCMP(oid, uidOid, oidSz) == 0) {
  11386. /* Set the user id, type string, length and NID. */
  11387. id = ASN_USER_ID;
  11388. typeStr = WOLFSSL_USER_ID;
  11389. typeStrLen = sizeof(WOLFSSL_USER_ID) - 1;
  11390. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11391. *nid = NID_userId;
  11392. #endif
  11393. }
  11394. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz) == 0) {
  11395. /* Set the domain component, type string, length and NID. */
  11396. id = ASN_DC;
  11397. typeStr = WOLFSSL_DOMAIN_COMPONENT;
  11398. typeStrLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  11399. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11400. *nid = NID_domainComponent;
  11401. #endif
  11402. }
  11403. else if (oidSz == sizeof(fvrtDrk) && XMEMCMP(oid, fvrtDrk, oidSz) == 0) {
  11404. /* Set the favourite drink, type string, length and NID. */
  11405. id = ASN_FAVOURITE_DRINK;
  11406. typeStr = WOLFSSL_FAVOURITE_DRINK;
  11407. typeStrLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
  11408. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11409. *nid = NID_favouriteDrink;
  11410. #endif
  11411. }
  11412. /* Other OIDs that start with the same values. */
  11413. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz-1) == 0) {
  11414. WOLFSSL_MSG("Unknown pilot attribute type");
  11415. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  11416. ret = ASN_PARSE_E;
  11417. }
  11418. else if (oidSz == ASN_JOI_PREFIX_SZ + 1 &&
  11419. XMEMCMP(oid, ASN_JOI_PREFIX, ASN_JOI_PREFIX_SZ) == 0) {
  11420. /* Set the jurisdiction id. */
  11421. id = 0x200 + oid[ASN_JOI_PREFIX_SZ];
  11422. /* Set the jurisdiction type string, length and NID if known. */
  11423. if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_C) {
  11424. typeStr = WOLFSSL_JOI_C;
  11425. typeStrLen = sizeof(WOLFSSL_JOI_C) - 1;
  11426. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11427. *nid = NID_jurisdictionCountryName;
  11428. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  11429. }
  11430. else if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_ST) {
  11431. typeStr = WOLFSSL_JOI_ST;
  11432. typeStrLen = sizeof(WOLFSSL_JOI_ST) - 1;
  11433. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11434. *nid = NID_jurisdictionStateOrProvinceName;
  11435. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  11436. }
  11437. else {
  11438. WOLFSSL_MSG("Unknown Jurisdiction, skipping");
  11439. }
  11440. }
  11441. if ((ret == 0) && (typeStr != NULL)) {
  11442. /* OID type to store for subject name and add to full string. */
  11443. byte* str;
  11444. word32 strLen;
  11445. byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
  11446. /* Get the string reference and length. */
  11447. GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
  11448. if (isSubject) {
  11449. /* Store subject field components. */
  11450. ret = SetSubject(cert, id, str, (int)strLen, tag);
  11451. }
  11452. if (ret == 0) {
  11453. /* Check there is space for this in the full name string and
  11454. * terminating NUL character. */
  11455. if ((typeStrLen + strLen) < (word32)(WC_ASN_NAME_MAX - *idx))
  11456. {
  11457. /* Add RDN to full string. */
  11458. XMEMCPY(&full[*idx], typeStr, typeStrLen);
  11459. *idx += typeStrLen;
  11460. XMEMCPY(&full[*idx], str, strLen);
  11461. *idx += strLen;
  11462. }
  11463. else {
  11464. WOLFSSL_MSG("ASN Name too big, skipping");
  11465. }
  11466. }
  11467. }
  11468. return ret;
  11469. }
  11470. #endif /* WOLFSSL_ASN_TEMPLATE */
  11471. /* Get a certificate name into the certificate object.
  11472. *
  11473. * @param [in, out] cert Decoded certificate object.
  11474. * @param [out] full Buffer to hold full name as a string.
  11475. * @param [out] hash Buffer to hold hash of name.
  11476. * @param [in] nameType ISSUER or SUBJECT.
  11477. * @param [in] input Buffer holding certificate name.
  11478. * @param [in, out] inOutIdx On in, start of certificate name.
  11479. * On out, start of ASN.1 item after cert name.
  11480. * @param [in] maxIdx Index of next item after certificate name.
  11481. * @return 0 on success.
  11482. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  11483. * is invalid.
  11484. * @return BUFFER_E when data in buffer is too small.
  11485. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  11486. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  11487. * @return MEMORY_E when dynamic memory allocation fails.
  11488. */
  11489. static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType,
  11490. const byte* input, word32* inOutIdx, word32 maxIdx)
  11491. {
  11492. #ifndef WOLFSSL_ASN_TEMPLATE
  11493. int length; /* length of all distinguished names */
  11494. int dummy;
  11495. int ret;
  11496. word32 idx;
  11497. word32 srcIdx = *inOutIdx;
  11498. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11499. !defined(WOLFCRYPT_ONLY)
  11500. WOLFSSL_X509_NAME* dName = NULL;
  11501. #endif
  11502. WOLFSSL_MSG("Getting Cert Name");
  11503. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  11504. * calculated over the entire DER encoding of the Name field, including
  11505. * the tag and length. */
  11506. if (CalcHashId(input + *inOutIdx, maxIdx - *inOutIdx, hash) != 0)
  11507. return ASN_PARSE_E;
  11508. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11509. !defined(WOLFCRYPT_ONLY)
  11510. dName = wolfSSL_X509_NAME_new();
  11511. if (dName == NULL) {
  11512. return MEMORY_E;
  11513. }
  11514. #endif /* OPENSSL_EXTRA */
  11515. if (GetSequence(input, &srcIdx, &length, maxIdx) < 0) {
  11516. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11517. !defined(WOLFCRYPT_ONLY)
  11518. wolfSSL_X509_NAME_free(dName);
  11519. #endif /* OPENSSL_EXTRA */
  11520. return ASN_PARSE_E;
  11521. }
  11522. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  11523. /* store pointer to raw issuer */
  11524. if (nameType == ISSUER) {
  11525. cert->issuerRaw = &input[srcIdx];
  11526. cert->issuerRawLen = length;
  11527. }
  11528. #endif
  11529. #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
  11530. if (nameType == SUBJECT) {
  11531. cert->subjectRaw = &input[srcIdx];
  11532. cert->subjectRawLen = length;
  11533. }
  11534. #endif
  11535. length += (int)srcIdx;
  11536. idx = 0;
  11537. while (srcIdx < (word32)length) {
  11538. byte b = 0;
  11539. byte joint[3];
  11540. byte tooBig = FALSE;
  11541. int oidSz;
  11542. const char* copy = NULL;
  11543. int copyLen = 0;
  11544. int strLen = 0;
  11545. byte id = 0;
  11546. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  11547. && !defined(WOLFCRYPT_ONLY)
  11548. int nid = NID_undef;
  11549. int enc;
  11550. #endif /* OPENSSL_EXTRA */
  11551. if (GetSet(input, &srcIdx, &dummy, maxIdx) < 0) {
  11552. WOLFSSL_MSG("Cert name lacks set header, trying sequence");
  11553. }
  11554. if (GetSequence(input, &srcIdx, &dummy, maxIdx) <= 0) {
  11555. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11556. !defined(WOLFCRYPT_ONLY)
  11557. wolfSSL_X509_NAME_free(dName);
  11558. #endif /* OPENSSL_EXTRA */
  11559. return ASN_PARSE_E;
  11560. }
  11561. ret = GetASNObjectId(input, &srcIdx, &oidSz, maxIdx);
  11562. if (ret != 0) {
  11563. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11564. !defined(WOLFCRYPT_ONLY)
  11565. wolfSSL_X509_NAME_free(dName);
  11566. #endif /* OPENSSL_EXTRA */
  11567. return ret;
  11568. }
  11569. /* make sure there is room for joint */
  11570. if ((srcIdx + sizeof(joint)) > (word32)maxIdx) {
  11571. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11572. !defined(WOLFCRYPT_ONLY)
  11573. wolfSSL_X509_NAME_free(dName);
  11574. #endif /* OPENSSL_EXTRA */
  11575. return ASN_PARSE_E;
  11576. }
  11577. XMEMCPY(joint, &input[srcIdx], sizeof(joint));
  11578. /* v1 name types */
  11579. if (joint[0] == 0x55 && joint[1] == 0x04) {
  11580. srcIdx += 3;
  11581. id = joint[2];
  11582. if (GetHeader(input, &b, &srcIdx, &strLen, maxIdx, 1) < 0) {
  11583. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11584. !defined(WOLFCRYPT_ONLY)
  11585. wolfSSL_X509_NAME_free(dName);
  11586. #endif /* OPENSSL_EXTRA */
  11587. return ASN_PARSE_E;
  11588. }
  11589. if (id == ASN_COMMON_NAME) {
  11590. if (nameType == SUBJECT) {
  11591. cert->subjectCN = (char *)&input[srcIdx];
  11592. cert->subjectCNLen = strLen;
  11593. cert->subjectCNEnc = (char)b;
  11594. }
  11595. #if (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)) && \
  11596. defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11597. else if (nameType == ISSUER) {
  11598. cert->issuerCN = (char*)&input[srcIdx];
  11599. cert->issuerCNLen = strLen;
  11600. cert->issuerCNEnc = (char)b;
  11601. }
  11602. #endif
  11603. copy = WOLFSSL_COMMON_NAME;
  11604. copyLen = sizeof(WOLFSSL_COMMON_NAME) - 1;
  11605. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  11606. && !defined(WOLFCRYPT_ONLY)
  11607. nid = NID_commonName;
  11608. #endif /* OPENSSL_EXTRA */
  11609. }
  11610. #ifdef WOLFSSL_CERT_NAME_ALL
  11611. else if (id == ASN_NAME) {
  11612. copy = WOLFSSL_NAME;
  11613. copyLen = sizeof(WOLFSSL_NAME) - 1;
  11614. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11615. if (nameType == SUBJECT) {
  11616. cert->subjectN = (char*)&input[srcIdx];
  11617. cert->subjectNLen = strLen;
  11618. cert->subjectNEnc = b;
  11619. }
  11620. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11621. #if (defined(OPENSSL_EXTRA) || \
  11622. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11623. && !defined(WOLFCRYPT_ONLY)
  11624. nid = NID_name;
  11625. #endif /* OPENSSL_EXTRA */
  11626. }
  11627. else if (id == ASN_INITIALS) {
  11628. copy = WOLFSSL_INITIALS;
  11629. copyLen = sizeof(WOLFSSL_INITIALS) - 1;
  11630. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11631. if (nameType == SUBJECT) {
  11632. cert->subjectI = (char*)&input[srcIdx];
  11633. cert->subjectILen = strLen;
  11634. cert->subjectIEnc = b;
  11635. }
  11636. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11637. #if (defined(OPENSSL_EXTRA) || \
  11638. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11639. && !defined(WOLFCRYPT_ONLY)
  11640. nid = NID_initials;
  11641. #endif /* OPENSSL_EXTRA */
  11642. }
  11643. else if (id == ASN_GIVEN_NAME) {
  11644. copy = WOLFSSL_GIVEN_NAME;
  11645. copyLen = sizeof(WOLFSSL_GIVEN_NAME) - 1;
  11646. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11647. if (nameType == SUBJECT) {
  11648. cert->subjectGN = (char*)&input[srcIdx];
  11649. cert->subjectGNLen = strLen;
  11650. cert->subjectGNEnc = b;
  11651. }
  11652. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11653. #if (defined(OPENSSL_EXTRA) || \
  11654. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11655. && !defined(WOLFCRYPT_ONLY)
  11656. nid = NID_givenName;
  11657. #endif /* OPENSSL_EXTRA */
  11658. }
  11659. else if (id == ASN_DNQUALIFIER) {
  11660. copy = WOLFSSL_DNQUALIFIER;
  11661. copyLen = sizeof(WOLFSSL_DNQUALIFIER) - 1;
  11662. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11663. if (nameType == SUBJECT) {
  11664. cert->subjectDNQ = (char*)&input[srcIdx];
  11665. cert->subjectDNQLen = strLen;
  11666. cert->subjectDNQEnc = b;
  11667. }
  11668. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11669. #if (defined(OPENSSL_EXTRA) || \
  11670. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11671. && !defined(WOLFCRYPT_ONLY)
  11672. nid = NID_dnQualifier;
  11673. #endif /* OPENSSL_EXTRA */
  11674. }
  11675. #endif /* WOLFSSL_CERT_NAME_ALL */
  11676. else if (id == ASN_SUR_NAME) {
  11677. copy = WOLFSSL_SUR_NAME;
  11678. copyLen = sizeof(WOLFSSL_SUR_NAME) - 1;
  11679. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11680. if (nameType == SUBJECT) {
  11681. cert->subjectSN = (char*)&input[srcIdx];
  11682. cert->subjectSNLen = strLen;
  11683. cert->subjectSNEnc = (char)b;
  11684. }
  11685. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11686. else if (nameType == ISSUER) {
  11687. cert->issuerSN = (char*)&input[srcIdx];
  11688. cert->issuerSNLen = strLen;
  11689. cert->issuerSNEnc = (char)b;
  11690. }
  11691. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11692. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11693. #if (defined(OPENSSL_EXTRA) || \
  11694. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11695. && !defined(WOLFCRYPT_ONLY)
  11696. nid = NID_surname;
  11697. #endif /* OPENSSL_EXTRA */
  11698. }
  11699. else if (id == ASN_COUNTRY_NAME) {
  11700. copy = WOLFSSL_COUNTRY_NAME;
  11701. copyLen = sizeof(WOLFSSL_COUNTRY_NAME) - 1;
  11702. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11703. if (nameType == SUBJECT) {
  11704. cert->subjectC = (char*)&input[srcIdx];
  11705. cert->subjectCLen = strLen;
  11706. cert->subjectCEnc = (char)b;
  11707. }
  11708. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11709. else if (nameType == ISSUER) {
  11710. cert->issuerC = (char*)&input[srcIdx];
  11711. cert->issuerCLen = strLen;
  11712. cert->issuerCEnc = (char)b;
  11713. }
  11714. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11715. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11716. #if (defined(OPENSSL_EXTRA) || \
  11717. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11718. && !defined(WOLFCRYPT_ONLY)
  11719. nid = NID_countryName;
  11720. #endif /* OPENSSL_EXTRA */
  11721. }
  11722. else if (id == ASN_LOCALITY_NAME) {
  11723. copy = WOLFSSL_LOCALITY_NAME;
  11724. copyLen = sizeof(WOLFSSL_LOCALITY_NAME) - 1;
  11725. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11726. if (nameType == SUBJECT) {
  11727. cert->subjectL = (char*)&input[srcIdx];
  11728. cert->subjectLLen = strLen;
  11729. cert->subjectLEnc = (char)b;
  11730. }
  11731. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11732. else if (nameType == ISSUER) {
  11733. cert->issuerL = (char*)&input[srcIdx];
  11734. cert->issuerLLen = strLen;
  11735. cert->issuerLEnc = (char)b;
  11736. }
  11737. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11738. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11739. #if (defined(OPENSSL_EXTRA) || \
  11740. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11741. && !defined(WOLFCRYPT_ONLY)
  11742. nid = NID_localityName;
  11743. #endif /* OPENSSL_EXTRA */
  11744. }
  11745. else if (id == ASN_STATE_NAME) {
  11746. copy = WOLFSSL_STATE_NAME;
  11747. copyLen = sizeof(WOLFSSL_STATE_NAME) - 1;
  11748. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11749. if (nameType == SUBJECT) {
  11750. cert->subjectST = (char*)&input[srcIdx];
  11751. cert->subjectSTLen = strLen;
  11752. cert->subjectSTEnc = (char)b;
  11753. }
  11754. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11755. else if (nameType == ISSUER) {
  11756. cert->issuerST = (char*)&input[srcIdx];
  11757. cert->issuerSTLen = strLen;
  11758. cert->issuerSTEnc = (char)b;
  11759. }
  11760. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11761. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
  11762. #if (defined(OPENSSL_EXTRA) || \
  11763. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11764. && !defined(WOLFCRYPT_ONLY)
  11765. nid = NID_stateOrProvinceName;
  11766. #endif /* OPENSSL_EXTRA */
  11767. }
  11768. else if (id == ASN_ORG_NAME) {
  11769. copy = WOLFSSL_ORG_NAME;
  11770. copyLen = sizeof(WOLFSSL_ORG_NAME) - 1;
  11771. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11772. if (nameType == SUBJECT) {
  11773. cert->subjectO = (char*)&input[srcIdx];
  11774. cert->subjectOLen = strLen;
  11775. cert->subjectOEnc = (char)b;
  11776. }
  11777. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11778. else if (nameType == ISSUER) {
  11779. cert->issuerO = (char*)&input[srcIdx];
  11780. cert->issuerOLen = strLen;
  11781. cert->issuerOEnc = (char)b;
  11782. }
  11783. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11784. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11785. #if (defined(OPENSSL_EXTRA) || \
  11786. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11787. && !defined(WOLFCRYPT_ONLY)
  11788. nid = NID_organizationName;
  11789. #endif /* OPENSSL_EXTRA */
  11790. }
  11791. else if (id == ASN_ORGUNIT_NAME) {
  11792. copy = WOLFSSL_ORGUNIT_NAME;
  11793. copyLen = sizeof(WOLFSSL_ORGUNIT_NAME) - 1;
  11794. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11795. if (nameType == SUBJECT) {
  11796. cert->subjectOU = (char*)&input[srcIdx];
  11797. cert->subjectOULen = strLen;
  11798. cert->subjectOUEnc = (char)b;
  11799. }
  11800. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11801. else if (nameType == ISSUER) {
  11802. cert->issuerOU = (char*)&input[srcIdx];
  11803. cert->issuerOULen = strLen;
  11804. cert->issuerOUEnc = (char)b;
  11805. }
  11806. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11807. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11808. #if (defined(OPENSSL_EXTRA) || \
  11809. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11810. && !defined(WOLFCRYPT_ONLY)
  11811. nid = NID_organizationalUnitName;
  11812. #endif /* OPENSSL_EXTRA */
  11813. }
  11814. else if (id == ASN_SERIAL_NUMBER) {
  11815. copy = WOLFSSL_SERIAL_NUMBER;
  11816. copyLen = sizeof(WOLFSSL_SERIAL_NUMBER) - 1;
  11817. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11818. if (nameType == SUBJECT) {
  11819. cert->subjectSND = (char*)&input[srcIdx];
  11820. cert->subjectSNDLen = strLen;
  11821. cert->subjectSNDEnc = (char)b;
  11822. }
  11823. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11824. else if (nameType == ISSUER) {
  11825. cert->issuerSND = (char*)&input[srcIdx];
  11826. cert->issuerSNDLen = strLen;
  11827. cert->issuerSNDEnc = (char)b;
  11828. }
  11829. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11830. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11831. #if (defined(OPENSSL_EXTRA) || \
  11832. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11833. && !defined(WOLFCRYPT_ONLY)
  11834. nid = NID_serialNumber;
  11835. #endif /* OPENSSL_EXTRA */
  11836. }
  11837. else if (id == ASN_USER_ID) {
  11838. copy = WOLFSSL_USER_ID;
  11839. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  11840. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11841. if (nameType == SUBJECT) {
  11842. cert->subjectUID = (char*)&input[srcIdx];
  11843. cert->subjectUIDLen = strLen;
  11844. cert->subjectUIDEnc = (char)b;
  11845. }
  11846. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11847. #if (defined(OPENSSL_EXTRA) || \
  11848. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11849. && !defined(WOLFCRYPT_ONLY)
  11850. nid = NID_userId;
  11851. #endif /* OPENSSL_EXTRA */
  11852. }
  11853. #ifdef WOLFSSL_CERT_EXT
  11854. else if (id == ASN_STREET_ADDR) {
  11855. copy = WOLFSSL_STREET_ADDR_NAME;
  11856. copyLen = sizeof(WOLFSSL_STREET_ADDR_NAME) - 1;
  11857. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11858. if (nameType == SUBJECT) {
  11859. cert->subjectStreet = (char*)&input[srcIdx];
  11860. cert->subjectStreetLen = strLen;
  11861. cert->subjectStreetEnc = (char)b;
  11862. }
  11863. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11864. #if (defined(OPENSSL_EXTRA) || \
  11865. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11866. && !defined(WOLFCRYPT_ONLY)
  11867. nid = NID_streetAddress;
  11868. #endif /* OPENSSL_EXTRA */
  11869. }
  11870. else if (id == ASN_BUS_CAT) {
  11871. copy = WOLFSSL_BUS_CAT;
  11872. copyLen = sizeof(WOLFSSL_BUS_CAT) - 1;
  11873. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11874. if (nameType == SUBJECT) {
  11875. cert->subjectBC = (char*)&input[srcIdx];
  11876. cert->subjectBCLen = strLen;
  11877. cert->subjectBCEnc = (char)b;
  11878. }
  11879. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11880. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  11881. && !defined(WOLFCRYPT_ONLY)
  11882. nid = NID_businessCategory;
  11883. #endif /* OPENSSL_EXTRA */
  11884. }
  11885. else if (id == ASN_POSTAL_CODE) {
  11886. copy = WOLFSSL_POSTAL_NAME;
  11887. copyLen = sizeof(WOLFSSL_POSTAL_NAME) - 1;
  11888. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11889. if (nameType == SUBJECT) {
  11890. cert->subjectPC = (char*)&input[srcIdx];
  11891. cert->subjectPCLen = strLen;
  11892. cert->subjectPCEnc = (char)b;
  11893. }
  11894. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
  11895. #if (defined(OPENSSL_EXTRA) || \
  11896. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11897. && !defined(WOLFCRYPT_ONLY)
  11898. nid = NID_postalCode;
  11899. #endif /* OPENSSL_EXTRA */
  11900. }
  11901. #endif /* WOLFSSL_CERT_EXT */
  11902. }
  11903. #ifdef WOLFSSL_CERT_EXT
  11904. else if ((srcIdx + ASN_JOI_PREFIX_SZ + 2 <= (word32)maxIdx) &&
  11905. (0 == XMEMCMP(&input[srcIdx], ASN_JOI_PREFIX,
  11906. ASN_JOI_PREFIX_SZ)) &&
  11907. ((input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_C) ||
  11908. (input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_ST)))
  11909. {
  11910. srcIdx += ASN_JOI_PREFIX_SZ;
  11911. id = input[srcIdx++];
  11912. b = input[srcIdx++]; /* encoding */
  11913. if (GetLength(input, &srcIdx, &strLen,
  11914. maxIdx) < 0) {
  11915. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11916. !defined(WOLFCRYPT_ONLY)
  11917. wolfSSL_X509_NAME_free(dName);
  11918. #endif /* OPENSSL_EXTRA */
  11919. return ASN_PARSE_E;
  11920. }
  11921. /* Check for jurisdiction of incorporation country name */
  11922. if (id == ASN_JOI_C) {
  11923. copy = WOLFSSL_JOI_C;
  11924. copyLen = sizeof(WOLFSSL_JOI_C) - 1;
  11925. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11926. if (nameType == SUBJECT) {
  11927. cert->subjectJC = (char*)&input[srcIdx];
  11928. cert->subjectJCLen = strLen;
  11929. cert->subjectJCEnc = (char)b;
  11930. }
  11931. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11932. #if (defined(OPENSSL_EXTRA) || \
  11933. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11934. && !defined(WOLFCRYPT_ONLY)
  11935. nid = NID_jurisdictionCountryName;
  11936. #endif /* OPENSSL_EXTRA */
  11937. }
  11938. /* Check for jurisdiction of incorporation state name */
  11939. else if (id == ASN_JOI_ST) {
  11940. copy = WOLFSSL_JOI_ST;
  11941. copyLen = sizeof(WOLFSSL_JOI_ST) - 1;
  11942. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11943. if (nameType == SUBJECT) {
  11944. cert->subjectJS = (char*)&input[srcIdx];
  11945. cert->subjectJSLen = strLen;
  11946. cert->subjectJSEnc = (char)b;
  11947. }
  11948. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11949. #if (defined(OPENSSL_EXTRA) || \
  11950. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11951. && !defined(WOLFCRYPT_ONLY)
  11952. nid = NID_jurisdictionStateOrProvinceName;
  11953. #endif /* OPENSSL_EXTRA */
  11954. }
  11955. if ((strLen + copyLen) > (int)(WC_ASN_NAME_MAX - idx)) {
  11956. WOLFSSL_MSG("ASN Name too big, skipping");
  11957. tooBig = TRUE;
  11958. }
  11959. }
  11960. #endif /* WOLFSSL_CERT_EXT */
  11961. else {
  11962. /* skip */
  11963. byte email = FALSE;
  11964. byte pilot = FALSE;
  11965. if (joint[0] == 0x2a && joint[1] == 0x86) { /* email id hdr 42.134.* */
  11966. id = ASN_EMAIL_NAME;
  11967. email = TRUE;
  11968. }
  11969. if (joint[0] == 0x9 && joint[1] == 0x92) { /* uid id hdr 9.146.* */
  11970. /* last value of OID is the type of pilot attribute */
  11971. id = input[srcIdx + (word32)oidSz - 1];
  11972. if (id == 0x01)
  11973. id = ASN_USER_ID;
  11974. pilot = TRUE;
  11975. }
  11976. srcIdx += (word32)oidSz + 1;
  11977. if (GetLength(input, &srcIdx, &strLen, maxIdx) < 0) {
  11978. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11979. !defined(WOLFCRYPT_ONLY)
  11980. wolfSSL_X509_NAME_free(dName);
  11981. #endif /* OPENSSL_EXTRA */
  11982. return ASN_PARSE_E;
  11983. }
  11984. if (strLen > (int)(WC_ASN_NAME_MAX - idx)) {
  11985. WOLFSSL_MSG("ASN name too big, skipping");
  11986. tooBig = TRUE;
  11987. }
  11988. if (email) {
  11989. copyLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  11990. if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx)) {
  11991. WOLFSSL_MSG("ASN name too big, skipping");
  11992. tooBig = TRUE;
  11993. }
  11994. else {
  11995. copy = WOLFSSL_EMAIL_ADDR;
  11996. }
  11997. #if !defined(IGNORE_NAME_CONSTRAINTS) || \
  11998. defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11999. if (nameType == SUBJECT) {
  12000. cert->subjectEmail = (char*)&input[srcIdx];
  12001. cert->subjectEmailLen = strLen;
  12002. }
  12003. #if defined(WOLFSSL_HAVE_ISSUER_NAMES) && \
  12004. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
  12005. else if (nameType == ISSUER) {
  12006. cert->issuerEmail = (char*)&input[srcIdx];
  12007. cert->issuerEmailLen = strLen;
  12008. }
  12009. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12010. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12011. #if (defined(OPENSSL_EXTRA) || \
  12012. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12013. && !defined(WOLFCRYPT_ONLY)
  12014. nid = NID_emailAddress;
  12015. #endif /* OPENSSL_EXTRA */
  12016. }
  12017. if (pilot) {
  12018. switch (id) {
  12019. case ASN_USER_ID:
  12020. copy = WOLFSSL_USER_ID;
  12021. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  12022. #if (defined(OPENSSL_EXTRA) || \
  12023. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12024. && !defined(WOLFCRYPT_ONLY)
  12025. nid = NID_userId;
  12026. #endif /* OPENSSL_EXTRA */
  12027. break;
  12028. case ASN_DOMAIN_COMPONENT:
  12029. copy = WOLFSSL_DOMAIN_COMPONENT;
  12030. copyLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  12031. #if (defined(OPENSSL_EXTRA) || \
  12032. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12033. && !defined(WOLFCRYPT_ONLY)
  12034. nid = NID_domainComponent;
  12035. #endif /* OPENSSL_EXTRA */
  12036. break;
  12037. case ASN_FAVOURITE_DRINK:
  12038. copy = WOLFSSL_FAVOURITE_DRINK;
  12039. copyLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
  12040. #if (defined(OPENSSL_EXTRA) || \
  12041. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12042. && !defined(WOLFCRYPT_ONLY)
  12043. nid = NID_favouriteDrink;
  12044. #endif /* OPENSSL_EXTRA */
  12045. break;
  12046. default:
  12047. WOLFSSL_MSG("Unknown pilot attribute type");
  12048. #if (defined(OPENSSL_EXTRA) || \
  12049. defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12050. !defined(WOLFCRYPT_ONLY)
  12051. wolfSSL_X509_NAME_free(dName);
  12052. #endif /* OPENSSL_EXTRA */
  12053. return ASN_PARSE_E;
  12054. }
  12055. }
  12056. }
  12057. if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx))
  12058. {
  12059. WOLFSSL_MSG("ASN Name too big, skipping");
  12060. tooBig = TRUE;
  12061. }
  12062. if ((copy != NULL) && !tooBig) {
  12063. XMEMCPY(&full[idx], copy, (size_t)copyLen);
  12064. idx += (word32)copyLen;
  12065. XMEMCPY(&full[idx], &input[srcIdx], (size_t)strLen);
  12066. idx += (word32)strLen;
  12067. }
  12068. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12069. !defined(WOLFCRYPT_ONLY)
  12070. switch (b) {
  12071. case CTC_UTF8:
  12072. enc = MBSTRING_UTF8;
  12073. break;
  12074. case CTC_PRINTABLE:
  12075. enc = V_ASN1_PRINTABLESTRING;
  12076. break;
  12077. default:
  12078. WOLFSSL_MSG("Unknown encoding type, using UTF8 by default");
  12079. enc = MBSTRING_UTF8;
  12080. }
  12081. if (nid != NID_undef) {
  12082. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc,
  12083. &input[srcIdx], strLen, -1, -1) !=
  12084. WOLFSSL_SUCCESS) {
  12085. wolfSSL_X509_NAME_free(dName);
  12086. return ASN_PARSE_E;
  12087. }
  12088. }
  12089. #endif /* OPENSSL_EXTRA */
  12090. srcIdx += (word32)strLen;
  12091. }
  12092. full[idx++] = 0;
  12093. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12094. !defined(WOLFCRYPT_ONLY)
  12095. if (nameType == ISSUER) {
  12096. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)) && \
  12097. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  12098. dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX);
  12099. XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
  12100. #endif
  12101. cert->issuerName = dName;
  12102. }
  12103. else {
  12104. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  12105. dName->rawLen = min(cert->subjectRawLen, WC_ASN_NAME_MAX);
  12106. XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
  12107. #endif
  12108. cert->subjectName = dName;
  12109. }
  12110. #endif
  12111. *inOutIdx = srcIdx;
  12112. return 0;
  12113. #else
  12114. DECL_ASNGETDATA(dataASN, rdnASN_Length);
  12115. int ret = 0;
  12116. word32 idx = 0;
  12117. int len;
  12118. word32 srcIdx = *inOutIdx;
  12119. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12120. WOLFSSL_X509_NAME* dName = NULL;
  12121. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12122. WOLFSSL_MSG("Getting Cert Name");
  12123. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  12124. * calculated over the entire DER encoding of the Name field, including
  12125. * the tag and length. */
  12126. if (CalcHashId(input + srcIdx, maxIdx - srcIdx, hash) != 0) {
  12127. ret = ASN_PARSE_E;
  12128. }
  12129. CALLOC_ASNGETDATA(dataASN, rdnASN_Length, ret, cert->heap);
  12130. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12131. if (ret == 0) {
  12132. /* Create an X509_NAME to hold data for OpenSSL compatability APIs. */
  12133. dName = wolfSSL_X509_NAME_new();
  12134. if (dName == NULL) {
  12135. ret = MEMORY_E;
  12136. }
  12137. }
  12138. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12139. if (ret == 0) {
  12140. /* Expecting a SEQUENCE using up all data. */
  12141. ret = GetASN_Sequence(input, &srcIdx, &len, maxIdx, 1);
  12142. }
  12143. if (ret == 0) {
  12144. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  12145. /* Store pointer and length to raw issuer. */
  12146. if (nameType == ISSUER) {
  12147. cert->issuerRaw = &input[srcIdx];
  12148. cert->issuerRawLen = len;
  12149. }
  12150. #endif
  12151. #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
  12152. /* Store pointer and length to raw subject. */
  12153. if (nameType == SUBJECT) {
  12154. cert->subjectRaw = &input[srcIdx];
  12155. cert->subjectRawLen = len;
  12156. }
  12157. #endif
  12158. /* Process all RDNs in name. */
  12159. while ((ret == 0) && (srcIdx < maxIdx)) {
  12160. int nid = 0;
  12161. /* Initialize for data and setup RDN choice. */
  12162. GetASN_Choice(&dataASN[RDNASN_IDX_ATTR_VAL], rdnChoice);
  12163. /* Ignore type OID as too many to store in table. */
  12164. GetASN_OID(&dataASN[RDNASN_IDX_ATTR_TYPE], oidIgnoreType);
  12165. /* Parse RDN. */
  12166. ret = GetASN_Items(rdnASN, dataASN, rdnASN_Length, 1, input,
  12167. &srcIdx, maxIdx);
  12168. if (ret == 0) {
  12169. /* Put RDN data into certificate. */
  12170. ret = GetRDN(cert, full, &idx, &nid, nameType == SUBJECT,
  12171. dataASN);
  12172. }
  12173. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12174. /* TODO: push this back up to ssl.c
  12175. * (do parsing for WOLFSSL_X509_NAME on demand) */
  12176. if (ret == 0) {
  12177. int enc;
  12178. byte* str;
  12179. word32 strLen;
  12180. byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
  12181. /* Get string reference. */
  12182. GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
  12183. /* Convert BER tag to a OpenSSL type. */
  12184. switch (tag) {
  12185. case CTC_UTF8:
  12186. enc = MBSTRING_UTF8;
  12187. break;
  12188. case CTC_PRINTABLE:
  12189. enc = V_ASN1_PRINTABLESTRING;
  12190. break;
  12191. default:
  12192. WOLFSSL_MSG("Unknown encoding type, default UTF8");
  12193. enc = MBSTRING_UTF8;
  12194. }
  12195. if (nid != 0) {
  12196. /* Add an entry to the X509_NAME. */
  12197. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc, str,
  12198. strLen, -1, -1) != WOLFSSL_SUCCESS) {
  12199. ret = ASN_PARSE_E;
  12200. }
  12201. }
  12202. }
  12203. #endif
  12204. }
  12205. }
  12206. if (ret == 0) {
  12207. /* Terminate string. */
  12208. full[idx] = 0;
  12209. /* Return index into encoding after name. */
  12210. *inOutIdx = srcIdx;
  12211. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12212. /* Store X509_NAME in certificate. */
  12213. if (nameType == ISSUER) {
  12214. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  12215. defined(HAVE_LIGHTY)) && \
  12216. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  12217. dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX);
  12218. XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
  12219. #endif
  12220. cert->issuerName = dName;
  12221. }
  12222. else {
  12223. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  12224. dName->rawLen = min(cert->subjectRawLen, WC_ASN_NAME_MAX);
  12225. XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
  12226. #endif
  12227. cert->subjectName = dName;
  12228. }
  12229. }
  12230. else {
  12231. /* Dispose of unused X509_NAME. */
  12232. wolfSSL_X509_NAME_free(dName);
  12233. #endif
  12234. }
  12235. FREE_ASNGETDATA(dataASN, cert->heap);
  12236. return ret;
  12237. #endif /* WOLFSSL_ASN_TEMPLATE */
  12238. }
  12239. #ifdef WOLFSSL_ASN_TEMPLATE
  12240. /* ASN.1 template for certificate name. */
  12241. static const ASNItem certNameASN[] = {
  12242. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  12243. /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  12244. };
  12245. enum {
  12246. CERTNAMEASN_IDX_OID = 0,
  12247. CERTNAMEASN_IDX_NAME
  12248. };
  12249. /* Number of items in ASN.1 template for certificate name. */
  12250. #define certNameASN_Length (sizeof(certNameASN) / sizeof(ASNItem))
  12251. #endif
  12252. /* Get a certificate name into the certificate object.
  12253. *
  12254. * Either the issuer or subject name.
  12255. *
  12256. * @param [in, out] cert Decoded certificate object.
  12257. * @param [in] nameType Type of name being decoded: ISSUER or SUBJECT.
  12258. * @param [in] maxIdx Index of next item after certificate name.
  12259. * @return 0 on success.
  12260. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12261. * is invalid.
  12262. * @return BUFFER_E when data in buffer is too small.
  12263. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  12264. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  12265. * @return MEMORY_E when dynamic memory allocation fails.
  12266. */
  12267. int GetName(DecodedCert* cert, int nameType, int maxIdx)
  12268. {
  12269. #ifndef WOLFSSL_ASN_TEMPLATE
  12270. char* full;
  12271. byte* hash;
  12272. int length;
  12273. word32 localIdx;
  12274. byte tag;
  12275. WOLFSSL_MSG("Getting Name");
  12276. if (nameType == ISSUER) {
  12277. full = cert->issuer;
  12278. hash = cert->issuerHash;
  12279. }
  12280. else {
  12281. full = cert->subject;
  12282. hash = cert->subjectHash;
  12283. }
  12284. if (cert->srcIdx >= (word32)maxIdx) {
  12285. return BUFFER_E;
  12286. }
  12287. localIdx = cert->srcIdx;
  12288. if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
  12289. return ASN_PARSE_E;
  12290. }
  12291. if (tag == ASN_OBJECT_ID) {
  12292. WOLFSSL_MSG("Trying optional prefix...");
  12293. if (SkipObjectId(cert->source, &cert->srcIdx, (word32)maxIdx) < 0)
  12294. return ASN_PARSE_E;
  12295. WOLFSSL_MSG("Got optional prefix");
  12296. }
  12297. localIdx = cert->srcIdx;
  12298. if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
  12299. return ASN_PARSE_E;
  12300. }
  12301. localIdx = cert->srcIdx + 1;
  12302. if (GetLength(cert->source, &localIdx, &length, (word32)maxIdx) < 0) {
  12303. return ASN_PARSE_E;
  12304. }
  12305. length += (int)(localIdx - cert->srcIdx);
  12306. return GetCertName(cert, full, hash, nameType, cert->source, &cert->srcIdx,
  12307. cert->srcIdx + (word32)length);
  12308. #else
  12309. ASNGetData dataASN[certNameASN_Length];
  12310. word32 idx = cert->srcIdx;
  12311. int ret = 0;
  12312. WOLFSSL_MSG("Getting Name");
  12313. XMEMSET(dataASN, 0, sizeof(dataASN));
  12314. /* Initialize for data and don't check optional prefix OID. */
  12315. GetASN_OID(&dataASN[CERTNAMEASN_IDX_OID], oidIgnoreType);
  12316. ret = GetASN_Items(certNameASN, dataASN, certNameASN_Length, 0,
  12317. cert->source, &idx, (word32)maxIdx);
  12318. if (ret == 0) {
  12319. char* full;
  12320. byte* hash;
  12321. /* Store offset of SEQUENCE that is start of name. */
  12322. cert->srcIdx = dataASN[CERTNAMEASN_IDX_NAME].offset;
  12323. /* Get fields to fill in based on name type. */
  12324. if (nameType == ISSUER) {
  12325. full = cert->issuer;
  12326. hash = cert->issuerHash;
  12327. }
  12328. else {
  12329. full = cert->subject;
  12330. hash = cert->subjectHash;
  12331. }
  12332. /* Parse certificate name. */
  12333. ret = GetCertName(cert, full, hash, nameType, cert->source,
  12334. &cert->srcIdx, idx);
  12335. }
  12336. return ret;
  12337. #endif
  12338. }
  12339. #ifndef NO_ASN_TIME
  12340. /* two byte date/time, add to value */
  12341. static WC_INLINE int GetTime(int* value, const byte* date, int* idx)
  12342. {
  12343. int i = *idx;
  12344. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  12345. date[i+1] > 0x39) {
  12346. return ASN_PARSE_E;
  12347. }
  12348. *value += (int)btoi(date[i++]) * 10;
  12349. *value += (int)btoi(date[i++]);
  12350. *idx = i;
  12351. return 0;
  12352. }
  12353. #ifdef WOLFSSL_LINUXKM
  12354. static WC_INLINE int GetTime_Long(long* value, const byte* date, int* idx)
  12355. {
  12356. int i = *idx;
  12357. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  12358. date[i+1] > 0x39) {
  12359. return ASN_PARSE_E;
  12360. }
  12361. *value += (long)btoi(date[i++]) * 10;
  12362. *value += (long)btoi(date[i++]);
  12363. *idx = i;
  12364. return 0;
  12365. }
  12366. #endif
  12367. int ExtractDate(const unsigned char* date, unsigned char format,
  12368. struct tm* certTime, int* idx)
  12369. {
  12370. XMEMSET(certTime, 0, sizeof(struct tm));
  12371. if (format == ASN_UTC_TIME) {
  12372. if (btoi(date[*idx]) >= 5)
  12373. certTime->tm_year = 1900;
  12374. else
  12375. certTime->tm_year = 2000;
  12376. }
  12377. else { /* format == GENERALIZED_TIME */
  12378. #ifdef WOLFSSL_LINUXKM
  12379. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  12380. #else
  12381. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  12382. #endif
  12383. certTime->tm_year *= 100;
  12384. }
  12385. #ifdef AVR
  12386. /* Extract the time from the struct tm and adjust tm_year, tm_mon */
  12387. /* AVR libc stores these as uint8_t instead of int */
  12388. /* AVR time_t also offsets from midnight 1 Jan 2000 */
  12389. int tm_year = certTime->tm_year - 2000;
  12390. int tm_mon = certTime->tm_mon - 1;
  12391. int tm_mday = certTime->tm_mday;
  12392. int tm_hour = certTime->tm_hour;
  12393. int tm_min = certTime->tm_min;
  12394. int tm_sec = certTime->tm_sec;
  12395. #ifdef WOLFSSL_LINUXKM
  12396. if (GetTime_Long(&tm_year, date, idx) != 0) return 0;
  12397. #else
  12398. if (GetTime(&tm_year, date, idx) != 0) return 0;
  12399. #endif
  12400. if (GetTime(&tm_mon , date, idx) != 0) return 0;
  12401. if (GetTime(&tm_mday, date, idx) != 0) return 0;
  12402. if (GetTime(&tm_hour, date, idx) != 0) return 0;
  12403. if (GetTime(&tm_min , date, idx) != 0) return 0;
  12404. if (GetTime(&tm_sec , date, idx) != 0) return 0;
  12405. /* Re-populate certTime with computed values */
  12406. certTime->tm_year = tm_year;
  12407. certTime->tm_mon = tm_mon;
  12408. certTime->tm_mday = tm_mday;
  12409. certTime->tm_hour = tm_hour;
  12410. certTime->tm_min = tm_min;
  12411. certTime->tm_sec = tm_sec;
  12412. #else
  12413. /* adjust tm_year, tm_mon */
  12414. #ifdef WOLFSSL_LINUXKM
  12415. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  12416. #else
  12417. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  12418. #endif
  12419. certTime->tm_year -= 1900;
  12420. if (GetTime(&certTime->tm_mon , date, idx) != 0) return 0;
  12421. certTime->tm_mon -= 1;
  12422. if (GetTime(&certTime->tm_mday, date, idx) != 0) return 0;
  12423. if (GetTime(&certTime->tm_hour, date, idx) != 0) return 0;
  12424. if (GetTime(&certTime->tm_min , date, idx) != 0) return 0;
  12425. if (GetTime(&certTime->tm_sec , date, idx) != 0) return 0;
  12426. #endif
  12427. return 1;
  12428. }
  12429. #if defined(OPENSSL_ALL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
  12430. defined(OPENSSL_EXTRA) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  12431. int GetTimeString(byte* date, int format, char* buf, int len)
  12432. {
  12433. struct tm t;
  12434. int idx = 0;
  12435. if (!ExtractDate(date, (unsigned char)format, &t, &idx)) {
  12436. return 0;
  12437. }
  12438. if (date[idx] != 'Z') {
  12439. WOLFSSL_MSG("UTCtime, not Zulu") ;
  12440. return 0;
  12441. }
  12442. /* place month in buffer */
  12443. buf[0] = '\0';
  12444. switch(t.tm_mon) {
  12445. case 0: XSTRNCAT(buf, "Jan ", 5); break;
  12446. case 1: XSTRNCAT(buf, "Feb ", 5); break;
  12447. case 2: XSTRNCAT(buf, "Mar ", 5); break;
  12448. case 3: XSTRNCAT(buf, "Apr ", 5); break;
  12449. case 4: XSTRNCAT(buf, "May ", 5); break;
  12450. case 5: XSTRNCAT(buf, "Jun ", 5); break;
  12451. case 6: XSTRNCAT(buf, "Jul ", 5); break;
  12452. case 7: XSTRNCAT(buf, "Aug ", 5); break;
  12453. case 8: XSTRNCAT(buf, "Sep ", 5); break;
  12454. case 9: XSTRNCAT(buf, "Oct ", 5); break;
  12455. case 10: XSTRNCAT(buf, "Nov ", 5); break;
  12456. case 11: XSTRNCAT(buf, "Dec ", 5); break;
  12457. default:
  12458. return 0;
  12459. }
  12460. idx = 4; /* use idx now for char buffer */
  12461. if (XSNPRINTF(buf + idx, len - idx, "%2d %02d:%02d:%02d %d GMT",
  12462. t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, (int)t.tm_year + 1900)
  12463. >= len - idx)
  12464. {
  12465. WOLFSSL_MSG("buffer overrun in GetTimeString");
  12466. return 0;
  12467. }
  12468. return 1;
  12469. }
  12470. #endif /* OPENSSL_ALL || WOLFSSL_MYSQL_COMPATIBLE || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
  12471. #if !defined(NO_ASN_TIME) && !defined(USER_TIME) && \
  12472. !defined(TIME_OVERRIDES) && (defined(OPENSSL_EXTRA) || defined(HAVE_PKCS7))
  12473. /* Set current time string, either UTC or GeneralizedTime.
  12474. * (void*) tm should be a pointer to time_t, output is placed in buf.
  12475. *
  12476. * Return time string length placed in buf on success, negative on error */
  12477. int GetAsnTimeString(void* currTime, byte* buf, word32 len)
  12478. {
  12479. byte* data_ptr = buf;
  12480. byte uf_time[ASN_GENERALIZED_TIME_SIZE];
  12481. int data_len = 0;
  12482. WOLFSSL_ENTER("GetAsnTimeString");
  12483. if (buf == NULL || len == 0)
  12484. return BAD_FUNC_ARG;
  12485. XMEMSET(uf_time, 0, sizeof(uf_time));
  12486. /* GetFormattedTime returns length with null terminator */
  12487. data_len = GetFormattedTime(currTime, uf_time, (word32)sizeof(uf_time));
  12488. if (data_len <= 0) {
  12489. return ASN_TIME_E;
  12490. }
  12491. /* ensure room to add 2 bytes (ASN type and length) before proceeding */
  12492. else if (len < (word32)data_len + 2) {
  12493. return BUFFER_E;
  12494. }
  12495. if (data_len == ASN_UTC_TIME_SIZE-1) {
  12496. /* increment data_len for ASN length byte after adding the data_ptr */
  12497. *data_ptr = (byte)ASN_UTC_TIME; data_ptr++; data_len++;
  12498. /* -1 below excludes null terminator */
  12499. *data_ptr = (byte)ASN_UTC_TIME_SIZE - 1; data_ptr++; data_len++;
  12500. XMEMCPY(data_ptr, (byte *)uf_time, ASN_UTC_TIME_SIZE - 1);
  12501. data_ptr += ASN_UTC_TIME_SIZE - 1;
  12502. }
  12503. else if (data_len == ASN_GENERALIZED_TIME_SIZE-1) {
  12504. /* increment data_len for ASN length byte after adding the data_ptr */
  12505. *data_ptr = (byte)ASN_GENERALIZED_TIME; data_ptr++; data_len++;
  12506. /* -1 below excludes null terminator */
  12507. *data_ptr = (byte)ASN_GENERALIZED_TIME_SIZE - 1; data_ptr++; data_len++;
  12508. XMEMCPY(data_ptr, (byte*)uf_time, ASN_GENERALIZED_TIME_SIZE - 1);
  12509. data_ptr += ASN_GENERALIZED_TIME_SIZE - 1;
  12510. }
  12511. else {
  12512. WOLFSSL_MSG("Invalid time size returned");
  12513. return ASN_TIME_E;
  12514. }
  12515. /* append null terminator */
  12516. *data_ptr = 0;
  12517. /* return length without null terminator */
  12518. return data_len;
  12519. }
  12520. /* return just the time string as either UTC or Generalized Time*/
  12521. int GetFormattedTime(void* currTime, byte* buf, word32 len)
  12522. {
  12523. struct tm* ts = NULL;
  12524. struct tm* tmpTime = NULL;
  12525. int year, mon, day, hour, mini, sec;
  12526. int ret;
  12527. #if defined(NEED_TMP_TIME)
  12528. struct tm tmpTimeStorage;
  12529. tmpTime = &tmpTimeStorage;
  12530. #endif
  12531. /* Needed in case XGMTIME does not use the tmpTime argument. */
  12532. (void)tmpTime;
  12533. WOLFSSL_ENTER("GetFormattedTime");
  12534. if (buf == NULL || len == 0)
  12535. return BAD_FUNC_ARG;
  12536. ts = (struct tm *)XGMTIME((time_t*)currTime, tmpTime);
  12537. if (ts == NULL) {
  12538. WOLFSSL_MSG("failed to get time data.");
  12539. return ASN_TIME_E;
  12540. }
  12541. /* Note ASN_UTC_TIME_SIZE and ASN_GENERALIZED_TIME_SIZE include space for
  12542. * the null terminator. ASN encoded values leave off the terminator. */
  12543. if (ts->tm_year >= 50 && ts->tm_year < 150) {
  12544. /* UTC Time */
  12545. if (ts->tm_year >= 50 && ts->tm_year < 100) {
  12546. year = ts->tm_year;
  12547. }
  12548. else {
  12549. year = ts->tm_year - 100;
  12550. }
  12551. mon = ts->tm_mon + 1;
  12552. day = ts->tm_mday;
  12553. hour = ts->tm_hour;
  12554. mini = ts->tm_min;
  12555. sec = ts->tm_sec;
  12556. #if defined(WOLF_C89)
  12557. if (len < ASN_UTC_TIME_SIZE) {
  12558. WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
  12559. return BUFFER_E;
  12560. }
  12561. ret = XSPRINTF((char*)buf,
  12562. "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
  12563. hour, mini, sec);
  12564. #else
  12565. ret = XSNPRINTF((char*)buf, len,
  12566. "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
  12567. hour, mini, sec);
  12568. #endif
  12569. }
  12570. else {
  12571. /* GeneralizedTime */
  12572. year = ts->tm_year + 1900;
  12573. mon = ts->tm_mon + 1;
  12574. day = ts->tm_mday;
  12575. hour = ts->tm_hour;
  12576. mini = ts->tm_min;
  12577. sec = ts->tm_sec;
  12578. #if defined(WOLF_C89)
  12579. if (len < ASN_GENERALIZED_TIME_SIZE) {
  12580. WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
  12581. return BUFFER_E;
  12582. }
  12583. ret = XSPRINTF((char*)buf,
  12584. "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
  12585. hour, mini, sec);
  12586. #else
  12587. ret = XSNPRINTF((char*)buf, len,
  12588. "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
  12589. hour, mini, sec);
  12590. #endif
  12591. }
  12592. return ret;
  12593. }
  12594. #endif /* !NO_ASN_TIME && !USER_TIME && !TIME_OVERRIDES &&
  12595. * (OPENSSL_EXTRA || HAVE_PKCS7) */
  12596. #if defined(USE_WOLF_VALIDDATE)
  12597. /* to the second */
  12598. int DateGreaterThan(const struct tm* a, const struct tm* b)
  12599. {
  12600. if (a->tm_year > b->tm_year)
  12601. return 1;
  12602. if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
  12603. return 1;
  12604. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  12605. a->tm_mday > b->tm_mday)
  12606. return 1;
  12607. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  12608. a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
  12609. return 1;
  12610. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  12611. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  12612. a->tm_min > b->tm_min)
  12613. return 1;
  12614. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  12615. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  12616. a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
  12617. return 1;
  12618. return 0; /* false */
  12619. }
  12620. static WC_INLINE int DateLessThan(const struct tm* a, const struct tm* b)
  12621. {
  12622. return DateGreaterThan(b,a);
  12623. }
  12624. /* like atoi but only use first byte */
  12625. /* Make sure before and after dates are valid */
  12626. int wc_ValidateDate(const byte* date, byte format, int dateType)
  12627. {
  12628. time_t ltime;
  12629. struct tm certTime;
  12630. struct tm* localTime;
  12631. struct tm* tmpTime;
  12632. int i = 0;
  12633. int timeDiff = 0;
  12634. int diffHH = 0, diffMM = 0;
  12635. #if defined(NEED_TMP_TIME)
  12636. struct tm tmpTimeStorage;
  12637. tmpTime = &tmpTimeStorage;
  12638. #else
  12639. tmpTime = NULL;
  12640. #endif
  12641. (void)tmpTime;
  12642. ltime = wc_Time(0);
  12643. if (sizeof(ltime) == sizeof(word32) && (int)ltime < 0){
  12644. /* A negative response here could be due to a 32-bit time_t
  12645. * where the year is 2038 or later. */
  12646. WOLFSSL_MSG("wc_Time failed to return a valid value");
  12647. return 0;
  12648. }
  12649. #ifdef WOLFSSL_BEFORE_DATE_CLOCK_SKEW
  12650. if (dateType == BEFORE) {
  12651. WOLFSSL_MSG("Skewing local time for before date check");
  12652. ltime += WOLFSSL_BEFORE_DATE_CLOCK_SKEW;
  12653. }
  12654. #endif
  12655. #ifdef WOLFSSL_AFTER_DATE_CLOCK_SKEW
  12656. if (dateType == AFTER) {
  12657. WOLFSSL_MSG("Skewing local time for after date check");
  12658. ltime -= WOLFSSL_AFTER_DATE_CLOCK_SKEW;
  12659. }
  12660. #endif
  12661. if (!ExtractDate(date, format, &certTime, &i)) {
  12662. WOLFSSL_MSG("Error extracting the date");
  12663. return 0;
  12664. }
  12665. if ((date[i] == '+') || (date[i] == '-')) {
  12666. int diffSign;
  12667. WOLFSSL_MSG("Using time differential, not Zulu") ;
  12668. diffSign = date[i++] == '+' ? 1 : -1 ;
  12669. if (GetTime(&diffHH, date, &i) != 0)
  12670. return 0;
  12671. if (GetTime(&diffMM, date, &i) != 0)
  12672. return 0;
  12673. timeDiff = diffSign * (diffHH*60 + diffMM) * 60 ;
  12674. } else if (date[i] != 'Z') {
  12675. WOLFSSL_MSG("UTCtime, neither Zulu or time differential") ;
  12676. return 0;
  12677. }
  12678. ltime -= (time_t)timeDiff ;
  12679. localTime = XGMTIME(&ltime, tmpTime);
  12680. if (localTime == NULL) {
  12681. WOLFSSL_MSG("XGMTIME failed");
  12682. return 0;
  12683. }
  12684. if (dateType == BEFORE) {
  12685. if (DateLessThan(localTime, &certTime)) {
  12686. WOLFSSL_MSG("Date BEFORE check failed");
  12687. return 0;
  12688. }
  12689. }
  12690. else { /* dateType == AFTER */
  12691. if (DateGreaterThan(localTime, &certTime)) {
  12692. WOLFSSL_MSG("Date AFTER check failed");
  12693. return 0;
  12694. }
  12695. }
  12696. return 1;
  12697. }
  12698. #endif /* USE_WOLF_VALIDDATE */
  12699. int wc_GetTime(void* timePtr, word32 timeSize)
  12700. {
  12701. time_t* ltime = (time_t*)timePtr;
  12702. if (timePtr == NULL) {
  12703. return BAD_FUNC_ARG;
  12704. }
  12705. if ((word32)sizeof(time_t) > timeSize) {
  12706. return BUFFER_E;
  12707. }
  12708. *ltime = wc_Time(0);
  12709. return 0;
  12710. }
  12711. #ifdef TIME_OVERRIDES
  12712. #ifndef HAVE_TIME_T_TYPE
  12713. typedef long time_t;
  12714. #endif
  12715. extern time_t XTIME(time_t* t);
  12716. #endif
  12717. static wc_time_cb timeFunc = NULL;
  12718. int wc_SetTimeCb(wc_time_cb f)
  12719. {
  12720. timeFunc = f;
  12721. return 0;
  12722. }
  12723. time_t wc_Time(time_t* t)
  12724. {
  12725. if (timeFunc != NULL) {
  12726. return timeFunc(t);
  12727. }
  12728. return XTIME(t);
  12729. }
  12730. #endif /* !NO_ASN_TIME */
  12731. #ifdef WOLFSSL_ASN_TEMPLATE
  12732. /* TODO: use a CHOICE instead of two items? */
  12733. /* ASN.1 template for a date - either UTC or Generalized Time. */
  12734. static const ASNItem dateASN[] = {
  12735. /* UTC */ { 0, ASN_UTC_TIME, 0, 0, 2 },
  12736. /* GT */ { 0, ASN_GENERALIZED_TIME, 0, 0, 2 },
  12737. };
  12738. enum {
  12739. DATEASN_IDX_UTC = 0,
  12740. DATEASN_IDX_GT
  12741. };
  12742. /* Number of items in ASN.1 template for a date. */
  12743. #define dateASN_Length (sizeof(dateASN) / sizeof(ASNItem))
  12744. #endif /* WOLFSSL_ASN_TEMPLATE */
  12745. /* Get date buffer, format and length. Returns 0=success or error */
  12746. /* Decode a DateInfo - choice of UTC TIME or GENERALIZED TIME.
  12747. *
  12748. * @param [in] source Buffer containing encoded date.
  12749. * @param [in, out] idx On in, the index of the date.
  12750. * On out, index after date.
  12751. * @param [out] pDate Pointer into buffer of data bytes.
  12752. * @param [out] pFormat Format of date - BER/DER tag.
  12753. * @param [out] pLength Length of date bytes.
  12754. * @param [in] maxIdx Index of next item after date.
  12755. * @return 0 on success.
  12756. * @return BAD_FUNC_ARG when source or idx is NULL.
  12757. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12758. * is invalid.
  12759. * @return BUFFER_E when data in buffer is too small.
  12760. */
  12761. static int GetDateInfo(const byte* source, word32* idx, const byte** pDate,
  12762. byte* pFormat, int* pLength, word32 maxIdx)
  12763. {
  12764. #ifndef WOLFSSL_ASN_TEMPLATE
  12765. int length;
  12766. byte format;
  12767. if (source == NULL || idx == NULL)
  12768. return BAD_FUNC_ARG;
  12769. /* get ASN format header */
  12770. if (*idx+1 > maxIdx)
  12771. return BUFFER_E;
  12772. format = source[*idx];
  12773. *idx += 1;
  12774. if (format != ASN_UTC_TIME && format != ASN_GENERALIZED_TIME) {
  12775. WOLFSSL_ERROR_VERBOSE(ASN_TIME_E);
  12776. return ASN_TIME_E;
  12777. }
  12778. /* get length */
  12779. if (GetLength(source, idx, &length, maxIdx) < 0)
  12780. return ASN_PARSE_E;
  12781. if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
  12782. return ASN_DATE_SZ_E;
  12783. /* return format, date and length */
  12784. if (pFormat)
  12785. *pFormat = format;
  12786. if (pDate)
  12787. *pDate = &source[*idx];
  12788. if (pLength)
  12789. *pLength = length;
  12790. *idx += (word32)length;
  12791. return 0;
  12792. #else
  12793. ASNGetData dataASN[dateASN_Length];
  12794. int ret = 0;
  12795. if ((source == NULL) || (idx == NULL)) {
  12796. ret = BAD_FUNC_ARG;
  12797. }
  12798. if (ret == 0) {
  12799. /* Initialize data. */
  12800. XMEMSET(dataASN, 0, sizeof(dataASN));
  12801. /* Parse date. */
  12802. ret = GetASN_Items(dateASN, dataASN, dateASN_Length, 0, source, idx,
  12803. maxIdx);
  12804. }
  12805. if (ret == 0) {
  12806. /* Determine which tag was seen. */
  12807. int i = (dataASN[DATEASN_IDX_UTC].tag != 0) ? DATEASN_IDX_UTC
  12808. : DATEASN_IDX_GT;
  12809. /* Return data from seen item. */
  12810. if (pFormat != NULL) {
  12811. *pFormat = dataASN[i].tag;
  12812. }
  12813. if (pDate != NULL) {
  12814. *pDate = dataASN[i].data.ref.data;
  12815. }
  12816. if (pLength != NULL) {
  12817. *pLength = (int)dataASN[i].data.ref.length;
  12818. }
  12819. }
  12820. return ret;
  12821. #endif
  12822. }
  12823. #ifndef WOLFSSL_ASN_TEMPLATE
  12824. static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx)
  12825. {
  12826. int ret, length;
  12827. const byte *datePtr = NULL;
  12828. byte date[MAX_DATE_SIZE];
  12829. byte format;
  12830. word32 startIdx = 0;
  12831. if (dateType == BEFORE)
  12832. cert->beforeDate = &cert->source[cert->srcIdx];
  12833. else
  12834. cert->afterDate = &cert->source[cert->srcIdx];
  12835. startIdx = cert->srcIdx;
  12836. ret = GetDateInfo(cert->source, &cert->srcIdx, &datePtr, &format,
  12837. &length, (word32)maxIdx);
  12838. if (ret < 0)
  12839. return ret;
  12840. XMEMSET(date, 0, MAX_DATE_SIZE);
  12841. XMEMCPY(date, datePtr, (size_t)length);
  12842. if (dateType == BEFORE)
  12843. cert->beforeDateLen = (int)(cert->srcIdx - startIdx);
  12844. else
  12845. cert->afterDateLen = (int)(cert->srcIdx - startIdx);
  12846. #ifndef NO_ASN_TIME_CHECK
  12847. if (verify != NO_VERIFY && verify != VERIFY_SKIP_DATE &&
  12848. !XVALIDATE_DATE(date, format, dateType)) {
  12849. if (dateType == BEFORE) {
  12850. WOLFSSL_ERROR_VERBOSE(ASN_BEFORE_DATE_E);
  12851. return ASN_BEFORE_DATE_E;
  12852. }
  12853. else {
  12854. WOLFSSL_ERROR_VERBOSE(ASN_AFTER_DATE_E);
  12855. return ASN_AFTER_DATE_E;
  12856. }
  12857. }
  12858. #else
  12859. (void)verify;
  12860. #endif
  12861. return 0;
  12862. }
  12863. static int GetValidity(DecodedCert* cert, int verify, int maxIdx)
  12864. {
  12865. int length;
  12866. int badDate = 0;
  12867. if (GetSequence(cert->source, &cert->srcIdx, &length, (word32)maxIdx) < 0)
  12868. return ASN_PARSE_E;
  12869. maxIdx = (int)cert->srcIdx + length;
  12870. if (GetDate(cert, BEFORE, verify, maxIdx) < 0)
  12871. badDate = ASN_BEFORE_DATE_E; /* continue parsing */
  12872. if (GetDate(cert, AFTER, verify, maxIdx) < 0)
  12873. return ASN_AFTER_DATE_E;
  12874. if (badDate != 0)
  12875. return badDate;
  12876. return 0;
  12877. }
  12878. #endif /* !WOLFSSL_ASN_TEMPLATE */
  12879. int wc_GetDateInfo(const byte* certDate, int certDateSz, const byte** date,
  12880. byte* format, int* length)
  12881. {
  12882. int ret;
  12883. word32 idx = 0;
  12884. ret = GetDateInfo(certDate, &idx, date, format, length, (word32)certDateSz);
  12885. return ret;
  12886. }
  12887. #ifndef NO_ASN_TIME
  12888. int wc_GetDateAsCalendarTime(const byte* date, int length, byte format,
  12889. struct tm* timearg)
  12890. {
  12891. int idx = 0;
  12892. (void)length;
  12893. if (!ExtractDate(date, format, timearg, &idx))
  12894. return ASN_TIME_E;
  12895. return 0;
  12896. }
  12897. #if defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_ALT_NAMES)
  12898. int wc_GetCertDates(Cert* cert, struct tm* before, struct tm* after)
  12899. {
  12900. int ret = 0;
  12901. const byte* date;
  12902. byte format;
  12903. int length;
  12904. if (cert == NULL)
  12905. return BAD_FUNC_ARG;
  12906. if (before && cert->beforeDateSz > 0) {
  12907. ret = wc_GetDateInfo(cert->beforeDate, cert->beforeDateSz, &date,
  12908. &format, &length);
  12909. if (ret == 0)
  12910. ret = wc_GetDateAsCalendarTime(date, length, format, before);
  12911. }
  12912. if (after && cert->afterDateSz > 0) {
  12913. ret = wc_GetDateInfo(cert->afterDate, cert->afterDateSz, &date,
  12914. &format, &length);
  12915. if (ret == 0)
  12916. ret = wc_GetDateAsCalendarTime(date, length, format, after);
  12917. }
  12918. return ret;
  12919. }
  12920. #endif /* WOLFSSL_CERT_GEN && WOLFSSL_ALT_NAMES */
  12921. #endif /* !NO_ASN_TIME */
  12922. #ifndef WOLFSSL_ASN_TEMPLATE
  12923. static int GetSigAlg(DecodedCert* cert, word32* sigOid, word32 maxIdx)
  12924. {
  12925. int length;
  12926. word32 endSeqIdx;
  12927. if (GetSequence(cert->source, &cert->srcIdx, &length, maxIdx) < 0)
  12928. return ASN_PARSE_E;
  12929. endSeqIdx = cert->srcIdx + (word32)length;
  12930. if (GetObjectId(cert->source, &cert->srcIdx, sigOid, oidSigType,
  12931. maxIdx) < 0) {
  12932. return ASN_OBJECT_ID_E;
  12933. }
  12934. if (cert->srcIdx != endSeqIdx) {
  12935. #ifdef WC_RSA_PSS
  12936. if (*sigOid == CTC_RSASSAPSS) {
  12937. cert->sigParamsIndex = cert->srcIdx;
  12938. cert->sigParamsLength = endSeqIdx - cert->srcIdx;
  12939. }
  12940. else
  12941. #endif
  12942. /* Only allowed a ASN NULL header with zero length. */
  12943. if (endSeqIdx - cert->srcIdx != 2)
  12944. return ASN_PARSE_E;
  12945. else {
  12946. byte tag;
  12947. if (GetASNTag(cert->source, &cert->srcIdx, &tag, endSeqIdx) != 0)
  12948. return ASN_PARSE_E;
  12949. if (tag != ASN_TAG_NULL)
  12950. return ASN_PARSE_E;
  12951. }
  12952. }
  12953. cert->srcIdx = endSeqIdx;
  12954. return 0;
  12955. }
  12956. #endif
  12957. #ifdef WOLFSSL_ASN_TEMPLATE
  12958. /* TODO: move code around to not require this. */
  12959. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  12960. int* badDateRet, int stopAtPubKey,
  12961. int stopAfterPubKey);
  12962. #endif
  12963. /* Parse the certificate up to the X.509 public key.
  12964. *
  12965. * If cert data is invalid then badDate get set to error value.
  12966. *
  12967. * @param [in, out] cert Decoded certificate object.
  12968. * @param [in] verify Whether to verify dates.
  12969. * @param [out] badDate Error code when verify dates.
  12970. * @return 0 on success.
  12971. * @return BAD_FUNC_ARG when cert or badDate is NULL.
  12972. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  12973. * @return ASN_DATE_SZ_E when time data is not supported.
  12974. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12975. * is invalid.
  12976. * @return BUFFER_E when data in buffer is too small.
  12977. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  12978. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  12979. */
  12980. int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate)
  12981. {
  12982. #ifndef WOLFSSL_ASN_TEMPLATE
  12983. int ret;
  12984. if (cert == NULL || badDate == NULL)
  12985. return BAD_FUNC_ARG;
  12986. *badDate = 0;
  12987. if ( (ret = GetCertHeader(cert)) < 0)
  12988. return ret;
  12989. WOLFSSL_MSG("Got Cert Header");
  12990. #ifdef WOLFSSL_CERT_REQ
  12991. if (!cert->isCSR) {
  12992. #endif
  12993. /* Using the sigIndex as the upper bound because that's where the
  12994. * actual certificate data ends. */
  12995. if ((ret = GetSigAlg(cert, &cert->signatureOID, cert->sigIndex)) < 0)
  12996. return ret;
  12997. WOLFSSL_MSG("Got Algo ID");
  12998. if ( (ret = GetName(cert, ISSUER, (int)cert->sigIndex)) < 0)
  12999. return ret;
  13000. if ( (ret = GetValidity(cert, verify, (int)cert->sigIndex)) < 0)
  13001. *badDate = ret;
  13002. #ifdef WOLFSSL_CERT_REQ
  13003. }
  13004. #endif
  13005. if ( (ret = GetName(cert, SUBJECT, (int)cert->sigIndex)) < 0)
  13006. return ret;
  13007. WOLFSSL_MSG("Got Subject Name");
  13008. return ret;
  13009. #else
  13010. /* Use common decode routine and stop at public key. */
  13011. int ret;
  13012. *badDate = 0;
  13013. ret = DecodeCertInternal(cert, verify, NULL, badDate, 1, 0);
  13014. if (ret >= 0) {
  13015. /* Store current index: public key. */
  13016. cert->srcIdx = (word32)ret;
  13017. }
  13018. return ret;
  13019. #endif /* WOLFSSL_ASN_TEMPLATE */
  13020. }
  13021. /* Parse the certificate up to and including X.509 public key.
  13022. *
  13023. * @param [in, out] cert Decoded certificate object.
  13024. * @param [in] verify Whether to verify dates.
  13025. * @return 0 on success.
  13026. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  13027. * @return ASN_DATE_SZ_E when time data is not supported.
  13028. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  13029. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  13030. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13031. * is invalid.
  13032. * @return BUFFER_E when data in buffer is too small.
  13033. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  13034. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  13035. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  13036. */
  13037. int DecodeToKey(DecodedCert* cert, int verify)
  13038. {
  13039. #ifndef WOLFSSL_ASN_TEMPLATE
  13040. int badDate = 0;
  13041. int ret;
  13042. if ( (ret = wc_GetPubX509(cert, verify, &badDate)) < 0)
  13043. return ret;
  13044. /* Determine if self signed */
  13045. #ifdef WOLFSSL_CERT_REQ
  13046. if (cert->isCSR)
  13047. cert->selfSigned = 1;
  13048. else
  13049. #endif
  13050. {
  13051. cert->selfSigned = XMEMCMP(cert->issuerHash,
  13052. cert->subjectHash,
  13053. KEYID_SIZE) == 0 ? 1 : 0;
  13054. }
  13055. ret = GetCertKey(cert, cert->source, &cert->srcIdx, cert->maxIdx);
  13056. if (ret != 0)
  13057. return ret;
  13058. WOLFSSL_MSG("Got Key");
  13059. if (badDate != 0)
  13060. return badDate;
  13061. return ret;
  13062. #else
  13063. int ret;
  13064. int badDate = 0;
  13065. /* Call internal version and stop after public key. */
  13066. ret = DecodeCertInternal(cert, verify, NULL, &badDate, 0, 1);
  13067. /* Always return date errors. */
  13068. if (ret == 0) {
  13069. ret = badDate;
  13070. }
  13071. return ret;
  13072. #endif /* WOLFSSL_ASN_TEMPLATE */
  13073. }
  13074. #if !defined(NO_CERTS) && !defined(WOLFSSL_ASN_TEMPLATE)
  13075. static int GetSignature(DecodedCert* cert)
  13076. {
  13077. int length;
  13078. int ret;
  13079. ret = CheckBitString(cert->source, &cert->srcIdx, &length, cert->maxIdx, 1,
  13080. NULL);
  13081. if (ret != 0)
  13082. return ret;
  13083. cert->sigLength = (word32)length;
  13084. cert->signature = &cert->source[cert->srcIdx];
  13085. cert->srcIdx += cert->sigLength;
  13086. if (cert->srcIdx != cert->maxIdx)
  13087. return ASN_PARSE_E;
  13088. return 0;
  13089. }
  13090. #endif /* !NO_CERTS && !WOLFSSL_ASN_TEMPLATE */
  13091. #ifndef WOLFSSL_ASN_TEMPLATE
  13092. static word32 SetOctetString8Bit(word32 len, byte* output)
  13093. {
  13094. output[0] = ASN_OCTET_STRING;
  13095. output[1] = (byte)len;
  13096. return 2;
  13097. }
  13098. static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
  13099. {
  13100. word32 idx = SetOctetString8Bit(digSz, output);
  13101. XMEMCPY(&output[idx], digest, digSz);
  13102. return idx + digSz;
  13103. }
  13104. #endif
  13105. /* Encode a length for DER.
  13106. *
  13107. * @param [in] length Value to encode.
  13108. * @param [out] output Buffer to encode into.
  13109. * @return Number of bytes encoded.
  13110. */
  13111. word32 SetLength(word32 length, byte* output)
  13112. {
  13113. /* Start encoding at start of buffer. */
  13114. word32 i = 0;
  13115. if (length < ASN_LONG_LENGTH) {
  13116. /* Only one byte needed to encode. */
  13117. if (output) {
  13118. /* Write out length value. */
  13119. output[i] = (byte)length;
  13120. }
  13121. /* Skip over length. */
  13122. i++;
  13123. }
  13124. else {
  13125. /* Calculate the number of bytes required to encode value. */
  13126. byte j = (byte)BytePrecision(length);
  13127. if (output) {
  13128. /* Encode count byte. */
  13129. output[i] = j | ASN_LONG_LENGTH;
  13130. }
  13131. /* Skip over count byte. */
  13132. i++;
  13133. /* Encode value as a big-endian byte array. */
  13134. for (; j > 0; --j) {
  13135. if (output) {
  13136. /* Encode next most-significant byte. */
  13137. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  13138. }
  13139. /* Skip over byte. */
  13140. i++;
  13141. }
  13142. }
  13143. /* Return number of bytes in encoded length. */
  13144. return i;
  13145. }
  13146. /* Encode a DER header - type/tag and length.
  13147. *
  13148. * @param [in] tag DER tag of ASN.1 item.
  13149. * @param [in] len Length of data in ASN.1 item.
  13150. * @param [out] output Buffer to encode into.
  13151. * @return Number of bytes encoded.
  13152. */
  13153. static word32 SetHeader(byte tag, word32 len, byte* output)
  13154. {
  13155. if (output) {
  13156. /* Encode tag first. */
  13157. output[0] = tag;
  13158. }
  13159. /* Encode the length. */
  13160. return SetLength(len, output ? output + ASN_TAG_SZ : NULL) + ASN_TAG_SZ;
  13161. }
  13162. /* Encode a SEQUENCE header in DER.
  13163. *
  13164. * @param [in] len Length of data in SEQUENCE.
  13165. * @param [out] output Buffer to encode into.
  13166. * @return Number of bytes encoded.
  13167. */
  13168. word32 SetSequence(word32 len, byte* output)
  13169. {
  13170. return SetHeader(ASN_SEQUENCE | ASN_CONSTRUCTED, len, output);
  13171. }
  13172. /* Encode an OCTET STRING header in DER.
  13173. *
  13174. * @param [in] len Length of data in OCTET STRING.
  13175. * @param [out] output Buffer to encode into.
  13176. * @return Number of bytes encoded.
  13177. */
  13178. word32 SetOctetString(word32 len, byte* output)
  13179. {
  13180. return SetHeader(ASN_OCTET_STRING, len, output);
  13181. }
  13182. /* Encode a SET header in DER.
  13183. *
  13184. * @param [in] len Length of data in SET.
  13185. * @param [out] output Buffer to encode into.
  13186. * @return Number of bytes encoded.
  13187. */
  13188. word32 SetSet(word32 len, byte* output)
  13189. {
  13190. return SetHeader(ASN_SET | ASN_CONSTRUCTED, len, output);
  13191. }
  13192. /* Encode an implicit context specific header in DER.
  13193. *
  13194. * Implicit means that it is constructed only if the included ASN.1 item is.
  13195. *
  13196. * @param [in] tag Tag for the implicit ASN.1 item.
  13197. * @param [in] number Context specific number.
  13198. * @param [in] len Length of data in SET.
  13199. * @param [out] output Buffer to encode into.
  13200. * @return Number of bytes encoded.
  13201. */
  13202. word32 SetImplicit(byte tag, byte number, word32 len, byte* output)
  13203. {
  13204. tag = ((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0)
  13205. | ASN_CONTEXT_SPECIFIC | number;
  13206. return SetHeader(tag, len, output);
  13207. }
  13208. /* Encode an explicit context specific header in DER.
  13209. *
  13210. * Explicit means that there will be an ASN.1 item underneath.
  13211. *
  13212. * @param [in] number Context specific number.
  13213. * @param [in] len Length of data in SET.
  13214. * @param [out] output Buffer to encode into.
  13215. * @return Number of bytes encoded.
  13216. */
  13217. word32 SetExplicit(byte number, word32 len, byte* output)
  13218. {
  13219. return SetHeader(ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | number, len,
  13220. output);
  13221. }
  13222. #if defined(OPENSSL_EXTRA)
  13223. /* Encode an Othername into DER.
  13224. *
  13225. * @param [in] name Pointer to the WOLFSSL_ASN1_OTHERNAME to be encoded.
  13226. * @param [out] output Buffer to encode into. If NULL, don't encode.
  13227. * @return Number of bytes encoded or WOLFSSL_FAILURE if name parameter is bad.
  13228. */
  13229. word32 SetOthername(void *name, byte *output)
  13230. {
  13231. WOLFSSL_ASN1_OTHERNAME *nm = (WOLFSSL_ASN1_OTHERNAME *)name;
  13232. char *nameStr = NULL;
  13233. int nameSz = 0;
  13234. word32 len = 0;
  13235. if ((nm == NULL) || (nm->value == NULL)) {
  13236. WOLFSSL_MSG("otherName value is NULL");
  13237. return WOLFSSL_FAILURE;
  13238. }
  13239. nameStr = nm->value->value.utf8string->data;
  13240. nameSz = nm->value->value.utf8string->length;
  13241. len = nm->type_id->objSz +
  13242. SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2, NULL) +
  13243. SetHeader(CTC_UTF8, nameSz, NULL) + nameSz;
  13244. if (output != NULL) {
  13245. /* otherName OID */
  13246. XMEMCPY(output, nm->type_id->obj, nm->type_id->objSz);
  13247. output += nm->type_id->objSz;
  13248. output += SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2,
  13249. output);
  13250. output += SetHeader(CTC_UTF8, nameSz, output);
  13251. XMEMCPY(output, nameStr, nameSz);
  13252. }
  13253. return len;
  13254. }
  13255. #endif /* OPENSSL_EXTRA */
  13256. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  13257. static int SetCurve(ecc_key* key, byte* output, size_t outSz)
  13258. {
  13259. #ifdef HAVE_OID_ENCODING
  13260. int ret;
  13261. #endif
  13262. int idx;
  13263. word32 oidSz = 0;
  13264. /* validate key */
  13265. if (key == NULL || key->dp == NULL) {
  13266. return BAD_FUNC_ARG;
  13267. }
  13268. #ifdef HAVE_OID_ENCODING
  13269. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, NULL, &oidSz);
  13270. if (ret != 0) {
  13271. return ret;
  13272. }
  13273. #else
  13274. oidSz = key->dp->oidSz;
  13275. #endif
  13276. idx = SetObjectId((int)oidSz, output);
  13277. /* length only */
  13278. if (output == NULL) {
  13279. return idx + (int)oidSz;
  13280. }
  13281. /* verify output buffer has room */
  13282. if (oidSz > outSz)
  13283. return BUFFER_E;
  13284. #ifdef HAVE_OID_ENCODING
  13285. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, output+idx, &oidSz);
  13286. if (ret != 0) {
  13287. return ret;
  13288. }
  13289. #else
  13290. XMEMCPY(output+idx, key->dp->oid, oidSz);
  13291. #endif
  13292. idx += (int)oidSz;
  13293. return idx;
  13294. }
  13295. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  13296. #ifdef HAVE_ECC
  13297. /* Determines whether the signature algorithm is using ECDSA.
  13298. *
  13299. * @param [in] algoOID Signature algorithm identifier.
  13300. * @return 1 when algorithm is using ECDSA.
  13301. * @return 0 otherwise.
  13302. */
  13303. static WC_INLINE int IsSigAlgoECDSA(word32 algoOID)
  13304. {
  13305. /* ECDSA sigAlgo must not have ASN1 NULL parameters */
  13306. if (algoOID == CTC_SHAwECDSA || algoOID == CTC_SHA256wECDSA ||
  13307. algoOID == CTC_SHA384wECDSA || algoOID == CTC_SHA512wECDSA) {
  13308. return 1;
  13309. }
  13310. return 0;
  13311. }
  13312. #endif
  13313. /* Determines if OID is for an EC signing algorithm including ECDSA and EdDSA
  13314. * and post-quantum algorithms.
  13315. *
  13316. * @param [in] algoOID Algorithm OID.
  13317. * @return 1 when is EC signing algorithm.
  13318. * @return 0 otherwise.
  13319. */
  13320. static WC_INLINE int IsSigAlgoECC(word32 algoOID)
  13321. {
  13322. (void)algoOID;
  13323. return (0
  13324. #ifdef HAVE_ECC
  13325. || IsSigAlgoECDSA(algoOID)
  13326. #endif
  13327. #ifdef HAVE_ED25519
  13328. || (algoOID == ED25519k)
  13329. #endif
  13330. #ifdef HAVE_CURVE25519
  13331. || (algoOID == X25519k)
  13332. #endif
  13333. #ifdef HAVE_ED448
  13334. || (algoOID == ED448k)
  13335. #endif
  13336. #ifdef HAVE_CURVE448
  13337. || (algoOID == X448k)
  13338. #endif
  13339. #ifdef HAVE_PQC
  13340. #ifdef HAVE_FACON
  13341. || (algoOID == FALCON_LEVEL1k)
  13342. || (algoOID == FALCON_LEVEL5k)
  13343. #endif
  13344. #ifdef HAVE_DILITHIUM
  13345. || (algoOID == DILITHIUM_LEVEL2k)
  13346. || (algoOID == DILITHIUM_LEVEL3k)
  13347. || (algoOID == DILITHIUM_LEVEL5k)
  13348. #endif
  13349. #ifdef HAVE_SPHINCS
  13350. || (algoOID == SPHINCS_FAST_LEVEL1k)
  13351. || (algoOID == SPHINCS_FAST_LEVEL3k)
  13352. || (algoOID == SPHINCS_FAST_LEVEL5k)
  13353. || (algoOID == SPHINCS_SMALL_LEVEL1k)
  13354. || (algoOID == SPHINCS_SMALL_LEVEL3k)
  13355. || (algoOID == SPHINCS_SMALL_LEVEL5k)
  13356. #endif
  13357. #endif /* HAVE_PQC */
  13358. );
  13359. }
  13360. /* Encode an algorithm identifier.
  13361. *
  13362. * [algoOID, type] is unique.
  13363. *
  13364. * @param [in] algoOID Algorithm identifier.
  13365. * @param [out] output Buffer to hold encoding.
  13366. * @param [in] type Type of OID being encoded.
  13367. * @param [in] curveSz Add extra space for curve data.
  13368. * @return Encoded data size on success.
  13369. * @return 0 when dynamic memory allocation fails.
  13370. */
  13371. word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz)
  13372. {
  13373. #ifndef WOLFSSL_ASN_TEMPLATE
  13374. word32 tagSz, idSz, seqSz, algoSz = 0;
  13375. const byte* algoName = 0;
  13376. byte ID_Length[1 + MAX_LENGTH_SZ];
  13377. byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
  13378. word32 length = 0;
  13379. tagSz = (type == oidHashType ||
  13380. (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
  13381. (type == oidKeyType && algoOID == RSAk)) ? 2 : 0;
  13382. algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
  13383. if (algoName == NULL) {
  13384. WOLFSSL_MSG("Unknown Algorithm");
  13385. return 0;
  13386. }
  13387. idSz = (word32)SetObjectId((int)algoSz, ID_Length);
  13388. seqSz = SetSequence(idSz + algoSz + tagSz + (word32)curveSz, seqArray);
  13389. /* Copy only algo to output for DSA keys */
  13390. if (algoOID == DSAk && output) {
  13391. XMEMCPY(output, ID_Length, idSz);
  13392. XMEMCPY(output + idSz, algoName, algoSz);
  13393. if (tagSz == 2)
  13394. SetASNNull(&output[seqSz + idSz + algoSz]);
  13395. }
  13396. else if (output) {
  13397. XMEMCPY(output, seqArray, seqSz);
  13398. XMEMCPY(output + seqSz, ID_Length, idSz);
  13399. XMEMCPY(output + seqSz + idSz, algoName, algoSz);
  13400. if (tagSz == 2)
  13401. SetASNNull(&output[seqSz + idSz + algoSz]);
  13402. }
  13403. if (algoOID == DSAk)
  13404. length = idSz + algoSz + tagSz;
  13405. else
  13406. length = seqSz + idSz + algoSz + tagSz;
  13407. return length;
  13408. #else
  13409. DECL_ASNSETDATA(dataASN, algoIdASN_Length);
  13410. int sz;
  13411. int ret = 0;
  13412. int o = 0;
  13413. const byte* algoName = 0;
  13414. word32 algoSz = 0;
  13415. CALLOC_ASNSETDATA(dataASN, algoIdASN_Length, ret, NULL);
  13416. algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
  13417. if (algoName == NULL) {
  13418. WOLFSSL_MSG("Unknown Algorithm");
  13419. }
  13420. else {
  13421. /* Set the OID and OID type to encode. */
  13422. SetASN_OID(&dataASN[ALGOIDASN_IDX_OID], (word32)algoOID, (word32)type);
  13423. /* Hashes, signatures not ECC and keys not RSA output NULL tag. */
  13424. if (!(type == oidHashType ||
  13425. (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
  13426. (type == oidKeyType && algoOID == RSAk))) {
  13427. /* Don't put out NULL DER item. */
  13428. dataASN[ALGOIDASN_IDX_NULL].noOut = 1;
  13429. }
  13430. if (algoOID == DSAk) {
  13431. /* Don't include SEQUENCE for DSA keys. */
  13432. o = 1;
  13433. }
  13434. else if (curveSz > 0) {
  13435. /* Don't put out NULL DER item. */
  13436. dataASN[ALGOIDASN_IDX_NULL].noOut = 0;
  13437. /* Include space for extra data of length curveSz.
  13438. * Subtract 1 for sequence and 1 for length encoding. */
  13439. SetASN_Buffer(&dataASN[ALGOIDASN_IDX_NULL], NULL,
  13440. (word32)curveSz - 2);
  13441. }
  13442. /* Calculate size of encoding. */
  13443. ret = SizeASN_Items(algoIdASN + o, dataASN + o,
  13444. (int)algoIdASN_Length - (int)o, &sz);
  13445. if (ret == 0 && output != NULL) {
  13446. /* Encode into buffer. */
  13447. SetASN_Items(algoIdASN + o, dataASN + o,
  13448. (int)algoIdASN_Length - (int)o, output);
  13449. if (curveSz > 0) {
  13450. /* Return size excluding curve data. */
  13451. sz = (int)(dataASN[o].offset -
  13452. dataASN[ALGOIDASN_IDX_NULL].offset);
  13453. }
  13454. }
  13455. if (ret == 0) {
  13456. /* Return encoded size. */
  13457. ret = sz;
  13458. }
  13459. else {
  13460. /* Unsigned return type so 0 indicates error. */
  13461. ret = 0;
  13462. }
  13463. }
  13464. FREE_ASNSETDATA(dataASN, NULL);
  13465. return (word32)ret;
  13466. #endif /* WOLFSSL_ASN_TEMPLATE */
  13467. }
  13468. #ifdef WOLFSSL_ASN_TEMPLATE
  13469. /* Always encode PKCS#1 v1.5 RSA signature and compare to encoded data. */
  13470. /* ASN.1 template for DigestInfo for a PKCS#1 v1.5 RSA signature.
  13471. * PKCS#1 v2.2: RFC 8017, A.2.4 - DigestInfo
  13472. */
  13473. static const ASNItem digestInfoASN[] = {
  13474. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  13475. /* digestAlgorithm */
  13476. /* DIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  13477. /* DIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  13478. /* DIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  13479. /* digest */
  13480. /* DIGEST */ { 1, ASN_OCTET_STRING, 0, 0, 0 }
  13481. };
  13482. enum {
  13483. DIGESTINFOASN_IDX_SEQ = 0,
  13484. DIGESTINFOASN_IDX_DIGALGO_SEQ,
  13485. DIGESTINFOASN_IDX_DIGALGO_OID,
  13486. DIGESTINFOASN_IDX_DIGALGO_NULL,
  13487. DIGESTINFOASN_IDX_DIGEST
  13488. };
  13489. /* Number of items in ASN.1 template for DigestInfo for RSA. */
  13490. #define digestInfoASN_Length (sizeof(digestInfoASN) / sizeof(ASNItem))
  13491. #endif
  13492. /* Encode signature.
  13493. *
  13494. * @param [out] out Buffer to hold encoding.
  13495. * @param [in] digest Buffer holding digest.
  13496. * @param [in] digSz Length of digest in bytes.
  13497. * @return Encoded data size on success.
  13498. * @return 0 when dynamic memory allocation fails.
  13499. */
  13500. word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz,
  13501. int hashOID)
  13502. {
  13503. #ifndef WOLFSSL_ASN_TEMPLATE
  13504. byte digArray[MAX_ENCODED_DIG_SZ];
  13505. byte algoArray[MAX_ALGO_SZ];
  13506. byte seqArray[MAX_SEQ_SZ];
  13507. word32 encDigSz, algoSz, seqSz;
  13508. encDigSz = SetDigest(digest, digSz, digArray);
  13509. algoSz = SetAlgoID(hashOID, algoArray, oidHashType, 0);
  13510. seqSz = SetSequence(encDigSz + algoSz, seqArray);
  13511. XMEMCPY(out, seqArray, seqSz);
  13512. XMEMCPY(out + seqSz, algoArray, algoSz);
  13513. XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
  13514. return encDigSz + algoSz + seqSz;
  13515. #else
  13516. DECL_ASNSETDATA(dataASN, digestInfoASN_Length);
  13517. int ret = 0;
  13518. int sz;
  13519. unsigned char dgst[WC_MAX_DIGEST_SIZE];
  13520. CALLOC_ASNSETDATA(dataASN, digestInfoASN_Length, ret, NULL);
  13521. if (ret == 0) {
  13522. /* Set hash OID and type. */
  13523. SetASN_OID(&dataASN[DIGESTINFOASN_IDX_DIGALGO_OID], (word32)hashOID,
  13524. oidHashType);
  13525. /* Set digest. */
  13526. if (digest == out) {
  13527. XMEMCPY(dgst, digest, digSz);
  13528. digest = dgst;
  13529. }
  13530. SetASN_Buffer(&dataASN[DIGESTINFOASN_IDX_DIGEST], digest, digSz);
  13531. /* Calculate size of encoding. */
  13532. ret = SizeASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, &sz);
  13533. }
  13534. if (ret == 0) {
  13535. /* Encode PKCS#1 v1.5 RSA signature. */
  13536. SetASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, out);
  13537. ret = sz;
  13538. }
  13539. else {
  13540. /* Unsigned return type so 0 indicates error. */
  13541. ret = 0;
  13542. }
  13543. FREE_ASNSETDATA(dataASN, NULL);
  13544. return (word32)ret;
  13545. #endif
  13546. }
  13547. #ifndef NO_CERTS
  13548. int wc_GetCTC_HashOID(int type)
  13549. {
  13550. int ret;
  13551. enum wc_HashType hType;
  13552. hType = wc_HashTypeConvert(type);
  13553. ret = wc_HashGetOID(hType);
  13554. if (ret < 0) {
  13555. ret = 0; /* backwards compatibility */
  13556. }
  13557. return ret;
  13558. }
  13559. /* Initialize a signature context object.
  13560. *
  13561. * Object used for signing and verifying a certificate signature.
  13562. *
  13563. * @param [in, out] sigCtx Signature context object.
  13564. * @param [in] heap Dynamic memory hint.
  13565. * @param [in] devId Hardware device identifier.
  13566. */
  13567. void InitSignatureCtx(SignatureCtx* sigCtx, void* heap, int devId)
  13568. {
  13569. if (sigCtx) {
  13570. XMEMSET(sigCtx, 0, sizeof(SignatureCtx));
  13571. sigCtx->devId = devId;
  13572. sigCtx->heap = heap;
  13573. }
  13574. }
  13575. /* Free dynamic data in a signature context object.
  13576. *
  13577. * @param [in, out] sigCtx Signature context object.
  13578. */
  13579. void FreeSignatureCtx(SignatureCtx* sigCtx)
  13580. {
  13581. if (sigCtx == NULL)
  13582. return;
  13583. if (sigCtx->digest) {
  13584. XFREE(sigCtx->digest, sigCtx->heap, DYNAMIC_TYPE_DIGEST);
  13585. sigCtx->digest = NULL;
  13586. }
  13587. #if !(defined(NO_RSA) && defined(NO_DSA))
  13588. if (sigCtx->sigCpy) {
  13589. XFREE(sigCtx->sigCpy, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  13590. sigCtx->sigCpy = NULL;
  13591. }
  13592. #endif
  13593. #ifndef NO_ASN_CRYPT
  13594. if (sigCtx->key.ptr) {
  13595. switch (sigCtx->keyOID) {
  13596. #ifndef NO_RSA
  13597. #ifdef WC_RSA_PSS
  13598. case RSAPSSk:
  13599. #endif
  13600. case RSAk:
  13601. wc_FreeRsaKey(sigCtx->key.rsa);
  13602. XFREE(sigCtx->key.rsa, sigCtx->heap, DYNAMIC_TYPE_RSA);
  13603. sigCtx->key.rsa = NULL;
  13604. break;
  13605. #endif /* !NO_RSA */
  13606. #ifndef NO_DSA
  13607. case DSAk:
  13608. wc_FreeDsaKey(sigCtx->key.dsa);
  13609. XFREE(sigCtx->key.dsa, sigCtx->heap, DYNAMIC_TYPE_DSA);
  13610. sigCtx->key.dsa = NULL;
  13611. break;
  13612. #endif
  13613. #ifdef HAVE_ECC
  13614. case ECDSAk:
  13615. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  13616. defined(WC_ASYNC_ENABLE_ECC)
  13617. if (sigCtx->key.ecc->nb_ctx != NULL) {
  13618. XFREE(sigCtx->key.ecc->nb_ctx, sigCtx->heap,
  13619. DYNAMIC_TYPE_TMP_BUFFER);
  13620. }
  13621. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  13622. WC_ASYNC_ENABLE_ECC */
  13623. wc_ecc_free(sigCtx->key.ecc);
  13624. XFREE(sigCtx->key.ecc, sigCtx->heap, DYNAMIC_TYPE_ECC);
  13625. sigCtx->key.ecc = NULL;
  13626. break;
  13627. #endif /* HAVE_ECC */
  13628. #ifdef HAVE_ED25519
  13629. case ED25519k:
  13630. wc_ed25519_free(sigCtx->key.ed25519);
  13631. XFREE(sigCtx->key.ed25519, sigCtx->heap, DYNAMIC_TYPE_ED25519);
  13632. sigCtx->key.ed25519 = NULL;
  13633. break;
  13634. #endif /* HAVE_ED25519 */
  13635. #ifdef HAVE_ED448
  13636. case ED448k:
  13637. wc_ed448_free(sigCtx->key.ed448);
  13638. XFREE(sigCtx->key.ed448, sigCtx->heap, DYNAMIC_TYPE_ED448);
  13639. sigCtx->key.ed448 = NULL;
  13640. break;
  13641. #endif /* HAVE_ED448 */
  13642. #if defined(HAVE_PQC)
  13643. #if defined(HAVE_FALCON)
  13644. case FALCON_LEVEL1k:
  13645. case FALCON_LEVEL5k:
  13646. wc_falcon_free(sigCtx->key.falcon);
  13647. XFREE(sigCtx->key.falcon, sigCtx->heap,
  13648. DYNAMIC_TYPE_FALCON);
  13649. sigCtx->key.falcon = NULL;
  13650. break;
  13651. #endif /* HAVE_FALCON */
  13652. #if defined(HAVE_DILITHIUM)
  13653. case DILITHIUM_LEVEL2k:
  13654. case DILITHIUM_LEVEL3k:
  13655. case DILITHIUM_LEVEL5k:
  13656. wc_dilithium_free(sigCtx->key.dilithium);
  13657. XFREE(sigCtx->key.dilithium, sigCtx->heap,
  13658. DYNAMIC_TYPE_DILITHIUM);
  13659. sigCtx->key.dilithium = NULL;
  13660. break;
  13661. #endif /* HAVE_DILITHIUM */
  13662. #if defined(HAVE_SPHINCS)
  13663. case SPHINCS_FAST_LEVEL1k:
  13664. case SPHINCS_FAST_LEVEL3k:
  13665. case SPHINCS_FAST_LEVEL5k:
  13666. case SPHINCS_SMALL_LEVEL1k:
  13667. case SPHINCS_SMALL_LEVEL3k:
  13668. case SPHINCS_SMALL_LEVEL5k:
  13669. wc_sphincs_free(sigCtx->key.sphincs);
  13670. XFREE(sigCtx->key.sphincs, sigCtx->heap,
  13671. DYNAMIC_TYPE_SPHINCS);
  13672. sigCtx->key.sphincs = NULL;
  13673. break;
  13674. #endif /* HAVE_SPHINCS */
  13675. #endif /* HAVE_PQC */
  13676. default:
  13677. break;
  13678. } /* switch (keyOID) */
  13679. sigCtx->key.ptr = NULL;
  13680. }
  13681. #endif
  13682. /* reset state, we are done */
  13683. sigCtx->state = SIG_STATE_BEGIN;
  13684. }
  13685. #if !defined(NO_ASN_CRYPT) && !defined(NO_HASH_WRAPPER)
  13686. static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID,
  13687. byte* digest, int* typeH, int* digestSz, int verify)
  13688. {
  13689. int ret = 0;
  13690. switch (sigOID) {
  13691. #if defined(WOLFSSL_MD2)
  13692. case CTC_MD2wRSA:
  13693. if (!verify) {
  13694. ret = HASH_TYPE_E;
  13695. WOLFSSL_MSG("MD2 not supported for signing");
  13696. }
  13697. else if ((ret = wc_Md2Hash(buf, bufSz, digest)) == 0) {
  13698. *typeH = MD2h;
  13699. *digestSz = MD2_DIGEST_SIZE;
  13700. }
  13701. break;
  13702. #endif
  13703. #ifndef NO_MD5
  13704. case CTC_MD5wRSA:
  13705. if ((ret = wc_Md5Hash(buf, bufSz, digest)) == 0) {
  13706. *typeH = MD5h;
  13707. *digestSz = WC_MD5_DIGEST_SIZE;
  13708. }
  13709. break;
  13710. #endif
  13711. #ifndef NO_SHA
  13712. case CTC_SHAwRSA:
  13713. case CTC_SHAwDSA:
  13714. case CTC_SHAwECDSA:
  13715. if ((ret = wc_ShaHash(buf, bufSz, digest)) == 0) {
  13716. *typeH = SHAh;
  13717. *digestSz = WC_SHA_DIGEST_SIZE;
  13718. }
  13719. break;
  13720. #endif
  13721. #ifdef WOLFSSL_SHA224
  13722. case CTC_SHA224wRSA:
  13723. case CTC_SHA224wECDSA:
  13724. if ((ret = wc_Sha224Hash(buf, bufSz, digest)) == 0) {
  13725. *typeH = SHA224h;
  13726. *digestSz = WC_SHA224_DIGEST_SIZE;
  13727. }
  13728. break;
  13729. #endif
  13730. #ifndef NO_SHA256
  13731. case CTC_SHA256wRSA:
  13732. case CTC_SHA256wECDSA:
  13733. case CTC_SHA256wDSA:
  13734. if ((ret = wc_Sha256Hash(buf, bufSz, digest)) == 0) {
  13735. *typeH = SHA256h;
  13736. *digestSz = WC_SHA256_DIGEST_SIZE;
  13737. }
  13738. break;
  13739. #endif
  13740. #ifdef WOLFSSL_SHA384
  13741. case CTC_SHA384wRSA:
  13742. case CTC_SHA384wECDSA:
  13743. if ((ret = wc_Sha384Hash(buf, bufSz, digest)) == 0) {
  13744. *typeH = SHA384h;
  13745. *digestSz = WC_SHA384_DIGEST_SIZE;
  13746. }
  13747. break;
  13748. #endif
  13749. #ifdef WOLFSSL_SHA512
  13750. case CTC_SHA512wRSA:
  13751. case CTC_SHA512wECDSA:
  13752. if ((ret = wc_Sha512Hash(buf, bufSz, digest)) == 0) {
  13753. *typeH = SHA512h;
  13754. *digestSz = WC_SHA512_DIGEST_SIZE;
  13755. }
  13756. break;
  13757. #endif
  13758. #ifdef WOLFSSL_SHA3
  13759. #ifndef WOLFSSL_NOSHA3_224
  13760. case CTC_SHA3_224wRSA:
  13761. case CTC_SHA3_224wECDSA:
  13762. if ((ret = wc_Sha3_224Hash(buf, bufSz, digest)) == 0) {
  13763. *typeH = SHA3_224h;
  13764. *digestSz = WC_SHA3_224_DIGEST_SIZE;
  13765. }
  13766. break;
  13767. #endif
  13768. #ifndef WOLFSSL_NOSHA3_256
  13769. case CTC_SHA3_256wRSA:
  13770. case CTC_SHA3_256wECDSA:
  13771. if ((ret = wc_Sha3_256Hash(buf, bufSz, digest)) == 0) {
  13772. *typeH = SHA3_256h;
  13773. *digestSz = WC_SHA3_256_DIGEST_SIZE;
  13774. }
  13775. break;
  13776. #endif
  13777. #ifndef WOLFSSL_NOSHA3_384
  13778. case CTC_SHA3_384wRSA:
  13779. case CTC_SHA3_384wECDSA:
  13780. if ((ret = wc_Sha3_384Hash(buf, bufSz, digest)) == 0) {
  13781. *typeH = SHA3_384h;
  13782. *digestSz = WC_SHA3_384_DIGEST_SIZE;
  13783. }
  13784. break;
  13785. #endif
  13786. #ifndef WOLFSSL_NOSHA3_512
  13787. case CTC_SHA3_512wRSA:
  13788. case CTC_SHA3_512wECDSA:
  13789. if ((ret = wc_Sha3_512Hash(buf, bufSz, digest)) == 0) {
  13790. *typeH = SHA3_512h;
  13791. *digestSz = WC_SHA3_512_DIGEST_SIZE;
  13792. }
  13793. break;
  13794. #endif
  13795. #endif
  13796. #ifdef HAVE_ED25519
  13797. case CTC_ED25519:
  13798. /* Hashes done in signing operation.
  13799. * Two dependent hashes with prefixes performed.
  13800. */
  13801. break;
  13802. #endif
  13803. #ifdef HAVE_ED448
  13804. case CTC_ED448:
  13805. /* Hashes done in signing operation.
  13806. * Two dependent hashes with prefixes performed.
  13807. */
  13808. break;
  13809. #endif
  13810. #ifdef HAVE_PQC
  13811. #ifdef HAVE_FALCON
  13812. case CTC_FALCON_LEVEL1:
  13813. case CTC_FALCON_LEVEL5:
  13814. /* Hashes done in signing operation. */
  13815. break;
  13816. #endif
  13817. #ifdef HAVE_DILITHIUM
  13818. case CTC_DILITHIUM_LEVEL2:
  13819. case CTC_DILITHIUM_LEVEL3:
  13820. case CTC_DILITHIUM_LEVEL5:
  13821. /* Hashes done in signing operation. */
  13822. break;
  13823. #endif
  13824. #ifdef HAVE_SPHINCS
  13825. case CTC_SPHINCS_FAST_LEVEL1:
  13826. case CTC_SPHINCS_FAST_LEVEL3:
  13827. case CTC_SPHINCS_FAST_LEVEL5:
  13828. case CTC_SPHINCS_SMALL_LEVEL1:
  13829. case CTC_SPHINCS_SMALL_LEVEL3:
  13830. case CTC_SPHINCS_SMALL_LEVEL5:
  13831. /* Hashes done in signing operation. */
  13832. break;
  13833. #endif
  13834. #endif /* HAVE_PQC */
  13835. default:
  13836. ret = HASH_TYPE_E;
  13837. WOLFSSL_MSG("Hash for Signature has unsupported type");
  13838. }
  13839. (void)buf;
  13840. (void)bufSz;
  13841. (void)sigOID;
  13842. (void)digest;
  13843. (void)digestSz;
  13844. (void)typeH;
  13845. (void)verify;
  13846. return ret;
  13847. }
  13848. #endif /* !NO_ASN_CRYPT && !NO_HASH_WRAPPER */
  13849. /* Return codes: 0=Success, Negative (see error-crypt.h), ASN_SIG_CONFIRM_E */
  13850. static int ConfirmSignature(SignatureCtx* sigCtx,
  13851. const byte* buf, word32 bufSz,
  13852. const byte* key, word32 keySz, word32 keyOID,
  13853. const byte* sig, word32 sigSz, word32 sigOID,
  13854. const byte* sigParams, word32 sigParamsSz,
  13855. byte* rsaKeyIdx)
  13856. {
  13857. int ret = 0;
  13858. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  13859. CertAttribute* certatt = NULL;
  13860. #endif
  13861. if (sigCtx == NULL || buf == NULL || bufSz == 0 || key == NULL ||
  13862. keySz == 0 || sig == NULL || sigSz == 0) {
  13863. return BAD_FUNC_ARG;
  13864. }
  13865. (void)key;
  13866. (void)keySz;
  13867. (void)sig;
  13868. (void)sigSz;
  13869. (void)sigParams;
  13870. (void)sigParamsSz;
  13871. WOLFSSL_ENTER("ConfirmSignature");
  13872. #if !defined(WOLFSSL_RENESAS_TSIP_TLS) && !defined(WOLFSSL_RENESAS_SCEPROTECT)
  13873. (void)rsaKeyIdx;
  13874. #else
  13875. #if !defined(NO_RSA) || defined(HAVE_ECC)
  13876. certatt = (CertAttribute*)&sigCtx->CertAtt;
  13877. #endif
  13878. if (certatt) {
  13879. certatt->keyIndex = rsaKeyIdx;
  13880. certatt->cert = buf;
  13881. certatt->certSz = bufSz;
  13882. }
  13883. #endif
  13884. #ifndef NO_ASN_CRYPT
  13885. switch (sigCtx->state) {
  13886. case SIG_STATE_BEGIN:
  13887. {
  13888. sigCtx->keyOID = keyOID; /* must set early for cleanup */
  13889. sigCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, sigCtx->heap,
  13890. DYNAMIC_TYPE_DIGEST);
  13891. if (sigCtx->digest == NULL) {
  13892. ERROR_OUT(MEMORY_E, exit_cs);
  13893. }
  13894. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  13895. /* RSA PSS Defaults */
  13896. sigCtx->hash = WC_HASH_TYPE_SHA;
  13897. sigCtx->mgf = WC_MGF1SHA1;
  13898. sigCtx->saltLen = 20;
  13899. #endif
  13900. sigCtx->state = SIG_STATE_HASH;
  13901. } /* SIG_STATE_BEGIN */
  13902. FALL_THROUGH;
  13903. case SIG_STATE_HASH:
  13904. {
  13905. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  13906. if (sigOID == RSAPSSk) {
  13907. word32 fakeSigOID = 0;
  13908. ret = DecodeRsaPssParams(sigParams, sigParamsSz, &sigCtx->hash,
  13909. &sigCtx->mgf, &sigCtx->saltLen);
  13910. if (ret != 0) {
  13911. goto exit_cs;
  13912. }
  13913. ret = RsaPssHashOidToSigOid(sigCtx->hash, &fakeSigOID);
  13914. if (ret != 0) {
  13915. goto exit_cs;
  13916. }
  13917. /* Decode parameters. */
  13918. ret = HashForSignature(buf, bufSz, fakeSigOID, sigCtx->digest,
  13919. &sigCtx->typeH, &sigCtx->digestSz, 1);
  13920. if (ret != 0) {
  13921. goto exit_cs;
  13922. }
  13923. }
  13924. else
  13925. #endif
  13926. {
  13927. ret = HashForSignature(buf, bufSz, sigOID, sigCtx->digest,
  13928. &sigCtx->typeH, &sigCtx->digestSz, 1);
  13929. if (ret != 0) {
  13930. goto exit_cs;
  13931. }
  13932. }
  13933. sigCtx->state = SIG_STATE_KEY;
  13934. } /* SIG_STATE_HASH */
  13935. FALL_THROUGH;
  13936. case SIG_STATE_KEY:
  13937. {
  13938. switch (keyOID) {
  13939. #ifndef NO_RSA
  13940. #ifdef WC_RSA_PSS
  13941. case RSAPSSk:
  13942. #endif
  13943. case RSAk:
  13944. {
  13945. word32 idx = 0;
  13946. sigCtx->key.rsa = (RsaKey*)XMALLOC(sizeof(RsaKey),
  13947. sigCtx->heap, DYNAMIC_TYPE_RSA);
  13948. sigCtx->sigCpy = (byte*)XMALLOC(sigSz, sigCtx->heap,
  13949. DYNAMIC_TYPE_SIGNATURE);
  13950. if (sigCtx->key.rsa == NULL || sigCtx->sigCpy == NULL) {
  13951. ERROR_OUT(MEMORY_E, exit_cs);
  13952. }
  13953. if ((ret = wc_InitRsaKey_ex(sigCtx->key.rsa, sigCtx->heap,
  13954. sigCtx->devId)) != 0) {
  13955. goto exit_cs;
  13956. }
  13957. if (sigSz > MAX_ENCODED_SIG_SZ) {
  13958. WOLFSSL_MSG("Verify Signature is too big");
  13959. ERROR_OUT(BUFFER_E, exit_cs);
  13960. }
  13961. if ((ret = wc_RsaPublicKeyDecode(key, &idx, sigCtx->key.rsa,
  13962. keySz)) != 0) {
  13963. WOLFSSL_MSG("ASN Key decode error RSA");
  13964. WOLFSSL_ERROR_VERBOSE(ret);
  13965. goto exit_cs;
  13966. }
  13967. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  13968. sigCtx->out = NULL;
  13969. #ifdef WOLFSSL_ASYNC_CRYPT
  13970. sigCtx->asyncDev = &sigCtx->key.rsa->asyncDev;
  13971. #endif
  13972. break;
  13973. }
  13974. #endif /* !NO_RSA */
  13975. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  13976. case DSAk:
  13977. {
  13978. word32 idx = 0;
  13979. if (sigSz < DSA_MIN_SIG_SIZE) {
  13980. WOLFSSL_MSG("Verify Signature is too small");
  13981. ERROR_OUT(BUFFER_E, exit_cs);
  13982. }
  13983. sigCtx->key.dsa = (DsaKey*)XMALLOC(sizeof(DsaKey),
  13984. sigCtx->heap, DYNAMIC_TYPE_DSA);
  13985. sigCtx->sigCpy = (byte*)XMALLOC(sigSz,
  13986. sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  13987. if (sigCtx->key.dsa == NULL || sigCtx->sigCpy == NULL) {
  13988. ERROR_OUT(MEMORY_E, exit_cs);
  13989. }
  13990. if ((ret = wc_InitDsaKey_h(sigCtx->key.dsa, sigCtx->heap)) != 0) {
  13991. WOLFSSL_MSG("wc_InitDsaKey_h error");
  13992. goto exit_cs;
  13993. }
  13994. if ((ret = wc_DsaPublicKeyDecode(key, &idx, sigCtx->key.dsa,
  13995. keySz)) != 0) {
  13996. WOLFSSL_MSG("ASN Key decode error DSA");
  13997. WOLFSSL_ERROR_VERBOSE(ret);
  13998. goto exit_cs;
  13999. }
  14000. if (sigSz != DSA_160_SIG_SIZE &&
  14001. sigSz != DSA_256_SIG_SIZE) {
  14002. /* Try to parse it as the contents of a bitstring */
  14003. #ifdef WOLFSSL_SMALL_STACK
  14004. mp_int* r;
  14005. mp_int* s;
  14006. #else
  14007. mp_int r[1];
  14008. mp_int s[1];
  14009. #endif
  14010. int rSz;
  14011. int sSz;
  14012. #ifdef WOLFSSL_SMALL_STACK
  14013. r = (mp_int*)XMALLOC(sizeof(*r), sigCtx->heap,
  14014. DYNAMIC_TYPE_TMP_BUFFER);
  14015. if (r == NULL) {
  14016. ERROR_OUT(MEMORY_E, exit_cs);
  14017. }
  14018. s = (mp_int*)XMALLOC(sizeof(*s), sigCtx->heap,
  14019. DYNAMIC_TYPE_TMP_BUFFER);
  14020. if (s == NULL) {
  14021. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14022. ERROR_OUT(MEMORY_E, exit_cs);
  14023. }
  14024. #endif
  14025. if ((ret = mp_init_multi(r, s, NULL, NULL, NULL, NULL)) != MP_OKAY) {
  14026. goto exit_cs;
  14027. }
  14028. idx = 0;
  14029. if (DecodeECC_DSA_Sig(sig + idx, sigSz - idx, r, s)
  14030. != 0) {
  14031. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14032. "incorrect format");
  14033. mp_free(r);
  14034. mp_free(s);
  14035. #ifdef WOLFSSL_SMALL_STACK
  14036. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14037. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14038. #endif
  14039. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14040. }
  14041. rSz = mp_unsigned_bin_size(r);
  14042. sSz = mp_unsigned_bin_size(s);
  14043. if (rSz + sSz > (int)sigSz) {
  14044. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14045. "incorrect format");
  14046. mp_free(r);
  14047. mp_free(s);
  14048. #ifdef WOLFSSL_SMALL_STACK
  14049. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14050. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14051. #endif
  14052. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14053. }
  14054. if (mp_to_unsigned_bin(r, sigCtx->sigCpy) != MP_OKAY ||
  14055. mp_to_unsigned_bin(s,
  14056. sigCtx->sigCpy + rSz) != MP_OKAY) {
  14057. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14058. "incorrect format");
  14059. mp_free(r);
  14060. mp_free(s);
  14061. #ifdef WOLFSSL_SMALL_STACK
  14062. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14063. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14064. #endif
  14065. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14066. }
  14067. mp_free(r);
  14068. mp_free(s);
  14069. #ifdef WOLFSSL_SMALL_STACK
  14070. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14071. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14072. #endif
  14073. }
  14074. else {
  14075. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  14076. }
  14077. break;
  14078. }
  14079. #endif /* !NO_DSA && !HAVE_SELFTEST */
  14080. #ifdef HAVE_ECC
  14081. case ECDSAk:
  14082. {
  14083. word32 idx = 0;
  14084. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14085. defined(WC_ASYNC_ENABLE_ECC)
  14086. ecc_nb_ctx_t* nbCtx;
  14087. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14088. WC_ASYNC_ENABLE_ECC */
  14089. sigCtx->verify = 0;
  14090. sigCtx->key.ecc = (ecc_key*)XMALLOC(sizeof(ecc_key),
  14091. sigCtx->heap, DYNAMIC_TYPE_ECC);
  14092. if (sigCtx->key.ecc == NULL) {
  14093. ERROR_OUT(MEMORY_E, exit_cs);
  14094. }
  14095. if ((ret = wc_ecc_init_ex(sigCtx->key.ecc, sigCtx->heap,
  14096. sigCtx->devId)) < 0) {
  14097. goto exit_cs;
  14098. }
  14099. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14100. defined(WC_ASYNC_ENABLE_ECC)
  14101. nbCtx = (ecc_nb_ctx_t*)XMALLOC(sizeof(ecc_nb_ctx_t),
  14102. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14103. if (nbCtx == NULL) {
  14104. ERROR_OUT(MEMORY_E, exit_cs);
  14105. }
  14106. else {
  14107. ret = wc_ecc_set_nonblock(sigCtx->key.ecc, nbCtx);
  14108. if (ret != 0) {
  14109. goto exit_cs;
  14110. }
  14111. }
  14112. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14113. WC_ASYNC_ENABLE_ECC */
  14114. ret = wc_EccPublicKeyDecode(key, &idx, sigCtx->key.ecc,
  14115. keySz);
  14116. if (ret < 0) {
  14117. WOLFSSL_MSG("ASN Key import error ECC");
  14118. WOLFSSL_ERROR_VERBOSE(ret);
  14119. goto exit_cs;
  14120. }
  14121. #ifdef WOLFSSL_ASYNC_CRYPT
  14122. sigCtx->asyncDev = &sigCtx->key.ecc->asyncDev;
  14123. #endif
  14124. break;
  14125. }
  14126. #endif /* HAVE_ECC */
  14127. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  14128. case ED25519k:
  14129. {
  14130. sigCtx->verify = 0;
  14131. sigCtx->key.ed25519 = (ed25519_key*)XMALLOC(
  14132. sizeof(ed25519_key), sigCtx->heap,
  14133. DYNAMIC_TYPE_ED25519);
  14134. if (sigCtx->key.ed25519 == NULL) {
  14135. ERROR_OUT(MEMORY_E, exit_cs);
  14136. }
  14137. if ((ret = wc_ed25519_init_ex(sigCtx->key.ed25519,
  14138. sigCtx->heap, sigCtx->devId)) < 0) {
  14139. goto exit_cs;
  14140. }
  14141. if ((ret = wc_ed25519_import_public(key, keySz,
  14142. sigCtx->key.ed25519)) < 0) {
  14143. WOLFSSL_MSG("ASN Key import error ED25519");
  14144. WOLFSSL_ERROR_VERBOSE(ret);
  14145. goto exit_cs;
  14146. }
  14147. #ifdef WOLFSSL_ASYNC_CRYPT
  14148. sigCtx->asyncDev = &sigCtx->key.ed25519->asyncDev;
  14149. #endif
  14150. break;
  14151. }
  14152. #endif
  14153. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  14154. case ED448k:
  14155. {
  14156. sigCtx->verify = 0;
  14157. sigCtx->key.ed448 = (ed448_key*)XMALLOC(
  14158. sizeof(ed448_key), sigCtx->heap,
  14159. DYNAMIC_TYPE_ED448);
  14160. if (sigCtx->key.ed448 == NULL) {
  14161. ERROR_OUT(MEMORY_E, exit_cs);
  14162. }
  14163. if ((ret = wc_ed448_init(sigCtx->key.ed448)) < 0) {
  14164. goto exit_cs;
  14165. }
  14166. if ((ret = wc_ed448_import_public(key, keySz,
  14167. sigCtx->key.ed448)) < 0) {
  14168. WOLFSSL_MSG("ASN Key import error ED448");
  14169. WOLFSSL_ERROR_VERBOSE(ret);
  14170. goto exit_cs;
  14171. }
  14172. #ifdef WOLFSSL_ASYNC_CRYPT
  14173. sigCtx->asyncDev = &sigCtx->key.ed448->asyncDev;
  14174. #endif
  14175. break;
  14176. }
  14177. #endif
  14178. #if defined(HAVE_PQC)
  14179. #if defined(HAVE_FALCON)
  14180. case FALCON_LEVEL1k:
  14181. {
  14182. sigCtx->verify = 0;
  14183. sigCtx->key.falcon =
  14184. (falcon_key*)XMALLOC(sizeof(falcon_key),
  14185. sigCtx->heap,
  14186. DYNAMIC_TYPE_FALCON);
  14187. if (sigCtx->key.falcon == NULL) {
  14188. ERROR_OUT(MEMORY_E, exit_cs);
  14189. }
  14190. if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
  14191. goto exit_cs;
  14192. }
  14193. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 1))
  14194. < 0) {
  14195. goto exit_cs;
  14196. }
  14197. if ((ret = wc_falcon_import_public(key, keySz,
  14198. sigCtx->key.falcon)) < 0) {
  14199. WOLFSSL_MSG("ASN Key import error Falcon Level 1");
  14200. WOLFSSL_ERROR_VERBOSE(ret);
  14201. goto exit_cs;
  14202. }
  14203. break;
  14204. }
  14205. case FALCON_LEVEL5k:
  14206. {
  14207. sigCtx->verify = 0;
  14208. sigCtx->key.falcon =
  14209. (falcon_key*)XMALLOC(sizeof(falcon_key),
  14210. sigCtx->heap,
  14211. DYNAMIC_TYPE_FALCON);
  14212. if (sigCtx->key.falcon == NULL) {
  14213. ERROR_OUT(MEMORY_E, exit_cs);
  14214. }
  14215. if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
  14216. goto exit_cs;
  14217. }
  14218. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 5))
  14219. < 0) {
  14220. goto exit_cs;
  14221. }
  14222. if ((ret = wc_falcon_import_public(key, keySz,
  14223. sigCtx->key.falcon)) < 0) {
  14224. WOLFSSL_MSG("ASN Key import error Falcon Level 5");
  14225. WOLFSSL_ERROR_VERBOSE(ret);
  14226. goto exit_cs;
  14227. }
  14228. break;
  14229. }
  14230. #endif /* HAVE_FALCON */
  14231. #if defined(HAVE_DILITHIUM)
  14232. case DILITHIUM_LEVEL2k:
  14233. {
  14234. sigCtx->verify = 0;
  14235. sigCtx->key.dilithium =
  14236. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14237. sigCtx->heap,
  14238. DYNAMIC_TYPE_DILITHIUM);
  14239. if (sigCtx->key.dilithium == NULL) {
  14240. ERROR_OUT(MEMORY_E, exit_cs);
  14241. }
  14242. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14243. goto exit_cs;
  14244. }
  14245. if ((ret = wc_dilithium_set_level(
  14246. sigCtx->key.dilithium, 2))
  14247. < 0) {
  14248. goto exit_cs;
  14249. }
  14250. if ((ret = wc_dilithium_import_public(key, keySz,
  14251. sigCtx->key.dilithium)) < 0) {
  14252. WOLFSSL_MSG("ASN Key import error Dilithium Level 2");
  14253. goto exit_cs;
  14254. }
  14255. break;
  14256. }
  14257. case DILITHIUM_LEVEL3k:
  14258. {
  14259. sigCtx->verify = 0;
  14260. sigCtx->key.dilithium =
  14261. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14262. sigCtx->heap,
  14263. DYNAMIC_TYPE_DILITHIUM);
  14264. if (sigCtx->key.dilithium == NULL) {
  14265. ERROR_OUT(MEMORY_E, exit_cs);
  14266. }
  14267. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14268. goto exit_cs;
  14269. }
  14270. if ((ret = wc_dilithium_set_level(
  14271. sigCtx->key.dilithium, 3))
  14272. < 0) {
  14273. goto exit_cs;
  14274. }
  14275. if ((ret = wc_dilithium_import_public(key, keySz,
  14276. sigCtx->key.dilithium)) < 0) {
  14277. WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
  14278. goto exit_cs;
  14279. }
  14280. break;
  14281. }
  14282. case DILITHIUM_LEVEL5k:
  14283. {
  14284. sigCtx->verify = 0;
  14285. sigCtx->key.dilithium =
  14286. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14287. sigCtx->heap,
  14288. DYNAMIC_TYPE_DILITHIUM);
  14289. if (sigCtx->key.dilithium == NULL) {
  14290. ERROR_OUT(MEMORY_E, exit_cs);
  14291. }
  14292. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14293. goto exit_cs;
  14294. }
  14295. if ((ret = wc_dilithium_set_level(
  14296. sigCtx->key.dilithium, 5))
  14297. < 0) {
  14298. goto exit_cs;
  14299. }
  14300. if ((ret = wc_dilithium_import_public(key, keySz,
  14301. sigCtx->key.dilithium)) < 0) {
  14302. WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
  14303. goto exit_cs;
  14304. }
  14305. break;
  14306. }
  14307. #endif /* HAVE_DILITHIUM */
  14308. #if defined(HAVE_SPHINCS)
  14309. case SPHINCS_FAST_LEVEL1k:
  14310. {
  14311. sigCtx->verify = 0;
  14312. sigCtx->key.sphincs =
  14313. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14314. sigCtx->heap,
  14315. DYNAMIC_TYPE_SPHINCS);
  14316. if (sigCtx->key.sphincs == NULL) {
  14317. ERROR_OUT(MEMORY_E, exit_cs);
  14318. }
  14319. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14320. goto exit_cs;
  14321. }
  14322. if ((ret = wc_sphincs_set_level_and_optim(
  14323. sigCtx->key.sphincs, 1, FAST_VARIANT))
  14324. < 0) {
  14325. goto exit_cs;
  14326. }
  14327. if ((ret = wc_sphincs_import_public(key, keySz,
  14328. sigCtx->key.sphincs)) < 0) {
  14329. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
  14330. goto exit_cs;
  14331. }
  14332. break;
  14333. }
  14334. case SPHINCS_FAST_LEVEL3k:
  14335. {
  14336. sigCtx->verify = 0;
  14337. sigCtx->key.sphincs =
  14338. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14339. sigCtx->heap,
  14340. DYNAMIC_TYPE_SPHINCS);
  14341. if (sigCtx->key.sphincs == NULL) {
  14342. ERROR_OUT(MEMORY_E, exit_cs);
  14343. }
  14344. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14345. goto exit_cs;
  14346. }
  14347. if ((ret = wc_sphincs_set_level_and_optim(
  14348. sigCtx->key.sphincs, 3, FAST_VARIANT))
  14349. < 0) {
  14350. goto exit_cs;
  14351. }
  14352. if ((ret = wc_sphincs_import_public(key, keySz,
  14353. sigCtx->key.sphincs)) < 0) {
  14354. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
  14355. goto exit_cs;
  14356. }
  14357. break;
  14358. }
  14359. case SPHINCS_FAST_LEVEL5k:
  14360. {
  14361. sigCtx->verify = 0;
  14362. sigCtx->key.sphincs =
  14363. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14364. sigCtx->heap,
  14365. DYNAMIC_TYPE_SPHINCS);
  14366. if (sigCtx->key.sphincs == NULL) {
  14367. ERROR_OUT(MEMORY_E, exit_cs);
  14368. }
  14369. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14370. goto exit_cs;
  14371. }
  14372. if ((ret = wc_sphincs_set_level_and_optim(
  14373. sigCtx->key.sphincs, 5, FAST_VARIANT))
  14374. < 0) {
  14375. goto exit_cs;
  14376. }
  14377. if ((ret = wc_sphincs_import_public(key, keySz,
  14378. sigCtx->key.sphincs)) < 0) {
  14379. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
  14380. goto exit_cs;
  14381. }
  14382. break;
  14383. }
  14384. case SPHINCS_SMALL_LEVEL1k:
  14385. {
  14386. sigCtx->verify = 0;
  14387. sigCtx->key.sphincs =
  14388. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14389. sigCtx->heap,
  14390. DYNAMIC_TYPE_SPHINCS);
  14391. if (sigCtx->key.sphincs == NULL) {
  14392. ERROR_OUT(MEMORY_E, exit_cs);
  14393. }
  14394. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14395. goto exit_cs;
  14396. }
  14397. if ((ret = wc_sphincs_set_level_and_optim(
  14398. sigCtx->key.sphincs, 1, SMALL_VARIANT))
  14399. < 0) {
  14400. goto exit_cs;
  14401. }
  14402. if ((ret = wc_sphincs_import_public(key, keySz,
  14403. sigCtx->key.sphincs)) < 0) {
  14404. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
  14405. goto exit_cs;
  14406. }
  14407. break;
  14408. }
  14409. case SPHINCS_SMALL_LEVEL3k:
  14410. {
  14411. sigCtx->verify = 0;
  14412. sigCtx->key.sphincs =
  14413. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14414. sigCtx->heap,
  14415. DYNAMIC_TYPE_SPHINCS);
  14416. if (sigCtx->key.sphincs == NULL) {
  14417. ERROR_OUT(MEMORY_E, exit_cs);
  14418. }
  14419. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14420. goto exit_cs;
  14421. }
  14422. if ((ret = wc_sphincs_set_level_and_optim(
  14423. sigCtx->key.sphincs, 3, SMALL_VARIANT))
  14424. < 0) {
  14425. goto exit_cs;
  14426. }
  14427. if ((ret = wc_sphincs_import_public(key, keySz,
  14428. sigCtx->key.sphincs)) < 0) {
  14429. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
  14430. goto exit_cs;
  14431. }
  14432. break;
  14433. }
  14434. case SPHINCS_SMALL_LEVEL5k:
  14435. {
  14436. sigCtx->verify = 0;
  14437. sigCtx->key.sphincs =
  14438. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14439. sigCtx->heap,
  14440. DYNAMIC_TYPE_SPHINCS);
  14441. if (sigCtx->key.sphincs == NULL) {
  14442. ERROR_OUT(MEMORY_E, exit_cs);
  14443. }
  14444. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14445. goto exit_cs;
  14446. }
  14447. if ((ret = wc_sphincs_set_level_and_optim(
  14448. sigCtx->key.sphincs, 5, SMALL_VARIANT))
  14449. < 0) {
  14450. goto exit_cs;
  14451. }
  14452. if ((ret = wc_sphincs_import_public(key, keySz,
  14453. sigCtx->key.sphincs)) < 0) {
  14454. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
  14455. goto exit_cs;
  14456. }
  14457. break;
  14458. }
  14459. #endif /* HAVE_SPHINCS */
  14460. #endif /* HAVE_PQC */
  14461. default:
  14462. WOLFSSL_MSG("Verify Key type unknown");
  14463. ret = ASN_UNKNOWN_OID_E;
  14464. WOLFSSL_ERROR_VERBOSE(ret);
  14465. break;
  14466. } /* switch (keyOID) */
  14467. if (ret != 0) {
  14468. goto exit_cs;
  14469. }
  14470. sigCtx->state = SIG_STATE_DO;
  14471. #ifdef WOLFSSL_ASYNC_CRYPT
  14472. if (sigCtx->devId != INVALID_DEVID && sigCtx->asyncDev && sigCtx->asyncCtx) {
  14473. /* make sure event is initialized */
  14474. WOLF_EVENT* event = &sigCtx->asyncDev->event;
  14475. ret = wolfAsync_EventInit(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL,
  14476. sigCtx->asyncCtx, WC_ASYNC_FLAG_CALL_AGAIN);
  14477. }
  14478. #endif
  14479. } /* SIG_STATE_KEY */
  14480. FALL_THROUGH;
  14481. case SIG_STATE_DO:
  14482. {
  14483. switch (keyOID) {
  14484. #ifndef NO_RSA
  14485. case RSAk:
  14486. #ifdef WC_RSA_PSS
  14487. case RSAPSSk:
  14488. if (sigOID == RSAPSSk) {
  14489. /* TODO: pkCbRsaPss - RSA PSS callback. */
  14490. ret = wc_RsaPSS_VerifyInline_ex(sigCtx->sigCpy, sigSz,
  14491. &sigCtx->out, sigCtx->hash, sigCtx->mgf,
  14492. sigCtx->saltLen, sigCtx->key.rsa);
  14493. }
  14494. else
  14495. #endif
  14496. {
  14497. #if defined(HAVE_PK_CALLBACKS)
  14498. if (sigCtx->pkCbRsa) {
  14499. ret = sigCtx->pkCbRsa(
  14500. sigCtx->sigCpy, sigSz, &sigCtx->out,
  14501. key, keySz,
  14502. sigCtx->pkCtxRsa);
  14503. }
  14504. #if !defined(WOLFSSL_RENESAS_SCEPROTECT) && \
  14505. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  14506. else
  14507. #else
  14508. if (!sigCtx->pkCbRsa || ret == CRYPTOCB_UNAVAILABLE)
  14509. #endif /* WOLFSSL_RENESAS_SCEPROTECT */
  14510. #endif /* HAVE_PK_CALLBACKS */
  14511. {
  14512. ret = wc_RsaSSL_VerifyInline(sigCtx->sigCpy, sigSz,
  14513. &sigCtx->out, sigCtx->key.rsa);
  14514. }
  14515. }
  14516. break;
  14517. #endif /* !NO_RSA */
  14518. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  14519. case DSAk:
  14520. {
  14521. ret = wc_DsaVerify(sigCtx->digest, sigCtx->sigCpy,
  14522. sigCtx->key.dsa, &sigCtx->verify);
  14523. break;
  14524. }
  14525. #endif /* !NO_DSA && !HAVE_SELFTEST */
  14526. #if defined(HAVE_ECC) && defined(HAVE_ECC_VERIFY)
  14527. case ECDSAk:
  14528. {
  14529. #if defined(HAVE_PK_CALLBACKS)
  14530. if (sigCtx->pkCbEcc) {
  14531. ret = sigCtx->pkCbEcc(
  14532. sig, sigSz,
  14533. sigCtx->digest, (unsigned int)sigCtx->digestSz,
  14534. key, keySz, &sigCtx->verify,
  14535. sigCtx->pkCtxEcc);
  14536. }
  14537. #if !defined(WOLFSSL_RENESAS_SCEPROTECT) && \
  14538. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  14539. else
  14540. #else
  14541. if (!sigCtx->pkCbEcc || ret == CRYPTOCB_UNAVAILABLE)
  14542. #endif /* WOLFSSL_RENESAS_SCEPROTECT */
  14543. #endif /* HAVE_PK_CALLBACKS */
  14544. {
  14545. ret = wc_ecc_verify_hash(sig, sigSz, sigCtx->digest,
  14546. (word32)sigCtx->digestSz, &sigCtx->verify,
  14547. sigCtx->key.ecc);
  14548. }
  14549. break;
  14550. }
  14551. #endif /* HAVE_ECC */
  14552. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_VERIFY)
  14553. case ED25519k:
  14554. {
  14555. ret = wc_ed25519_verify_msg(sig, sigSz, buf, bufSz,
  14556. &sigCtx->verify, sigCtx->key.ed25519);
  14557. break;
  14558. }
  14559. #endif
  14560. #if defined(HAVE_ED448) && defined(HAVE_ED448_VERIFY)
  14561. case ED448k:
  14562. {
  14563. ret = wc_ed448_verify_msg(sig, sigSz, buf, bufSz,
  14564. &sigCtx->verify, sigCtx->key.ed448,
  14565. NULL, 0);
  14566. break;
  14567. }
  14568. #endif
  14569. #if defined(HAVE_PQC)
  14570. #if defined(HAVE_FALCON)
  14571. case FALCON_LEVEL1k:
  14572. case FALCON_LEVEL5k:
  14573. {
  14574. ret = wc_falcon_verify_msg(sig, sigSz, buf, bufSz,
  14575. &sigCtx->verify,
  14576. sigCtx->key.falcon);
  14577. break;
  14578. }
  14579. #endif /* HAVE_FALCON */
  14580. #if defined(HAVE_DILITHIUM)
  14581. case DILITHIUM_LEVEL2k:
  14582. case DILITHIUM_LEVEL3k:
  14583. case DILITHIUM_LEVEL5k:
  14584. {
  14585. ret = wc_dilithium_verify_msg(sig, sigSz, buf, bufSz,
  14586. &sigCtx->verify,
  14587. sigCtx->key.dilithium);
  14588. break;
  14589. }
  14590. #endif /* HAVE_DILITHIUM */
  14591. #if defined(HAVE_SPHINCS)
  14592. case SPHINCS_FAST_LEVEL1k:
  14593. case SPHINCS_FAST_LEVEL3k:
  14594. case SPHINCS_FAST_LEVEL5k:
  14595. case SPHINCS_SMALL_LEVEL1k:
  14596. case SPHINCS_SMALL_LEVEL3k:
  14597. case SPHINCS_SMALL_LEVEL5k:
  14598. {
  14599. ret = wc_sphincs_verify_msg(sig, sigSz, buf, bufSz,
  14600. &sigCtx->verify,
  14601. sigCtx->key.sphincs);
  14602. break;
  14603. }
  14604. #endif /* HAVE_SPHINCS */
  14605. #endif /* HAVE_PQC */
  14606. default:
  14607. break;
  14608. } /* switch (keyOID) */
  14609. #ifdef WOLFSSL_ASYNC_CRYPT
  14610. if (ret == WC_PENDING_E) {
  14611. goto exit_cs;
  14612. }
  14613. #endif
  14614. if (ret < 0) {
  14615. /* treat all errors as ASN_SIG_CONFIRM_E */
  14616. ret = ASN_SIG_CONFIRM_E;
  14617. WOLFSSL_ERROR_VERBOSE(ret);
  14618. goto exit_cs;
  14619. }
  14620. sigCtx->state = SIG_STATE_CHECK;
  14621. } /* SIG_STATE_DO */
  14622. FALL_THROUGH;
  14623. case SIG_STATE_CHECK:
  14624. {
  14625. switch (keyOID) {
  14626. #ifndef NO_RSA
  14627. case RSAk:
  14628. #ifdef WC_RSA_PSS
  14629. case RSAPSSk:
  14630. if (sigOID == RSAPSSk) {
  14631. #if (defined(HAVE_SELFTEST) && \
  14632. (!defined(HAVE_SELFTEST_VERSION) || \
  14633. (HAVE_SELFTEST_VERSION < 2))) || \
  14634. (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  14635. (HAVE_FIPS_VERSION < 2))
  14636. ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
  14637. sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
  14638. sigCtx->saltLen);
  14639. #elif (defined(HAVE_SELFTEST) && \
  14640. (HAVE_SELFTEST_VERSION == 2)) || \
  14641. (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  14642. (HAVE_FIPS_VERSION == 2))
  14643. ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
  14644. sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
  14645. sigCtx->saltLen, 0);
  14646. #else
  14647. ret = wc_RsaPSS_CheckPadding_ex2(sigCtx->digest,
  14648. (word32)sigCtx->digestSz, sigCtx->out, (word32)ret, sigCtx->hash,
  14649. sigCtx->saltLen, wc_RsaEncryptSize(sigCtx->key.rsa) * 8,
  14650. sigCtx->heap);
  14651. #endif
  14652. break;
  14653. }
  14654. else
  14655. #endif
  14656. {
  14657. int encodedSigSz, verifySz;
  14658. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || \
  14659. defined(WOLFSSL_RENESAS_SCEPROTECT)
  14660. if (sigCtx->CertAtt.verifyByTSIP_SCE == 1) break;
  14661. #endif
  14662. #ifdef WOLFSSL_SMALL_STACK
  14663. byte* encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  14664. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14665. if (encodedSig == NULL) {
  14666. ERROR_OUT(MEMORY_E, exit_cs);
  14667. }
  14668. #else
  14669. byte encodedSig[MAX_ENCODED_SIG_SZ];
  14670. #endif
  14671. verifySz = ret;
  14672. /* make sure we're right justified */
  14673. encodedSigSz = (int)wc_EncodeSignature(encodedSig,
  14674. sigCtx->digest, (word32)sigCtx->digestSz,
  14675. sigCtx->typeH);
  14676. if (encodedSigSz == verifySz && sigCtx->out != NULL &&
  14677. XMEMCMP(sigCtx->out, encodedSig,
  14678. (size_t)encodedSigSz) == 0) {
  14679. ret = 0;
  14680. }
  14681. else {
  14682. WOLFSSL_MSG("RSA SSL verify match encode error");
  14683. ret = ASN_SIG_CONFIRM_E;
  14684. WOLFSSL_ERROR_VERBOSE(ret);
  14685. }
  14686. #ifdef WOLFSSL_SMALL_STACK
  14687. XFREE(encodedSig, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14688. #endif
  14689. break;
  14690. }
  14691. #endif /* NO_RSA */
  14692. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  14693. case DSAk:
  14694. {
  14695. if (sigCtx->verify == 1) {
  14696. ret = 0;
  14697. }
  14698. else {
  14699. WOLFSSL_MSG("DSA Verify didn't match");
  14700. ret = ASN_SIG_CONFIRM_E;
  14701. WOLFSSL_ERROR_VERBOSE(ret);
  14702. }
  14703. break;
  14704. }
  14705. #endif /* !NO_DSA && !HAVE_SELFTEST */
  14706. #ifdef HAVE_ECC
  14707. case ECDSAk:
  14708. {
  14709. if (sigCtx->verify == 1) {
  14710. ret = 0;
  14711. }
  14712. else {
  14713. WOLFSSL_MSG("ECC Verify didn't match");
  14714. ret = ASN_SIG_CONFIRM_E;
  14715. WOLFSSL_ERROR_VERBOSE(ret);
  14716. }
  14717. break;
  14718. }
  14719. #endif /* HAVE_ECC */
  14720. #ifdef HAVE_ED25519
  14721. case ED25519k:
  14722. {
  14723. if (sigCtx->verify == 1) {
  14724. ret = 0;
  14725. }
  14726. else {
  14727. WOLFSSL_MSG("ED25519 Verify didn't match");
  14728. ret = ASN_SIG_CONFIRM_E;
  14729. WOLFSSL_ERROR_VERBOSE(ret);
  14730. }
  14731. break;
  14732. }
  14733. #endif /* HAVE_ED25519 */
  14734. #ifdef HAVE_ED448
  14735. case ED448k:
  14736. {
  14737. if (sigCtx->verify == 1) {
  14738. ret = 0;
  14739. }
  14740. else {
  14741. WOLFSSL_MSG("ED448 Verify didn't match");
  14742. ret = ASN_SIG_CONFIRM_E;
  14743. WOLFSSL_ERROR_VERBOSE(ret);
  14744. }
  14745. break;
  14746. }
  14747. #endif /* HAVE_ED448 */
  14748. #ifdef HAVE_PQC
  14749. #ifdef HAVE_FALCON
  14750. case FALCON_LEVEL1k:
  14751. {
  14752. if (sigCtx->verify == 1) {
  14753. ret = 0;
  14754. }
  14755. else {
  14756. WOLFSSL_MSG("FALCON_LEVEL1 Verify didn't match");
  14757. ret = ASN_SIG_CONFIRM_E;
  14758. WOLFSSL_ERROR_VERBOSE(ret);
  14759. }
  14760. break;
  14761. }
  14762. case FALCON_LEVEL5k:
  14763. {
  14764. if (sigCtx->verify == 1) {
  14765. ret = 0;
  14766. }
  14767. else {
  14768. WOLFSSL_MSG("FALCON_LEVEL5 Verify didn't match");
  14769. ret = ASN_SIG_CONFIRM_E;
  14770. WOLFSSL_ERROR_VERBOSE(ret);
  14771. }
  14772. break;
  14773. }
  14774. #endif /* HAVE_FALCON */
  14775. #ifdef HAVE_DILITHIUM
  14776. case DILITHIUM_LEVEL2k:
  14777. {
  14778. if (sigCtx->verify == 1) {
  14779. ret = 0;
  14780. }
  14781. else {
  14782. WOLFSSL_MSG("DILITHIUM_LEVEL2 Verify didn't match");
  14783. ret = ASN_SIG_CONFIRM_E;
  14784. }
  14785. break;
  14786. }
  14787. case DILITHIUM_LEVEL3k:
  14788. {
  14789. if (sigCtx->verify == 1) {
  14790. ret = 0;
  14791. }
  14792. else {
  14793. WOLFSSL_MSG("DILITHIUM_LEVEL3 Verify didn't match");
  14794. ret = ASN_SIG_CONFIRM_E;
  14795. }
  14796. break;
  14797. }
  14798. case DILITHIUM_LEVEL5k:
  14799. {
  14800. if (sigCtx->verify == 1) {
  14801. ret = 0;
  14802. }
  14803. else {
  14804. WOLFSSL_MSG("DILITHIUM_LEVEL5 Verify didn't match");
  14805. ret = ASN_SIG_CONFIRM_E;
  14806. }
  14807. break;
  14808. }
  14809. #endif /* HAVE_DILITHIUM */
  14810. #ifdef HAVE_SPHINCS
  14811. case SPHINCS_FAST_LEVEL1k:
  14812. {
  14813. if (sigCtx->verify == 1) {
  14814. ret = 0;
  14815. }
  14816. else {
  14817. WOLFSSL_MSG("SPHINCS_FAST_LEVEL1 Verify didn't match");
  14818. ret = ASN_SIG_CONFIRM_E;
  14819. }
  14820. break;
  14821. }
  14822. case SPHINCS_FAST_LEVEL3k:
  14823. {
  14824. if (sigCtx->verify == 1) {
  14825. ret = 0;
  14826. }
  14827. else {
  14828. WOLFSSL_MSG("SPHINCS_FAST_LEVEL3 Verify didn't match");
  14829. ret = ASN_SIG_CONFIRM_E;
  14830. }
  14831. break;
  14832. }
  14833. case SPHINCS_FAST_LEVEL5k:
  14834. {
  14835. if (sigCtx->verify == 1) {
  14836. ret = 0;
  14837. }
  14838. else {
  14839. WOLFSSL_MSG("SPHINCS_FAST_LEVEL5 Verify didn't match");
  14840. ret = ASN_SIG_CONFIRM_E;
  14841. }
  14842. break;
  14843. }
  14844. case SPHINCS_SMALL_LEVEL1k:
  14845. {
  14846. if (sigCtx->verify == 1) {
  14847. ret = 0;
  14848. }
  14849. else {
  14850. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL1 Verify didn't match");
  14851. ret = ASN_SIG_CONFIRM_E;
  14852. }
  14853. break;
  14854. }
  14855. case SPHINCS_SMALL_LEVEL3k:
  14856. {
  14857. if (sigCtx->verify == 1) {
  14858. ret = 0;
  14859. }
  14860. else {
  14861. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL3 Verify didn't match");
  14862. ret = ASN_SIG_CONFIRM_E;
  14863. }
  14864. break;
  14865. }
  14866. case SPHINCS_SMALL_LEVEL5k:
  14867. {
  14868. if (sigCtx->verify == 1) {
  14869. ret = 0;
  14870. }
  14871. else {
  14872. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL5 Verify didn't match");
  14873. ret = ASN_SIG_CONFIRM_E;
  14874. }
  14875. break;
  14876. }
  14877. #endif /* HAVE_SPHINCS */
  14878. #endif /* HAVE_PQC */
  14879. default:
  14880. break;
  14881. } /* switch (keyOID) */
  14882. break;
  14883. } /* SIG_STATE_CHECK */
  14884. default:
  14885. break;
  14886. } /* switch (sigCtx->state) */
  14887. exit_cs:
  14888. #endif /* !NO_ASN_CRYPT */
  14889. (void)keyOID;
  14890. (void)sigOID;
  14891. WOLFSSL_LEAVE("ConfirmSignature", ret);
  14892. #ifdef WOLFSSL_ASYNC_CRYPT
  14893. if (ret == WC_PENDING_E)
  14894. return ret;
  14895. #endif
  14896. FreeSignatureCtx(sigCtx);
  14897. return ret;
  14898. }
  14899. #ifndef IGNORE_NAME_CONSTRAINTS
  14900. static int MatchBaseName(int type, const char* name, int nameSz,
  14901. const char* base, int baseSz)
  14902. {
  14903. if (base == NULL || baseSz <= 0 || name == NULL || nameSz <= 0 ||
  14904. name[0] == '.' || nameSz < baseSz ||
  14905. (type != ASN_RFC822_TYPE && type != ASN_DNS_TYPE &&
  14906. type != ASN_DIR_TYPE)) {
  14907. return 0;
  14908. }
  14909. if (type == ASN_DIR_TYPE)
  14910. return XMEMCMP(name, base, (size_t)baseSz) == 0;
  14911. /* If an email type, handle special cases where the base is only
  14912. * a domain, or is an email address itself. */
  14913. if (type == ASN_RFC822_TYPE) {
  14914. const char* p = NULL;
  14915. int count = 0;
  14916. if (base[0] != '.') {
  14917. p = base;
  14918. count = 0;
  14919. /* find the '@' in the base */
  14920. while (*p != '@' && count < baseSz) {
  14921. count++;
  14922. p++;
  14923. }
  14924. /* No '@' in base, reset p to NULL */
  14925. if (count >= baseSz)
  14926. p = NULL;
  14927. }
  14928. if (p == NULL) {
  14929. /* Base isn't an email address, it is a domain name,
  14930. * wind the name forward one character past its '@'. */
  14931. p = name;
  14932. count = 0;
  14933. while (*p != '@' && count < baseSz) {
  14934. count++;
  14935. p++;
  14936. }
  14937. if (count < baseSz && *p == '@') {
  14938. name = p + 1;
  14939. nameSz -= count + 1;
  14940. }
  14941. }
  14942. }
  14943. /* RFC 5280 section 4.2.1.10
  14944. * "...Any DNS name that can be constructed by simply adding zero or more
  14945. * labels to the left-hand side of the name satisfies the name constraint."
  14946. * i.e www.host.example.com works for host.example.com name constraint and
  14947. * host1.example.com does not. */
  14948. if (type == ASN_DNS_TYPE || (type == ASN_RFC822_TYPE && base[0] == '.')) {
  14949. int szAdjust = nameSz - baseSz;
  14950. name += szAdjust;
  14951. nameSz -= szAdjust;
  14952. }
  14953. while (nameSz > 0) {
  14954. if (XTOLOWER((unsigned char)*name++) !=
  14955. XTOLOWER((unsigned char)*base++))
  14956. return 0;
  14957. nameSz--;
  14958. }
  14959. return 1;
  14960. }
  14961. /* Search through the list to find if the name is permitted.
  14962. * name The DNS name to search for
  14963. * dnsList The list to search through
  14964. * nameType Type of DNS name to currently searching
  14965. * return 1 if found in list or if not needed
  14966. * return 0 if not found in the list but is needed
  14967. */
  14968. static int PermittedListOk(DNS_entry* name, Base_entry* dnsList, byte nameType)
  14969. {
  14970. Base_entry* current = dnsList;
  14971. int match = 0;
  14972. int need = 0;
  14973. int ret = 1; /* is ok unless needed and no match found */
  14974. while (current != NULL) {
  14975. if (current->type == nameType) {
  14976. need = 1; /* restriction on permitted names is set for this type */
  14977. if (name->len >= current->nameSz &&
  14978. MatchBaseName(nameType, name->name, name->len,
  14979. current->name, current->nameSz)) {
  14980. match = 1; /* found the current name in the permitted list*/
  14981. break;
  14982. }
  14983. }
  14984. current = current->next;
  14985. }
  14986. /* check if permitted name restriction was set and no matching name found */
  14987. if (need && !match)
  14988. ret = 0;
  14989. return ret;
  14990. }
  14991. /* Search through the list to find if the name is excluded.
  14992. * name The DNS name to search for
  14993. * dnsList The list to search through
  14994. * nameType Type of DNS name to currently searching
  14995. * return 1 if found in list and 0 if not found in the list
  14996. */
  14997. static int IsInExcludedList(DNS_entry* name, Base_entry* dnsList, byte nameType)
  14998. {
  14999. int ret = 0; /* default of not found in the list */
  15000. Base_entry* current = dnsList;
  15001. while (current != NULL) {
  15002. if (current->type == nameType) {
  15003. if (name->len >= current->nameSz &&
  15004. MatchBaseName(nameType, name->name, name->len,
  15005. current->name, current->nameSz)) {
  15006. ret = 1;
  15007. break;
  15008. }
  15009. }
  15010. current = current->next;
  15011. }
  15012. return ret;
  15013. }
  15014. static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert)
  15015. {
  15016. const byte nameTypes[] = {ASN_RFC822_TYPE, ASN_DNS_TYPE, ASN_DIR_TYPE};
  15017. int i;
  15018. if (signer == NULL || cert == NULL)
  15019. return 0;
  15020. if (signer->excludedNames == NULL && signer->permittedNames == NULL)
  15021. return 1;
  15022. for (i=0; i < (int)sizeof(nameTypes); i++) {
  15023. byte nameType = nameTypes[i];
  15024. DNS_entry* name = NULL;
  15025. DNS_entry subjectDnsName; /* temporary node used for subject name */
  15026. XMEMSET(&subjectDnsName, 0, sizeof(DNS_entry));
  15027. switch (nameType) {
  15028. case ASN_DNS_TYPE:
  15029. /* Should it also consider CN in subject? It could use
  15030. * subjectDnsName too */
  15031. name = cert->altNames;
  15032. break;
  15033. case ASN_RFC822_TYPE:
  15034. /* Shouldn't it validade E= in subject as well? */
  15035. name = cert->altEmailNames;
  15036. /* Add subject email for checking. */
  15037. if (cert->subjectEmail != NULL) {
  15038. /* RFC 5280 section 4.2.1.10
  15039. * "When constraints are imposed on the rfc822Name name
  15040. * form, but the certificate does not include a subject
  15041. * alternative name, the rfc822Name constraint MUST be
  15042. * applied to the attribute of type emailAddress in the
  15043. * subject distinguished name" */
  15044. subjectDnsName.next = NULL;
  15045. subjectDnsName.type = ASN_RFC822_TYPE;
  15046. subjectDnsName.len = cert->subjectEmailLen;
  15047. subjectDnsName.name = (char *)cert->subjectEmail;
  15048. }
  15049. break;
  15050. case ASN_DIR_TYPE:
  15051. #ifndef WOLFSSL_NO_ASN_STRICT
  15052. name = cert->altDirNames;
  15053. #endif
  15054. /* RFC 5280 section 4.2.1.10
  15055. "Restrictions of the form directoryName MUST be
  15056. applied to the subject field .... and to any names
  15057. of type directoryName in the subjectAltName
  15058. extension"
  15059. */
  15060. if (cert->subjectRaw != NULL) {
  15061. subjectDnsName.next = NULL;
  15062. subjectDnsName.type = ASN_DIR_TYPE;
  15063. subjectDnsName.len = cert->subjectRawLen;
  15064. subjectDnsName.name = (char *)cert->subjectRaw;
  15065. }
  15066. break;
  15067. default:
  15068. /* Other types of names are ignored for now.
  15069. * Shouldn't it be rejected if it there is a altNamesByType[nameType]
  15070. * and signer->extNameConstraintCrit is set? */
  15071. return 0;
  15072. }
  15073. while (name != NULL) {
  15074. if (IsInExcludedList(name, signer->excludedNames, nameType) == 1) {
  15075. WOLFSSL_MSG("Excluded name was found!");
  15076. return 0;
  15077. }
  15078. /* Check against the permitted list */
  15079. if (PermittedListOk(name, signer->permittedNames, nameType) != 1) {
  15080. WOLFSSL_MSG("Permitted name was not found!");
  15081. return 0;
  15082. }
  15083. name = name->next;
  15084. }
  15085. /* handle comparing against subject name too */
  15086. if (subjectDnsName.len > 0 && subjectDnsName.name != NULL) {
  15087. if (IsInExcludedList(&subjectDnsName, signer->excludedNames,
  15088. nameType) == 1) {
  15089. WOLFSSL_MSG("Excluded name was found!");
  15090. return 0;
  15091. }
  15092. /* Check against the permitted list */
  15093. if (PermittedListOk(&subjectDnsName, signer->permittedNames,
  15094. nameType) != 1) {
  15095. WOLFSSL_MSG("Permitted name was not found!");
  15096. return 0;
  15097. }
  15098. }
  15099. }
  15100. return 1;
  15101. }
  15102. #endif /* IGNORE_NAME_CONSTRAINTS */
  15103. #ifndef WOLFSSL_ASN_TEMPLATE
  15104. static void AddAltName(DecodedCert* cert, DNS_entry* dnsEntry)
  15105. {
  15106. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  15107. dnsEntry->next = NULL;
  15108. if (cert->altNames == NULL) {
  15109. /* First on list */
  15110. cert->altNames = dnsEntry;
  15111. }
  15112. else {
  15113. DNS_entry* temp = cert->altNames;
  15114. /* Find end */
  15115. for (; (temp->next != NULL); temp = temp->next);
  15116. /* Add to end */
  15117. temp->next = dnsEntry;
  15118. }
  15119. #else
  15120. dnsEntry->next = cert->altNames;
  15121. cert->altNames = dnsEntry;
  15122. #endif
  15123. }
  15124. #endif
  15125. #ifdef WOLFSSL_ASN_TEMPLATE
  15126. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
  15127. /* ASN.1 template for OtherName of an X.509 certificate.
  15128. * X.509: RFC 5280, 4.2.1.6 - OtherName (without implicit outer SEQUENCE).
  15129. * HW Name: RFC 4108, 5 - Hardware Module Name
  15130. * Only support HW Name where the type is a HW serial number.
  15131. *
  15132. * Other Names handled for FPKI (Federal PKI) use:
  15133. * UPN (Universal Principal Name), a non-standard Other Name
  15134. * (RFC3280 sec 4.2.1.7). Often used with FIPS 201 smartcard login.
  15135. * FASC-N (Federal Agency Smart Credential Number), defined in the document
  15136. * fpki-x509-cert-policy-common.pdf. Used for a smart card ID.
  15137. */
  15138. static const ASNItem otherNameASN[] = {
  15139. /* TYPEID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  15140. /* VALUE */ { 0, ASN_CONTEXT_SPECIFIC | ASN_OTHERNAME_VALUE, 1, 1, 0 },
  15141. /* UPN */ { 1, ASN_UTF8STRING, 0, 0, 2 },
  15142. /* FASC-N */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
  15143. /* HWN_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 2 },
  15144. /* HWN_TYPE */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  15145. /* HWN_NUM */ { 2, ASN_OCTET_STRING, 0, 0, 0 }
  15146. };
  15147. enum {
  15148. OTHERNAMEASN_IDX_TYPEID = 0,
  15149. OTHERNAMEASN_IDX_VALUE,
  15150. OTHERNAMEASN_IDX_UPN,
  15151. OTHERNAMEASN_IDX_FASCN,
  15152. OTHERNAMEASN_IDX_HWN_SEQ,
  15153. OTHERNAMEASN_IDX_HWN_TYPE,
  15154. OTHERNAMEASN_IDX_HWN_NUM
  15155. };
  15156. /* Number of items in ASN.1 template for OtherName of an X.509 certificate. */
  15157. #define otherNameASN_Length (sizeof(otherNameASN) / sizeof(ASNItem))
  15158. #ifdef WOLFSSL_SEP
  15159. static int DecodeSEP(ASNGetData* dataASN, DecodedCert* cert)
  15160. {
  15161. int ret = 0;
  15162. word32 oidLen, serialLen;
  15163. oidLen = dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.length;
  15164. serialLen = dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.length;
  15165. /* Allocate space for HW type OID. */
  15166. cert->hwType = (byte*)XMALLOC(oidLen, cert->heap,
  15167. DYNAMIC_TYPE_X509_EXT);
  15168. if (cert->hwType == NULL)
  15169. ret = MEMORY_E;
  15170. if (ret == 0) {
  15171. /* Copy, into cert HW type OID */
  15172. XMEMCPY(cert->hwType,
  15173. dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.data, oidLen);
  15174. cert->hwTypeSz = (int)oidLen;
  15175. /* TODO: check this is the HW serial number OID - no test data. */
  15176. /* Allocate space for HW serial number. */
  15177. cert->hwSerialNum = (byte*)XMALLOC(serialLen, cert->heap,
  15178. DYNAMIC_TYPE_X509_EXT);
  15179. if (cert->hwSerialNum == NULL) {
  15180. WOLFSSL_MSG("\tOut of Memory");
  15181. ret = MEMORY_E;
  15182. }
  15183. }
  15184. if (ret == 0) {
  15185. /* Copy into cert HW serial number. */
  15186. XMEMCPY(cert->hwSerialNum,
  15187. dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.data, serialLen);
  15188. cert->hwSerialNum[serialLen] = '\0';
  15189. cert->hwSerialNumSz = (int)serialLen;
  15190. }
  15191. return ret;
  15192. }
  15193. #endif /* WOLFSSL_SEP */
  15194. static int DecodeOtherHelper(ASNGetData* dataASN, DecodedCert* cert, int oid)
  15195. {
  15196. DNS_entry* entry = NULL;
  15197. int ret = 0;
  15198. word32 bufLen = 0;
  15199. const char* buf = NULL;
  15200. switch (oid) {
  15201. #ifdef WOLFSSL_FPKI
  15202. case FASCN_OID:
  15203. bufLen = dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.length;
  15204. buf = (const char*)dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.data;
  15205. break;
  15206. #endif /* WOLFSSL_FPKI */
  15207. case UPN_OID:
  15208. bufLen = dataASN[OTHERNAMEASN_IDX_UPN].data.ref.length;
  15209. buf = (const char*)dataASN[OTHERNAMEASN_IDX_UPN].data.ref.data;
  15210. break;
  15211. default:
  15212. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  15213. ret = ASN_UNKNOWN_OID_E;
  15214. break;
  15215. }
  15216. if (ret == 0) {
  15217. ret = SetDNSEntry(cert, buf, (int)bufLen, ASN_OTHER_TYPE, &entry);
  15218. if (ret == 0) {
  15219. #ifdef WOLFSSL_FPKI
  15220. entry->oidSum = oid;
  15221. #endif
  15222. AddDNSEntryToList(&cert->altNames, entry);
  15223. }
  15224. }
  15225. return ret;
  15226. }
  15227. /* Decode data with OtherName format from after implicit SEQUENCE.
  15228. *
  15229. * @param [in, out] cert Certificate object.
  15230. * @param [in] input Buffer containing encoded OtherName.
  15231. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  15232. * On out, index after OtherName.
  15233. * @param [in] maxIdx Maximum index of data in buffer.
  15234. * @return 0 on success.
  15235. * @return MEMORY_E on dynamic memory allocation failure.
  15236. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15237. * is invalid.
  15238. * @return ASN_PARSE_E when OID does is not HW Name.
  15239. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15240. * @return BUFFER_E when data in buffer is too small.
  15241. */
  15242. static int DecodeOtherName(DecodedCert* cert, const byte* input,
  15243. word32* inOutIdx, word32 maxIdx)
  15244. {
  15245. DECL_ASNGETDATA(dataASN, otherNameASN_Length);
  15246. int ret = 0;
  15247. CALLOC_ASNGETDATA(dataASN, otherNameASN_Length, ret, cert->heap);
  15248. if (ret == 0) {
  15249. /* Check the first OID is a recognized Alt Cert Name type. */
  15250. GetASN_OID(&dataASN[OTHERNAMEASN_IDX_TYPEID], oidCertAltNameType);
  15251. /* Parse OtherName. */
  15252. ret = GetASN_Items(otherNameASN, dataASN, otherNameASN_Length, 1, input,
  15253. inOutIdx, maxIdx);
  15254. }
  15255. if (ret == 0) {
  15256. /* Ensure expected OID. */
  15257. switch (dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum) {
  15258. #ifdef WOLFSSL_SEP
  15259. case HW_NAME_OID:
  15260. /* Only support HW serial number. */
  15261. GetASN_OID(&dataASN[OTHERNAMEASN_IDX_HWN_TYPE], oidIgnoreType);
  15262. ret = DecodeSEP(dataASN, cert);
  15263. break;
  15264. #endif /* WOLFSSL_SEP */
  15265. #ifdef WOLFSSL_FPKI
  15266. case FASCN_OID:
  15267. #endif /* WOLFSSL_FPKI */
  15268. case UPN_OID:
  15269. ret = DecodeOtherHelper(dataASN, cert,
  15270. (int)dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum);
  15271. break;
  15272. default:
  15273. WOLFSSL_MSG("\tunsupported OID skipping");
  15274. break;
  15275. }
  15276. }
  15277. FREE_ASNGETDATA(dataASN, cert->heap);
  15278. return ret;
  15279. }
  15280. #endif /* WOLFSSL_SEP || WOLFSSL_FPKI */
  15281. /* Decode a GeneralName.
  15282. *
  15283. * @param [in] input Buffer containing encoded OtherName.
  15284. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  15285. * On out, index after OtherName.
  15286. * @param [in] len Length of data in buffer.
  15287. * @param [in] cert Decoded certificate object.
  15288. * @return 0 on success.
  15289. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15290. * is invalid.
  15291. * @return BUFFER_E when data in buffer is too small.
  15292. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15293. * @return MEMORY_E when dynamic memory allocation fails.
  15294. */
  15295. static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag,
  15296. int len, DecodedCert* cert)
  15297. {
  15298. int ret = 0;
  15299. word32 idx = *inOutIdx;
  15300. /* GeneralName choice: dnsName */
  15301. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  15302. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_DNS_TYPE,
  15303. &cert->altNames);
  15304. if (ret == 0) {
  15305. idx += (word32)len;
  15306. }
  15307. }
  15308. #ifndef IGNORE_NAME_CONSTRAINTS
  15309. /* GeneralName choice: directoryName */
  15310. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  15311. int strLen;
  15312. word32 idxDir = idx;
  15313. /* Expecting a SEQUENCE using up all data. */
  15314. if (GetASN_Sequence(input, &idxDir, &strLen, idx + (word32)len, 1) < 0)
  15315. {
  15316. WOLFSSL_MSG("\tfail: seq length");
  15317. return ASN_PARSE_E;
  15318. }
  15319. ret = SetDNSEntry(cert, (const char*)(input + idxDir), strLen,
  15320. ASN_DIR_TYPE, &cert->altDirNames);
  15321. if (ret == 0) {
  15322. idx += (word32)len;
  15323. }
  15324. }
  15325. /* GeneralName choice: rfc822Name */
  15326. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  15327. ret = SetDNSEntry(cert, (const char*)(input + idx), len,
  15328. ASN_RFC822_TYPE, &cert->altEmailNames);
  15329. if (ret == 0) {
  15330. idx += (word32)len;
  15331. }
  15332. }
  15333. /* GeneralName choice: uniformResourceIdentifier */
  15334. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  15335. WOLFSSL_MSG("\tPutting URI into list but not using");
  15336. #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
  15337. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  15338. "The name MUST NOT be a relative URI"
  15339. As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
  15340. a scheme and hier-part. So the only strict requirement is a ':'
  15341. being present after the scheme. If a '/' is present as part of the
  15342. hier-part, it must come after the ':' (see RFC 3986 Sec 3). */
  15343. {
  15344. int i;
  15345. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  15346. for (i = 0; i < len; i++) {
  15347. if (input[idx + (word32)i] == ':') {
  15348. break;
  15349. }
  15350. if (input[idx + (word32)i] == '/') {
  15351. i = len; /* error, found relative path since '/' was
  15352. * encountered before ':'. Returning error
  15353. * value in next if statement. */
  15354. }
  15355. }
  15356. /* test hier-part is empty */
  15357. if (i == 0 || i == len) {
  15358. WOLFSSL_MSG("\tEmpty or malformed URI");
  15359. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15360. return ASN_ALT_NAME_E;
  15361. }
  15362. /* test if scheme is missing */
  15363. if (input[idx + (word32)i] != ':') {
  15364. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  15365. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15366. return ASN_ALT_NAME_E;
  15367. }
  15368. }
  15369. #endif
  15370. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_URI_TYPE,
  15371. &cert->altNames);
  15372. if (ret == 0) {
  15373. idx += (word32)len;
  15374. }
  15375. }
  15376. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || \
  15377. defined(WOLFSSL_IP_ALT_NAME)
  15378. /* GeneralName choice: iPAddress */
  15379. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  15380. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_IP_TYPE,
  15381. &cert->altNames);
  15382. if (ret == 0) {
  15383. idx += len;
  15384. }
  15385. }
  15386. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  15387. #endif /* IGNORE_NAME_CONSTRAINTS */
  15388. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
  15389. /* GeneralName choice: otherName */
  15390. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
  15391. /* TODO: test data for code path */
  15392. ret = DecodeOtherName(cert, input, &idx, idx + (word32)len);
  15393. }
  15394. #endif
  15395. /* GeneralName choice: dNSName, x400Address, ediPartyName,
  15396. * registeredID */
  15397. else {
  15398. WOLFSSL_MSG("\tUnsupported name type, skipping");
  15399. idx += (word32)len;
  15400. }
  15401. if (ret == 0) {
  15402. /* Return index of next encoded byte. */
  15403. *inOutIdx = idx;
  15404. }
  15405. return ret;
  15406. }
  15407. /* ASN.1 choices for GeneralName.
  15408. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  15409. */
  15410. static const byte generalNameChoice[] = {
  15411. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0,
  15412. ASN_CONTEXT_SPECIFIC | 1,
  15413. ASN_CONTEXT_SPECIFIC | 2,
  15414. ASN_CONTEXT_SPECIFIC | 3,
  15415. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 4,
  15416. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 5,
  15417. ASN_CONTEXT_SPECIFIC | 6,
  15418. ASN_CONTEXT_SPECIFIC | 7,
  15419. ASN_CONTEXT_SPECIFIC | 8,
  15420. 0
  15421. };
  15422. /* ASN.1 template for GeneralName.
  15423. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  15424. */
  15425. static const ASNItem altNameASN[] = {
  15426. { 0, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 0 }
  15427. };
  15428. enum {
  15429. ALTNAMEASN_IDX_GN = 0
  15430. };
  15431. /* Number of items in ASN.1 template for GeneralName. */
  15432. #define altNameASN_Length (sizeof(altNameASN) / sizeof(ASNItem))
  15433. #endif /* WOLFSSL_ASN_TEMPLATE */
  15434. #if defined(WOLFSSL_SEP) && !defined(WOLFSSL_ASN_TEMPLATE)
  15435. /* return 0 on success */
  15436. static int DecodeSepHwAltName(DecodedCert* cert, const byte* input,
  15437. word32* idxIn, word32 sz)
  15438. {
  15439. word32 idx = *idxIn;
  15440. int strLen;
  15441. int ret;
  15442. byte tag;
  15443. /* Certificates issued with this OID in the subject alt name are for
  15444. * verifying signatures created on a module.
  15445. * RFC 4108 Section 5. */
  15446. if (cert->hwType != NULL) {
  15447. WOLFSSL_MSG("\tAlready seen Hardware Module Name");
  15448. return ASN_PARSE_E;
  15449. }
  15450. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  15451. return ASN_PARSE_E;
  15452. }
  15453. if (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  15454. WOLFSSL_MSG("\twrong type");
  15455. return ASN_PARSE_E;
  15456. }
  15457. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15458. WOLFSSL_MSG("\tfail: str len");
  15459. return ASN_PARSE_E;
  15460. }
  15461. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  15462. WOLFSSL_MSG("\tBad Sequence");
  15463. return ASN_PARSE_E;
  15464. }
  15465. ret = GetASNObjectId(input, &idx, &strLen, sz);
  15466. if (ret != 0) {
  15467. WOLFSSL_MSG("\tbad OID");
  15468. return ret;
  15469. }
  15470. cert->hwType = (byte*)XMALLOC((size_t)strLen, cert->heap,
  15471. DYNAMIC_TYPE_X509_EXT);
  15472. if (cert->hwType == NULL) {
  15473. WOLFSSL_MSG("\tOut of Memory");
  15474. return MEMORY_E;
  15475. }
  15476. XMEMCPY(cert->hwType, &input[idx], (size_t)strLen);
  15477. cert->hwTypeSz = strLen;
  15478. idx += (word32)strLen;
  15479. ret = GetOctetString(input, &idx, &strLen, sz);
  15480. if (ret < 0) {
  15481. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  15482. cert->hwType = NULL;
  15483. return ret;
  15484. }
  15485. cert->hwSerialNum = (byte*)XMALLOC((size_t)strLen + 1, cert->heap,
  15486. DYNAMIC_TYPE_X509_EXT);
  15487. if (cert->hwSerialNum == NULL) {
  15488. WOLFSSL_MSG("\tOut of Memory");
  15489. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  15490. cert->hwType = NULL;
  15491. return MEMORY_E;
  15492. }
  15493. XMEMCPY(cert->hwSerialNum, &input[idx], (size_t)strLen);
  15494. cert->hwSerialNum[strLen] = '\0';
  15495. cert->hwSerialNumSz = strLen;
  15496. idx += (word32)strLen;
  15497. *idxIn = idx;
  15498. return 0;
  15499. }
  15500. #endif /* WOLFSSL_SEP */
  15501. #if !defined(WOLFSSL_ASN_TEMPLATE)
  15502. /* return 0 on success */
  15503. static int DecodeConstructedOtherName(DecodedCert* cert, const byte* input,
  15504. word32* idx, word32 sz, int oid)
  15505. {
  15506. int ret = 0;
  15507. int strLen = 0;
  15508. byte tag;
  15509. DNS_entry* dnsEntry = NULL;
  15510. if (GetASNTag(input, idx, &tag, sz) < 0) {
  15511. ret = ASN_PARSE_E;
  15512. }
  15513. if (ret == 0 && (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))) {
  15514. ret = ASN_PARSE_E;
  15515. }
  15516. if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
  15517. ret = ASN_PARSE_E;
  15518. }
  15519. if (ret == 0) {
  15520. dnsEntry = AltNameNew(cert->heap);
  15521. if (dnsEntry == NULL) {
  15522. WOLFSSL_MSG("\tOut of Memory");
  15523. return MEMORY_E;
  15524. }
  15525. }
  15526. if (ret == 0) {
  15527. switch (oid) {
  15528. #ifdef WOLFSSL_FPKI
  15529. case FASCN_OID:
  15530. ret = GetOctetString(input, idx, &strLen, sz);
  15531. if (ret > 0) {
  15532. ret = 0;
  15533. }
  15534. break;
  15535. #endif /* WOLFSSL_FPKI */
  15536. case UPN_OID:
  15537. if (GetASNTag(input, idx, &tag, sz) < 0) {
  15538. ret = ASN_PARSE_E;
  15539. }
  15540. if (ret == 0 &&
  15541. tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  15542. tag != ASN_IA5_STRING) {
  15543. WOLFSSL_MSG("Was expecting a string for UPN");
  15544. ret = ASN_PARSE_E;
  15545. }
  15546. if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
  15547. WOLFSSL_MSG("Was expecting a string for UPN");
  15548. ret = ASN_PARSE_E;
  15549. }
  15550. break;
  15551. default:
  15552. WOLFSSL_MSG("Unknown constructed other name, skipping");
  15553. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15554. dnsEntry = NULL;
  15555. }
  15556. }
  15557. if (ret == 0 && dnsEntry != NULL) {
  15558. dnsEntry->type = ASN_OTHER_TYPE;
  15559. dnsEntry->len = strLen;
  15560. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  15561. DYNAMIC_TYPE_ALTNAME);
  15562. #ifdef WOLFSSL_FPKI
  15563. dnsEntry->oidSum = oid;
  15564. #endif /* WOLFSSL_FPKI */
  15565. if (dnsEntry->name == NULL) {
  15566. WOLFSSL_MSG("\tOut of Memory");
  15567. ret = MEMORY_E;
  15568. }
  15569. else {
  15570. XMEMCPY(dnsEntry->name, &input[*idx], (size_t)strLen);
  15571. dnsEntry->name[strLen] = '\0';
  15572. AddAltName(cert, dnsEntry);
  15573. }
  15574. }
  15575. if (ret == 0) {
  15576. *idx += (word32)strLen;
  15577. }
  15578. else {
  15579. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15580. }
  15581. return ret;
  15582. }
  15583. #endif
  15584. /* Decode subject alternative names extension.
  15585. *
  15586. * RFC 5280 4.2.1.6. Subject Alternative Name
  15587. *
  15588. * @param [in] input Buffer holding encoded data.
  15589. * @param [in] sz Size of encoded data in bytes.
  15590. * @param [in, out] cert Decoded certificate object.
  15591. * @return 0 on success.
  15592. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15593. * is invalid.
  15594. * @return BUFFER_E when data in buffer is too small.
  15595. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15596. * @return MEMORY_E when dynamic memory allocation fails.
  15597. */
  15598. static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert)
  15599. {
  15600. #ifndef WOLFSSL_ASN_TEMPLATE
  15601. word32 idx = 0;
  15602. int length = 0;
  15603. byte current_byte;
  15604. WOLFSSL_ENTER("DecodeAltNames");
  15605. if (GetSequence(input, &idx, &length, sz) < 0) {
  15606. WOLFSSL_MSG("\tBad Sequence");
  15607. return ASN_PARSE_E;
  15608. }
  15609. if (length == 0) {
  15610. /* RFC 5280 4.2.1.6. Subject Alternative Name
  15611. If the subjectAltName extension is present, the sequence MUST
  15612. contain at least one entry. */
  15613. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  15614. return ASN_PARSE_E;
  15615. }
  15616. #ifdef OPENSSL_ALL
  15617. cert->extSubjAltNameSrc = input;
  15618. cert->extSubjAltNameSz = sz;
  15619. #endif
  15620. cert->weOwnAltNames = 1;
  15621. while (length > 0) {
  15622. /* Verify idx can't overflow input buffer */
  15623. if (idx >= (word32)sz) {
  15624. WOLFSSL_MSG("\tBad Index");
  15625. return BUFFER_E;
  15626. }
  15627. current_byte = input[idx++];
  15628. length--;
  15629. /* Save DNS Type names in the altNames list. */
  15630. /* Save Other Type names in the cert's OidMap */
  15631. if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  15632. DNS_entry* dnsEntry;
  15633. int strLen;
  15634. word32 lenStartIdx = idx;
  15635. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15636. WOLFSSL_MSG("\tfail: str length");
  15637. return ASN_PARSE_E;
  15638. }
  15639. length -= (int)(idx - lenStartIdx);
  15640. dnsEntry = AltNameNew(cert->heap);
  15641. if (dnsEntry == NULL) {
  15642. WOLFSSL_MSG("\tOut of Memory");
  15643. return MEMORY_E;
  15644. }
  15645. dnsEntry->type = ASN_DNS_TYPE;
  15646. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  15647. DYNAMIC_TYPE_ALTNAME);
  15648. if (dnsEntry->name == NULL) {
  15649. WOLFSSL_MSG("\tOut of Memory");
  15650. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15651. return MEMORY_E;
  15652. }
  15653. dnsEntry->len = strLen;
  15654. XMEMCPY(dnsEntry->name, &input[idx], (size_t)strLen);
  15655. dnsEntry->name[strLen] = '\0';
  15656. AddAltName(cert, dnsEntry);
  15657. length -= strLen;
  15658. idx += (word32)strLen;
  15659. }
  15660. #ifndef IGNORE_NAME_CONSTRAINTS
  15661. else if (current_byte ==
  15662. (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  15663. DNS_entry* dirEntry;
  15664. int strLen;
  15665. word32 lenStartIdx = idx;
  15666. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15667. WOLFSSL_MSG("\tfail: str length");
  15668. return ASN_PARSE_E;
  15669. }
  15670. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  15671. WOLFSSL_MSG("\tfail: seq length");
  15672. return ASN_PARSE_E;
  15673. }
  15674. length -= (int)(idx - lenStartIdx);
  15675. dirEntry = AltNameNew(cert->heap);
  15676. if (dirEntry == NULL) {
  15677. WOLFSSL_MSG("\tOut of Memory");
  15678. return MEMORY_E;
  15679. }
  15680. dirEntry->type = ASN_DIR_TYPE;
  15681. dirEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  15682. DYNAMIC_TYPE_ALTNAME);
  15683. if (dirEntry->name == NULL) {
  15684. WOLFSSL_MSG("\tOut of Memory");
  15685. XFREE(dirEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15686. return MEMORY_E;
  15687. }
  15688. dirEntry->len = strLen;
  15689. XMEMCPY(dirEntry->name, &input[idx], (size_t)strLen);
  15690. dirEntry->name[strLen] = '\0';
  15691. dirEntry->next = cert->altDirNames;
  15692. cert->altDirNames = dirEntry;
  15693. length -= strLen;
  15694. idx += (word32)strLen;
  15695. }
  15696. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  15697. DNS_entry* emailEntry;
  15698. int strLen;
  15699. word32 lenStartIdx = idx;
  15700. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15701. WOLFSSL_MSG("\tfail: str length");
  15702. return ASN_PARSE_E;
  15703. }
  15704. length -= (int)(idx - lenStartIdx);
  15705. emailEntry = AltNameNew(cert->heap);
  15706. if (emailEntry == NULL) {
  15707. WOLFSSL_MSG("\tOut of Memory");
  15708. return MEMORY_E;
  15709. }
  15710. emailEntry->type = ASN_RFC822_TYPE;
  15711. emailEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  15712. DYNAMIC_TYPE_ALTNAME);
  15713. if (emailEntry->name == NULL) {
  15714. WOLFSSL_MSG("\tOut of Memory");
  15715. XFREE(emailEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15716. return MEMORY_E;
  15717. }
  15718. emailEntry->len = strLen;
  15719. XMEMCPY(emailEntry->name, &input[idx], (size_t)strLen);
  15720. emailEntry->name[strLen] = '\0';
  15721. emailEntry->next = cert->altEmailNames;
  15722. cert->altEmailNames = emailEntry;
  15723. length -= strLen;
  15724. idx += (word32)strLen;
  15725. }
  15726. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  15727. DNS_entry* uriEntry;
  15728. int strLen;
  15729. word32 lenStartIdx = idx;
  15730. WOLFSSL_MSG("\tPutting URI into list but not using");
  15731. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15732. WOLFSSL_MSG("\tfail: str length");
  15733. return ASN_PARSE_E;
  15734. }
  15735. length -= (int)(idx - lenStartIdx);
  15736. /* check that strLen at index is not past input buffer */
  15737. if ((word32)strLen + idx > sz) {
  15738. return BUFFER_E;
  15739. }
  15740. #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
  15741. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  15742. "The name MUST NOT be a relative URI"
  15743. As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
  15744. a scheme and hier-part. So the only strict requirement is a ':'
  15745. being present after the scheme. If a '/' is present as part of the
  15746. hier-part, it must come after the ':' (see RFC 3986 Sec 3). */
  15747. {
  15748. word32 i;
  15749. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  15750. for (i = 0; i < (word32)strLen; i++) {
  15751. if (input[idx + i] == ':') {
  15752. break;
  15753. }
  15754. if (input[idx + i] == '/') {
  15755. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  15756. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15757. return ASN_ALT_NAME_E;
  15758. }
  15759. }
  15760. /* test hier-part is empty */
  15761. if (i == 0 || i == (word32)strLen) {
  15762. WOLFSSL_MSG("\tEmpty or malformed URI");
  15763. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15764. return ASN_ALT_NAME_E;
  15765. }
  15766. /* test if scheme is missing */
  15767. if (input[idx + i] != ':') {
  15768. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  15769. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15770. return ASN_ALT_NAME_E;
  15771. }
  15772. }
  15773. #endif
  15774. uriEntry = AltNameNew(cert->heap);
  15775. if (uriEntry == NULL) {
  15776. WOLFSSL_MSG("\tOut of Memory");
  15777. return MEMORY_E;
  15778. }
  15779. uriEntry->type = ASN_URI_TYPE;
  15780. uriEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  15781. DYNAMIC_TYPE_ALTNAME);
  15782. if (uriEntry->name == NULL) {
  15783. WOLFSSL_MSG("\tOut of Memory");
  15784. XFREE(uriEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15785. return MEMORY_E;
  15786. }
  15787. uriEntry->len = strLen;
  15788. XMEMCPY(uriEntry->name, &input[idx], (size_t)strLen);
  15789. uriEntry->name[strLen] = '\0';
  15790. AddAltName(cert, uriEntry);
  15791. length -= strLen;
  15792. idx += (word32)strLen;
  15793. }
  15794. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  15795. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  15796. DNS_entry* ipAddr;
  15797. int strLen;
  15798. word32 lenStartIdx = idx;
  15799. WOLFSSL_MSG("Decoding Subject Alt. Name: IP Address");
  15800. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15801. WOLFSSL_MSG("\tfail: str length");
  15802. return ASN_PARSE_E;
  15803. }
  15804. length -= (idx - lenStartIdx);
  15805. /* check that strLen at index is not past input buffer */
  15806. if (strLen + idx > sz) {
  15807. return BUFFER_E;
  15808. }
  15809. ipAddr = AltNameNew(cert->heap);
  15810. if (ipAddr == NULL) {
  15811. WOLFSSL_MSG("\tOut of Memory");
  15812. return MEMORY_E;
  15813. }
  15814. ipAddr->type = ASN_IP_TYPE;
  15815. ipAddr->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  15816. DYNAMIC_TYPE_ALTNAME);
  15817. if (ipAddr->name == NULL) {
  15818. WOLFSSL_MSG("\tOut of Memory");
  15819. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15820. return MEMORY_E;
  15821. }
  15822. ipAddr->len = strLen;
  15823. XMEMCPY(ipAddr->name, &input[idx], strLen);
  15824. ipAddr->name[strLen] = '\0';
  15825. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  15826. if (GenerateDNSEntryIPString(ipAddr, cert->heap) != 0) {
  15827. WOLFSSL_MSG("\tOut of Memory for IP string");
  15828. XFREE(ipAddr->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15829. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15830. return MEMORY_E;
  15831. }
  15832. #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  15833. AddAltName(cert, ipAddr);
  15834. length -= strLen;
  15835. idx += (word32)strLen;
  15836. }
  15837. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  15838. #endif /* IGNORE_NAME_CONSTRAINTS */
  15839. else if (current_byte ==
  15840. (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
  15841. int strLen;
  15842. word32 lenStartIdx = idx;
  15843. word32 oid = 0;
  15844. int ret = 0;
  15845. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15846. WOLFSSL_MSG("\tfail: other name length");
  15847. return ASN_PARSE_E;
  15848. }
  15849. /* Consume the rest of this sequence. */
  15850. length -= (int)(((word32)strLen + idx - lenStartIdx));
  15851. if (GetObjectId(input, &idx, &oid, oidCertAltNameType, sz) < 0) {
  15852. WOLFSSL_MSG("\tbad OID");
  15853. return ASN_PARSE_E;
  15854. }
  15855. /* handle parsing other type alt names */
  15856. switch (oid) {
  15857. #ifdef WOLFSSL_SEP
  15858. case HW_NAME_OID:
  15859. ret = DecodeSepHwAltName(cert, input, &idx, sz);
  15860. if (ret != 0)
  15861. return ret;
  15862. break;
  15863. #endif /* WOLFSSL_SEP */
  15864. #ifdef WOLFSSL_FPKI
  15865. case FASCN_OID:
  15866. case UPN_OID:
  15867. ret = DecodeConstructedOtherName(cert, input, &idx, sz,
  15868. oid);
  15869. if (ret != 0)
  15870. return ret;
  15871. break;
  15872. #endif /* WOLFSSL_FPKI */
  15873. default:
  15874. WOLFSSL_MSG("\tUnsupported other name type, skipping");
  15875. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15876. /* check to skip constructed other names too */
  15877. if (DecodeConstructedOtherName(cert, input, &idx, sz,
  15878. (int)oid) != 0) {
  15879. WOLFSSL_MSG("\tfail: unsupported other name length");
  15880. return ASN_PARSE_E;
  15881. }
  15882. }
  15883. else {
  15884. idx += (word32)strLen;
  15885. }
  15886. }
  15887. (void)ret;
  15888. }
  15889. else {
  15890. int strLen;
  15891. word32 lenStartIdx = idx;
  15892. WOLFSSL_MSG("\tUnsupported name type, skipping");
  15893. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15894. WOLFSSL_MSG("\tfail: unsupported name length");
  15895. return ASN_PARSE_E;
  15896. }
  15897. length -= (int)((word32)strLen + idx - lenStartIdx);
  15898. idx += (word32)strLen;
  15899. }
  15900. }
  15901. return 0;
  15902. #else
  15903. word32 idx = 0;
  15904. int length = 0;
  15905. int ret = 0;
  15906. WOLFSSL_ENTER("DecodeAltNames");
  15907. /* Get SEQUENCE and expect all data to be accounted for. */
  15908. if (GetASN_Sequence(input, &idx, &length, sz, 1) != 0) {
  15909. WOLFSSL_MSG("\tBad Sequence");
  15910. ret = ASN_PARSE_E;
  15911. }
  15912. if ((ret == 0) && (length == 0)) {
  15913. /* RFC 5280 4.2.1.6. Subject Alternative Name
  15914. If the subjectAltName extension is present, the sequence MUST
  15915. contain at least one entry. */
  15916. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  15917. ret = ASN_PARSE_E;
  15918. }
  15919. if (ret == 0) {
  15920. #ifdef OPENSSL_ALL
  15921. cert->extSubjAltNameSrc = input;
  15922. cert->extSubjAltNameSz = sz;
  15923. #endif
  15924. cert->weOwnAltNames = 1;
  15925. if ((word32)length + idx != sz) {
  15926. ret = ASN_PARSE_E;
  15927. }
  15928. }
  15929. while ((ret == 0) && (idx < sz)) {
  15930. ASNGetData dataASN[altNameASN_Length];
  15931. /* Clear dynamic data items. */
  15932. XMEMSET(dataASN, 0, sizeof(dataASN));
  15933. /* Parse GeneralName with the choices supported. */
  15934. GetASN_Choice(&dataASN[ALTNAMEASN_IDX_GN], generalNameChoice);
  15935. /* Decode a GeneralName choice. */
  15936. ret = GetASN_Items(altNameASN, dataASN, altNameASN_Length, 0, input,
  15937. &idx, sz);
  15938. if (ret == 0) {
  15939. ret = DecodeGeneralName(input, &idx, dataASN[ALTNAMEASN_IDX_GN].tag,
  15940. (int)dataASN[ALTNAMEASN_IDX_GN].length, cert);
  15941. }
  15942. }
  15943. return ret;
  15944. #endif
  15945. }
  15946. #ifdef WOLFSSL_ASN_TEMPLATE
  15947. /* ASN.1 template for BasicContraints.
  15948. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  15949. */
  15950. static const ASNItem basicConsASN[] = {
  15951. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  15952. /* CA */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  15953. /* PLEN */ { 1, ASN_INTEGER, 0, 0, 1 }
  15954. };
  15955. enum {
  15956. BASICCONSASN_IDX_SEQ = 0,
  15957. BASICCONSASN_IDX_CA,
  15958. BASICCONSASN_IDX_PLEN
  15959. };
  15960. /* Number of items in ASN.1 template for BasicContraints. */
  15961. #define basicConsASN_Length (sizeof(basicConsASN) / sizeof(ASNItem))
  15962. #endif
  15963. /* Decode basic constraints extension in a certificate.
  15964. *
  15965. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  15966. *
  15967. * @param [in] input Buffer holding data.
  15968. * @param [in] sz Size of data in buffer.
  15969. * @param [in, out] cert Certificate object.
  15970. * @return 0 on success.
  15971. * @return MEMORY_E on dynamic memory allocation failure.
  15972. * @return ASN_PARSE_E when CA boolean is present and false (default is false).
  15973. * @return ASN_PARSE_E when CA boolean is not present unless
  15974. * WOLFSSL_X509_BASICCONS_INT is defined. Only a CA extension.
  15975. * @return ASN_PARSE_E when path length more than 7 bits.
  15976. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15977. * is invalid.
  15978. * @return BUFFER_E when data in buffer is too small.
  15979. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  15980. * non-zero length.
  15981. */
  15982. static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert)
  15983. {
  15984. #ifndef WOLFSSL_ASN_TEMPLATE
  15985. word32 idx = 0;
  15986. int length = 0;
  15987. int ret;
  15988. WOLFSSL_ENTER("DecodeBasicCaConstraint");
  15989. if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
  15990. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  15991. return ASN_PARSE_E;
  15992. }
  15993. if (length == 0)
  15994. return 0;
  15995. /* If the basic ca constraint is false, this extension may be named, but
  15996. * left empty. So, if the length is 0, just return. */
  15997. ret = GetBoolean(input, &idx, (word32)sz);
  15998. /* Removed logic for WOLFSSL_X509_BASICCONS_INT which was mistreating the
  15999. * pathlen value as if it were the CA Boolean value 7/2/2021 - KH.
  16000. * When CA Boolean not asserted use the default value "False" */
  16001. if (ret < 0) {
  16002. WOLFSSL_MSG("\tfail: constraint not valid BOOLEAN, set default FALSE");
  16003. ret = 0;
  16004. }
  16005. cert->isCA = ret ? 1 : 0;
  16006. /* If there isn't any more data, return. */
  16007. if (idx >= (word32)sz) {
  16008. return 0;
  16009. }
  16010. ret = GetInteger7Bit(input, &idx, (word32)sz);
  16011. if (ret < 0)
  16012. return ret;
  16013. cert->pathLength = (byte)ret;
  16014. cert->pathLengthSet = 1;
  16015. return 0;
  16016. #else
  16017. DECL_ASNGETDATA(dataASN, basicConsASN_Length);
  16018. int ret = 0;
  16019. word32 idx = 0;
  16020. byte isCA = 0;
  16021. WOLFSSL_ENTER("DecodeBasicCaConstraints");
  16022. CALLOC_ASNGETDATA(dataASN, basicConsASN_Length, ret, cert->heap);
  16023. if (ret == 0) {
  16024. /* Get the CA boolean and path length when present. */
  16025. GetASN_Boolean(&dataASN[BASICCONSASN_IDX_CA], &isCA);
  16026. GetASN_Int8Bit(&dataASN[BASICCONSASN_IDX_PLEN], &cert->pathLength);
  16027. ret = GetASN_Items(basicConsASN, dataASN, basicConsASN_Length, 1, input,
  16028. &idx, (word32)sz);
  16029. }
  16030. /* Empty SEQUENCE is OK - nothing to store. */
  16031. if ((ret == 0) && (dataASN[BASICCONSASN_IDX_SEQ].length != 0)) {
  16032. /* Bad encoding when CA Boolean is false
  16033. * (default when not present). */
  16034. if ((dataASN[BASICCONSASN_IDX_CA].length != 0) && (!isCA)) {
  16035. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16036. ret = ASN_PARSE_E;
  16037. }
  16038. /* Path length must be a 7-bit value. */
  16039. if ((ret == 0) && (cert->pathLength >= (1 << 7))) {
  16040. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16041. ret = ASN_PARSE_E;
  16042. }
  16043. /* Store CA boolean and whether a path length was seen. */
  16044. if (ret == 0) {
  16045. /* isCA in certificate is a 1 bit of a byte. */
  16046. cert->isCA = isCA ? 1 : 0;
  16047. cert->pathLengthSet = (dataASN[BASICCONSASN_IDX_PLEN].length > 0);
  16048. }
  16049. }
  16050. FREE_ASNGETDATA(dataASN, cert->heap);
  16051. return ret;
  16052. #endif
  16053. }
  16054. static int DecodePolicyConstraints(const byte* input, int sz, DecodedCert* cert)
  16055. {
  16056. word32 idx = 0;
  16057. int length = 0;
  16058. int skipLength = 0;
  16059. int ret;
  16060. byte tag;
  16061. WOLFSSL_ENTER("DecodePolicyConstraints");
  16062. if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
  16063. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  16064. return ASN_PARSE_E;
  16065. }
  16066. if (length == 0)
  16067. return ASN_PARSE_E;
  16068. if (GetASNTag(input, &idx, &tag, (word32)sz) < 0) {
  16069. WOLFSSL_MSG("\tfail: bad TAG");
  16070. return ASN_PARSE_E;
  16071. }
  16072. if (tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  16073. /* requireExplicitPolicy */
  16074. cert->extPolicyConstRxpSet = 1;
  16075. }
  16076. else if (tag == (ASN_CONTEXT_SPECIFIC | 1)) {
  16077. /* inhibitPolicyMapping */
  16078. cert->extPolicyConstIpmSet = 1;
  16079. }
  16080. else {
  16081. WOLFSSL_MSG("\tfail: invalid TAG");
  16082. return ASN_PARSE_E;
  16083. }
  16084. ret = GetLength(input, &idx, &skipLength, (word32)sz);
  16085. if (ret < 0) {
  16086. WOLFSSL_MSG("\tfail: invalid length");
  16087. return ret;
  16088. }
  16089. if (skipLength > 1) {
  16090. WOLFSSL_MSG("\tfail: skip value too big");
  16091. return BUFFER_E;
  16092. }
  16093. if (idx >= (word32)sz) {
  16094. WOLFSSL_MSG("\tfail: no policy const skip to read");
  16095. return BUFFER_E;
  16096. }
  16097. cert->policyConstSkip = input[idx];
  16098. return 0;
  16099. }
  16100. /* Context-Specific value for: DistributionPoint.distributionPoint
  16101. * From RFC5280 SS4.2.1.13, Distribution Point */
  16102. #define DISTRIBUTION_POINT (ASN_CONTEXT_SPECIFIC | 0)
  16103. /* Context-Specific value for: DistributionPoint.DistributionPointName.fullName
  16104. * From RFC3280 SS4.2.1.13, Distribution Point Name */
  16105. #define CRLDP_FULL_NAME (ASN_CONTEXT_SPECIFIC | 0)
  16106. /* Context-Specific value for choice: GeneralName.uniformResourceIdentifier
  16107. * From RFC3280 SS4.2.1.7, GeneralName */
  16108. #define GENERALNAME_URI (ASN_CONTEXT_SPECIFIC | 6)
  16109. #ifdef WOLFSSL_ASN_TEMPLATE
  16110. /* ASN.1 template for CRL distribution points.
  16111. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  16112. */
  16113. static const ASNItem crlDistASN[] = {
  16114. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16115. /* DP_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  16116. /* Distribution point name */
  16117. /* DP_DISTPOINT */ { 2, DISTRIBUTION_POINT, 1, 1, 1 },
  16118. /* fullName */
  16119. /* DP_DISTPOINT_FN */ { 3, CRLDP_FULL_NAME, 1, 1, 2 },
  16120. /* DP_DISTPOINT_FN_GN */ { 4, GENERALNAME_URI, 0, 0, 0 },
  16121. /* nameRelativeToCRLIssuer */
  16122. /* DP_DISTPOINT_RN */ { 3, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  16123. /* reasons: IMPLICIT BIT STRING */
  16124. /* DP_REASONS */ { 2, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  16125. /* cRLIssuer */
  16126. /* DP_CRLISSUER */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 1 },
  16127. };
  16128. enum {
  16129. CRLDISTASN_IDX_SEQ = 0,
  16130. CRLDISTASN_IDX_DP_SEQ,
  16131. CRLDISTASN_IDX_DP_DISTPOINT,
  16132. CRLDISTASN_IDX_DP_DISTPOINT_FN,
  16133. CRLDISTASN_IDX_DP_DISTPOINT_FN_GN,
  16134. CRLDISTASN_IDX_DP_DISTPOINT_RN, /* Relative name */
  16135. CRLDISTASN_IDX_DP_REASONS,
  16136. CRLDISTASN_IDX_DP_CRLISSUER
  16137. };
  16138. /* Number of items in ASN.1 template for CRL distribution points. */
  16139. #define crlDistASN_Length (sizeof(crlDistASN) / sizeof(ASNItem))
  16140. #endif
  16141. /* Decode CRL distribution point extension in a certificate.
  16142. *
  16143. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  16144. *
  16145. * @param [in] input Buffer holding data.
  16146. * @param [in] sz Size of data in buffer.
  16147. * @param [in, out] cert Certificate object.
  16148. * @return 0 on success.
  16149. * @return MEMORY_E on dynamic memory allocation failure.
  16150. * @return ASN_PARSE_E when invalid bits of reason are set.
  16151. * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
  16152. * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
  16153. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16154. * is invalid.
  16155. * @return BUFFER_E when data in buffer is too small.
  16156. */
  16157. static int DecodeCrlDist(const byte* input, word32 sz, DecodedCert* cert)
  16158. {
  16159. #ifndef WOLFSSL_ASN_TEMPLATE
  16160. word32 idx = 0, localIdx;
  16161. int length = 0;
  16162. byte tag = 0;
  16163. WOLFSSL_ENTER("DecodeCrlDist");
  16164. cert->extCrlInfoRaw = input;
  16165. cert->extCrlInfoRawSz = (int)sz;
  16166. /* Unwrap the list of Distribution Points*/
  16167. if (GetSequence(input, &idx, &length, sz) < 0)
  16168. return ASN_PARSE_E;
  16169. /* Unwrap a single Distribution Point */
  16170. if (GetSequence(input, &idx, &length, sz) < 0)
  16171. return ASN_PARSE_E;
  16172. /* The Distribution Point has three explicit optional members
  16173. * First check for a DistributionPointName
  16174. */
  16175. localIdx = idx;
  16176. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16177. tag == (ASN_CONSTRUCTED | DISTRIBUTION_POINT))
  16178. {
  16179. idx++;
  16180. if (GetLength(input, &idx, &length, sz) < 0)
  16181. return ASN_PARSE_E;
  16182. localIdx = idx;
  16183. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16184. tag == (ASN_CONSTRUCTED | CRLDP_FULL_NAME))
  16185. {
  16186. idx++;
  16187. if (GetLength(input, &idx, &length, sz) < 0)
  16188. return ASN_PARSE_E;
  16189. localIdx = idx;
  16190. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16191. tag == GENERALNAME_URI)
  16192. {
  16193. idx++;
  16194. if (GetLength(input, &idx, &length, sz) < 0)
  16195. return ASN_PARSE_E;
  16196. cert->extCrlInfoSz = length;
  16197. cert->extCrlInfo = input + idx;
  16198. idx += (word32)length;
  16199. }
  16200. else
  16201. /* This isn't a URI, skip it. */
  16202. idx += (word32)length;
  16203. }
  16204. else {
  16205. /* This isn't a FULLNAME, skip it. */
  16206. idx += (word32)length;
  16207. }
  16208. }
  16209. /* Check for reasonFlags */
  16210. localIdx = idx;
  16211. if (idx < (word32)sz &&
  16212. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16213. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  16214. {
  16215. idx++;
  16216. if (GetLength(input, &idx, &length, sz) < 0)
  16217. return ASN_PARSE_E;
  16218. idx += (word32)length;
  16219. }
  16220. /* Check for cRLIssuer */
  16221. localIdx = idx;
  16222. if (idx < (word32)sz &&
  16223. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16224. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
  16225. {
  16226. idx++;
  16227. if (GetLength(input, &idx, &length, sz) < 0)
  16228. return ASN_PARSE_E;
  16229. idx += (word32)length;
  16230. }
  16231. if (idx < (word32)sz)
  16232. {
  16233. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  16234. "but we only use the first one.");
  16235. }
  16236. return 0;
  16237. #else
  16238. DECL_ASNGETDATA(dataASN, crlDistASN_Length);
  16239. word32 idx = 0;
  16240. int ret = 0;
  16241. #ifdef CRLDP_VALIDATE_DATA
  16242. word16 reason;
  16243. #endif
  16244. WOLFSSL_ENTER("DecodeCrlDist");
  16245. CALLOC_ASNGETDATA(dataASN, crlDistASN_Length, ret, cert->heap);
  16246. cert->extCrlInfoRaw = input;
  16247. cert->extCrlInfoRawSz = (int)sz;
  16248. if (ret == 0) {
  16249. /* Get the GeneralName choice */
  16250. GetASN_Choice(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN], generalNameChoice);
  16251. /* Parse CRL distribtion point. */
  16252. ret = GetASN_Items(crlDistASN, dataASN, crlDistASN_Length, 0, input,
  16253. &idx, sz);
  16254. }
  16255. if (ret == 0) {
  16256. /* If the choice was a URI, store it in certificate. */
  16257. if (dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN].tag == GENERALNAME_URI) {
  16258. word32 sz32;
  16259. GetASN_GetConstRef(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN],
  16260. &cert->extCrlInfo, &sz32);
  16261. cert->extCrlInfoSz = (int)sz32;
  16262. }
  16263. #ifdef CRLDP_VALIDATE_DATA
  16264. if (dataASN[CRLDISTASN_IDX_DP_REASONS].data.ref.data != NULL) {
  16265. /* TODO: test case */
  16266. /* Validate ReasonFlags. */
  16267. ret = GetASN_BitString_Int16Bit(&dataASN[CRLDISTASN_IDX_DP_REASONS],
  16268. &reason);
  16269. /* First bit (LSB) unused and eight other bits defined. */
  16270. if ((ret == 0) && ((reason >> 9) || (reason & 0x01))) {
  16271. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16272. ret = ASN_PARSE_E;
  16273. }
  16274. }
  16275. #endif
  16276. }
  16277. /* Only parsing the first one. */
  16278. if (ret == 0 && idx < (word32)sz) {
  16279. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  16280. "but we only use the first one.");
  16281. }
  16282. /* TODO: validate other points. */
  16283. FREE_ASNGETDATA(dataASN, cert->heap);
  16284. return ret;
  16285. #endif /* WOLFSSL_ASN_TEMPLATE */
  16286. }
  16287. #ifdef WOLFSSL_ASN_TEMPLATE
  16288. /* ASN.1 template for the access description.
  16289. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16290. */
  16291. static const ASNItem accessDescASN[] = {
  16292. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16293. /* accessMethod */
  16294. /* METH */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  16295. /* accessLocation: GeneralName */
  16296. /* LOC */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  16297. };
  16298. enum {
  16299. ACCESSDESCASN_IDX_SEQ = 0,
  16300. ACCESSDESCASN_IDX_METH,
  16301. ACCESSDESCASN_IDX_LOC
  16302. };
  16303. /* Number of items in ASN.1 template for the access description. */
  16304. #define accessDescASN_Length (sizeof(accessDescASN) / sizeof(ASNItem))
  16305. #endif
  16306. /* Decode authority information access extension in a certificate.
  16307. *
  16308. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16309. *
  16310. * @param [in] input Buffer holding data.
  16311. * @param [in] sz Size of data in buffer.
  16312. * @param [in, out] cert Certificate object.
  16313. * @return 0 on success.
  16314. * @return MEMORY_E on dynamic memory allocation failure.
  16315. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16316. * is invalid.
  16317. * @return BUFFER_E when data in buffer is too small.
  16318. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  16319. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  16320. */
  16321. static int DecodeAuthInfo(const byte* input, word32 sz, DecodedCert* cert)
  16322. {
  16323. #ifndef WOLFSSL_ASN_TEMPLATE
  16324. word32 idx = 0;
  16325. int length = 0;
  16326. int count = 0;
  16327. byte b = 0;
  16328. word32 oid;
  16329. WOLFSSL_ENTER("DecodeAuthInfo");
  16330. /* Unwrap the list of AIAs */
  16331. if (GetSequence(input, &idx, &length, sz) < 0)
  16332. return ASN_PARSE_E;
  16333. while ((idx < (word32)sz) && (count < MAX_AIA_SZ)) {
  16334. /* Unwrap a single AIA */
  16335. if (GetSequence(input, &idx, &length, sz) < 0)
  16336. return ASN_PARSE_E;
  16337. oid = 0;
  16338. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0) {
  16339. return ASN_PARSE_E;
  16340. }
  16341. /* Only supporting URIs right now. */
  16342. if (GetASNTag(input, &idx, &b, sz) < 0)
  16343. return ASN_PARSE_E;
  16344. if (GetLength(input, &idx, &length, sz) < 0)
  16345. return ASN_PARSE_E;
  16346. /* Set ocsp entry */
  16347. if (b == GENERALNAME_URI && oid == AIA_OCSP_OID)
  16348. {
  16349. cert->extAuthInfoSz = length;
  16350. cert->extAuthInfo = input + idx;
  16351. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16352. count++;
  16353. #else
  16354. break;
  16355. #endif
  16356. }
  16357. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16358. /* Set CaIssuers entry */
  16359. else if ((b == GENERALNAME_URI) && oid == AIA_CA_ISSUER_OID)
  16360. {
  16361. cert->extAuthInfoCaIssuerSz = length;
  16362. cert->extAuthInfoCaIssuer = input + idx;
  16363. count++;
  16364. }
  16365. #endif
  16366. idx += (word32)length;
  16367. }
  16368. return 0;
  16369. #else
  16370. word32 idx = 0;
  16371. int length = 0;
  16372. int count = 0;
  16373. int ret = 0;
  16374. WOLFSSL_ENTER("DecodeAuthInfo");
  16375. /* Unwrap the list of AIAs */
  16376. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  16377. ret = ASN_PARSE_E;
  16378. }
  16379. while ((ret == 0) && (idx < (word32)sz) && (count < MAX_AIA_SZ)) {
  16380. ASNGetData dataASN[accessDescASN_Length];
  16381. /* Clear dynamic data and retrieve OID and name. */
  16382. XMEMSET(dataASN, 0, sizeof(dataASN));
  16383. GetASN_OID(&dataASN[ACCESSDESCASN_IDX_METH], oidCertAuthInfoType);
  16384. GetASN_Choice(&dataASN[ACCESSDESCASN_IDX_LOC], generalNameChoice);
  16385. /* Parse AccessDescription. */
  16386. ret = GetASN_Items(accessDescASN, dataASN, accessDescASN_Length, 0,
  16387. input, &idx, sz);
  16388. if (ret == 0) {
  16389. word32 sz32;
  16390. /* Check we have OCSP and URI. */
  16391. if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum == AIA_OCSP_OID) &&
  16392. (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
  16393. /* Store URI for OCSP lookup. */
  16394. GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
  16395. &cert->extAuthInfo, &sz32);
  16396. cert->extAuthInfoSz = (int)sz32;
  16397. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16398. count++;
  16399. #else
  16400. break;
  16401. #endif
  16402. }
  16403. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16404. /* Check we have CA Issuer and URI. */
  16405. else if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum ==
  16406. AIA_CA_ISSUER_OID) &&
  16407. (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
  16408. /* Set CaIssuers entry */
  16409. GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
  16410. &cert->extAuthInfoCaIssuer, &sz32);
  16411. cert->extAuthInfoCaIssuerSz = sz32;
  16412. count++;
  16413. }
  16414. #endif
  16415. /* Otherwise skip. */
  16416. }
  16417. }
  16418. return ret;
  16419. #endif
  16420. }
  16421. #ifdef WOLFSSL_ASN_TEMPLATE
  16422. /* ASN.1 template for AuthorityKeyIdentifier.
  16423. * X.509: RFC 5280, 4.2.1.1 - Authority Key Identifier.
  16424. */
  16425. static const ASNItem authKeyIdASN[] = {
  16426. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16427. /* keyIdentifier */
  16428. /* KEYID */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_KEYID, 0, 0, 1 },
  16429. /* authorityCertIssuer */
  16430. /* ISSUER */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_ISSUER, 1, 0, 1 },
  16431. /* authorityCertSerialNumber */
  16432. /* SERIAL */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_SERIAL, 0, 0, 1 },
  16433. };
  16434. enum {
  16435. AUTHKEYIDASN_IDX_SEQ = 0,
  16436. AUTHKEYIDASN_IDX_KEYID,
  16437. AUTHKEYIDASN_IDX_ISSUER,
  16438. AUTHKEYIDASN_IDX_SERIAL
  16439. };
  16440. /* Number of items in ASN.1 template for AuthorityKeyIdentifier. */
  16441. #define authKeyIdASN_Length (sizeof(authKeyIdASN) / sizeof(ASNItem))
  16442. #endif
  16443. /* Decode authority information access extension in a certificate.
  16444. *
  16445. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16446. *
  16447. * @param [in] input Buffer holding data.
  16448. * @param [in] sz Size of data in buffer.
  16449. * @param [in, out] cert Certificate object.
  16450. * @return 0 on success.
  16451. * @return MEMORY_E on dynamic memory allocation failure.
  16452. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16453. * is invalid.
  16454. * @return BUFFER_E when data in buffer is too small.
  16455. */
  16456. static int DecodeAuthKeyId(const byte* input, word32 sz, DecodedCert* cert)
  16457. {
  16458. #ifndef WOLFSSL_ASN_TEMPLATE
  16459. word32 idx = 0;
  16460. int length = 0;
  16461. byte tag;
  16462. WOLFSSL_ENTER("DecodeAuthKeyId");
  16463. if (GetSequence(input, &idx, &length, sz) < 0) {
  16464. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  16465. return ASN_PARSE_E;
  16466. }
  16467. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  16468. return ASN_PARSE_E;
  16469. }
  16470. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  16471. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  16472. cert->extAuthKeyIdSet = 0;
  16473. return 0;
  16474. }
  16475. if (GetLength(input, &idx, &length, sz) <= 0) {
  16476. WOLFSSL_MSG("\tfail: extension data length");
  16477. return ASN_PARSE_E;
  16478. }
  16479. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16480. #ifdef WOLFSSL_AKID_NAME
  16481. cert->extRawAuthKeyIdSrc = input;
  16482. cert->extRawAuthKeyIdSz = sz;
  16483. #endif
  16484. cert->extAuthKeyIdSrc = &input[idx];
  16485. cert->extAuthKeyIdSz = length;
  16486. #endif /* OPENSSL_EXTRA */
  16487. return GetHashId(input + idx, length, cert->extAuthKeyId);
  16488. #else
  16489. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  16490. int ret = 0;
  16491. word32 idx = 0;
  16492. WOLFSSL_ENTER("DecodeAuthKeyId");
  16493. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, cert->heap);
  16494. if (ret == 0) {
  16495. /* Parse an authority key identifier. */
  16496. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  16497. &idx, sz);
  16498. }
  16499. if (ret == 0) {
  16500. /* Key id is optional. */
  16501. if (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data == NULL) {
  16502. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  16503. }
  16504. else {
  16505. #ifdef OPENSSL_EXTRA
  16506. /* Store the authority key id. */
  16507. #ifdef WOLFSSL_AKID_NAME
  16508. cert->extRawAuthKeyIdSrc = input;
  16509. cert->extRawAuthKeyIdSz = sz;
  16510. #endif
  16511. GetASN_GetConstRef(&dataASN[AUTHKEYIDASN_IDX_KEYID], &cert->extAuthKeyIdSrc,
  16512. &cert->extAuthKeyIdSz);
  16513. #endif /* OPENSSL_EXTRA */
  16514. /* Get the hash or hash of the hash if wrong size. */
  16515. ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  16516. (int)dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  16517. cert->extAuthKeyId);
  16518. }
  16519. }
  16520. FREE_ASNGETDATA(dataASN, cert->heap);
  16521. return ret;
  16522. #endif /* WOLFSSL_ASN_TEMPLATE */
  16523. }
  16524. /* Decode subject key id extension in a certificate.
  16525. *
  16526. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16527. *
  16528. * @param [in] input Buffer holding data.
  16529. * @param [in] sz Size of data in buffer.
  16530. * @param [in, out] cert Certificate object.
  16531. * @return 0 on success.
  16532. * @return ASN_PARSE_E when the OCTET_STRING tag is not found or length is
  16533. * invalid.
  16534. * @return MEMORY_E on dynamic memory allocation failure.
  16535. */
  16536. static int DecodeSubjKeyId(const byte* input, word32 sz, DecodedCert* cert)
  16537. {
  16538. word32 idx = 0;
  16539. int length = 0;
  16540. int ret = 0;
  16541. WOLFSSL_ENTER("DecodeSubjKeyId");
  16542. if (sz <= 0) {
  16543. ret = ASN_PARSE_E;
  16544. }
  16545. if (ret == 0) {
  16546. ret = GetOctetString(input, &idx, &length, sz);
  16547. }
  16548. if (ret > 0) {
  16549. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16550. cert->extSubjKeyIdSrc = &input[idx];
  16551. cert->extSubjKeyIdSz = length;
  16552. #endif /* OPENSSL_EXTRA */
  16553. /* Get the hash or hash of the hash if wrong size. */
  16554. ret = GetHashId(input + idx, length, cert->extSubjKeyId);
  16555. }
  16556. return ret;
  16557. }
  16558. #ifdef WOLFSSL_ASN_TEMPLATE
  16559. /* ASN.1 template for KeyUsage.
  16560. * X.509: RFC 5280, 4.2.1.3 - Key Usage.
  16561. */
  16562. static const ASNItem keyUsageASN[] = {
  16563. /* STR */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  16564. };
  16565. enum {
  16566. KEYUSAGEASN_IDX_STR = 0
  16567. };
  16568. /* Number of items in ASN.1 template for KeyUsage. */
  16569. #define keyUsageASN_Length (sizeof(keyUsageASN) / sizeof(ASNItem))
  16570. #endif
  16571. /* Decode key usage extension in a certificate.
  16572. *
  16573. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16574. *
  16575. * @param [in] input Buffer holding data.
  16576. * @param [in] sz Size of data in buffer.
  16577. * @param [in, out] cert Certificate object.
  16578. * @return 0 on success.
  16579. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  16580. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16581. * is invalid.
  16582. * @return MEMORY_E on dynamic memory allocation failure.
  16583. */
  16584. static int DecodeKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
  16585. {
  16586. #ifndef WOLFSSL_ASN_TEMPLATE
  16587. word32 idx = 0;
  16588. int length;
  16589. int ret;
  16590. WOLFSSL_ENTER("DecodeKeyUsage");
  16591. ret = CheckBitString(input, &idx, &length, sz, 0, NULL);
  16592. if (ret != 0)
  16593. return ret;
  16594. if (length == 0 || length > 2)
  16595. return ASN_PARSE_E;
  16596. cert->extKeyUsage = (word16)(input[idx]);
  16597. if (length == 2)
  16598. cert->extKeyUsage |= (word16)(input[idx+1] << 8);
  16599. return 0;
  16600. #else
  16601. ASNGetData dataASN[keyUsageASN_Length];
  16602. word32 idx = 0;
  16603. WOLFSSL_ENTER("DecodeKeyUsage");
  16604. /* Clear dynamic data and set where to store extended key usage. */
  16605. XMEMSET(dataASN, 0, sizeof(dataASN));
  16606. GetASN_Int16Bit(&dataASN[KEYUSAGEASN_IDX_STR], &cert->extKeyUsage);
  16607. /* Parse key usage. */
  16608. return GetASN_Items(keyUsageASN, dataASN, keyUsageASN_Length, 0, input,
  16609. &idx, sz);
  16610. #endif /* WOLFSSL_ASN_TEMPLATE */
  16611. }
  16612. #ifdef WOLFSSL_ASN_TEMPLATE
  16613. /* ASN.1 template for KeyPurposeId.
  16614. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  16615. */
  16616. static const ASNItem keyPurposeIdASN[] = {
  16617. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  16618. };
  16619. enum {
  16620. KEYPURPOSEIDASN_IDX_OID = 0
  16621. };
  16622. /* Number of items in ASN.1 template for KeyPurposeId. */
  16623. #define keyPurposeIdASN_Length (sizeof(keyPurposeIdASN) / sizeof(ASNItem))
  16624. #endif
  16625. /* Decode extended key usage extension in a certificate.
  16626. *
  16627. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  16628. *
  16629. * @param [in] input Buffer holding data.
  16630. * @param [in] sz Size of data in buffer.
  16631. * @param [in, out] cert Certificate object.
  16632. * @return 0 on success.
  16633. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  16634. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16635. * is invalid.
  16636. * @return MEMORY_E on dynamic memory allocation failure.
  16637. */
  16638. static int DecodeExtKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
  16639. {
  16640. #ifndef WOLFSSL_ASN_TEMPLATE
  16641. word32 idx = 0, oid;
  16642. int length, ret;
  16643. WOLFSSL_ENTER("DecodeExtKeyUsage");
  16644. if (GetSequence(input, &idx, &length, sz) < 0) {
  16645. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  16646. return ASN_PARSE_E;
  16647. }
  16648. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16649. cert->extExtKeyUsageSrc = input + idx;
  16650. cert->extExtKeyUsageSz = length;
  16651. #endif
  16652. while (idx < (word32)sz) {
  16653. ret = GetObjectId(input, &idx, &oid, oidCertKeyUseType, sz);
  16654. if (ret == ASN_UNKNOWN_OID_E)
  16655. continue;
  16656. else if (ret < 0)
  16657. return ret;
  16658. switch (oid) {
  16659. case EKU_ANY_OID:
  16660. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  16661. break;
  16662. case EKU_SERVER_AUTH_OID:
  16663. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  16664. break;
  16665. case EKU_CLIENT_AUTH_OID:
  16666. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  16667. break;
  16668. case EKU_CODESIGNING_OID:
  16669. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  16670. break;
  16671. case EKU_EMAILPROTECT_OID:
  16672. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  16673. break;
  16674. case EKU_TIMESTAMP_OID:
  16675. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  16676. break;
  16677. case EKU_OCSP_SIGN_OID:
  16678. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  16679. break;
  16680. #ifdef WOLFSSL_WOLFSSH
  16681. case EKU_SSH_CLIENT_AUTH_OID:
  16682. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_CLIENT_AUTH;
  16683. break;
  16684. case EKU_SSH_MSCL_OID:
  16685. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_MSCL;
  16686. break;
  16687. case EKU_SSH_KP_CLIENT_AUTH_OID:
  16688. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_KP_CLIENT_AUTH;
  16689. break;
  16690. #endif /* WOLFSSL_WOLFSSH */
  16691. default:
  16692. break;
  16693. }
  16694. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16695. cert->extExtKeyUsageCount++;
  16696. #endif
  16697. }
  16698. return 0;
  16699. #else
  16700. word32 idx = 0;
  16701. int length;
  16702. int ret = 0;
  16703. WOLFSSL_ENTER("DecodeExtKeyUsage");
  16704. /* Strip SEQUENCE OF and expect to account for all the data. */
  16705. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  16706. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  16707. ret = ASN_PARSE_E;
  16708. }
  16709. if (ret == 0) {
  16710. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16711. /* Keep reference for WOLFSSL_X509. */
  16712. cert->extExtKeyUsageSrc = input + idx;
  16713. cert->extExtKeyUsageSz = length;
  16714. #endif
  16715. }
  16716. /* Check all OIDs. */
  16717. while ((ret == 0) && (idx < (word32)sz)) {
  16718. ASNGetData dataASN[keyPurposeIdASN_Length];
  16719. /* Clear dynamic data items and set OID type expected. */
  16720. XMEMSET(dataASN, 0, sizeof(dataASN));
  16721. GetASN_OID(&dataASN[KEYPURPOSEIDASN_IDX_OID], oidIgnoreType);
  16722. /* Decode KeyPurposeId. */
  16723. ret = GetASN_Items(keyPurposeIdASN, dataASN, keyPurposeIdASN_Length, 0,
  16724. input, &idx, sz);
  16725. /* Skip unknown OIDs. */
  16726. if (ret == ASN_UNKNOWN_OID_E) {
  16727. ret = 0;
  16728. }
  16729. else if (ret == 0) {
  16730. /* Store the bit for the OID. */
  16731. switch (dataASN[KEYPURPOSEIDASN_IDX_OID].data.oid.sum) {
  16732. case EKU_ANY_OID:
  16733. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  16734. break;
  16735. case EKU_SERVER_AUTH_OID:
  16736. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  16737. break;
  16738. case EKU_CLIENT_AUTH_OID:
  16739. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  16740. break;
  16741. case EKU_CODESIGNING_OID:
  16742. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  16743. break;
  16744. case EKU_EMAILPROTECT_OID:
  16745. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  16746. break;
  16747. case EKU_TIMESTAMP_OID:
  16748. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  16749. break;
  16750. case EKU_OCSP_SIGN_OID:
  16751. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  16752. break;
  16753. }
  16754. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16755. /* Keep count for WOLFSSL_X509. */
  16756. cert->extExtKeyUsageCount++;
  16757. #endif
  16758. }
  16759. }
  16760. return ret;
  16761. #endif /* WOLFSSL_ASN_TEMPLATE */
  16762. }
  16763. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  16764. static int DecodeNsCertType(const byte* input, int sz, DecodedCert* cert)
  16765. {
  16766. word32 idx = 0;
  16767. int len = 0;
  16768. WOLFSSL_ENTER("DecodeNsCertType");
  16769. if (CheckBitString(input, &idx, &len, (word32)sz, 0, NULL) < 0)
  16770. return ASN_PARSE_E;
  16771. /* Don't need to worry about unused bits as CheckBitString makes sure
  16772. * they're zero. */
  16773. if (idx < (word32)sz)
  16774. cert->nsCertType = input[idx];
  16775. else
  16776. return ASN_PARSE_E;
  16777. return 0;
  16778. }
  16779. #endif
  16780. #ifndef IGNORE_NAME_CONSTRAINTS
  16781. #ifdef WOLFSSL_ASN_TEMPLATE
  16782. /* ASN.1 template for GeneralSubtree.
  16783. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  16784. */
  16785. static const ASNItem subTreeASN[] = {
  16786. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16787. /* base GeneralName */
  16788. /* BASE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  16789. /* minimum BaseDistance DEFAULT 0*/
  16790. /* MIN */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MIN, 0, 0, 1 },
  16791. /* maximum BaseDistance OPTIONAL */
  16792. /* MAX */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MAX, 0, 0, 1 },
  16793. };
  16794. enum {
  16795. SUBTREEASN_IDX_SEQ = 0,
  16796. SUBTREEASN_IDX_BASE,
  16797. SUBTREEASN_IDX_MIN,
  16798. SUBTREEASN_IDX_MAX
  16799. };
  16800. /* Number of items in ASN.1 template for GeneralSubtree. */
  16801. #define subTreeASN_Length (sizeof(subTreeASN) / sizeof(ASNItem))
  16802. #endif
  16803. #ifdef WOLFSSL_ASN_TEMPLATE
  16804. /* Decode the Subtree's GeneralName.
  16805. *
  16806. * @param [in] input Buffer holding data.
  16807. * @param [in] sz Size of data in buffer.
  16808. * @param [in] tag BER tag on GeneralName.
  16809. * @param [in, out] head Linked list of subtree names.
  16810. * @param [in] heap Dynamic memory hint.
  16811. * @return 0 on success.
  16812. * @return MEMORY_E when dynamic memory allocation fails.
  16813. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  16814. */
  16815. static int DecodeSubtreeGeneralName(const byte* input, word32 sz, byte tag,
  16816. Base_entry** head, void* heap)
  16817. {
  16818. Base_entry* entry;
  16819. word32 nameIdx = 0;
  16820. word32 len = sz;
  16821. int strLen;
  16822. int ret = 0;
  16823. (void)heap;
  16824. /* if constructed has leading sequence */
  16825. if ((tag & ASN_CONSTRUCTED) == ASN_CONSTRUCTED) {
  16826. ret = GetASN_Sequence(input, &nameIdx, &strLen, sz, 0);
  16827. if (ret < 0) {
  16828. ret = ASN_PARSE_E;
  16829. }
  16830. else {
  16831. len = (word32)strLen;
  16832. ret = 0;
  16833. }
  16834. }
  16835. if (ret == 0) {
  16836. /* TODO: consider one malloc. */
  16837. /* Allocate Base Entry object. */
  16838. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  16839. DYNAMIC_TYPE_ALTNAME);
  16840. if (entry == NULL) {
  16841. ret = MEMORY_E;
  16842. }
  16843. }
  16844. if (ret == 0) {
  16845. /* Allocate name. */
  16846. entry->name = (char*)XMALLOC(len + 1, heap, DYNAMIC_TYPE_ALTNAME);
  16847. if (entry->name == NULL) {
  16848. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  16849. ret = MEMORY_E;
  16850. }
  16851. }
  16852. if (ret == 0) {
  16853. /* Store name, size and tag in object. */
  16854. XMEMCPY(entry->name, &input[nameIdx], len);
  16855. entry->name[len] = '\0';
  16856. entry->nameSz = (int)len;
  16857. entry->type = tag & ASN_TYPE_MASK;
  16858. /* Put entry at front of linked list. */
  16859. entry->next = *head;
  16860. *head = entry;
  16861. }
  16862. return ret;
  16863. }
  16864. #endif
  16865. /* Decode a subtree of a name constraints in a certificate.
  16866. *
  16867. * X.509: RFC 5280, 4.2.1.10 - Name Contraints.
  16868. *
  16869. * @param [in] input Buffer holding data.
  16870. * @param [in] sz Size of data in buffer.
  16871. * @param [in, out] head Linked list of subtree names.
  16872. * @param [in] heap Dynamic memory hint.
  16873. * @return 0 on success.
  16874. * @return MEMORY_E when dynamic memory allocation fails.
  16875. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  16876. */
  16877. static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head,
  16878. void* heap)
  16879. {
  16880. #ifndef WOLFSSL_ASN_TEMPLATE
  16881. word32 idx = 0;
  16882. int ret = 0;
  16883. (void)heap;
  16884. while (idx < (word32)sz) {
  16885. int seqLength, strLength;
  16886. word32 nameIdx;
  16887. byte b, bType;
  16888. if (GetSequence(input, &idx, &seqLength, sz) < 0) {
  16889. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  16890. return ASN_PARSE_E;
  16891. }
  16892. if (idx >= (word32)sz) {
  16893. WOLFSSL_MSG("\tfail: expecting tag");
  16894. return ASN_PARSE_E;
  16895. }
  16896. nameIdx = idx;
  16897. b = input[nameIdx++];
  16898. if (GetLength(input, &nameIdx, &strLength, sz) <= 0) {
  16899. WOLFSSL_MSG("\tinvalid length");
  16900. return ASN_PARSE_E;
  16901. }
  16902. /* Get type, LSB 4-bits */
  16903. bType = (b & ASN_TYPE_MASK);
  16904. if (bType == ASN_DNS_TYPE || bType == ASN_RFC822_TYPE ||
  16905. bType == ASN_DIR_TYPE) {
  16906. Base_entry* entry;
  16907. /* if constructed has leading sequence */
  16908. if (b & ASN_CONSTRUCTED) {
  16909. if (GetSequence(input, &nameIdx, &strLength, sz) < 0) {
  16910. WOLFSSL_MSG("\tfail: constructed be a SEQUENCE");
  16911. return ASN_PARSE_E;
  16912. }
  16913. }
  16914. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  16915. DYNAMIC_TYPE_ALTNAME);
  16916. if (entry == NULL) {
  16917. WOLFSSL_MSG("allocate error");
  16918. return MEMORY_E;
  16919. }
  16920. entry->name = (char*)XMALLOC((size_t)strLength+1, heap,
  16921. DYNAMIC_TYPE_ALTNAME);
  16922. if (entry->name == NULL) {
  16923. WOLFSSL_MSG("allocate error");
  16924. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  16925. return MEMORY_E;
  16926. }
  16927. XMEMCPY(entry->name, &input[nameIdx], (size_t)strLength);
  16928. entry->name[strLength] = '\0';
  16929. entry->nameSz = strLength;
  16930. entry->type = bType;
  16931. entry->next = *head;
  16932. *head = entry;
  16933. }
  16934. idx += (word32)seqLength;
  16935. }
  16936. return ret;
  16937. #else
  16938. DECL_ASNGETDATA(dataASN, subTreeASN_Length);
  16939. word32 idx = 0;
  16940. int ret = 0;
  16941. (void)heap;
  16942. ALLOC_ASNGETDATA(dataASN, subTreeASN_Length, ret, heap);
  16943. /* Process all subtrees. */
  16944. while ((ret == 0) && (idx < (word32)sz)) {
  16945. byte minVal = 0;
  16946. byte maxVal = 0;
  16947. /* Clear dynamic data and set choice for GeneralName and location to
  16948. * store minimum and maximum.
  16949. */
  16950. XMEMSET(dataASN, 0, sizeof(*dataASN) * subTreeASN_Length);
  16951. GetASN_Choice(&dataASN[SUBTREEASN_IDX_BASE], generalNameChoice);
  16952. GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MIN], &minVal);
  16953. GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MAX], &maxVal);
  16954. /* Parse GeneralSubtree. */
  16955. ret = GetASN_Items(subTreeASN, dataASN, subTreeASN_Length, 0, input,
  16956. &idx, sz);
  16957. if (ret == 0) {
  16958. byte t = dataASN[SUBTREEASN_IDX_BASE].tag;
  16959. /* Check GeneralName tag is one of the types we can handle. */
  16960. if (t == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE) ||
  16961. t == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE) ||
  16962. t == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  16963. /* Parse the general name and store a new entry. */
  16964. ret = DecodeSubtreeGeneralName(input +
  16965. GetASNItem_DataIdx(dataASN[SUBTREEASN_IDX_BASE], input),
  16966. dataASN[SUBTREEASN_IDX_BASE].length, t, head, heap);
  16967. }
  16968. /* Skip entry. */
  16969. }
  16970. }
  16971. FREE_ASNGETDATA(dataASN, heap);
  16972. return ret;
  16973. #endif
  16974. }
  16975. #ifdef WOLFSSL_ASN_TEMPLATE
  16976. /* ASN.1 template for NameConstraints.
  16977. * X.509: RFC 5280, 4.2.1.10 - Name Contraints.
  16978. */
  16979. static const ASNItem nameConstraintsASN[] = {
  16980. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16981. /* permittedSubtrees */
  16982. /* PERMIT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  16983. /* excludededSubtrees */
  16984. /* EXCLUDE */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  16985. };
  16986. enum {
  16987. NAMECONSTRAINTSASN_IDX_SEQ = 0,
  16988. NAMECONSTRAINTSASN_IDX_PERMIT,
  16989. NAMECONSTRAINTSASN_IDX_EXCLUDE
  16990. };
  16991. /* Number of items in ASN.1 template for NameConstraints. */
  16992. #define nameConstraintsASN_Length (sizeof(nameConstraintsASN) / sizeof(ASNItem))
  16993. #endif
  16994. /* Decode name constraints extension in a certificate.
  16995. *
  16996. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  16997. *
  16998. * @param [in] input Buffer holding data.
  16999. * @param [in] sz Size of data in buffer.
  17000. * @param [in, out] cert Certificate object.
  17001. * @return 0 on success.
  17002. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17003. * is invalid.
  17004. * @return MEMORY_E on dynamic memory allocation failure.
  17005. */
  17006. static int DecodeNameConstraints(const byte* input, word32 sz,
  17007. DecodedCert* cert)
  17008. {
  17009. #ifndef WOLFSSL_ASN_TEMPLATE
  17010. word32 idx = 0;
  17011. int length = 0;
  17012. WOLFSSL_ENTER("DecodeNameConstraints");
  17013. if (GetSequence(input, &idx, &length, sz) < 0) {
  17014. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17015. return ASN_PARSE_E;
  17016. }
  17017. while (idx < (word32)sz) {
  17018. byte b = input[idx++];
  17019. Base_entry** subtree = NULL;
  17020. if (GetLength(input, &idx, &length, sz) <= 0) {
  17021. WOLFSSL_MSG("\tinvalid length");
  17022. return ASN_PARSE_E;
  17023. }
  17024. if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
  17025. subtree = &cert->permittedNames;
  17026. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
  17027. subtree = &cert->excludedNames;
  17028. else {
  17029. WOLFSSL_MSG("\tinvalid subtree");
  17030. return ASN_PARSE_E;
  17031. }
  17032. if (DecodeSubtree(input + idx, (word32)length, subtree,
  17033. cert->heap) < 0) {
  17034. WOLFSSL_MSG("\terror parsing subtree");
  17035. return ASN_PARSE_E;
  17036. }
  17037. idx += (word32)length;
  17038. }
  17039. return 0;
  17040. #else
  17041. DECL_ASNGETDATA(dataASN, nameConstraintsASN_Length);
  17042. word32 idx = 0;
  17043. int ret = 0;
  17044. CALLOC_ASNGETDATA(dataASN, nameConstraintsASN_Length, ret, cert->heap);
  17045. if (ret == 0) {
  17046. /* Parse NameConstraints. */
  17047. ret = GetASN_Items(nameConstraintsASN, dataASN,
  17048. nameConstraintsASN_Length, 1, input, &idx, sz);
  17049. }
  17050. if (ret == 0) {
  17051. /* If there was a permittedSubtrees then parse it. */
  17052. if (dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data != NULL) {
  17053. ret = DecodeSubtree(
  17054. dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data,
  17055. dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.length,
  17056. &cert->permittedNames, cert->heap);
  17057. }
  17058. }
  17059. if (ret == 0) {
  17060. /* If there was a excludedSubtrees then parse it. */
  17061. if (dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data != NULL) {
  17062. ret = DecodeSubtree(
  17063. dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data,
  17064. dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.length,
  17065. &cert->excludedNames, cert->heap);
  17066. }
  17067. }
  17068. FREE_ASNGETDATA(dataASN, cert->heap);
  17069. return ret;
  17070. #endif /* WOLFSSL_ASN_TEMPLATE */
  17071. }
  17072. #endif /* IGNORE_NAME_CONSTRAINTS */
  17073. #if (defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_SEP)) || \
  17074. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17075. /* Decode ITU-T X.690 OID format to a string representation
  17076. * return string length */
  17077. int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz)
  17078. {
  17079. word32 val, inIdx = 0, outIdx = 0;
  17080. int w = 0;
  17081. if (out == NULL || in == NULL || outSz < 4 || inSz < 2)
  17082. return BAD_FUNC_ARG;
  17083. /* The first byte expands into b/40 dot b%40. */
  17084. val = in[inIdx++];
  17085. w = XSNPRINTF(out, outSz, "%u.%u", val / 40, val % 40);
  17086. if (w < 0) {
  17087. w = BUFFER_E;
  17088. goto exit;
  17089. }
  17090. outIdx += w;
  17091. val = 0;
  17092. while (inIdx < inSz && outIdx < outSz) {
  17093. /* extract the next OID digit from in to val */
  17094. /* first bit is used to set if value is coded on 1 or multiple bytes */
  17095. if (in[inIdx] & 0x80) {
  17096. val += in[inIdx] & 0x7F;
  17097. val *= 128;
  17098. }
  17099. else {
  17100. /* write val as text into out */
  17101. val += in[inIdx];
  17102. w = XSNPRINTF(out + outIdx, outSz - outIdx, ".%u", val);
  17103. if (w < 0 || (word32)w > outSz - outIdx) {
  17104. w = BUFFER_E;
  17105. goto exit;
  17106. }
  17107. outIdx += w;
  17108. val = 0;
  17109. }
  17110. inIdx++;
  17111. }
  17112. if (outIdx == outSz)
  17113. outIdx--;
  17114. out[outIdx] = 0;
  17115. w = (int)outIdx;
  17116. exit:
  17117. return w;
  17118. }
  17119. #endif /* WOLFSSL_CERT_EXT && !WOLFSSL_SEP */
  17120. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_QT)
  17121. #ifdef WOLFSSL_ASN_TEMPLATE
  17122. /* ASN.1 template for PolicyInformation.
  17123. * X.509: RFC 5280, 4.2.1.4 - Certificate Policies.
  17124. */
  17125. static const ASNItem policyInfoASN[] = {
  17126. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17127. /* policyIdentifier */
  17128. /* ID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  17129. /* policyQualifiers */
  17130. /* QUALI */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  17131. };
  17132. enum {
  17133. POLICYINFOASN_IDX_SEQ = 0,
  17134. POLICYINFOASN_IDX_ID,
  17135. POLICYINFOASN_IDX_QUALI
  17136. };
  17137. /* Number of items in ASN.1 template for PolicyInformation. */
  17138. #define policyInfoASN_Length (sizeof(policyInfoASN) / sizeof(ASNItem))
  17139. #endif
  17140. /* Reference: https://tools.ietf.org/html/rfc5280#section-4.2.1.4 */
  17141. static int DecodeCertPolicy(const byte* input, word32 sz, DecodedCert* cert)
  17142. {
  17143. #ifndef WOLFSSL_ASN_TEMPLATE
  17144. word32 idx = 0;
  17145. word32 oldIdx;
  17146. int policy_length = 0;
  17147. int ret;
  17148. int total_length = 0;
  17149. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  17150. !defined(WOLFSSL_DUP_CERTPOL)
  17151. int i;
  17152. #endif
  17153. WOLFSSL_ENTER("DecodeCertPolicy");
  17154. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  17155. /* Check if cert is null before dereferencing below */
  17156. if (cert == NULL)
  17157. return BAD_FUNC_ARG;
  17158. #else
  17159. (void)cert;
  17160. #endif
  17161. #if defined(WOLFSSL_CERT_EXT)
  17162. cert->extCertPoliciesNb = 0;
  17163. #endif
  17164. if (GetSequence(input, &idx, &total_length, sz) < 0) {
  17165. WOLFSSL_MSG("\tGet CertPolicy total seq failed");
  17166. return ASN_PARSE_E;
  17167. }
  17168. /* Validate total length */
  17169. if (total_length > (int)(sz - idx)) {
  17170. WOLFSSL_MSG("\tCertPolicy length mismatch");
  17171. return ASN_PARSE_E;
  17172. }
  17173. /* Unwrap certificatePolicies */
  17174. do {
  17175. int length = 0;
  17176. if (GetSequence(input, &idx, &policy_length, sz) < 0) {
  17177. WOLFSSL_MSG("\tGet CertPolicy seq failed");
  17178. return ASN_PARSE_E;
  17179. }
  17180. oldIdx = idx;
  17181. ret = GetASNObjectId(input, &idx, &length, sz);
  17182. if (ret != 0)
  17183. return ret;
  17184. policy_length -= (int)(idx - oldIdx);
  17185. if (length > 0) {
  17186. /* Verify length won't overrun buffer */
  17187. if (length > (int)(sz - idx)) {
  17188. WOLFSSL_MSG("\tCertPolicy length exceeds input buffer");
  17189. return ASN_PARSE_E;
  17190. }
  17191. #if defined(WOLFSSL_SEP)
  17192. cert->deviceType = (byte*)XMALLOC((size_t)length, cert->heap,
  17193. DYNAMIC_TYPE_X509_EXT);
  17194. if (cert->deviceType == NULL) {
  17195. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  17196. return MEMORY_E;
  17197. }
  17198. cert->deviceTypeSz = length;
  17199. XMEMCPY(cert->deviceType, input + idx, (size_t)length);
  17200. break;
  17201. #elif defined(WOLFSSL_CERT_EXT)
  17202. /* decode cert policy */
  17203. if (DecodePolicyOID(cert->extCertPolicies[
  17204. cert->extCertPoliciesNb], MAX_CERTPOL_SZ,
  17205. input + idx, length) <= 0) {
  17206. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  17207. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17208. return ASN_PARSE_E;
  17209. }
  17210. #ifndef WOLFSSL_DUP_CERTPOL
  17211. /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
  17212. * NOT appear more than once in a certificate policies
  17213. * extension". This is a sanity check for duplicates.
  17214. * extCertPolicies should only have OID values, additional
  17215. * qualifiers need to be stored in a separate array. */
  17216. for (i = 0; i < cert->extCertPoliciesNb; i++) {
  17217. if (XMEMCMP(cert->extCertPolicies[i],
  17218. cert->extCertPolicies[cert->extCertPoliciesNb],
  17219. MAX_CERTPOL_SZ) == 0) {
  17220. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  17221. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  17222. WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
  17223. return CERTPOLICIES_E;
  17224. }
  17225. }
  17226. #endif /* !WOLFSSL_DUP_CERTPOL */
  17227. cert->extCertPoliciesNb++;
  17228. #else
  17229. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  17230. return 0;
  17231. #endif
  17232. }
  17233. idx += (word32)policy_length;
  17234. } while((int)idx < total_length
  17235. #if defined(WOLFSSL_CERT_EXT)
  17236. && cert->extCertPoliciesNb < MAX_CERTPOL_NB
  17237. #endif
  17238. );
  17239. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  17240. return 0;
  17241. #else /* WOLFSSL_ASN_TEMPLATE */
  17242. word32 idx = 0;
  17243. int ret = 0;
  17244. int total_length = 0;
  17245. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  17246. !defined(WOLFSSL_DUP_CERTPOL)
  17247. int i;
  17248. #endif
  17249. WOLFSSL_ENTER("DecodeCertPolicy");
  17250. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  17251. /* Check if cert is null before dereferencing below */
  17252. if (cert == NULL)
  17253. ret = BAD_FUNC_ARG;
  17254. #endif
  17255. if (ret == 0) {
  17256. #if defined(WOLFSSL_CERT_EXT)
  17257. cert->extCertPoliciesNb = 0;
  17258. #endif
  17259. /* Strip SEQUENCE OF and check using all data. */
  17260. if (GetASN_Sequence(input, &idx, &total_length, (word32)sz, 1) < 0)
  17261. {
  17262. ret = ASN_PARSE_E;
  17263. }
  17264. }
  17265. /* Unwrap certificatePolicies */
  17266. while ((ret == 0) && ((int)idx < total_length)
  17267. #if defined(WOLFSSL_CERT_EXT)
  17268. && (cert->extCertPoliciesNb < MAX_CERTPOL_NB)
  17269. #endif
  17270. ) {
  17271. ASNGetData dataASN[policyInfoASN_Length];
  17272. byte* data = NULL;
  17273. word32 length = 0;
  17274. /* Clear dynamic data and check OID is a cert policy type. */
  17275. XMEMSET(dataASN, 0, sizeof(dataASN));
  17276. GetASN_OID(&dataASN[POLICYINFOASN_IDX_ID], oidCertPolicyType);
  17277. ret = GetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length, 1,
  17278. input, &idx, (word32)sz);
  17279. if (ret == 0) {
  17280. /* Get the OID. */
  17281. GetASN_OIDData(&dataASN[POLICYINFOASN_IDX_ID], &data, &length);
  17282. if (length == 0) {
  17283. ret = ASN_PARSE_E;
  17284. }
  17285. }
  17286. #if defined(WOLFSSL_SEP)
  17287. /* Store OID in device type. */
  17288. if (ret == 0) {
  17289. cert->deviceType = (byte*)XMALLOC(length, cert->heap,
  17290. DYNAMIC_TYPE_X509_EXT);
  17291. if (cert->deviceType == NULL) {
  17292. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  17293. ret = MEMORY_E;
  17294. }
  17295. }
  17296. if (ret == 0) {
  17297. /* Store device type data and length. */
  17298. cert->deviceTypeSz = (int)length;
  17299. XMEMCPY(cert->deviceType, data, length);
  17300. break;
  17301. }
  17302. #elif defined(WOLFSSL_CERT_EXT)
  17303. if (ret == 0) {
  17304. /* Decode cert policy. */
  17305. if (DecodePolicyOID(
  17306. cert->extCertPolicies[cert->extCertPoliciesNb],
  17307. MAX_CERTPOL_SZ, data, length) <= 0) {
  17308. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  17309. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17310. ret = ASN_PARSE_E;
  17311. }
  17312. }
  17313. #ifndef WOLFSSL_DUP_CERTPOL
  17314. /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
  17315. * NOT appear more than once in a certificate policies
  17316. * extension". This is a sanity check for duplicates.
  17317. * extCertPolicies should only have OID values, additional
  17318. * qualifiers need to be stored in a seperate array. */
  17319. for (i = 0; (ret == 0) && (i < cert->extCertPoliciesNb); i++) {
  17320. if (XMEMCMP(cert->extCertPolicies[i],
  17321. cert->extCertPolicies[cert->extCertPoliciesNb],
  17322. MAX_CERTPOL_SZ) == 0) {
  17323. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  17324. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  17325. WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
  17326. ret = CERTPOLICIES_E;
  17327. }
  17328. }
  17329. #endif /* !defined(WOLFSSL_DUP_CERTPOL) */
  17330. if (ret == 0) {
  17331. /* Keep count of policies seen. */
  17332. cert->extCertPoliciesNb++;
  17333. }
  17334. #else
  17335. (void)data;
  17336. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  17337. break;
  17338. #endif
  17339. }
  17340. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  17341. return ret;
  17342. #endif /* WOLFSSL_ASN_TEMPLATE */
  17343. }
  17344. #endif /* WOLFSSL_SEP */
  17345. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  17346. #ifdef WOLFSSL_ASN_TEMPLATE
  17347. /* ASN.1 template for subject dir attribute.
  17348. * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
  17349. */
  17350. static const ASNItem subjDirAttrASN[] = {
  17351. /* SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  17352. /* OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  17353. /* PLEN */ { 2, ASN_SET, 1, 0, 0 },
  17354. };
  17355. enum {
  17356. SUBJDIRATTRASN_IDX_SEQ = 0,
  17357. SUBJDIRATTRASN_IDX_OID,
  17358. SUBJDIRATTRASN_IDX_SET,
  17359. };
  17360. /* Number of items in ASN.1 template for BasicContraints. */
  17361. #define subjDirAttrASN_Length (sizeof(subjDirAttrASN) / sizeof(ASNItem))
  17362. #endif
  17363. /* Decode subject directory attributes extension in a certificate.
  17364. *
  17365. * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
  17366. *
  17367. * @param [in] input Buffer holding data.
  17368. * @param [in] sz Size of data in buffer.
  17369. * @param [in, out] cert Certificate object.
  17370. * @return 0 on success.
  17371. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17372. * is invalid.
  17373. */
  17374. static int DecodeSubjDirAttr(const byte* input, int sz, DecodedCert* cert)
  17375. {
  17376. #ifndef WOLFSSL_ASN_TEMPLATE
  17377. word32 idx = 0;
  17378. int length = 0;
  17379. int ret = 0;
  17380. WOLFSSL_ENTER("DecodeSubjDirAttr");
  17381. #ifdef OPENSSL_ALL
  17382. cert->extSubjDirAttrSrc = input;
  17383. cert->extSubjDirAttrSz = sz;
  17384. #endif /* OPENSSL_ALL */
  17385. /* Unwrap the list of Attributes */
  17386. if (GetSequence(input, &idx, &length, sz) < 0)
  17387. return ASN_PARSE_E;
  17388. if (length == 0) {
  17389. /* RFC 5280 4.2.1.8. Subject Directory Attributes
  17390. If the subjectDirectoryAttributes extension is present, the
  17391. sequence MUST contain at least one entry. */
  17392. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17393. return ASN_PARSE_E;
  17394. }
  17395. /* length is the length of the list contents */
  17396. while (idx < (word32)sz) {
  17397. word32 oid;
  17398. if (GetSequence(input, &idx, &length, sz) < 0)
  17399. return ASN_PARSE_E;
  17400. if (GetObjectId(input, &idx, &oid, oidSubjDirAttrType, sz) < 0)
  17401. return ASN_PARSE_E;
  17402. if (GetSet(input, &idx, &length, sz) < 0)
  17403. return ASN_PARSE_E;
  17404. /* There may be more than one countryOfCitizenship, but save the
  17405. * first one for now. */
  17406. if (oid == SDA_COC_OID) {
  17407. byte tag;
  17408. if (GetHeader(input, &tag, &idx, &length, sz, 1) < 0)
  17409. return ASN_PARSE_E;
  17410. if (length != COUNTRY_CODE_LEN)
  17411. return ASN_PARSE_E;
  17412. if (tag == ASN_PRINTABLE_STRING) {
  17413. XMEMCPY(cert->countryOfCitizenship,
  17414. input + idx, COUNTRY_CODE_LEN);
  17415. cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
  17416. }
  17417. }
  17418. idx += length;
  17419. }
  17420. return ret;
  17421. #else
  17422. DECL_ASNGETDATA(dataASN, subjDirAttrASN_Length);
  17423. int ret = 0;
  17424. word32 idx = 0;
  17425. int length;
  17426. WOLFSSL_ENTER("DecodeSubjDirAttr");
  17427. CALLOC_ASNGETDATA(dataASN, subjDirAttrASN_Length, ret, cert->heap);
  17428. /* Strip outer SEQUENCE. */
  17429. if ((ret == 0) && (GetSequence(input, &idx, &length, sz) < 0)) {
  17430. ret = ASN_PARSE_E;
  17431. }
  17432. /* Handle each inner SEQUENCE. */
  17433. while ((ret == 0) && (idx < (word32)sz)) {
  17434. ret = GetASN_Items(subjDirAttrASN, dataASN, subjDirAttrASN_Length, 1,
  17435. input, &idx, sz);
  17436. /* There may be more than one countryOfCitizenship, but save the
  17437. * first one for now. */
  17438. if ((ret == 0) &&
  17439. (dataASN[SUBJDIRATTRASN_IDX_OID].data.oid.sum == SDA_COC_OID)) {
  17440. int cuLen;
  17441. word32 setIdx = 0;
  17442. byte* setData;
  17443. word32 setLen;
  17444. GetASN_GetRef(&dataASN[SUBJDIRATTRASN_IDX_SET], &setData, &setLen);
  17445. if (GetASNHeader(setData, ASN_PRINTABLE_STRING, &setIdx, &cuLen,
  17446. setLen) < 0) {
  17447. ret = ASN_PARSE_E;
  17448. }
  17449. if ((ret == 0) && (cuLen != COUNTRY_CODE_LEN)) {
  17450. ret = ASN_PARSE_E;
  17451. }
  17452. if (ret == 0) {
  17453. XMEMCPY(cert->countryOfCitizenship, setData + setIdx, cuLen);
  17454. cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
  17455. }
  17456. }
  17457. }
  17458. FREE_ASNGETDATA(dataASN, cert->heap);
  17459. return ret;
  17460. #endif /* WOLFSSL_ASN_TEMPLATE */
  17461. }
  17462. #endif /* WOLFSSL_SUBJ_DIR_ATTR */
  17463. #ifdef WOLFSSL_SUBJ_INFO_ACC
  17464. /* Decode subject infomation access extension in a certificate.
  17465. *
  17466. * X.509: RFC 5280, 4.2.2.2 - Subject Information Access.
  17467. *
  17468. * @param [in] input Buffer holding data.
  17469. * @param [in] sz Size of data in buffer.
  17470. * @param [in, out] cert Certificate object.
  17471. * @return 0 on success.
  17472. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  17473. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17474. * is invalid.
  17475. * @return MEMORY_E on dynamic memory allocation failure.
  17476. */
  17477. static int DecodeSubjInfoAcc(const byte* input, int sz, DecodedCert* cert)
  17478. {
  17479. word32 idx = 0;
  17480. int length = 0;
  17481. int ret = 0;
  17482. WOLFSSL_ENTER("DecodeSubjInfoAcc");
  17483. #ifdef OPENSSL_ALL
  17484. cert->extSubjAltNameSrc = input;
  17485. cert->extSubjAltNameSz = sz;
  17486. #endif /* OPENSSL_ALL */
  17487. /* Unwrap SubjectInfoAccessSyntax, the list of AccessDescriptions */
  17488. if (GetSequence(input, &idx, &length, sz) < 0)
  17489. return ASN_PARSE_E;
  17490. if (length == 0) {
  17491. /* RFC 5280 4.2.2.2. Subject Information Access
  17492. If the subjectInformationAccess extension is present, the
  17493. sequence MUST contain at least one entry. */
  17494. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17495. return ASN_PARSE_E;
  17496. }
  17497. /* Per fpkx-x509-cert-profile-common... section 5.3.
  17498. * [The] subjectInfoAccess extension must contain at least one
  17499. * instance of the id-ad-caRepository access method containing a
  17500. * publicly accessible HTTP URI which returns as certs-only
  17501. * CMS.
  17502. */
  17503. while (idx < (word32)sz) {
  17504. word32 oid = 0;
  17505. byte b;
  17506. /* Unwrap an AccessDescription */
  17507. if (GetSequence(input, &idx, &length, sz) < 0)
  17508. return ASN_PARSE_E;
  17509. /* Get the accessMethod */
  17510. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0)
  17511. return ASN_PARSE_E;
  17512. /* Only supporting URIs right now. */
  17513. if (GetASNTag(input, &idx, &b, sz) < 0)
  17514. return ASN_PARSE_E;
  17515. if (GetLength(input, &idx, &length, sz) < 0)
  17516. return ASN_PARSE_E;
  17517. /* Set caRepo entry */
  17518. if (b == GENERALNAME_URI && oid == AIA_CA_REPO_OID) {
  17519. cert->extSubjInfoAccCaRepoSz = length;
  17520. cert->extSubjInfoAccCaRepo = input + idx;
  17521. break;
  17522. }
  17523. idx += length;
  17524. }
  17525. if (cert->extSubjInfoAccCaRepo == NULL ||
  17526. cert->extSubjInfoAccCaRepoSz == 0) {
  17527. WOLFSSL_MSG("SubjectInfoAccess missing an URL.");
  17528. ret = ASN_PARSE_E;
  17529. }
  17530. WOLFSSL_LEAVE("DecodeSubjInfoAcc", ret);
  17531. return ret;
  17532. }
  17533. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  17534. /* Macro to check if bit is set, if not sets and return success.
  17535. Otherwise returns failure */
  17536. /* Macro required here because bit-field operation */
  17537. #ifndef WOLFSSL_NO_ASN_STRICT
  17538. #define VERIFY_AND_SET_OID(bit) \
  17539. if ((bit) == 0) \
  17540. (bit) = 1; \
  17541. else \
  17542. return ASN_OBJECT_ID_E;
  17543. #else
  17544. /* With no strict defined, the verify is skipped */
  17545. #define VERIFY_AND_SET_OID(bit) bit = 1;
  17546. #endif
  17547. /* Parse extension type specific data based on OID sum.
  17548. *
  17549. * Supported extensions:
  17550. * Basic Constraints - BASIC_CA_OID
  17551. * CRL Distribution Points - CRL_DIST_OID
  17552. * Authority Information Access - AUTH_INFO_OID
  17553. * Subject Alternative Name - ALT_NAMES_OID
  17554. * Authority Key Identifier - AUTH_KEY_OID
  17555. * Subject Key Identifier - SUBJ_KEY_OID
  17556. * Certificate Policies - CERT_POLICY_OID (conditional parsing)
  17557. * Key Usage - KEY_USAGE_OID
  17558. * Extended Key Usage - EXT_KEY_USAGE_OID
  17559. * Name Constraints - NAME_CONS_OID
  17560. * Inhibit anyPolicy - INHIBIT_ANY_OID
  17561. * Netscape Certificate Type - NETSCAPE_CT_OID (able to be excluded)
  17562. * OCSP no check - OCSP_NOCHECK_OID (when compiling OCSP)
  17563. * Subject Directory Attributes - SUBJ_DIR_ATTR_OID
  17564. * Subject Information Access - SUBJ_INFO_ACC_OID
  17565. * Unsupported extensions from RFC 5280:
  17566. * 4.2.1.5 - Policy mappings
  17567. * 4.2.1.7 - Issuer Alternative Name
  17568. * 4.2.1.11 - Policy Constraints
  17569. * 4.2.1.15 - Freshest CRL
  17570. *
  17571. * @param [in] input Buffer containing extension type specific data.
  17572. * @param [in] length Length of data.
  17573. * @param [in] oid OID sum for extension.
  17574. * @param [in] critical Whether extension is critical.
  17575. * @param [in, out] cert Certificate object.
  17576. * @return 0 on success.
  17577. * @return ASN_PARSE_E when BER encoding is invalid.
  17578. * @return MEMORY_E on dynamic memory allocation failure.
  17579. * @return Other negative values on error.
  17580. */
  17581. static int DecodeExtensionType(const byte* input, word32 length, word32 oid,
  17582. byte critical, DecodedCert* cert,
  17583. int *isUnknownExt)
  17584. {
  17585. int ret = 0;
  17586. word32 idx = 0;
  17587. if (isUnknownExt != NULL)
  17588. *isUnknownExt = 0;
  17589. switch (oid) {
  17590. /* Basic Constraints. */
  17591. case BASIC_CA_OID:
  17592. VERIFY_AND_SET_OID(cert->extBasicConstSet);
  17593. cert->extBasicConstCrit = critical ? 1 : 0;
  17594. if (DecodeBasicCaConstraint(input, (int)length, cert) < 0) {
  17595. ret = ASN_PARSE_E;
  17596. }
  17597. break;
  17598. /* CRL Distribution point. */
  17599. case CRL_DIST_OID:
  17600. VERIFY_AND_SET_OID(cert->extCRLdistSet);
  17601. cert->extCRLdistCrit = critical ? 1 : 0;
  17602. if (DecodeCrlDist(input, length, cert) < 0) {
  17603. ret = ASN_PARSE_E;
  17604. }
  17605. break;
  17606. /* Authority information access. */
  17607. case AUTH_INFO_OID:
  17608. VERIFY_AND_SET_OID(cert->extAuthInfoSet);
  17609. cert->extAuthInfoCrit = critical ? 1 : 0;
  17610. if (DecodeAuthInfo(input, length, cert) < 0) {
  17611. ret = ASN_PARSE_E;
  17612. }
  17613. break;
  17614. /* Subject alternative name. */
  17615. case ALT_NAMES_OID:
  17616. VERIFY_AND_SET_OID(cert->extSubjAltNameSet);
  17617. cert->extSubjAltNameCrit = critical ? 1 : 0;
  17618. ret = DecodeAltNames(input, length, cert);
  17619. break;
  17620. /* Authority Key Identifier. */
  17621. case AUTH_KEY_OID:
  17622. VERIFY_AND_SET_OID(cert->extAuthKeyIdSet);
  17623. cert->extAuthKeyIdCrit = critical ? 1 : 0;
  17624. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  17625. /* This check is added due to RFC 5280 section 4.2.1.1
  17626. * stating that conforming CA's must mark this extension
  17627. * as non-critical. When parsing extensions check that
  17628. * certificate was made in compliance with this. */
  17629. if (critical) {
  17630. WOLFSSL_MSG("Critical Auth Key ID is not allowed");
  17631. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  17632. ret = ASN_CRIT_EXT_E;
  17633. }
  17634. #endif
  17635. if ((ret == 0) && (DecodeAuthKeyId(input, length, cert) < 0)) {
  17636. ret = ASN_PARSE_E;
  17637. }
  17638. break;
  17639. /* Subject Key Identifier. */
  17640. case SUBJ_KEY_OID:
  17641. VERIFY_AND_SET_OID(cert->extSubjKeyIdSet);
  17642. cert->extSubjKeyIdCrit = critical ? 1 : 0;
  17643. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  17644. /* This check is added due to RFC 5280 section 4.2.1.2
  17645. * stating that conforming CA's must mark this extension
  17646. * as non-critical. When parsing extensions check that
  17647. * certificate was made in compliance with this. */
  17648. if (critical) {
  17649. WOLFSSL_MSG("Critical Subject Key ID is not allowed");
  17650. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  17651. ret = ASN_CRIT_EXT_E;
  17652. }
  17653. #endif
  17654. if ((ret == 0) && (DecodeSubjKeyId(input, length, cert) < 0)) {
  17655. ret = ASN_PARSE_E;
  17656. }
  17657. break;
  17658. /* Certificate policies. */
  17659. case CERT_POLICY_OID:
  17660. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT)
  17661. VERIFY_AND_SET_OID(cert->extCertPolicySet);
  17662. #if defined(OPENSSL_EXTRA) || \
  17663. defined(OPENSSL_EXTRA_X509_SMALL)
  17664. cert->extCertPolicyCrit = critical ? 1 : 0;
  17665. #endif
  17666. #endif
  17667. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || \
  17668. defined(WOLFSSL_QT)
  17669. if (DecodeCertPolicy(input, length, cert) < 0) {
  17670. ret = ASN_PARSE_E;
  17671. }
  17672. #else
  17673. WOLFSSL_MSG("Certificate Policy extension not supported yet.");
  17674. #endif
  17675. break;
  17676. /* Key usage. */
  17677. case KEY_USAGE_OID:
  17678. VERIFY_AND_SET_OID(cert->extKeyUsageSet);
  17679. cert->extKeyUsageCrit = critical ? 1 : 0;
  17680. if (DecodeKeyUsage(input, length, cert) < 0) {
  17681. ret = ASN_PARSE_E;
  17682. }
  17683. break;
  17684. /* Extended key usage. */
  17685. case EXT_KEY_USAGE_OID:
  17686. VERIFY_AND_SET_OID(cert->extExtKeyUsageSet);
  17687. cert->extExtKeyUsageCrit = critical ? 1 : 0;
  17688. if (DecodeExtKeyUsage(input, length, cert) < 0) {
  17689. ret = ASN_PARSE_E;
  17690. }
  17691. break;
  17692. #ifndef IGNORE_NAME_CONSTRAINTS
  17693. /* Name constraints. */
  17694. case NAME_CONS_OID:
  17695. #ifndef WOLFSSL_NO_ASN_STRICT
  17696. /* Verify RFC 5280 Sec 4.2.1.10 rule:
  17697. "The name constraints extension,
  17698. which MUST be used only in a CA certificate" */
  17699. if (!cert->isCA) {
  17700. WOLFSSL_MSG("Name constraints allowed only for CA certs");
  17701. WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
  17702. ret = ASN_NAME_INVALID_E;
  17703. }
  17704. #endif
  17705. VERIFY_AND_SET_OID(cert->extNameConstraintSet);
  17706. cert->extNameConstraintCrit = critical ? 1 : 0;
  17707. if (DecodeNameConstraints(input, length, cert) < 0) {
  17708. ret = ASN_PARSE_E;
  17709. }
  17710. break;
  17711. #endif /* IGNORE_NAME_CONSTRAINTS */
  17712. /* Inhibit anyPolicy. */
  17713. case INHIBIT_ANY_OID:
  17714. VERIFY_AND_SET_OID(cert->inhibitAnyOidSet);
  17715. WOLFSSL_MSG("Inhibit anyPolicy extension not supported yet.");
  17716. break;
  17717. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  17718. /* Netscape's certificate type. */
  17719. case NETSCAPE_CT_OID:
  17720. if (DecodeNsCertType(input, (int)length, cert) < 0)
  17721. ret = ASN_PARSE_E;
  17722. break;
  17723. #endif
  17724. #ifdef HAVE_OCSP
  17725. /* OCSP no check. */
  17726. case OCSP_NOCHECK_OID:
  17727. VERIFY_AND_SET_OID(cert->ocspNoCheckSet);
  17728. ret = GetASNNull(input, &idx, length);
  17729. if (ret != 0) {
  17730. ret = ASN_PARSE_E;
  17731. }
  17732. break;
  17733. #endif
  17734. case POLICY_CONST_OID:
  17735. VERIFY_AND_SET_OID(cert->extPolicyConstSet);
  17736. cert->extPolicyConstCrit = critical ? 1 : 0;
  17737. if (DecodePolicyConstraints(&input[idx], (int)length, cert) < 0)
  17738. return ASN_PARSE_E;
  17739. break;
  17740. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  17741. case SUBJ_DIR_ATTR_OID:
  17742. VERIFY_AND_SET_OID(cert->extSubjDirAttrSet);
  17743. if (DecodeSubjDirAttr(&input[idx], length, cert) < 0)
  17744. return ASN_PARSE_E;
  17745. break;
  17746. #endif
  17747. #ifdef WOLFSSL_SUBJ_INFO_ACC
  17748. case SUBJ_INFO_ACC_OID:
  17749. VERIFY_AND_SET_OID(cert->extSubjInfoAccSet);
  17750. if (DecodeSubjInfoAcc(&input[idx], length, cert) < 0)
  17751. return ASN_PARSE_E;
  17752. break;
  17753. #endif
  17754. default:
  17755. if (isUnknownExt != NULL)
  17756. *isUnknownExt = 1;
  17757. #ifndef WOLFSSL_NO_ASN_STRICT
  17758. /* While it is a failure to not support critical extensions,
  17759. * still parse the certificate ignoring the unsupported
  17760. * extension to allow caller to accept it with the verify
  17761. * callback. */
  17762. if (critical) {
  17763. WOLFSSL_ERROR_VERBOSE(ASN_CRIT_EXT_E);
  17764. ret = ASN_CRIT_EXT_E;
  17765. }
  17766. #endif
  17767. break;
  17768. }
  17769. return ret;
  17770. }
  17771. #ifdef WOLFSSL_ASN_TEMPLATE
  17772. /* ASN.1 template for extensions.
  17773. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  17774. */
  17775. static const ASNItem certExtHdrASN[] = {
  17776. /* EXTTAG */ { 0, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 0 },
  17777. /* EXTSEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  17778. };
  17779. enum {
  17780. CERTEXTHDRASN_IDX_EXTTAG = 0,
  17781. CERTEXTHDRASN_IDX_EXTSEQ
  17782. };
  17783. /* Number of itesm in ASN.1 template for extensions. */
  17784. #define certExtHdrASN_Length (sizeof(certExtHdrASN) / sizeof(ASNItem))
  17785. /* ASN.1 template for Extension.
  17786. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  17787. */
  17788. static const ASNItem certExtASN[] = {
  17789. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17790. /* Extension object id */
  17791. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  17792. /* critical - when true, must be parseable. */
  17793. /* CRIT */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  17794. /* Data for extension - leave index at start of data. */
  17795. /* VAL */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  17796. };
  17797. enum {
  17798. CERTEXTASN_IDX_SEQ = 0,
  17799. CERTEXTASN_IDX_OID,
  17800. CERTEXTASN_IDX_CRIT,
  17801. CERTEXTASN_IDX_VAL
  17802. };
  17803. /* Number of items in ASN.1 template for Extension. */
  17804. #define certExtASN_Length (sizeof(certExtASN) / sizeof(ASNItem))
  17805. #endif
  17806. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \
  17807. && defined(HAVE_OID_DECODING)
  17808. int wc_SetUnknownExtCallback(DecodedCert* cert,
  17809. wc_UnknownExtCallback cb) {
  17810. if (cert == NULL) {
  17811. return BAD_FUNC_ARG;
  17812. }
  17813. cert->unknownExtCallback = cb;
  17814. return 0;
  17815. }
  17816. #endif
  17817. /*
  17818. * Processing the Certificate Extensions. This does not modify the current
  17819. * index. It is works starting with the recorded extensions pointer.
  17820. */
  17821. static int DecodeCertExtensions(DecodedCert* cert)
  17822. {
  17823. #ifndef WOLFSSL_ASN_TEMPLATE
  17824. int ret = 0;
  17825. word32 idx = 0;
  17826. word32 sz = (word32)cert->extensionsSz;
  17827. const byte* input = cert->extensions;
  17828. int length;
  17829. word32 oid;
  17830. byte critical = 0;
  17831. byte criticalFail = 0;
  17832. byte tag = 0;
  17833. WOLFSSL_ENTER("DecodeCertExtensions");
  17834. if (input == NULL || sz == 0)
  17835. return BAD_FUNC_ARG;
  17836. #ifdef WOLFSSL_CERT_REQ
  17837. if (!cert->isCSR)
  17838. #endif
  17839. { /* Not included in CSR */
  17840. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  17841. return ASN_PARSE_E;
  17842. }
  17843. if (tag != ASN_EXTENSIONS) {
  17844. WOLFSSL_MSG("\tfail: should be an EXTENSIONS");
  17845. return ASN_PARSE_E;
  17846. }
  17847. if (GetLength(input, &idx, &length, sz) < 0) {
  17848. WOLFSSL_MSG("\tfail: invalid length");
  17849. return ASN_PARSE_E;
  17850. }
  17851. }
  17852. if (GetSequence(input, &idx, &length, sz) < 0) {
  17853. WOLFSSL_MSG("\tfail: should be a SEQUENCE (1)");
  17854. return ASN_PARSE_E;
  17855. }
  17856. while (idx < (word32)sz) {
  17857. word32 localIdx;
  17858. if (GetSequence(input, &idx, &length, sz) < 0) {
  17859. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17860. return ASN_PARSE_E;
  17861. }
  17862. oid = 0;
  17863. if ((ret = GetObjectId(input, &idx, &oid, oidCertExtType, sz)) < 0) {
  17864. WOLFSSL_MSG("\tfail: OBJECT ID");
  17865. return ret;
  17866. }
  17867. /* check for critical flag */
  17868. critical = 0;
  17869. if ((idx + 1) > (word32)sz) {
  17870. WOLFSSL_MSG("\tfail: malformed buffer");
  17871. return BUFFER_E;
  17872. }
  17873. localIdx = idx;
  17874. if (GetASNTag(input, &localIdx, &tag, sz) == 0) {
  17875. if (tag == ASN_BOOLEAN) {
  17876. ret = GetBoolean(input, &idx, sz);
  17877. if (ret < 0) {
  17878. WOLFSSL_MSG("\tfail: critical boolean");
  17879. return ret;
  17880. }
  17881. critical = (byte)ret;
  17882. }
  17883. }
  17884. /* process the extension based on the OID */
  17885. ret = GetOctetString(input, &idx, &length, sz);
  17886. if (ret < 0) {
  17887. WOLFSSL_MSG("\tfail: bad OCTET STRING");
  17888. return ret;
  17889. }
  17890. ret = DecodeExtensionType(input + idx, (word32)length, oid, critical,
  17891. cert, NULL);
  17892. if (ret == ASN_CRIT_EXT_E) {
  17893. ret = 0;
  17894. criticalFail = 1;
  17895. }
  17896. if (ret < 0)
  17897. goto end;
  17898. idx += (word32)length;
  17899. }
  17900. ret = criticalFail ? ASN_CRIT_EXT_E : 0;
  17901. end:
  17902. return ret;
  17903. #else
  17904. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  17905. ASNGetData dataExtsASN[certExtHdrASN_Length];
  17906. int ret = 0;
  17907. const byte* input = cert->extensions;
  17908. int sz = cert->extensionsSz;
  17909. word32 idx = 0;
  17910. int criticalRet = 0;
  17911. int offset = 0;
  17912. WOLFSSL_ENTER("DecodeCertExtensions");
  17913. if (input == NULL || sz == 0)
  17914. ret = BAD_FUNC_ARG;
  17915. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, cert->heap);
  17916. #ifdef WOLFSSL_CERT_REQ
  17917. if (cert->isCSR) {
  17918. offset = CERTEXTHDRASN_IDX_EXTSEQ;
  17919. }
  17920. #endif
  17921. if (ret == 0) {
  17922. /* Clear dynamic data. */
  17923. XMEMSET(dataExtsASN, 0, sizeof(dataExtsASN));
  17924. /* Parse extensions header. */
  17925. ret = GetASN_Items(certExtHdrASN + offset, dataExtsASN + offset,
  17926. (int)(certExtHdrASN_Length - (size_t)offset), 0,
  17927. input, &idx, (word32)sz);
  17928. }
  17929. /* Parse each extension. */
  17930. while ((ret == 0) && (idx < (word32)sz)) {
  17931. byte critical = 0;
  17932. int isUnknownExt = 0;
  17933. /* Clear dynamic data. */
  17934. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  17935. /* Ensure OID is an extention type. */
  17936. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  17937. /* Set criticality variable. */
  17938. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  17939. /* Parse extension wrapper. */
  17940. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  17941. &idx, (word32)sz);
  17942. if (ret == 0) {
  17943. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  17944. word32 length = dataASN[CERTEXTASN_IDX_VAL].length;
  17945. /* Decode the extension by type. */
  17946. ret = DecodeExtensionType(input + idx, length, oid, critical, cert,
  17947. &isUnknownExt);
  17948. #if defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_DECODING)
  17949. if (isUnknownExt && (cert->unknownExtCallback != NULL)) {
  17950. word16 decOid[MAX_OID_SZ];
  17951. word32 decOidSz = sizeof(decOid);
  17952. ret = DecodeObjectId(
  17953. dataASN[CERTEXTASN_IDX_OID].data.oid.data,
  17954. dataASN[CERTEXTASN_IDX_OID].data.oid.length,
  17955. decOid, &decOidSz);
  17956. if (ret != 0) {
  17957. /* Should never get here as the extension was successfully
  17958. * decoded earlier. Something might be corrupted. */
  17959. WOLFSSL_MSG("DecodeObjectId() failed. Corruption?");
  17960. WOLFSSL_ERROR(ret);
  17961. }
  17962. ret = cert->unknownExtCallback(decOid, decOidSz, critical,
  17963. dataASN[CERTEXTASN_IDX_VAL].data.buffer.data,
  17964. dataASN[CERTEXTASN_IDX_VAL].length);
  17965. }
  17966. #endif
  17967. (void)isUnknownExt;
  17968. /* Move index on to next extension. */
  17969. idx += length;
  17970. }
  17971. /* Don't fail criticality until all other extensions have been checked.
  17972. */
  17973. if (ret == ASN_CRIT_EXT_E) {
  17974. criticalRet = ASN_CRIT_EXT_E;
  17975. ret = 0;
  17976. }
  17977. }
  17978. if (ret == 0) {
  17979. /* Use criticality return. */
  17980. ret = criticalRet;
  17981. }
  17982. FREE_ASNGETDATA(dataASN, cert->heap);
  17983. return ret;
  17984. #endif
  17985. }
  17986. #ifdef WOLFSSL_ASN_TEMPLATE
  17987. /* ASN template for an X509 certificate.
  17988. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  17989. */
  17990. static const ASNItem x509CertASN[] = {
  17991. /* Certificate ::= SEQUENCE */
  17992. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17993. /* tbsCertificate TBSCertificate */
  17994. /* TBSCertificate ::= SEQUENCE */
  17995. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  17996. /* version [0] EXPLICT Version DEFAULT v1 */
  17997. /* TBS_VER */ { 2, ASN_CONTEXT_SPECIFIC | ASN_X509_CERT_VERSION, 1, 1, 1 },
  17998. /* Version ::= INTEGER { v1(0), v2(1), v3(2) */
  17999. /* TBS_VER_INT */ { 3, ASN_INTEGER, 0, 0, 0 },
  18000. /* serialNumber CertificateSerialNumber */
  18001. /* CetificateSerialNumber ::= INTEGER */
  18002. /* TBS_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
  18003. /* signature AlgorithmIdentifier */
  18004. /* AlgorithmIdentifier ::= SEQUENCE */
  18005. /* TBS_ALGOID_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18006. /* Algorithm OBJECT IDENTIFIER */
  18007. /* TBS_ALGOID_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  18008. /* parameters ANY defined by algorithm OPTIONAL */
  18009. /* TBS_ALGOID_PARAMS_NULL */ { 3, ASN_TAG_NULL, 0, 0, 2 },
  18010. #ifdef WC_RSA_PSS
  18011. /* TBS_ALGOID_PARAMS */ { 3, ASN_SEQUENCE, 1, 0, 2 },
  18012. #endif
  18013. /* issuer Name */
  18014. /* TBS_ISSUER_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  18015. /* validity Validity */
  18016. /* Validity ::= SEQUENCE */
  18017. /* TBS_VALIDITY_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18018. /* notBefore Time */
  18019. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  18020. /* TBS_VALIDITY_NOTB_UTC */ { 3, ASN_UTC_TIME, 0, 0, 2 },
  18021. /* TBS_VALIDITY_NOTB_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 2 },
  18022. /* notAfter Time */
  18023. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  18024. /* TBS_VALIDITY_NOTA_UTC */ { 3, ASN_UTC_TIME, 0, 0, 3 },
  18025. /* TBS_VALIDITY_NOTA_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 3 },
  18026. /* subject Name */
  18027. /* TBS_SUBJECT_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  18028. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  18029. /* TBS_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18030. /* algorithm AlgorithmIdentifier */
  18031. /* AlgorithmIdentifier ::= SEQUENCE */
  18032. /* TBS_SPUBKEYINFO_ALGO_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  18033. /* Algorithm OBJECT IDENTIFIER */
  18034. /* TBS_SPUBKEYINFO_ALGO_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  18035. /* parameters ANY defined by algorithm OPTIONAL */
  18036. /* TBS_SPUBKEYINFO_ALGO_NULL */ { 4, ASN_TAG_NULL, 0, 0, 2 },
  18037. /* TBS_SPUBKEYINFO_ALGO_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 2 },
  18038. #ifdef WC_RSA_PSS
  18039. /* TBS_SPUBKEYINFO_ALGO_P_SEQ */ { 4, ASN_SEQUENCE, 1, 0, 2 },
  18040. #endif
  18041. /* subjectPublicKey BIT STRING */
  18042. /* TBS_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  18043. /* issuerUniqueID UniqueIdentfier OPTIONAL */
  18044. /* TBS_ISSUERUID */ { 2, ASN_CONTEXT_SPECIFIC | 1, 0, 0, 1 },
  18045. /* subjectUniqueID UniqueIdentfier OPTIONAL */
  18046. /* TBS_SUBJECTUID */ { 2, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 1 },
  18047. /* extensions Extensions OPTIONAL */
  18048. /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 1 },
  18049. /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
  18050. /* signatureAlgorithm AlgorithmIdentifier */
  18051. /* AlgorithmIdentifier ::= SEQUENCE */
  18052. /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18053. /* Algorithm OBJECT IDENTIFIER */
  18054. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  18055. /* parameters ANY defined by algorithm OPTIONAL */
  18056. /* SIGALGO_PARAMS_NULL */ { 2, ASN_TAG_NULL, 0, 0, 2 },
  18057. #ifdef WC_RSA_PSS
  18058. /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  18059. #endif
  18060. /* signature BIT STRING */
  18061. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  18062. };
  18063. enum {
  18064. X509CERTASN_IDX_SEQ = 0,
  18065. X509CERTASN_IDX_TBS_SEQ,
  18066. X509CERTASN_IDX_TBS_VER,
  18067. X509CERTASN_IDX_TBS_VER_INT,
  18068. X509CERTASN_IDX_TBS_SERIAL,
  18069. X509CERTASN_IDX_TBS_ALGOID_SEQ,
  18070. X509CERTASN_IDX_TBS_ALGOID_OID,
  18071. X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL,
  18072. #ifdef WC_RSA_PSS
  18073. X509CERTASN_IDX_TBS_ALGOID_PARAMS,
  18074. #endif
  18075. X509CERTASN_IDX_TBS_ISSUER_SEQ,
  18076. X509CERTASN_IDX_TBS_VALIDITY_SEQ,
  18077. X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC,
  18078. X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT,
  18079. X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC,
  18080. X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT,
  18081. X509CERTASN_IDX_TBS_SUBJECT_SEQ,
  18082. X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ,
  18083. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
  18084. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID,
  18085. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_NULL,
  18086. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID,
  18087. #ifdef WC_RSA_PSS
  18088. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_P_SEQ,
  18089. #endif
  18090. X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY,
  18091. X509CERTASN_IDX_TBS_ISSUERUID,
  18092. X509CERTASN_IDX_TBS_SUBJECTUID,
  18093. X509CERTASN_IDX_TBS_EXT,
  18094. X509CERTASN_IDX_TBS_EXT_SEQ,
  18095. X509CERTASN_IDX_SIGALGO_SEQ,
  18096. X509CERTASN_IDX_SIGALGO_OID,
  18097. X509CERTASN_IDX_SIGALGO_PARAMS_NULL,
  18098. #ifdef WC_RSA_PSS
  18099. X509CERTASN_IDX_SIGALGO_PARAMS,
  18100. #endif
  18101. X509CERTASN_IDX_SIGNATURE,
  18102. WOLF_ENUM_DUMMY_LAST_ELEMENT(X509CERTASN_IDX)
  18103. };
  18104. /* Number of items in ASN template for an X509 certificate. */
  18105. #define x509CertASN_Length (sizeof(x509CertASN) / sizeof(ASNItem))
  18106. /* Check the data data.
  18107. *
  18108. * @param [in] dataASN ASN template dynamic data item.
  18109. * @param [in] dataType BEFORE or AFTER date.
  18110. * @return 0 on success.
  18111. * @return ASN_TIME_E when BER tag is nor UTC or GENERALIZED time.
  18112. * @return ASN_DATE_SZ_E when time data is not supported.
  18113. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  18114. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  18115. */
  18116. static int CheckDate(ASNGetData *dataASN, int dateType)
  18117. {
  18118. int ret = 0;
  18119. /* Check BER tag is valid. */
  18120. if ((dataASN->tag != ASN_UTC_TIME) &&
  18121. (dataASN->tag != ASN_GENERALIZED_TIME)) {
  18122. ret = ASN_TIME_E;
  18123. }
  18124. /* Check date length is valid. */
  18125. if ((ret == 0) && ((dataASN->length > MAX_DATE_SIZE) ||
  18126. (dataASN->length < MIN_DATE_SIZE))) {
  18127. ret = ASN_DATE_SZ_E;
  18128. }
  18129. #ifndef NO_ASN_TIME_CHECK
  18130. /* Check date is a valid string and BEFORE or AFTER now. */
  18131. if ((ret == 0) &&
  18132. (!XVALIDATE_DATE(dataASN->data.ref.data, dataASN->tag, dateType))) {
  18133. if (dateType == BEFORE) {
  18134. ret = ASN_BEFORE_DATE_E;
  18135. }
  18136. else {
  18137. ret = ASN_AFTER_DATE_E;
  18138. }
  18139. }
  18140. #endif
  18141. (void)dateType;
  18142. return ret;
  18143. }
  18144. /* Decode a certificate. Internal/non-public API.
  18145. *
  18146. * @param [in] cert Certificate object.
  18147. * @param [in] verify Whether to verify dates before and after now.
  18148. * @param [out] criticalExt Critical extension return code.
  18149. * @param [out] badDateRet Bad date return code.
  18150. * @param [in] stopAtPubKey Stop parsing before subkectPublicKeyInfo.
  18151. * @param [in] stopAfterPubKey Stop parsing after subkectPublicKeyInfo.
  18152. * @return 0 on success.
  18153. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  18154. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  18155. * @return ASN_DATE_SZ_E when time data is not supported.
  18156. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  18157. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  18158. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18159. * is invalid.
  18160. * @return BUFFER_E when data in buffer is too small.
  18161. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  18162. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  18163. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  18164. * non-zero length.
  18165. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  18166. */
  18167. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  18168. int* badDateRet, int stopAtPubKey,
  18169. int stopAfterPubKey)
  18170. {
  18171. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  18172. int ret = 0;
  18173. int badDate = 0;
  18174. byte version;
  18175. word32 idx;
  18176. word32 serialSz;
  18177. const unsigned char* issuer = NULL;
  18178. word32 issuerSz = 0;
  18179. const unsigned char* subject = NULL;
  18180. word32 subjectSz = 0;
  18181. word32 pubKeyOffset = 0;
  18182. word32 pubKeyEnd = 0;
  18183. int done = 0;
  18184. CALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  18185. if (ret == 0) {
  18186. version = 0;
  18187. serialSz = EXTERNAL_SERIAL_SIZE;
  18188. /* Get the version and put the serial number into the buffer. */
  18189. GetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT], &version);
  18190. GetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
  18191. &serialSz);
  18192. /* Check OID types for signature, algorithm, ECC curve and sigAlg. */
  18193. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
  18194. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
  18195. oidKeyType);
  18196. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
  18197. oidCurveType);
  18198. GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
  18199. /* Parse the X509 certificate. */
  18200. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1,
  18201. cert->source, &cert->srcIdx, cert->maxIdx);
  18202. #ifdef WOLFSSL_CLANG_TIDY
  18203. /* work around clang-tidy false positive re cert->source. */
  18204. if ((ret == 0) && (cert->source == NULL)) {
  18205. ret = ASN_PARSE_E;
  18206. }
  18207. #endif
  18208. }
  18209. /* Check version is valid/supported - can't be negative. */
  18210. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  18211. WOLFSSL_MSG("Unexpected certificate version");
  18212. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18213. ret = ASN_PARSE_E;
  18214. }
  18215. if (ret == 0) {
  18216. int i;
  18217. pubKeyOffset = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset;
  18218. /* Set fields extracted from data. */
  18219. cert->version = version;
  18220. cert->serialSz = (int)serialSz;
  18221. cert->signatureOID = dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum;
  18222. cert->keyOID = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID].data.oid.sum;
  18223. cert->certBegin = dataASN[X509CERTASN_IDX_TBS_SEQ].offset;
  18224. /* No bad date error - don't always care. */
  18225. badDate = 0;
  18226. /* Find the item with the BEFORE date and check it. */
  18227. i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].tag != 0)
  18228. ? X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC
  18229. : X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT;
  18230. if ((CheckDate(&dataASN[i], BEFORE) < 0) && verify) {
  18231. badDate = ASN_BEFORE_DATE_E;
  18232. }
  18233. /* Store reference to BEFOREdate. */
  18234. cert->beforeDate = GetASNItem_Addr(dataASN[i], cert->source);
  18235. cert->beforeDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);
  18236. /* Find the item with the AFTER date and check it. */
  18237. i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].tag != 0)
  18238. ? X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC
  18239. : X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT;
  18240. if ((CheckDate(&dataASN[i], AFTER) < 0) && verify) {
  18241. badDate = ASN_AFTER_DATE_E;
  18242. }
  18243. /* Store reference to AFTER date. */
  18244. cert->afterDate = GetASNItem_Addr(dataASN[i], cert->source);
  18245. cert->afterDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);
  18246. /* Get the issuer name. */
  18247. issuer = cert->source + dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
  18248. issuerSz = dataASN[X509CERTASN_IDX_TBS_VALIDITY_SEQ].offset -
  18249. dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
  18250. }
  18251. if (ret == 0) {
  18252. /* Get the subject name. */
  18253. subject = cert->source +
  18254. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
  18255. subjectSz = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset -
  18256. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
  18257. }
  18258. if ((ret == 0) && (stopAtPubKey)) {
  18259. /* Return any bad date error through badDateRet and return offset of
  18260. * subjectPublicKeyInfo.
  18261. */
  18262. if (badDateRet != NULL) {
  18263. *badDateRet = badDate;
  18264. }
  18265. done = 1;
  18266. }
  18267. if ((ret == 0) && (!done)) {
  18268. /* Store the signature information. */
  18269. cert->sigIndex = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
  18270. GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE],
  18271. &cert->signature, &cert->sigLength);
  18272. /* Make sure 'signature' and 'signatureAlgorithm' are the same. */
  18273. if (dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum
  18274. != cert->signatureOID) {
  18275. WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
  18276. ret = ASN_SIG_OID_E;
  18277. }
  18278. /* Parameters not allowed after ECDSA or EdDSA algorithm OID. */
  18279. else if (IsSigAlgoECC(cert->signatureOID)) {
  18280. if ((dataASN[X509CERTASN_IDX_SIGALGO_PARAMS_NULL].tag != 0)
  18281. #ifdef WC_RSA_PSS
  18282. || (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0)
  18283. #endif
  18284. ) {
  18285. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18286. ret = ASN_PARSE_E;
  18287. }
  18288. }
  18289. #ifdef WC_RSA_PSS
  18290. /* Check parameters starting with a SEQUENCE. */
  18291. else if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
  18292. word32 oid = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
  18293. word32 sigAlgParamsSz = 0;
  18294. /* Parameters only with RSA PSS. */
  18295. if (oid != CTC_RSASSAPSS) {
  18296. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18297. ret = ASN_PARSE_E;
  18298. }
  18299. if (ret == 0) {
  18300. const byte* tbsParams;
  18301. word32 tbsParamsSz;
  18302. const byte* sigAlgParams;
  18303. /* Check RSA PSS parameters are the same. */
  18304. tbsParams =
  18305. GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  18306. cert->source);
  18307. tbsParamsSz =
  18308. GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  18309. cert->source);
  18310. sigAlgParams =
  18311. GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  18312. cert->source);
  18313. sigAlgParamsSz =
  18314. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  18315. cert->source);
  18316. if ((tbsParamsSz != sigAlgParamsSz) ||
  18317. (XMEMCMP(tbsParams, sigAlgParams, tbsParamsSz) != 0)) {
  18318. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18319. ret = ASN_PARSE_E;
  18320. }
  18321. }
  18322. if (ret == 0) {
  18323. /* Store parameters for use in signature verification. */
  18324. cert->sigParamsIndex =
  18325. dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].offset;
  18326. cert->sigParamsLength = sigAlgParamsSz;
  18327. }
  18328. }
  18329. #endif
  18330. }
  18331. if ((ret == 0) && (!done)) {
  18332. pubKeyEnd = dataASN[X509CERTASN_IDX_TBS_ISSUERUID].offset;
  18333. if (stopAfterPubKey) {
  18334. /* Return any bad date error through badDateRed and return offset
  18335. * after subjectPublicKeyInfo.
  18336. */
  18337. if (badDateRet != NULL) {
  18338. *badDateRet = badDate;
  18339. }
  18340. done = 1;
  18341. }
  18342. }
  18343. if ((ret == 0) && (!done) &&
  18344. (dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data != NULL)) {
  18345. #ifndef ALLOW_V1_EXTENSIONS
  18346. /* Certificate extensions were only defined in version 2. */
  18347. if (cert->version < 2) {
  18348. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  18349. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  18350. ret = ASN_VERSION_E;
  18351. }
  18352. #endif
  18353. if (ret == 0) {
  18354. /* Save references to extension data. */
  18355. cert->extensions = GetASNItem_Addr(
  18356. dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
  18357. cert->extensionsSz = (int)GetASNItem_Length(
  18358. dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
  18359. cert->extensionsIdx = dataASN[X509CERTASN_IDX_TBS_EXT].offset;
  18360. /* Advance past extensions. */
  18361. cert->srcIdx = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
  18362. }
  18363. }
  18364. /* Dispose of memory before allocating for extension decoding. */
  18365. FREE_ASNGETDATA(dataASN, cert->heap);
  18366. if ((ret == 0) && (issuer != NULL)) {
  18367. idx = 0;
  18368. /* Put issuer into cert and calculate hash. */
  18369. ret = GetCertName(cert, cert->issuer, cert->issuerHash, ISSUER, issuer,
  18370. &idx, issuerSz);
  18371. }
  18372. if ((ret == 0) && (subject != NULL)) {
  18373. idx = 0;
  18374. /* Put subject into cert and calculate hash. */
  18375. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  18376. subject, &idx, subjectSz);
  18377. }
  18378. if (ret == 0) {
  18379. /* Determine if self signed by comparing issuer and subject hashes. */
  18380. #ifdef WOLFSSL_CERT_REQ
  18381. if (cert->isCSR) {
  18382. cert->selfSigned = 1;
  18383. }
  18384. else
  18385. #endif
  18386. {
  18387. cert->selfSigned = (XMEMCMP(cert->issuerHash, cert->subjectHash,
  18388. KEYID_SIZE) == 0);
  18389. }
  18390. if (stopAtPubKey) {
  18391. ret = (int)pubKeyOffset;
  18392. }
  18393. }
  18394. if ((ret == 0) && (!stopAtPubKey)) {
  18395. /* Parse the public key. */
  18396. idx = pubKeyOffset;
  18397. ret = GetCertKey(cert, cert->source, &idx, pubKeyEnd);
  18398. }
  18399. if ((ret == 0) && (!stopAtPubKey) && (!stopAfterPubKey) &&
  18400. (cert->extensions != NULL)) {
  18401. /* Decode the extension data starting at [3]. */
  18402. ret = DecodeCertExtensions(cert);
  18403. if (criticalExt != NULL) {
  18404. if (ret == ASN_CRIT_EXT_E) {
  18405. /* Return critical extension not recognized. */
  18406. *criticalExt = ret;
  18407. ret = 0;
  18408. }
  18409. else {
  18410. /* No critical extension error. */
  18411. *criticalExt = 0;
  18412. }
  18413. }
  18414. }
  18415. if ((ret == 0) && (!done) && (badDate != 0)) {
  18416. /* Parsed whole certificate fine but return any date errors. */
  18417. ret = badDate;
  18418. }
  18419. return ret;
  18420. }
  18421. /* Decode BER/DER data into certificate object.
  18422. *
  18423. * BER/DER data information held in source, srcIdx and maxIdx fields of
  18424. * certificate object.
  18425. *
  18426. * @param [in] cert Decoded certificate object.
  18427. * @param [in] verify Whether to find CA and verify certificate.
  18428. * @param [in] criticalExt Any error for critical extensions not recognized.
  18429. * @return 0 on success.
  18430. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  18431. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  18432. * @return ASN_DATE_SZ_E when time data is not supported.
  18433. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  18434. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  18435. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18436. * is invalid.
  18437. * @return BUFFER_E when data in buffer is too small.
  18438. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  18439. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  18440. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  18441. * non-zero length.
  18442. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  18443. */
  18444. int DecodeCert(DecodedCert* cert, int verify, int* criticalExt)
  18445. {
  18446. return DecodeCertInternal(cert, verify, criticalExt, NULL, 0, 0);
  18447. }
  18448. #ifdef WOLFSSL_CERT_REQ
  18449. /* ASN.1 template for certificate request Attribute.
  18450. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  18451. */
  18452. static const ASNItem reqAttrASN[] = {
  18453. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18454. /* type */
  18455. /* TYPE */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  18456. /* values */
  18457. /* VALS */ { 1, ASN_SET, 1, 0, 0 },
  18458. };
  18459. enum {
  18460. REQATTRASN_IDX_SEQ = 0,
  18461. REQATTRASN_IDX_TYPE,
  18462. REQATTRASN_IDX_VALS
  18463. };
  18464. /* Number of items in ASN.1 template for certificate request Attribute. */
  18465. #define reqAttrASN_Length (sizeof(reqAttrASN) / sizeof(ASNItem))
  18466. /* ASN.1 template for a string choice. */
  18467. static const ASNItem strAttrASN[] = {
  18468. { 0, 0, 0, 0, 0 },
  18469. };
  18470. enum {
  18471. STRATTRASN_IDX_STR = 0
  18472. };
  18473. /* Number of items in ASN.1 template for a string choice. */
  18474. #define strAttrASN_Length (sizeof(strAttrASN) / sizeof(ASNItem))
  18475. /* ASN.1 choices for types for a string in an attribute. */
  18476. static const byte strAttrChoice[] = {
  18477. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, 0
  18478. };
  18479. /* Decode a certificate request attribute's value.
  18480. *
  18481. * @param [in] cert Certificate request object.
  18482. * @param [out] criticalExt Critical extension return code.
  18483. * @param [in] oid OID decribing which attribute was found.
  18484. * @param [in] aIdx Index into certificate source to start parsing.
  18485. * @param [in] input Attribute value data.
  18486. * @param [in] maxIdx Maximum index to parse to.
  18487. * @return 0 on success.
  18488. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18489. * is invalid.
  18490. */
  18491. static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt,
  18492. word32 oid, word32 aIdx, const byte* input, word32 maxIdx)
  18493. {
  18494. int ret = 0;
  18495. word32 idx = 0;
  18496. ASNGetData strDataASN[strAttrASN_Length];
  18497. switch (oid) {
  18498. case PKCS9_CONTENT_TYPE_OID:
  18499. /* Clear dynamic data and specify choices acceptable. */
  18500. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  18501. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  18502. /* Parse a string. */
  18503. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  18504. 1, input, &idx, maxIdx);
  18505. if (ret == 0) {
  18506. /* Store references to password data. */
  18507. cert->contentType =
  18508. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  18509. cert->contentTypeLen =
  18510. (int)strDataASN[STRATTRASN_IDX_STR].data.ref.length;
  18511. }
  18512. break;
  18513. /* A password by which the entity may request certificate revocation.
  18514. * PKCS#9: RFC 2985, 5.4.1 - Challenge password
  18515. */
  18516. case CHALLENGE_PASSWORD_OID:
  18517. /* Clear dynamic data and specify choices acceptable. */
  18518. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  18519. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  18520. /* Parse a string. */
  18521. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  18522. 1, input, &idx, maxIdx);
  18523. if (ret == 0) {
  18524. /* Store references to password data. */
  18525. cert->cPwd =
  18526. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  18527. cert->cPwdLen = (int)strDataASN[STRATTRASN_IDX_STR].
  18528. data.ref.length;
  18529. }
  18530. break;
  18531. /* Requested serial number to issue with.
  18532. * PKCS#9: RFC 2985, 5.2.10 - Serial Number
  18533. * (References: ISO/IEC 9594-6:1997)
  18534. */
  18535. case SERIAL_NUMBER_OID:
  18536. /* Clear dynamic data and specify choices acceptable. */
  18537. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  18538. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  18539. /* Parse a string. */
  18540. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  18541. 1, input, &idx, maxIdx);
  18542. if (ret == 0) {
  18543. /* Store references to serial number. */
  18544. cert->sNum =
  18545. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  18546. cert->sNumLen = (int)strDataASN[STRATTRASN_IDX_STR].
  18547. data.ref.length;
  18548. /* Store serial number if small enough. */
  18549. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  18550. XMEMCPY(cert->serial, cert->sNum, (size_t)cert->sNumLen);
  18551. cert->serialSz = cert->sNumLen;
  18552. }
  18553. }
  18554. break;
  18555. /* Certificate extensions to be included in generated certificate.
  18556. * PKCS#9: RFC 2985, 5.4.2 - Extension request
  18557. */
  18558. case EXTENSION_REQUEST_OID:
  18559. /* Store references to all extensions. */
  18560. cert->extensions = input;
  18561. cert->extensionsSz = (int)maxIdx;
  18562. cert->extensionsIdx = aIdx;
  18563. /* Decode and validate extensions. */
  18564. ret = DecodeCertExtensions(cert);
  18565. if (ret == ASN_CRIT_EXT_E) {
  18566. /* Return critical extension not recognized. */
  18567. *criticalExt = ret;
  18568. ret = 0;
  18569. }
  18570. else {
  18571. /* No critical extension error. */
  18572. *criticalExt = 0;
  18573. }
  18574. break;
  18575. default:
  18576. ret = ASN_PARSE_E;
  18577. break;
  18578. }
  18579. return ret;
  18580. }
  18581. /* Decode attributes of a BER encoded certificate request.
  18582. *
  18583. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  18584. *
  18585. * Outer sequence has been removed.
  18586. *
  18587. * @param [in] cert Certificate request object.
  18588. * @param [out] criticalExt Critical extension return code.
  18589. * @param [in] idx Index into certificate source to start parsing.
  18590. * @param [in] maxIdx Maximum index to parse to.
  18591. * @return 0 on success.
  18592. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  18593. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18594. * is invalid.
  18595. * @return BUFFER_E when data in buffer is too small.
  18596. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  18597. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  18598. * non-zero length.
  18599. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  18600. */
  18601. static int DecodeCertReqAttributes(DecodedCert* cert, int* criticalExt,
  18602. word32 idx, word32 maxIdx)
  18603. {
  18604. DECL_ASNGETDATA(dataASN, reqAttrASN_Length);
  18605. int ret = 0;
  18606. WOLFSSL_ENTER("DecodeCertReqAttributes");
  18607. ALLOC_ASNGETDATA(dataASN, reqAttrASN_Length, ret, cert->heap);
  18608. /* Parse each attribute until all data used up. */
  18609. while ((ret == 0) && (idx < maxIdx)) {
  18610. /* Clear dynamic data. */
  18611. XMEMSET(dataASN, 0, sizeof(ASNGetData) * reqAttrASN_Length);
  18612. GetASN_OID(&dataASN[REQATTRASN_IDX_TYPE], oidIgnoreType);
  18613. /* Parse an attribute. */
  18614. ret = GetASN_Items(reqAttrASN, dataASN, reqAttrASN_Length, 0,
  18615. cert->source, &idx, maxIdx);
  18616. /* idx is now at end of attribute data. */
  18617. if (ret == 0) {
  18618. ret = DecodeCertReqAttrValue(cert, criticalExt,
  18619. dataASN[REQATTRASN_IDX_TYPE].data.oid.sum,
  18620. GetASNItem_DataIdx(dataASN[REQATTRASN_IDX_VALS], cert->source),
  18621. dataASN[REQATTRASN_IDX_VALS].data.ref.data,
  18622. dataASN[REQATTRASN_IDX_VALS].data.ref.length);
  18623. }
  18624. }
  18625. FREE_ASNGETDATA(dataASN, cert->heap);
  18626. return ret;
  18627. }
  18628. /* ASN.1 template for a certificate request.
  18629. * PKCS#10: RFC 2986, 4.1 - CertificationRequestInfo
  18630. * PKCS#10: RFC 2986, 4.2 - CertificationRequest
  18631. */
  18632. static const ASNItem certReqASN[] = {
  18633. /* CertificationRequest */
  18634. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18635. /* CertificationRequestInfo */
  18636. /* INFO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18637. /* version INTEGER { v1(0), v2(1), v3(2) */
  18638. /* INFO_VER */ { 2, ASN_INTEGER, 0, 0, 0 },
  18639. /* subject Name */
  18640. /* INFO_SUBJ_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  18641. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  18642. /* INFO_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18643. /* algorithm AlgorithmIdentifier */
  18644. /* INFO_SPUBKEYINFO_ALGOID_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  18645. /* Algorithm OBJECT IDENTIFIER */
  18646. /* INFO_SPUBKEYINFO_ALGOID_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  18647. /* parameters ANY defined by algorithm OPTIONAL */
  18648. /* INFO_SPUBKEYINFO_ALGOID_NULL */ { 4, ASN_TAG_NULL, 0, 0, 1 },
  18649. /* INFO_SPUBKEYINFO_ALGOID_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 1 },
  18650. /* INFO_SPUBKEYINFO_ALGOID_PARAMS */ { 4, ASN_SEQUENCE, 1, 0, 1 },
  18651. /* subjectPublicKey BIT STRING */
  18652. /* INFO_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  18653. /* attributes [0] Attributes */
  18654. /* INFO_ATTRS */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  18655. /* signatureAlgorithm AlgorithmIdentifier */
  18656. /* INFO_SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18657. /* Algorithm OBJECT IDENTIFIER */
  18658. /* INFO_SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  18659. /* parameters ANY defined by algorithm OPTIONAL */
  18660. /* INFO_SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  18661. /* signature BIT STRING */
  18662. /* INFO_SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  18663. };
  18664. enum {
  18665. CERTREQASN_IDX_SEQ = 0,
  18666. CERTREQASN_IDX_INFO_SEQ,
  18667. CERTREQASN_IDX_INFO_VER,
  18668. CERTREQASN_IDX_INFO_SUBJ_SEQ,
  18669. CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ,
  18670. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_SEQ,
  18671. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID,
  18672. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_NULL,
  18673. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID,
  18674. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_PARAMS,
  18675. CERTREQASN_IDX_INFO_SPUBKEYINFO_PUBKEY,
  18676. CERTREQASN_IDX_INFO_ATTRS,
  18677. CERTREQASN_IDX_INFO_SIGALGO_SEQ,
  18678. CERTREQASN_IDX_INFO_SIGALGO_OID,
  18679. CERTREQASN_IDX_INFO_SIGALGO_NULL,
  18680. CERTREQASN_IDX_INFO_SIGNATURE
  18681. };
  18682. /* Number of items in ASN.1 template for a certificate request. */
  18683. #define certReqASN_Length (sizeof(certReqASN) / sizeof(ASNItem))
  18684. /* Parse BER encoded certificate request.
  18685. *
  18686. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  18687. *
  18688. * @param [in] cert Certificate request object.
  18689. * @param [out] criticalExt Critical extension return code.
  18690. * @return 0 on success.
  18691. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  18692. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18693. * is invalid.
  18694. * @return BUFFER_E when data in buffer is too small.
  18695. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  18696. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  18697. * non-zero length.
  18698. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  18699. * @return MEMORY_E on dynamic memory allocation failure.
  18700. */
  18701. static int DecodeCertReq(DecodedCert* cert, int* criticalExt)
  18702. {
  18703. DECL_ASNGETDATA(dataASN, certReqASN_Length);
  18704. int ret = 0;
  18705. byte version;
  18706. word32 idx;
  18707. CALLOC_ASNGETDATA(dataASN, certReqASN_Length, ret, cert->heap);
  18708. if (ret == 0) {
  18709. /* Default version is 0. */
  18710. version = 0;
  18711. /* Set version var and OID types to expect. */
  18712. GetASN_Int8Bit(&dataASN[CERTREQASN_IDX_INFO_VER], &version);
  18713. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
  18714. oidKeyType);
  18715. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
  18716. oidCurveType);
  18717. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
  18718. /* Parse a certificate request. */
  18719. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1,
  18720. cert->source, &cert->srcIdx, cert->maxIdx);
  18721. }
  18722. /* Check version is valid/supported - can't be negative. */
  18723. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  18724. WOLFSSL_MSG("Unexpected certificate request version");
  18725. ret = ASN_PARSE_E;
  18726. }
  18727. if (ret == 0) {
  18728. /* Set fields of certificate request. */
  18729. cert->version = version;
  18730. cert->signatureOID =
  18731. dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
  18732. cert->keyOID =
  18733. dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID].data.oid.sum;
  18734. cert->certBegin = dataASN[CERTREQASN_IDX_INFO_SEQ].offset;
  18735. /* Parse the subject name. */
  18736. idx = dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ].offset;
  18737. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  18738. cert->source, &idx,
  18739. dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset);
  18740. }
  18741. if (ret == 0) {
  18742. /* Parse the certificate request Attributes. */
  18743. ret = DecodeCertReqAttributes(cert, criticalExt,
  18744. GetASNItem_DataIdx(dataASN[CERTREQASN_IDX_INFO_ATTRS],
  18745. cert->source),
  18746. dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset);
  18747. }
  18748. if (ret == 0) {
  18749. /* Parse the certificate request's key. */
  18750. idx = dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset;
  18751. ret = GetCertKey(cert, cert->source, &idx,
  18752. dataASN[CERTREQASN_IDX_INFO_ATTRS].offset);
  18753. }
  18754. if (ret == 0) {
  18755. /* Store references to signature. */
  18756. cert->sigIndex = dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset;
  18757. GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE],
  18758. &cert->signature, &cert->sigLength);
  18759. }
  18760. FREE_ASNGETDATA(dataASN, cert->heap);
  18761. return ret;
  18762. }
  18763. #endif /* WOLFSSL_CERT_REQ */
  18764. #endif
  18765. int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  18766. {
  18767. int ret;
  18768. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  18769. defined(WOLFSSL_DYN_CERT)
  18770. char* ptr;
  18771. #endif
  18772. ret = ParseCertRelative(cert, type, verify, cm);
  18773. if (ret < 0)
  18774. return ret;
  18775. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  18776. defined(WOLFSSL_DYN_CERT)
  18777. /* cert->subjectCN not stored as copy of WOLFSSL_NO_MALLOC defind */
  18778. if (cert->subjectCNLen > 0) {
  18779. ptr = (char*)XMALLOC((size_t)cert->subjectCNLen + 1, cert->heap,
  18780. DYNAMIC_TYPE_SUBJECT_CN);
  18781. if (ptr == NULL)
  18782. return MEMORY_E;
  18783. XMEMCPY(ptr, cert->subjectCN, (size_t)cert->subjectCNLen);
  18784. ptr[cert->subjectCNLen] = '\0';
  18785. cert->subjectCN = ptr;
  18786. cert->subjectCNStored = 1;
  18787. }
  18788. #endif
  18789. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  18790. defined(WOLFSSL_DYN_CERT)
  18791. /* cert->publicKey not stored as copy if WOLFSSL_NO_MALLOC defined */
  18792. if ((cert->keyOID == RSAk
  18793. #ifdef WC_RSA_PSS
  18794. || cert->keyOID == RSAPSSk
  18795. #endif
  18796. ) && cert->publicKey != NULL && cert->pubKeySize > 0) {
  18797. ptr = (char*)XMALLOC(cert->pubKeySize, cert->heap,
  18798. DYNAMIC_TYPE_PUBLIC_KEY);
  18799. if (ptr == NULL)
  18800. return MEMORY_E;
  18801. XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
  18802. cert->publicKey = (byte *)ptr;
  18803. cert->pubKeyStored = 1;
  18804. }
  18805. #endif
  18806. return ret;
  18807. }
  18808. int wc_ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  18809. {
  18810. return ParseCert(cert, type, verify, cm);
  18811. }
  18812. #if !defined(OPENSSL_EXTRA) && !defined(OPENSSL_EXTRA_X509_SMALL) && \
  18813. !defined(GetCA)
  18814. /* from SSL proper, for locking can't do find here anymore.
  18815. * brought in from internal.h if built with compat layer.
  18816. * if defined(GetCA), it's a predefined macro and these prototypes
  18817. * would conflict.
  18818. */
  18819. #ifdef __cplusplus
  18820. extern "C" {
  18821. #endif
  18822. Signer* GetCA(void* signers, byte* hash);
  18823. #ifndef NO_SKID
  18824. Signer* GetCAByName(void* signers, byte* hash);
  18825. #endif
  18826. #ifdef __cplusplus
  18827. }
  18828. #endif
  18829. #endif /* !OPENSSL_EXTRA && !OPENSSL_EXTRA_X509_SMALL && !GetCA */
  18830. #if defined(WOLFCRYPT_ONLY)
  18831. /* dummy functions, not using wolfSSL so don't need actual ones */
  18832. Signer* GetCA(void* signers, byte* hash)
  18833. {
  18834. (void)hash;
  18835. return (Signer*)signers;
  18836. }
  18837. #ifndef NO_SKID
  18838. Signer* GetCAByName(void* signers, byte* hash)
  18839. {
  18840. (void)hash;
  18841. return (Signer*)signers;
  18842. }
  18843. #endif /* NO_SKID */
  18844. #endif /* WOLFCRYPT_ONLY */
  18845. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  18846. static Signer* GetCABySubjectAndPubKey(DecodedCert* cert, void* cm)
  18847. {
  18848. Signer* ca = NULL;
  18849. if (cert->extSubjKeyIdSet)
  18850. ca = GetCA(cm, cert->extSubjKeyId);
  18851. if (ca == NULL)
  18852. ca = GetCAByName(cm, cert->subjectHash);
  18853. if (ca) {
  18854. if ((ca->pubKeySize == cert->pubKeySize) &&
  18855. (XMEMCMP(ca->publicKey, cert->publicKey, ca->pubKeySize) == 0)) {
  18856. return ca;
  18857. }
  18858. }
  18859. return NULL;
  18860. }
  18861. #endif
  18862. #if defined(WOLFSSL_SMALL_CERT_VERIFY) || defined(OPENSSL_EXTRA)
  18863. #ifdef WOLFSSL_ASN_TEMPLATE
  18864. /* Get the Hash of the Authority Key Identifier from the list of extensions.
  18865. *
  18866. * @param [in] input Input data.
  18867. * @param [in] maxIdx Maximum index for data.
  18868. * @param [out] hash Hash of AKI.
  18869. * @param [out] set Whether the hash buffer was set.
  18870. * @param [in] heap Dynamic memory allocation hint.
  18871. * @return 0 on success.
  18872. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18873. * is invalid.
  18874. * @return MEMORY_E on dynamic memory allocation failure.
  18875. */
  18876. static int GetAKIHash(const byte* input, word32 maxIdx, byte* hash, int* set,
  18877. void* heap)
  18878. {
  18879. /* AKI and Certificate Extenion ASN.1 templates are the same length. */
  18880. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  18881. int ret = 0;
  18882. word32 idx = 0;
  18883. word32 extEndIdx;
  18884. byte* extData;
  18885. word32 extDataSz;
  18886. byte critical;
  18887. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, heap);
  18888. (void)heap;
  18889. extEndIdx = idx + maxIdx;
  18890. /* Step through each extension looking for AKI. */
  18891. while ((ret == 0) && (idx < extEndIdx)) {
  18892. /* Clear dynamic data and check for certificate extension type OIDs. */
  18893. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  18894. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  18895. /* Set criticality variable. */
  18896. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  18897. /* Parse an extension. */
  18898. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  18899. &idx, extEndIdx);
  18900. if (ret == 0) {
  18901. /* Get reference to extension data and move index on past this
  18902. * extension. */
  18903. GetASN_GetRef(&dataASN[CERTEXTASN_IDX_VAL], &extData, &extDataSz);
  18904. idx += extDataSz;
  18905. /* Check whether we have the AKI extension. */
  18906. if (dataASN[CERTEXTASN_IDX_OID].data.oid.sum == AUTH_KEY_OID) {
  18907. /* Clear dynamic data. */
  18908. XMEMSET(dataASN, 0, sizeof(*dataASN) * authKeyIdASN_Length);
  18909. /* Start parsing extension data from the start. */
  18910. idx = 0;
  18911. /* Parse AKI extension data. */
  18912. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length,
  18913. 1, extData, &idx, extDataSz);
  18914. if ((ret == 0) &&
  18915. (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data
  18916. != NULL)) {
  18917. /* We parsed successfully and have data. */
  18918. *set = 1;
  18919. /* Get the hash or hash of the hash if wrong size. */
  18920. ret = GetHashId(
  18921. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  18922. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  18923. hash);
  18924. }
  18925. break;
  18926. }
  18927. }
  18928. }
  18929. FREE_ASNGETDATA(dataASN, heap);
  18930. return ret;
  18931. }
  18932. #endif
  18933. /* Only quick step through the certificate to find fields that are then used
  18934. * in certificate signature verification.
  18935. * Must use the signature OID from the signed part of the certificate.
  18936. * Works also on certificate signing requests.
  18937. *
  18938. * This is only for minimizing dynamic memory usage during TLS certificate
  18939. * chain processing.
  18940. * Doesn't support:
  18941. * OCSP Only: alt lookup using subject and pub key w/o sig check
  18942. */
  18943. static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap,
  18944. void* cm, const byte* pubKey, word32 pubKeySz, int pubKeyOID, int req)
  18945. {
  18946. #ifndef WOLFSSL_ASN_TEMPLATE
  18947. #ifndef WOLFSSL_SMALL_STACK
  18948. SignatureCtx sigCtx[1];
  18949. #else
  18950. SignatureCtx* sigCtx;
  18951. #endif
  18952. byte hash[KEYID_SIZE];
  18953. Signer* ca = NULL;
  18954. word32 idx = 0;
  18955. int len;
  18956. word32 tbsCertIdx = 0;
  18957. word32 sigIndex = 0;
  18958. word32 signatureOID = 0;
  18959. word32 oid = 0;
  18960. word32 issuerIdx = 0;
  18961. word32 issuerSz = 0;
  18962. #ifndef NO_SKID
  18963. int extLen = 0;
  18964. word32 extIdx = 0;
  18965. word32 extEndIdx = 0;
  18966. int extAuthKeyIdSet = 0;
  18967. #endif
  18968. int ret = 0;
  18969. word32 localIdx;
  18970. byte tag;
  18971. const byte* sigParams = NULL;
  18972. word32 sigParamsSz = 0;
  18973. if (cert == NULL) {
  18974. return BAD_FUNC_ARG;
  18975. }
  18976. #ifdef WOLFSSL_SMALL_STACK
  18977. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, DYNAMIC_TYPE_SIGNATURE);
  18978. if (sigCtx == NULL)
  18979. return MEMORY_E;
  18980. #endif
  18981. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  18982. /* Certificate SEQUENCE */
  18983. if (GetSequence(cert, &idx, &len, certSz) < 0)
  18984. ret = ASN_PARSE_E;
  18985. if (ret == 0) {
  18986. tbsCertIdx = idx;
  18987. /* TBSCertificate SEQUENCE */
  18988. if (GetSequence(cert, &idx, &len, certSz) < 0)
  18989. ret = ASN_PARSE_E;
  18990. }
  18991. if (ret == 0) {
  18992. sigIndex = len + idx;
  18993. if ((idx + 1) > certSz)
  18994. ret = BUFFER_E;
  18995. }
  18996. if (ret == 0) {
  18997. /* version - optional */
  18998. localIdx = idx;
  18999. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19000. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  19001. idx++;
  19002. if (GetLength(cert, &idx, &len, certSz) < 0)
  19003. ret = ASN_PARSE_E;
  19004. idx += len;
  19005. }
  19006. }
  19007. }
  19008. if (ret == 0) {
  19009. /* serialNumber */
  19010. if (GetASNHeader(cert, ASN_INTEGER, &idx, &len, certSz) < 0)
  19011. ret = ASN_PARSE_E;
  19012. }
  19013. if (ret == 0) {
  19014. idx += len;
  19015. /* signature */
  19016. if (!req) {
  19017. if (GetAlgoId(cert, &idx, &signatureOID, oidSigType, certSz) < 0)
  19018. ret = ASN_PARSE_E;
  19019. #ifdef WC_RSA_PSS
  19020. else if (signatureOID == CTC_RSASSAPSS) {
  19021. int start = idx;
  19022. sigParams = cert + idx;
  19023. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19024. ret = ASN_PARSE_E;
  19025. if (ret == 0) {
  19026. idx += len;
  19027. sigParamsSz = idx - start;
  19028. }
  19029. }
  19030. #endif
  19031. }
  19032. }
  19033. if (ret == 0) {
  19034. issuerIdx = idx;
  19035. /* issuer for cert or subject for csr */
  19036. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19037. ret = ASN_PARSE_E;
  19038. }
  19039. if (ret == 0) {
  19040. issuerSz = len + idx - issuerIdx;
  19041. }
  19042. #ifndef NO_SKID
  19043. if (!req && ret == 0) {
  19044. idx += len;
  19045. /* validity */
  19046. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19047. ret = ASN_PARSE_E;
  19048. }
  19049. if (!req && ret == 0) {
  19050. idx += len;
  19051. /* subject */
  19052. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19053. ret = ASN_PARSE_E;
  19054. }
  19055. if (ret == 0) {
  19056. idx += len;
  19057. /* subjectPublicKeyInfo */
  19058. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19059. ret = ASN_PARSE_E;
  19060. }
  19061. if (req && ret == 0) {
  19062. idx += len;
  19063. /* attributes */
  19064. if (GetASNHeader_ex(cert,
  19065. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &idx,
  19066. &len, certSz, 1) < 0)
  19067. ret = ASN_PARSE_E;
  19068. }
  19069. if (!req) {
  19070. if (ret == 0) {
  19071. idx += len;
  19072. if ((idx + 1) > certSz)
  19073. ret = BUFFER_E;
  19074. }
  19075. if (ret == 0) {
  19076. /* issuerUniqueID - optional */
  19077. localIdx = idx;
  19078. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19079. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) {
  19080. idx++;
  19081. if (GetLength(cert, &idx, &len, certSz) < 0)
  19082. ret = ASN_PARSE_E;
  19083. idx += len;
  19084. }
  19085. }
  19086. }
  19087. if (ret == 0) {
  19088. if ((idx + 1) > certSz)
  19089. ret = BUFFER_E;
  19090. }
  19091. if (ret == 0) {
  19092. /* subjectUniqueID - optional */
  19093. localIdx = idx;
  19094. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19095. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)) {
  19096. idx++;
  19097. if (GetLength(cert, &idx, &len, certSz) < 0)
  19098. ret = ASN_PARSE_E;
  19099. idx += len;
  19100. }
  19101. }
  19102. }
  19103. if (ret == 0) {
  19104. if ((idx + 1) > certSz)
  19105. ret = BUFFER_E;
  19106. }
  19107. /* extensions - optional */
  19108. localIdx = idx;
  19109. if (ret == 0 && GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  19110. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)) {
  19111. idx++;
  19112. if (GetLength(cert, &idx, &extLen, certSz) < 0)
  19113. ret = ASN_PARSE_E;
  19114. if (ret == 0) {
  19115. if (GetSequence(cert, &idx, &extLen, certSz) < 0)
  19116. ret = ASN_PARSE_E;
  19117. }
  19118. if (ret == 0) {
  19119. extEndIdx = idx + extLen;
  19120. /* Check each extension for the ones we want. */
  19121. while (ret == 0 && idx < extEndIdx) {
  19122. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19123. ret = ASN_PARSE_E;
  19124. if (ret == 0) {
  19125. extIdx = idx;
  19126. if (GetObjectId(cert, &extIdx, &oid, oidCertExtType,
  19127. certSz) < 0) {
  19128. ret = ASN_PARSE_E;
  19129. }
  19130. if (ret == 0) {
  19131. if ((extIdx + 1) > certSz)
  19132. ret = BUFFER_E;
  19133. }
  19134. }
  19135. if (ret == 0) {
  19136. localIdx = extIdx;
  19137. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  19138. tag == ASN_BOOLEAN) {
  19139. if (GetBoolean(cert, &extIdx, certSz) < 0)
  19140. ret = ASN_PARSE_E;
  19141. }
  19142. }
  19143. if (ret == 0) {
  19144. if (GetOctetString(cert, &extIdx, &extLen, certSz) < 0)
  19145. ret = ASN_PARSE_E;
  19146. }
  19147. if (ret == 0) {
  19148. switch (oid) {
  19149. case AUTH_KEY_OID:
  19150. if (GetSequence(cert, &extIdx, &extLen, certSz) < 0)
  19151. ret = ASN_PARSE_E;
  19152. if (ret == 0 && (extIdx + 1) >= certSz)
  19153. ret = BUFFER_E;
  19154. if (ret == 0 &&
  19155. GetASNTag(cert, &extIdx, &tag, certSz) == 0 &&
  19156. tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  19157. if (GetLength(cert, &extIdx, &extLen, certSz) <= 0)
  19158. ret = ASN_PARSE_E;
  19159. if (ret == 0) {
  19160. extAuthKeyIdSet = 1;
  19161. /* Get the hash or hash of the hash if wrong
  19162. * size. */
  19163. ret = GetHashId(cert + extIdx, extLen,
  19164. hash);
  19165. }
  19166. }
  19167. break;
  19168. default:
  19169. break;
  19170. }
  19171. }
  19172. idx += len;
  19173. }
  19174. }
  19175. }
  19176. }
  19177. else if (ret == 0) {
  19178. idx += len;
  19179. }
  19180. if (ret == 0 && pubKey == NULL) {
  19181. if (extAuthKeyIdSet)
  19182. ca = GetCA(cm, hash);
  19183. if (ca == NULL) {
  19184. ret = CalcHashId(cert + issuerIdx, issuerSz, hash);
  19185. if (ret == 0)
  19186. ca = GetCAByName(cm, hash);
  19187. }
  19188. }
  19189. #else
  19190. if (ret == 0 && pubKey == NULL) {
  19191. ret = CalcHashId(cert + issuerIdx, issuerSz, hash);
  19192. if (ret == 0)
  19193. ca = GetCA(cm, hash);
  19194. }
  19195. #endif /* !NO_SKID */
  19196. if (ca == NULL && pubKey == NULL)
  19197. ret = ASN_NO_SIGNER_E;
  19198. if (ret == 0) {
  19199. idx = sigIndex;
  19200. /* signatureAlgorithm */
  19201. if (GetAlgoId(cert, &idx, &oid, oidSigType, certSz) < 0)
  19202. ret = ASN_PARSE_E;
  19203. #ifdef WC_RSA_PSS
  19204. else if (signatureOID == CTC_RSASSAPSS) {
  19205. word32 sz = idx;
  19206. const byte* params = cert + idx;
  19207. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19208. ret = ASN_PARSE_E;
  19209. if (ret == 0) {
  19210. idx += len;
  19211. sz = idx - sz;
  19212. if (req) {
  19213. if ((sz != sigParamsSz) ||
  19214. (XMEMCMP(sigParams, params, sz) != 0)) {
  19215. ret = ASN_PARSE_E;
  19216. }
  19217. }
  19218. else {
  19219. sigParams = params;
  19220. sigParamsSz = sz;
  19221. }
  19222. }
  19223. }
  19224. #endif
  19225. /* In CSR signature data is not present in body */
  19226. if (req)
  19227. signatureOID = oid;
  19228. }
  19229. if (ret == 0) {
  19230. if (oid != signatureOID)
  19231. ret = ASN_SIG_OID_E;
  19232. }
  19233. if (ret == 0) {
  19234. /* signatureValue */
  19235. if (CheckBitString(cert, &idx, &len, certSz, 1, NULL) < 0)
  19236. ret = ASN_PARSE_E;
  19237. }
  19238. if (ret == 0) {
  19239. if (pubKey != NULL) {
  19240. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  19241. sigIndex - tbsCertIdx, pubKey, pubKeySz, pubKeyOID,
  19242. cert + idx, len, signatureOID, sigParams, sigParamsSz, NULL);
  19243. }
  19244. else {
  19245. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  19246. sigIndex - tbsCertIdx, ca->publicKey, ca->pubKeySize,
  19247. ca->keyOID, cert + idx, len, signatureOID, sigParams,
  19248. sigParamsSz, NULL);
  19249. }
  19250. if (ret != 0) {
  19251. WOLFSSL_ERROR_VERBOSE(ret);
  19252. WOLFSSL_MSG("Confirm signature failed");
  19253. }
  19254. }
  19255. FreeSignatureCtx(sigCtx);
  19256. #ifdef WOLFSSL_SMALL_STACK
  19257. if (sigCtx != NULL)
  19258. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  19259. #endif
  19260. return ret;
  19261. #else /* WOLFSSL_ASN_TEMPLATE */
  19262. /* X509 ASN.1 template longer than Certificate Request template. */
  19263. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  19264. #ifndef WOLFSSL_SMALL_STACK
  19265. SignatureCtx sigCtx[1];
  19266. #else
  19267. SignatureCtx* sigCtx = NULL;
  19268. #endif
  19269. byte hash[KEYID_SIZE];
  19270. Signer* ca = NULL;
  19271. int ret = 0;
  19272. word32 idx = 0;
  19273. #ifndef NO_SKID
  19274. int extAuthKeyIdSet = 0;
  19275. #endif
  19276. const byte* tbs = NULL;
  19277. word32 tbsSz = 0;
  19278. #ifdef WC_RSA_PSS
  19279. const byte* tbsParams = NULL;
  19280. word32 tbsParamsSz = 0;
  19281. #endif
  19282. const byte* sig = NULL;
  19283. word32 sigSz = 0;
  19284. word32 sigOID = 0;
  19285. const byte* sigParams = NULL;
  19286. word32 sigParamsSz = 0;
  19287. const byte* caName = NULL;
  19288. word32 caNameLen = 0;
  19289. #ifndef NO_SKID
  19290. const byte* akiData = NULL;
  19291. word32 akiLen = 0;
  19292. #endif
  19293. (void)req;
  19294. (void)heap;
  19295. if (cert == NULL) {
  19296. ret = BAD_FUNC_ARG;
  19297. }
  19298. ALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, heap);
  19299. if ((ret == 0) && (!req)) {
  19300. /* Clear dynamic data for certificate items. */
  19301. XMEMSET(dataASN, 0, sizeof(ASNGetData) * x509CertASN_Length);
  19302. /* Set OID types expected for signature and public key. */
  19303. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
  19304. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
  19305. oidKeyType);
  19306. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
  19307. oidCurveType);
  19308. GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
  19309. /* Parse certificate. */
  19310. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1, cert,
  19311. &idx, certSz);
  19312. /* Check signature OIDs match. */
  19313. if ((ret == 0) && dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum
  19314. != dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum) {
  19315. ret = ASN_SIG_OID_E;
  19316. }
  19317. /* Store the data for verification in the certificate. */
  19318. if (ret == 0) {
  19319. tbs = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
  19320. tbsSz = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
  19321. caName = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  19322. cert);
  19323. caNameLen = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  19324. cert);
  19325. sigOID = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
  19326. #ifdef WC_RSA_PSS
  19327. if (dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].tag != 0) {
  19328. tbsParams =
  19329. GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  19330. cert);
  19331. tbsParamsSz =
  19332. GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  19333. cert);
  19334. }
  19335. if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
  19336. sigParams =
  19337. GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19338. cert);
  19339. sigParamsSz =
  19340. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19341. cert);
  19342. }
  19343. #endif
  19344. GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE], &sig, &sigSz);
  19345. #ifdef WC_RSA_PSS
  19346. if (tbsParamsSz != sigParamsSz) {
  19347. ret = ASN_PARSE_E;
  19348. }
  19349. else if ((tbsParamsSz > 0) && (sigOID != CTC_RSASSAPSS)) {
  19350. ret = ASN_PARSE_E;
  19351. }
  19352. else if ((tbsParamsSz > 0) &&
  19353. (XMEMCMP(tbsParams, sigParams, tbsParamsSz) != 0)) {
  19354. ret = ASN_PARSE_E;
  19355. }
  19356. #endif
  19357. }
  19358. }
  19359. else if (ret == 0) {
  19360. #ifndef WOLFSSL_CERT_REQ
  19361. ret = NOT_COMPILED_IN;
  19362. #else
  19363. /* Clear dynamic data for certificate request items. */
  19364. XMEMSET(dataASN, 0, sizeof(ASNGetData) * certReqASN_Length);
  19365. /* Set OID types expected for signature and public key. */
  19366. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
  19367. oidKeyType);
  19368. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
  19369. oidCurveType);
  19370. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
  19371. /* Parse certificate request. */
  19372. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1, cert,
  19373. &idx, certSz);
  19374. if (ret == 0) {
  19375. /* Store the data for verification in the certificate. */
  19376. tbs = GetASNItem_Addr(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
  19377. tbsSz = GetASNItem_Length(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
  19378. caName = GetASNItem_Addr(
  19379. dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
  19380. caNameLen = GetASNItem_Length(
  19381. dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
  19382. sigOID = dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
  19383. #ifdef WC_RSA_PSS
  19384. sigParams = GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19385. cert);
  19386. sigParamsSz =
  19387. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19388. cert);
  19389. #endif
  19390. GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE], &sig,
  19391. &sigSz);
  19392. }
  19393. #endif
  19394. }
  19395. #ifndef NO_SKID
  19396. if ((ret == 0) && (pubKey == NULL) && !req) {
  19397. akiData = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data;
  19398. akiLen = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.length;
  19399. }
  19400. #endif
  19401. FREE_ASNGETDATA(dataASN, heap);
  19402. /* If no public passed, then find the CA. */
  19403. if ((ret == 0) && (pubKey == NULL)) {
  19404. #ifndef NO_SKID
  19405. /* Find the AKI extension in list of extensions and get hash. */
  19406. if ((!req) && (akiData != NULL)) {
  19407. /* TODO: test case */
  19408. ret = GetAKIHash(akiData, akiLen, hash, &extAuthKeyIdSet, heap);
  19409. }
  19410. /* Get the CA by hash one was found. */
  19411. if (extAuthKeyIdSet) {
  19412. ca = GetCA(cm, hash);
  19413. }
  19414. if (ca == NULL)
  19415. #endif
  19416. {
  19417. /* Try hash of issuer name. */
  19418. ret = CalcHashId(caName, caNameLen, hash);
  19419. if (ret == 0) {
  19420. ca = GetCAByName(cm, hash);
  19421. }
  19422. }
  19423. if (ca != NULL) {
  19424. /* Extract public key information. */
  19425. pubKey = ca->publicKey;
  19426. pubKeySz = ca->pubKeySize;
  19427. pubKeyOID = ca->keyOID;
  19428. }
  19429. else {
  19430. /* No public key to verify with. */
  19431. ret = ASN_NO_SIGNER_E;
  19432. }
  19433. }
  19434. if (ret == 0) {
  19435. #ifdef WOLFSSL_SMALL_STACK
  19436. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap,
  19437. DYNAMIC_TYPE_SIGNATURE);
  19438. if (sigCtx == NULL) {
  19439. ret = MEMORY_E;
  19440. }
  19441. if (ret == 0)
  19442. #endif
  19443. {
  19444. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  19445. /* Check signature. */
  19446. ret = ConfirmSignature(sigCtx, tbs, tbsSz, pubKey, pubKeySz,
  19447. pubKeyOID, sig, sigSz, sigOID, sigParams, sigParamsSz, NULL);
  19448. if (ret != 0) {
  19449. WOLFSSL_MSG("Confirm signature failed");
  19450. }
  19451. FreeSignatureCtx(sigCtx);
  19452. #ifdef WOLFSSL_SMALL_STACK
  19453. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  19454. #endif
  19455. }
  19456. }
  19457. return ret;
  19458. #endif /* WOLFSSL_ASN_TEMPLATE */
  19459. }
  19460. #ifdef OPENSSL_EXTRA
  19461. /* Call CheckCertSignature_ex using a public key buffer for verification
  19462. */
  19463. int CheckCertSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  19464. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  19465. {
  19466. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  19467. pubKey, pubKeySz, pubKeyOID, 0);
  19468. }
  19469. int wc_CheckCertSigPubKey(const byte* cert, word32 certSz, void* heap,
  19470. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  19471. {
  19472. return CheckCertSignaturePubKey(cert, certSz, heap, pubKey, pubKeySz,
  19473. pubKeyOID);
  19474. }
  19475. #ifdef WOLFSSL_CERT_REQ
  19476. int CheckCSRSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  19477. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  19478. {
  19479. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  19480. pubKey, pubKeySz, pubKeyOID, 1);
  19481. }
  19482. #endif /* WOLFSSL_CERT_REQ */
  19483. #endif /* OPENSSL_EXTRA */
  19484. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  19485. /* Call CheckCertSignature_ex using a certificate manager (cm)
  19486. */
  19487. int CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm)
  19488. {
  19489. return CheckCertSignature_ex(cert, certSz, heap, cm, NULL, 0, 0, 0);
  19490. }
  19491. #endif /* WOLFSSL_SMALL_CERT_VERIFY */
  19492. #endif /* WOLFSSL_SMALL_CERT_VERIFY || OPENSSL_EXTRA */
  19493. #if (defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) || \
  19494. (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)))
  19495. /* ASN.1 DER decode instruction. */
  19496. typedef struct DecodeInstr {
  19497. /* Tag expected. */
  19498. byte tag;
  19499. /* Operation to perform: step in or go over */
  19500. byte op:1;
  19501. /* ASN.1 item is optional. */
  19502. byte optional:1;
  19503. } DecodeInstr;
  19504. /* Step into ASN.1 item. */
  19505. #define DECODE_INSTR_IN 0
  19506. /* Step over ASN.1 item. */
  19507. #define DECODE_INSTR_OVER 1
  19508. /* Get the public key data from the DER encoded X.509 certificate.
  19509. *
  19510. * Assumes data has previously been parsed for complete validity.
  19511. *
  19512. * @param [in] cert DER encoded X.509 certificate data.
  19513. * @param [in] certSz Length of DER encoding.
  19514. * @param [out] pubKey Public key data. (From the BIT_STRING.)
  19515. * @param [out] pubKeySz Length of public key data in bytes.
  19516. * @return 0 on success.
  19517. * @return BAD_FUNC_ARG when cert, pubKey or pubKeySz is NULL.
  19518. * @return ASN_PARSE_E when certificate encoding is invalid.
  19519. */
  19520. int wc_CertGetPubKey(const byte* cert, word32 certSz,
  19521. const unsigned char** pubKey, word32* pubKeySz)
  19522. {
  19523. int ret = 0;
  19524. int l;
  19525. word32 o = 0;
  19526. int i;
  19527. static DecodeInstr ops[] = {
  19528. /* Outer SEQ */
  19529. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  19530. /* TBSCertificate: SEQ */
  19531. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  19532. /* Version: [0] */
  19533. { ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_X509_CERT_VERSION,
  19534. DECODE_INSTR_OVER, 1 },
  19535. /* CertificateSerialNumber: INT */
  19536. { ASN_INTEGER, DECODE_INSTR_OVER, 0 },
  19537. /* AlgorithmIdentifier: SEQ */
  19538. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  19539. /* issuer: SEQ */
  19540. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  19541. /* Validity: SEQ */
  19542. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  19543. /* subject: SEQ */
  19544. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  19545. /* subjectPublicKeyInfo SEQ */
  19546. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  19547. /* AlgorithmIdentifier: SEQ */
  19548. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  19549. /* PublicKey: BIT_STRING */
  19550. { ASN_BIT_STRING, DECODE_INSTR_IN , 0 },
  19551. };
  19552. /* Validate parameters. */
  19553. if ((cert == NULL) || (pubKey == NULL) || (pubKeySz == NULL)) {
  19554. ret = BAD_FUNC_ARG;
  19555. }
  19556. /* Process each instruction to take us to public key data. */
  19557. for (i = 0; (ret == 0) && (i < (int)(sizeof(ops) / sizeof(*ops))); i++) {
  19558. DecodeInstr op = ops[i];
  19559. /* Check the current ASN.1 item has the expected tag. */
  19560. if (cert[o] != op.tag) {
  19561. /* If not optional then error, otherwise skip op. */
  19562. if (!op.optional) {
  19563. ret = ASN_PARSE_E;
  19564. }
  19565. }
  19566. else {
  19567. /* Move past tag. */
  19568. o++;
  19569. /* Get the length of ASN.1 item and move past length encoding. */
  19570. if (GetLength(cert, &o, &l, certSz) < 0) {
  19571. ret = ASN_PARSE_E;
  19572. }
  19573. /* Skip data if required. */
  19574. else if (op.op == DECODE_INSTR_OVER) {
  19575. o += l;
  19576. }
  19577. }
  19578. }
  19579. if (ret == 0) {
  19580. /* Return the public key data and length.
  19581. * Skip first byte of BIT_STRING data: unused bits. */
  19582. *pubKey = cert + o + 1;
  19583. *pubKeySz = l - 1;
  19584. }
  19585. return ret;
  19586. }
  19587. #endif
  19588. int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
  19589. {
  19590. int ret = 0;
  19591. #ifndef WOLFSSL_ASN_TEMPLATE
  19592. word32 confirmOID = 0;
  19593. #ifdef WOLFSSL_CERT_REQ
  19594. int len = 0;
  19595. #endif
  19596. #endif
  19597. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  19598. int idx = 0;
  19599. #endif
  19600. byte* sce_tsip_encRsaKeyIdx;
  19601. if (cert == NULL) {
  19602. return BAD_FUNC_ARG;
  19603. }
  19604. #ifdef WOLFSSL_CERT_REQ
  19605. if (type == CERTREQ_TYPE)
  19606. cert->isCSR = 1;
  19607. #endif
  19608. if (cert->sigCtx.state == SIG_STATE_BEGIN) {
  19609. #ifndef WOLFSSL_ASN_TEMPLATE
  19610. cert->badDate = 0;
  19611. cert->criticalExt = 0;
  19612. if ((ret = DecodeToKey(cert, verify)) < 0) {
  19613. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
  19614. cert->badDate = ret;
  19615. if (verify == VERIFY_SKIP_DATE)
  19616. ret = 0;
  19617. }
  19618. else
  19619. return ret;
  19620. }
  19621. WOLFSSL_MSG("Parsed Past Key");
  19622. #ifdef WOLFSSL_CERT_REQ
  19623. /* Read attributes */
  19624. if (cert->isCSR) {
  19625. if (GetASNHeader_ex(cert->source,
  19626. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &cert->srcIdx,
  19627. &len, cert->maxIdx, 1) < 0) {
  19628. WOLFSSL_MSG("GetASNHeader_ex error");
  19629. return ASN_PARSE_E;
  19630. }
  19631. if (len) {
  19632. word32 attrMaxIdx = cert->srcIdx + (word32)len;
  19633. word32 oid;
  19634. byte tag;
  19635. if (attrMaxIdx > cert->maxIdx) {
  19636. WOLFSSL_MSG("Attribute length greater than CSR length");
  19637. return ASN_PARSE_E;
  19638. }
  19639. while (cert->srcIdx < attrMaxIdx) {
  19640. /* Attributes have the structure:
  19641. * SEQ -> OID -> SET -> ATTRIBUTE */
  19642. if (GetSequence(cert->source, &cert->srcIdx, &len,
  19643. attrMaxIdx) < 0) {
  19644. WOLFSSL_MSG("attr GetSequence error");
  19645. return ASN_PARSE_E;
  19646. }
  19647. if (GetObjectId(cert->source, &cert->srcIdx, &oid,
  19648. oidCsrAttrType, attrMaxIdx) < 0) {
  19649. WOLFSSL_MSG("attr GetObjectId error");
  19650. return ASN_PARSE_E;
  19651. }
  19652. if (GetSet(cert->source, &cert->srcIdx, &len,
  19653. attrMaxIdx) < 0) {
  19654. WOLFSSL_MSG("attr GetSet error");
  19655. return ASN_PARSE_E;
  19656. }
  19657. switch (oid) {
  19658. case PKCS9_CONTENT_TYPE_OID:
  19659. if (GetHeader(cert->source, &tag,
  19660. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19661. WOLFSSL_MSG("attr GetHeader error");
  19662. return ASN_PARSE_E;
  19663. }
  19664. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  19665. tag != ASN_IA5_STRING) {
  19666. WOLFSSL_MSG("Unsupported attribute value format");
  19667. return ASN_PARSE_E;
  19668. }
  19669. cert->contentType = (char*)cert->source + cert->srcIdx;
  19670. cert->contentTypeLen = len;
  19671. cert->srcIdx += (word32)len;
  19672. break;
  19673. case CHALLENGE_PASSWORD_OID:
  19674. if (GetHeader(cert->source, &tag,
  19675. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19676. WOLFSSL_MSG("attr GetHeader error");
  19677. return ASN_PARSE_E;
  19678. }
  19679. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  19680. tag != ASN_IA5_STRING) {
  19681. WOLFSSL_MSG("Unsupported attribute value format");
  19682. return ASN_PARSE_E;
  19683. }
  19684. cert->cPwd = (char*)cert->source + cert->srcIdx;
  19685. cert->cPwdLen = len;
  19686. cert->srcIdx += (word32)len;
  19687. break;
  19688. case SERIAL_NUMBER_OID:
  19689. if (GetHeader(cert->source, &tag,
  19690. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19691. WOLFSSL_MSG("attr GetHeader error");
  19692. return ASN_PARSE_E;
  19693. }
  19694. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  19695. tag != ASN_IA5_STRING) {
  19696. WOLFSSL_MSG("Unsupported attribute value format");
  19697. return ASN_PARSE_E;
  19698. }
  19699. cert->sNum = (char*)cert->source + cert->srcIdx;
  19700. cert->sNumLen = len;
  19701. cert->srcIdx += (word32)len;
  19702. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  19703. XMEMCPY(cert->serial, cert->sNum,
  19704. (size_t)cert->sNumLen);
  19705. cert->serialSz = cert->sNumLen;
  19706. }
  19707. break;
  19708. case DNQUALIFIER_OID:
  19709. if (GetHeader(cert->source, &tag,
  19710. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19711. WOLFSSL_MSG("attr GetHeader error");
  19712. return ASN_PARSE_E;
  19713. }
  19714. cert->dnQualifier = (char*)cert->source + cert->srcIdx;
  19715. cert->dnQualifierLen = len;
  19716. cert->srcIdx += (word32)len;
  19717. break;
  19718. case INITIALS_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. cert->initials = (char*)cert->source + cert->srcIdx;
  19725. cert->initialsLen = len;
  19726. cert->srcIdx += (word32)len;
  19727. break;
  19728. case SURNAME_OID:
  19729. if (GetHeader(cert->source, &tag,
  19730. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19731. WOLFSSL_MSG("attr GetHeader error");
  19732. return ASN_PARSE_E;
  19733. }
  19734. cert->surname = (char*)cert->source + cert->srcIdx;
  19735. cert->surnameLen = len;
  19736. cert->srcIdx += (word32)len;
  19737. break;
  19738. case GIVEN_NAME_OID:
  19739. if (GetHeader(cert->source, &tag,
  19740. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19741. WOLFSSL_MSG("attr GetHeader error");
  19742. return ASN_PARSE_E;
  19743. }
  19744. cert->givenName = (char*)cert->source + cert->srcIdx;
  19745. cert->givenNameLen = len;
  19746. cert->srcIdx += (word32)len;
  19747. break;
  19748. case UNSTRUCTURED_NAME_OID:
  19749. if (GetHeader(cert->source, &tag,
  19750. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19751. WOLFSSL_MSG("attr GetHeader error");
  19752. return ASN_PARSE_E;
  19753. }
  19754. cert->unstructuredName =
  19755. (char*)cert->source + cert->srcIdx;
  19756. cert->unstructuredNameLen = len;
  19757. cert->srcIdx += (word32)len;
  19758. break;
  19759. case EXTENSION_REQUEST_OID:
  19760. /* save extensions */
  19761. cert->extensions = &cert->source[cert->srcIdx];
  19762. cert->extensionsSz = len;
  19763. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  19764. if ((ret = DecodeCertExtensions(cert)) < 0) {
  19765. if (ret == ASN_CRIT_EXT_E) {
  19766. cert->criticalExt = ret;
  19767. }
  19768. else {
  19769. return ret;
  19770. }
  19771. }
  19772. cert->srcIdx += (word32)len;
  19773. break;
  19774. default:
  19775. WOLFSSL_MSG("Unsupported attribute type");
  19776. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  19777. return ASN_PARSE_E;
  19778. }
  19779. }
  19780. }
  19781. }
  19782. #endif
  19783. if (cert->srcIdx < cert->sigIndex) {
  19784. #ifndef ALLOW_V1_EXTENSIONS
  19785. if (cert->version < 2) {
  19786. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  19787. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  19788. return ASN_VERSION_E;
  19789. }
  19790. #endif
  19791. /* save extensions */
  19792. cert->extensions = &cert->source[cert->srcIdx];
  19793. cert->extensionsSz = (int)(cert->sigIndex - cert->srcIdx);
  19794. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  19795. if ((ret = DecodeCertExtensions(cert)) < 0) {
  19796. if (ret == ASN_CRIT_EXT_E)
  19797. cert->criticalExt = ret;
  19798. else
  19799. return ret;
  19800. }
  19801. #ifdef HAVE_OCSP
  19802. if (verify == VERIFY_OCSP_CERT) {
  19803. /* trust for the lifetime of the responder's cert*/
  19804. if (cert->ocspNoCheckSet)
  19805. verify = VERIFY;
  19806. else
  19807. verify = VERIFY_OCSP;
  19808. }
  19809. #endif
  19810. /* advance past extensions */
  19811. cert->srcIdx = cert->sigIndex;
  19812. }
  19813. if ((ret = GetSigAlg(cert,
  19814. #ifdef WOLFSSL_CERT_REQ
  19815. !cert->isCSR ? &confirmOID : &cert->signatureOID,
  19816. #else
  19817. &confirmOID,
  19818. #endif
  19819. cert->maxIdx)) < 0) {
  19820. return ret;
  19821. }
  19822. if ((ret = GetSignature(cert)) < 0) {
  19823. return ret;
  19824. }
  19825. if (confirmOID != cert->signatureOID
  19826. #ifdef WOLFSSL_CERT_REQ
  19827. && !cert->isCSR
  19828. #endif
  19829. ) {
  19830. WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
  19831. return ASN_SIG_OID_E;
  19832. }
  19833. #else
  19834. #ifdef WOLFSSL_CERT_REQ
  19835. if (cert->isCSR) {
  19836. ret = DecodeCertReq(cert, &cert->criticalExt);
  19837. if (ret < 0) {
  19838. return ret;
  19839. }
  19840. }
  19841. else
  19842. #endif
  19843. {
  19844. ret = DecodeCert(cert, verify, &cert->criticalExt);
  19845. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
  19846. cert->badDate = ret;
  19847. if (verify == VERIFY_SKIP_DATE)
  19848. ret = 0;
  19849. }
  19850. else if (ret < 0) {
  19851. WOLFSSL_ERROR_VERBOSE(ret);
  19852. return ret;
  19853. }
  19854. }
  19855. #endif
  19856. #ifndef NO_SKID
  19857. if (cert->extSubjKeyIdSet == 0 && cert->publicKey != NULL &&
  19858. cert->pubKeySize > 0) {
  19859. ret = CalcHashId(cert->publicKey, cert->pubKeySize,
  19860. cert->extSubjKeyId);
  19861. if (ret != 0) {
  19862. WOLFSSL_ERROR_VERBOSE(ret);
  19863. return ret;
  19864. }
  19865. }
  19866. #endif /* !NO_SKID */
  19867. if (!cert->selfSigned || (verify != NO_VERIFY && type != CA_TYPE &&
  19868. type != TRUSTED_PEER_TYPE)) {
  19869. cert->ca = NULL;
  19870. #ifndef NO_SKID
  19871. if (cert->extAuthKeyIdSet) {
  19872. cert->ca = GetCA(cm, cert->extAuthKeyId);
  19873. }
  19874. if (cert->ca == NULL && cert->extSubjKeyIdSet
  19875. && verify != VERIFY_OCSP) {
  19876. cert->ca = GetCA(cm, cert->extSubjKeyId);
  19877. }
  19878. if (cert->ca != NULL && XMEMCMP(cert->issuerHash,
  19879. cert->ca->subjectNameHash, KEYID_SIZE) != 0) {
  19880. cert->ca = NULL;
  19881. }
  19882. if (cert->ca == NULL) {
  19883. cert->ca = GetCAByName(cm, cert->issuerHash);
  19884. /* If AKID is available then this CA doesn't have the public
  19885. * key required */
  19886. if (cert->ca && cert->extAuthKeyIdSet) {
  19887. WOLFSSL_MSG("CA SKID doesn't match AKID");
  19888. cert->ca = NULL;
  19889. }
  19890. }
  19891. /* OCSP Only: alt lookup using subject and pub key w/o sig check */
  19892. #ifdef WOLFSSL_NO_TRUSTED_CERTS_VERIFY
  19893. if (cert->ca == NULL && verify == VERIFY_OCSP) {
  19894. cert->ca = GetCABySubjectAndPubKey(cert, cm);
  19895. if (cert->ca) {
  19896. ret = 0; /* success */
  19897. goto exit_pcr;
  19898. }
  19899. }
  19900. #endif /* WOLFSSL_NO_TRUSTED_CERTS_VERIFY */
  19901. #else
  19902. cert->ca = GetCA(cm, cert->issuerHash);
  19903. #endif /* !NO_SKID */
  19904. if (cert->ca) {
  19905. WOLFSSL_MSG("CA found");
  19906. }
  19907. }
  19908. if (cert->selfSigned) {
  19909. cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
  19910. } else {
  19911. /* RFC 5280 Section 4.2.1.9:
  19912. *
  19913. * load/receive check
  19914. *
  19915. * 1) Is CA boolean set?
  19916. * No - SKIP CHECK
  19917. * Yes - Check key usage
  19918. * 2) Is Key usage extension present?
  19919. * No - goto 3
  19920. * Yes - check keyCertSign assertion
  19921. * 2.a) Is keyCertSign asserted?
  19922. * No - goto 4
  19923. * Yes - goto 3
  19924. * 3) Is pathLen set?
  19925. * No - goto 4
  19926. * Yes - check pathLen against maxPathLen.
  19927. * 3.a) Is pathLen less than maxPathLen?
  19928. * No - goto 4
  19929. * Yes - set maxPathLen to pathLen and EXIT
  19930. * 4) Is maxPathLen > 0?
  19931. * Yes - Reduce by 1
  19932. * No - ERROR
  19933. */
  19934. if (cert->ca && cert->pathLengthSet) {
  19935. int checkPathLen = 0;
  19936. int decrementMaxPathLen = 0;
  19937. cert->maxPathLen = cert->pathLength;
  19938. if (cert->isCA) {
  19939. WOLFSSL_MSG("\tCA boolean set");
  19940. if (cert->extKeyUsageSet) {
  19941. WOLFSSL_MSG("\tExtension Key Usage Set");
  19942. if ((cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) != 0) {
  19943. checkPathLen = 1;
  19944. }
  19945. else {
  19946. decrementMaxPathLen = 1;
  19947. }
  19948. }
  19949. else {
  19950. checkPathLen = 1;
  19951. } /* !cert->ca check */
  19952. } /* cert is not a CA (assuming entity cert) */
  19953. if (checkPathLen && cert->pathLengthSet) {
  19954. if (cert->pathLength < cert->ca->maxPathLen) {
  19955. WOLFSSL_MSG("\tmaxPathLen status: set to pathLength");
  19956. cert->maxPathLen = cert->pathLength;
  19957. }
  19958. else {
  19959. decrementMaxPathLen = 1;
  19960. }
  19961. }
  19962. if (decrementMaxPathLen && cert->ca->maxPathLen > 0) {
  19963. WOLFSSL_MSG("\tmaxPathLen status: reduce by 1");
  19964. cert->maxPathLen = cert->ca->maxPathLen - 1;
  19965. if (verify != NO_VERIFY && type != CA_TYPE &&
  19966. type != TRUSTED_PEER_TYPE) {
  19967. WOLFSSL_MSG("\tmaxPathLen status: OK");
  19968. }
  19969. } else if (decrementMaxPathLen && cert->ca->maxPathLen == 0) {
  19970. cert->maxPathLen = 0;
  19971. if (verify != NO_VERIFY && type != CA_TYPE &&
  19972. type != TRUSTED_PEER_TYPE) {
  19973. WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
  19974. WOLFSSL_MSG("\tmaxPathLen status: ERROR");
  19975. WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_INV_E);
  19976. return ASN_PATHLEN_INV_E;
  19977. }
  19978. }
  19979. } else if (cert->ca && cert->isCA) {
  19980. /* case where cert->pathLength extension is not set */
  19981. if (cert->ca->maxPathLen > 0) {
  19982. cert->maxPathLen = cert->ca->maxPathLen - 1;
  19983. } else {
  19984. cert->maxPathLen = 0;
  19985. if (verify != NO_VERIFY && type != CA_TYPE &&
  19986. type != TRUSTED_PEER_TYPE) {
  19987. WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
  19988. WOLFSSL_MSG("\tmaxPathLen status: ERROR");
  19989. WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_INV_E);
  19990. return ASN_PATHLEN_INV_E;
  19991. }
  19992. }
  19993. }
  19994. }
  19995. #ifdef HAVE_OCSP
  19996. if (verify != NO_VERIFY && type != CA_TYPE &&
  19997. type != TRUSTED_PEER_TYPE) {
  19998. if (cert->ca) {
  19999. /* Need the CA's public key hash for OCSP */
  20000. XMEMCPY(cert->issuerKeyHash, cert->ca->subjectKeyHash,
  20001. KEYID_SIZE);
  20002. }
  20003. }
  20004. #endif /* HAVE_OCSP */
  20005. }
  20006. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  20007. /* prepare for TSIP TLS cert verification API use */
  20008. if (cert->keyOID == RSAk) {
  20009. /* to call TSIP API, it needs keys position info in bytes */
  20010. if ((ret = RsaPublicKeyDecodeRawIndex(cert->publicKey, (word32*)&idx,
  20011. cert->pubKeySize,
  20012. &cert->sigCtx.CertAtt.pubkey_n_start,
  20013. &cert->sigCtx.CertAtt.pubkey_n_len,
  20014. &cert->sigCtx.CertAtt.pubkey_e_start,
  20015. &cert->sigCtx.CertAtt.pubkey_e_len)) != 0) {
  20016. WOLFSSL_MSG("Decoding index from cert failed.");
  20017. return ret;
  20018. }
  20019. cert->sigCtx.CertAtt.certBegin = cert->certBegin;
  20020. } else if (cert->keyOID == ECDSAk) {
  20021. cert->sigCtx.CertAtt.certBegin = cert->certBegin;
  20022. }
  20023. /* check if we can use TSIP for cert verification */
  20024. /* if the ca is verified as tsip root ca. */
  20025. /* TSIP can only handle 2048 bits(256 byte) key. */
  20026. if (cert->ca && Renesas_cmn_checkCA(cert->ca->cm_idx) != 0 &&
  20027. (cert->sigCtx.CertAtt.pubkey_n_len == 256 ||
  20028. cert->sigCtx.CertAtt.curve_id == ECC_SECP256R1)) {
  20029. /* assign memory to encrypted tsip Rsa key index */
  20030. if (!cert->sce_tsip_encRsaKeyIdx)
  20031. cert->sce_tsip_encRsaKeyIdx =
  20032. (byte*)XMALLOC(TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY,
  20033. cert->heap, DYNAMIC_TYPE_RSA);
  20034. if (cert->sce_tsip_encRsaKeyIdx == NULL)
  20035. return MEMORY_E;
  20036. }
  20037. else {
  20038. if (cert->ca) {
  20039. /* TSIP isn't usable */
  20040. if (Renesas_cmn_checkCA(cert->ca->cm_idx) == 0)
  20041. WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't verified "
  20042. "by TSIP.");
  20043. else if (cert->sigCtx.CertAtt.pubkey_n_len != 256)
  20044. WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't signed by "
  20045. "RSA 2048.");
  20046. else
  20047. WOLFSSL_MSG("SCE-TSIP isn't usable");
  20048. }
  20049. cert->sce_tsip_encRsaKeyIdx = NULL;
  20050. }
  20051. sce_tsip_encRsaKeyIdx = cert->sce_tsip_encRsaKeyIdx;
  20052. #else
  20053. sce_tsip_encRsaKeyIdx = NULL;
  20054. #endif
  20055. if (verify != NO_VERIFY && type != CA_TYPE && type != TRUSTED_PEER_TYPE) {
  20056. if (cert->ca) {
  20057. if (verify == VERIFY || verify == VERIFY_OCSP ||
  20058. verify == VERIFY_SKIP_DATE) {
  20059. /* try to confirm/verify signature */
  20060. if ((ret = ConfirmSignature(&cert->sigCtx,
  20061. cert->source + cert->certBegin,
  20062. cert->sigIndex - cert->certBegin,
  20063. cert->ca->publicKey, cert->ca->pubKeySize,
  20064. cert->ca->keyOID, cert->signature,
  20065. cert->sigLength, cert->signatureOID,
  20066. #ifdef WC_RSA_PSS
  20067. cert->source + cert->sigParamsIndex,
  20068. cert->sigParamsLength,
  20069. #else
  20070. NULL, 0,
  20071. #endif
  20072. sce_tsip_encRsaKeyIdx)) != 0) {
  20073. if (ret != WC_PENDING_E) {
  20074. WOLFSSL_MSG("Confirm signature failed");
  20075. }
  20076. WOLFSSL_ERROR_VERBOSE(ret);
  20077. return ret;
  20078. }
  20079. }
  20080. #ifndef IGNORE_NAME_CONSTRAINTS
  20081. if (verify == VERIFY || verify == VERIFY_OCSP ||
  20082. verify == VERIFY_NAME || verify == VERIFY_SKIP_DATE) {
  20083. /* check that this cert's name is permitted by the signer's
  20084. * name constraints */
  20085. if (!ConfirmNameConstraints(cert->ca, cert)) {
  20086. WOLFSSL_MSG("Confirm name constraint failed");
  20087. WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
  20088. return ASN_NAME_INVALID_E;
  20089. }
  20090. }
  20091. #endif /* IGNORE_NAME_CONSTRAINTS */
  20092. }
  20093. #ifdef WOLFSSL_CERT_REQ
  20094. else if (type == CERTREQ_TYPE) {
  20095. if ((ret = ConfirmSignature(&cert->sigCtx,
  20096. cert->source + cert->certBegin,
  20097. cert->sigIndex - cert->certBegin,
  20098. cert->publicKey, cert->pubKeySize,
  20099. cert->keyOID, cert->signature,
  20100. cert->sigLength, cert->signatureOID,
  20101. #ifdef WC_RSA_PSS
  20102. cert->source + cert->sigParamsIndex, cert->sigParamsLength,
  20103. #else
  20104. NULL, 0,
  20105. #endif
  20106. sce_tsip_encRsaKeyIdx)) != 0) {
  20107. if (ret != WC_PENDING_E) {
  20108. WOLFSSL_MSG("Confirm signature failed");
  20109. }
  20110. WOLFSSL_ERROR_VERBOSE(ret);
  20111. return ret;
  20112. }
  20113. }
  20114. #endif
  20115. else {
  20116. /* no signer */
  20117. WOLFSSL_MSG("No CA signer to verify with");
  20118. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  20119. /* ret needs to be self-signer error for Qt compat */
  20120. if (cert->selfSigned) {
  20121. WOLFSSL_ERROR_VERBOSE(ASN_SELF_SIGNED_E);
  20122. return ASN_SELF_SIGNED_E;
  20123. }
  20124. else
  20125. #endif
  20126. {
  20127. WOLFSSL_ERROR_VERBOSE(ASN_NO_SIGNER_E);
  20128. return ASN_NO_SIGNER_E;
  20129. }
  20130. }
  20131. }
  20132. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  20133. exit_pcr:
  20134. #endif
  20135. if (cert->badDate != 0) {
  20136. if (verify != VERIFY_SKIP_DATE) {
  20137. return cert->badDate;
  20138. }
  20139. WOLFSSL_MSG("Date error: Verify option is skipping");
  20140. }
  20141. if (cert->criticalExt != 0)
  20142. return cert->criticalExt;
  20143. return ret;
  20144. }
  20145. /* Create and init an new signer */
  20146. Signer* MakeSigner(void* heap)
  20147. {
  20148. Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
  20149. DYNAMIC_TYPE_SIGNER);
  20150. if (signer) {
  20151. XMEMSET(signer, 0, sizeof(Signer));
  20152. }
  20153. (void)heap;
  20154. return signer;
  20155. }
  20156. /* Free an individual signer.
  20157. *
  20158. * Used by Certificate Manager.
  20159. *
  20160. * @param [in, out] signer On in, signer object.
  20161. * On out, pointer is no longer valid.
  20162. * @param [in] heap Dynamic memory hint.
  20163. */
  20164. void FreeSigner(Signer* signer, void* heap)
  20165. {
  20166. (void)signer;
  20167. (void)heap;
  20168. XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  20169. XFREE((void*)signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  20170. #ifndef IGNORE_NAME_CONSTRAINTS
  20171. if (signer->permittedNames)
  20172. FreeNameSubtrees(signer->permittedNames, heap);
  20173. if (signer->excludedNames)
  20174. FreeNameSubtrees(signer->excludedNames, heap);
  20175. #endif
  20176. #ifdef WOLFSSL_SIGNER_DER_CERT
  20177. FreeDer(&signer->derCert);
  20178. #endif
  20179. XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
  20180. }
  20181. /* Free the whole singer table with number of rows.
  20182. *
  20183. * Each table entry is a linked list of signers.
  20184. * Used by Certificate Manager.
  20185. *
  20186. * @param [in, out] table Array of signer objects.
  20187. * @param [in] rows Number of entries in table.
  20188. * @param [in] heap Dynamic memory hint.
  20189. */
  20190. void FreeSignerTable(Signer** table, int rows, void* heap)
  20191. {
  20192. int i;
  20193. for (i = 0; i < rows; i++) {
  20194. Signer* signer = table[i];
  20195. while (signer) {
  20196. Signer* next = signer->next;
  20197. FreeSigner(signer, heap);
  20198. signer = next;
  20199. }
  20200. table[i] = NULL;
  20201. }
  20202. }
  20203. #ifdef WOLFSSL_TRUST_PEER_CERT
  20204. /* Free an individual trusted peer cert.
  20205. *
  20206. * @param [in, out] tp Trusted peer certificate object.
  20207. * @param [in] heap Dynamic memory hint.
  20208. */
  20209. void FreeTrustedPeer(TrustedPeerCert* tp, void* heap)
  20210. {
  20211. if (tp == NULL) {
  20212. return;
  20213. }
  20214. if (tp->name) {
  20215. XFREE(tp->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  20216. }
  20217. if (tp->sig) {
  20218. XFREE(tp->sig, heap, DYNAMIC_TYPE_SIGNATURE);
  20219. }
  20220. #ifndef IGNORE_NAME_CONSTRAINTS
  20221. if (tp->permittedNames)
  20222. FreeNameSubtrees(tp->permittedNames, heap);
  20223. if (tp->excludedNames)
  20224. FreeNameSubtrees(tp->excludedNames, heap);
  20225. #endif
  20226. XFREE(tp, heap, DYNAMIC_TYPE_CERT);
  20227. (void)heap;
  20228. }
  20229. /* Free the whole Trusted Peer linked list.
  20230. *
  20231. * Each table entry is a linked list of trusted peer certificates.
  20232. * Used by Certificate Manager.
  20233. *
  20234. * @param [in, out] table Array of trusted peer certificate objects.
  20235. * @param [in] rows Number of entries in table.
  20236. * @param [in] heap Dynamic memory hint.
  20237. */
  20238. void FreeTrustedPeerTable(TrustedPeerCert** table, int rows, void* heap)
  20239. {
  20240. int i;
  20241. for (i = 0; i < rows; i++) {
  20242. TrustedPeerCert* tp = table[i];
  20243. while (tp) {
  20244. TrustedPeerCert* next = tp->next;
  20245. FreeTrustedPeer(tp, heap);
  20246. tp = next;
  20247. }
  20248. table[i] = NULL;
  20249. }
  20250. }
  20251. #endif /* WOLFSSL_TRUST_PEER_CERT */
  20252. int SetMyVersion(word32 version, byte* output, int header)
  20253. {
  20254. int i = 0;
  20255. if (output == NULL)
  20256. return BAD_FUNC_ARG;
  20257. if (header) {
  20258. output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  20259. output[i++] = 3;
  20260. }
  20261. output[i++] = ASN_INTEGER;
  20262. output[i++] = 0x01;
  20263. output[i++] = (byte)version;
  20264. return i;
  20265. }
  20266. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7)
  20267. int SetSerialNumber(const byte* sn, word32 snSz, byte* output,
  20268. word32 outputSz, int maxSnSz)
  20269. {
  20270. int i;
  20271. int snSzInt = (int)snSz;
  20272. if (sn == NULL || output == NULL || snSzInt < 0)
  20273. return BAD_FUNC_ARG;
  20274. /* remove leading zeros */
  20275. while (snSzInt > 0 && sn[0] == 0) {
  20276. snSzInt--;
  20277. sn++;
  20278. }
  20279. /* RFC 5280 - 4.1.2.2:
  20280. * Serial numbers must be a positive value (and not zero) */
  20281. if (snSzInt == 0) {
  20282. WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
  20283. return BAD_FUNC_ARG;
  20284. }
  20285. if (sn[0] & 0x80)
  20286. maxSnSz--;
  20287. /* truncate if input is too long */
  20288. if (snSzInt > maxSnSz)
  20289. snSzInt = maxSnSz;
  20290. i = SetASNInt(snSzInt, sn[0], NULL);
  20291. /* truncate if input is too long */
  20292. if (snSzInt > (int)outputSz - i)
  20293. snSzInt = (int)outputSz - i;
  20294. /* sanity check number of bytes to copy */
  20295. if (snSzInt <= 0) {
  20296. return BUFFER_E;
  20297. }
  20298. /* write out ASN.1 Integer */
  20299. (void)SetASNInt(snSzInt, sn[0], output);
  20300. XMEMCPY(output + i, sn, (size_t)snSzInt);
  20301. /* compute final length */
  20302. i += snSzInt;
  20303. return i;
  20304. }
  20305. #endif /* !WOLFSSL_ASN_TEMPLATE */
  20306. #endif /* !NO_CERTS */
  20307. #ifndef WOLFSSL_ASN_TEMPLATE
  20308. int wc_GetSerialNumber(const byte* input, word32* inOutIdx,
  20309. byte* serial, int* serialSz, word32 maxIdx)
  20310. {
  20311. int result = 0;
  20312. int ret;
  20313. WOLFSSL_ENTER("wc_GetSerialNumber");
  20314. if (serial == NULL || input == NULL || serialSz == NULL) {
  20315. return BAD_FUNC_ARG;
  20316. }
  20317. /* First byte is ASN type */
  20318. if ((*inOutIdx+1) > maxIdx) {
  20319. WOLFSSL_MSG("Bad idx first");
  20320. return BUFFER_E;
  20321. }
  20322. ret = GetASNInt(input, inOutIdx, serialSz, maxIdx);
  20323. if (ret != 0)
  20324. return ret;
  20325. if (*serialSz > EXTERNAL_SERIAL_SIZE || *serialSz <= 0) {
  20326. WOLFSSL_MSG("Serial size bad");
  20327. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  20328. return ASN_PARSE_E;
  20329. }
  20330. /* return serial */
  20331. XMEMCPY(serial, &input[*inOutIdx], (size_t)*serialSz);
  20332. *inOutIdx += (word32)*serialSz;
  20333. return result;
  20334. }
  20335. #endif
  20336. #ifndef NO_CERTS
  20337. /* TODO: consider moving PEM code out to a different file. */
  20338. int AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  20339. {
  20340. int ret = BAD_FUNC_ARG;
  20341. if (pDer) {
  20342. int dynType = 0;
  20343. DerBuffer* der;
  20344. /* Determine dynamic type */
  20345. switch (type) {
  20346. case CA_TYPE: dynType = DYNAMIC_TYPE_CA; break;
  20347. case CERT_TYPE: dynType = DYNAMIC_TYPE_CERT; break;
  20348. case CRL_TYPE: dynType = DYNAMIC_TYPE_CRL; break;
  20349. case DSA_TYPE: dynType = DYNAMIC_TYPE_DSA; break;
  20350. case ECC_TYPE: dynType = DYNAMIC_TYPE_ECC; break;
  20351. case RSA_TYPE: dynType = DYNAMIC_TYPE_RSA; break;
  20352. default: dynType = DYNAMIC_TYPE_KEY; break;
  20353. }
  20354. /* Setup new buffer */
  20355. *pDer = (DerBuffer*)XMALLOC(sizeof(DerBuffer) + length, heap, dynType);
  20356. if (*pDer == NULL) {
  20357. return MEMORY_E;
  20358. }
  20359. XMEMSET(*pDer, 0, sizeof(DerBuffer) + length);
  20360. der = *pDer;
  20361. der->type = type;
  20362. der->dynType = dynType; /* Cache this for FreeDer */
  20363. der->heap = heap;
  20364. der->buffer = (byte*)der + sizeof(DerBuffer);
  20365. der->length = length;
  20366. ret = 0; /* Success */
  20367. }
  20368. return ret;
  20369. }
  20370. void FreeDer(DerBuffer** pDer)
  20371. {
  20372. if (pDer && *pDer)
  20373. {
  20374. DerBuffer* der = (DerBuffer*)*pDer;
  20375. /* ForceZero private keys */
  20376. if (der->type == PRIVATEKEY_TYPE && der->buffer != NULL) {
  20377. ForceZero(der->buffer, der->length);
  20378. }
  20379. der->buffer = NULL;
  20380. der->length = 0;
  20381. XFREE(der, der->heap, der->dynType);
  20382. *pDer = NULL;
  20383. }
  20384. }
  20385. int wc_AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  20386. {
  20387. return AllocDer(pDer, length, type, heap);
  20388. }
  20389. void wc_FreeDer(DerBuffer** pDer)
  20390. {
  20391. FreeDer(pDer);
  20392. }
  20393. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  20394. /* Note: If items added make sure MAX_X509_HEADER_SZ is
  20395. updated to reflect maximum length and pem_struct_min_sz
  20396. to reflect minimum size */
  20397. wcchar BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
  20398. wcchar END_CERT = "-----END CERTIFICATE-----";
  20399. #ifdef WOLFSSL_CERT_REQ
  20400. wcchar BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----";
  20401. wcchar END_CERT_REQ = "-----END CERTIFICATE REQUEST-----";
  20402. #endif
  20403. #ifndef NO_DH
  20404. wcchar BEGIN_DH_PARAM = "-----BEGIN DH PARAMETERS-----";
  20405. wcchar END_DH_PARAM = "-----END DH PARAMETERS-----";
  20406. wcchar BEGIN_X942_PARAM = "-----BEGIN X9.42 DH PARAMETERS-----";
  20407. wcchar END_X942_PARAM = "-----END X9.42 DH PARAMETERS-----";
  20408. #endif
  20409. #ifndef NO_DSA
  20410. wcchar BEGIN_DSA_PARAM = "-----BEGIN DSA PARAMETERS-----";
  20411. wcchar END_DSA_PARAM = "-----END DSA PARAMETERS-----";
  20412. #endif
  20413. wcchar BEGIN_X509_CRL = "-----BEGIN X509 CRL-----";
  20414. wcchar END_X509_CRL = "-----END X509 CRL-----";
  20415. wcchar BEGIN_RSA_PRIV = "-----BEGIN RSA PRIVATE KEY-----";
  20416. wcchar END_RSA_PRIV = "-----END RSA PRIVATE KEY-----";
  20417. wcchar BEGIN_RSA_PUB = "-----BEGIN RSA PUBLIC KEY-----";
  20418. wcchar END_RSA_PUB = "-----END RSA PUBLIC KEY-----";
  20419. wcchar BEGIN_PRIV_KEY = "-----BEGIN PRIVATE KEY-----";
  20420. wcchar END_PRIV_KEY = "-----END PRIVATE KEY-----";
  20421. wcchar BEGIN_ENC_PRIV_KEY = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
  20422. wcchar END_ENC_PRIV_KEY = "-----END ENCRYPTED PRIVATE KEY-----";
  20423. #ifdef HAVE_ECC
  20424. wcchar BEGIN_EC_PRIV = "-----BEGIN EC PRIVATE KEY-----";
  20425. wcchar END_EC_PRIV = "-----END EC PRIVATE KEY-----";
  20426. #ifdef OPENSSL_EXTRA
  20427. wcchar BEGIN_EC_PARAM = "-----BEGIN EC PARAMETERS-----";
  20428. wcchar END_EC_PARAM = "-----END EC PARAMETERS-----";
  20429. #endif
  20430. #endif
  20431. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  20432. !defined(NO_DSA)
  20433. wcchar BEGIN_DSA_PRIV = "-----BEGIN DSA PRIVATE KEY-----";
  20434. wcchar END_DSA_PRIV = "-----END DSA PRIVATE KEY-----";
  20435. #endif
  20436. #ifdef OPENSSL_EXTRA
  20437. const char BEGIN_PRIV_KEY_PREFIX[] = "-----BEGIN";
  20438. const char PRIV_KEY_SUFFIX[] = "PRIVATE KEY-----";
  20439. const char END_PRIV_KEY_PREFIX[] = "-----END";
  20440. #endif
  20441. wcchar BEGIN_PUB_KEY = "-----BEGIN PUBLIC KEY-----";
  20442. wcchar END_PUB_KEY = "-----END PUBLIC KEY-----";
  20443. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  20444. wcchar BEGIN_EDDSA_PRIV = "-----BEGIN EDDSA PRIVATE KEY-----";
  20445. wcchar END_EDDSA_PRIV = "-----END EDDSA PRIVATE KEY-----";
  20446. #endif
  20447. #if defined(HAVE_PQC)
  20448. #if defined(HAVE_FALCON)
  20449. wcchar BEGIN_FALCON_LEVEL1_PRIV = "-----BEGIN FALCON_LEVEL1 PRIVATE KEY-----";
  20450. wcchar END_FALCON_LEVEL1_PRIV = "-----END FALCON_LEVEL1 PRIVATE KEY-----";
  20451. wcchar BEGIN_FALCON_LEVEL5_PRIV = "-----BEGIN FALCON_LEVEL5 PRIVATE KEY-----";
  20452. wcchar END_FALCON_LEVEL5_PRIV = "-----END FALCON_LEVEL5 PRIVATE KEY-----";
  20453. #endif /* HAVE_FALCON */
  20454. #if defined(HAVE_DILITHIUM)
  20455. wcchar BEGIN_DILITHIUM_LEVEL2_PRIV = "-----BEGIN DILITHIUM_LEVEL2 PRIVATE KEY-----";
  20456. wcchar END_DILITHIUM_LEVEL2_PRIV = "-----END DILITHIUM_LEVEL2 PRIVATE KEY-----";
  20457. wcchar BEGIN_DILITHIUM_LEVEL3_PRIV = "-----BEGIN DILITHIUM_LEVEL3 PRIVATE KEY-----";
  20458. wcchar END_DILITHIUM_LEVEL3_PRIV = "-----END DILITHIUM_LEVEL3 PRIVATE KEY-----";
  20459. wcchar BEGIN_DILITHIUM_LEVEL5_PRIV = "-----BEGIN DILITHIUM_LEVEL5 PRIVATE KEY-----";
  20460. wcchar END_DILITHIUM_LEVEL5_PRIV = "-----END DILITHIUM_LEVEL5 PRIVATE KEY-----";
  20461. #endif /* HAVE_DILITHIUM */
  20462. #if defined(HAVE_SPHINCS)
  20463. wcchar BEGIN_SPHINCS_FAST_LEVEL1_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
  20464. wcchar END_SPHINCS_FAST_LEVEL1_PRIV = "-----END SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
  20465. wcchar BEGIN_SPHINCS_FAST_LEVEL3_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
  20466. wcchar END_SPHINCS_FAST_LEVEL3_PRIV = "-----END SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
  20467. wcchar BEGIN_SPHINCS_FAST_LEVEL5_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
  20468. wcchar END_SPHINCS_FAST_LEVEL5_PRIV = "-----END SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
  20469. wcchar BEGIN_SPHINCS_SMALL_LEVEL1_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
  20470. wcchar END_SPHINCS_SMALL_LEVEL1_PRIV = "-----END SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
  20471. wcchar BEGIN_SPHINCS_SMALL_LEVEL3_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
  20472. wcchar END_SPHINCS_SMALL_LEVEL3_PRIV = "-----END SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
  20473. wcchar BEGIN_SPHINCS_SMALL_LEVEL5_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
  20474. wcchar END_SPHINCS_SMALL_LEVEL5_PRIV = "-----END SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
  20475. #endif /* HAVE_SPHINCS */
  20476. #endif /* HAVE_PQC */
  20477. const int pem_struct_min_sz = XSTR_SIZEOF("-----BEGIN X509 CRL-----"
  20478. "-----END X509 CRL-----");
  20479. #ifdef WOLFSSL_PEM_TO_DER
  20480. static WC_INLINE const char* SkipEndOfLineChars(const char* line,
  20481. const char* endOfLine)
  20482. {
  20483. /* eat end of line characters */
  20484. while (line < endOfLine &&
  20485. (line[0] == '\r' || line[0] == '\n')) {
  20486. line++;
  20487. }
  20488. return line;
  20489. }
  20490. #endif
  20491. int wc_PemGetHeaderFooter(int type, const char** header, const char** footer)
  20492. {
  20493. int ret = BAD_FUNC_ARG;
  20494. switch (type) {
  20495. case CA_TYPE: /* same as below */
  20496. case TRUSTED_PEER_TYPE:
  20497. case CERT_TYPE:
  20498. if (header) *header = BEGIN_CERT;
  20499. if (footer) *footer = END_CERT;
  20500. ret = 0;
  20501. break;
  20502. case CRL_TYPE:
  20503. if (header) *header = BEGIN_X509_CRL;
  20504. if (footer) *footer = END_X509_CRL;
  20505. ret = 0;
  20506. break;
  20507. #ifndef NO_DH
  20508. case DH_PARAM_TYPE:
  20509. if (header) *header = BEGIN_DH_PARAM;
  20510. if (footer) *footer = END_DH_PARAM;
  20511. ret = 0;
  20512. break;
  20513. case X942_PARAM_TYPE:
  20514. if (header) *header = BEGIN_X942_PARAM;
  20515. if (footer) *footer = END_X942_PARAM;
  20516. ret = 0;
  20517. break;
  20518. #endif
  20519. #ifndef NO_DSA
  20520. case DSA_PARAM_TYPE:
  20521. if (header) *header = BEGIN_DSA_PARAM;
  20522. if (footer) *footer = END_DSA_PARAM;
  20523. ret = 0;
  20524. break;
  20525. #endif
  20526. #ifdef WOLFSSL_CERT_REQ
  20527. case CERTREQ_TYPE:
  20528. if (header) *header = BEGIN_CERT_REQ;
  20529. if (footer) *footer = END_CERT_REQ;
  20530. ret = 0;
  20531. break;
  20532. #endif
  20533. #ifndef NO_DSA
  20534. case DSA_TYPE:
  20535. case DSA_PRIVATEKEY_TYPE:
  20536. if (header) *header = BEGIN_DSA_PRIV;
  20537. if (footer) *footer = END_DSA_PRIV;
  20538. ret = 0;
  20539. break;
  20540. #endif
  20541. #ifdef HAVE_ECC
  20542. case ECC_TYPE:
  20543. case ECC_PRIVATEKEY_TYPE:
  20544. if (header) *header = BEGIN_EC_PRIV;
  20545. if (footer) *footer = END_EC_PRIV;
  20546. ret = 0;
  20547. break;
  20548. #ifdef OPENSSL_EXTRA
  20549. case ECC_PARAM_TYPE:
  20550. if (header) *header = BEGIN_EC_PARAM;
  20551. if (footer) *footer = END_EC_PARAM;
  20552. ret = 0;
  20553. break;
  20554. #endif
  20555. #endif
  20556. case RSA_TYPE:
  20557. case PRIVATEKEY_TYPE:
  20558. if (header) *header = BEGIN_RSA_PRIV;
  20559. if (footer) *footer = END_RSA_PRIV;
  20560. ret = 0;
  20561. break;
  20562. #ifdef HAVE_ED25519
  20563. case ED25519_TYPE:
  20564. #endif
  20565. #ifdef HAVE_ED448
  20566. case ED448_TYPE:
  20567. #endif
  20568. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  20569. case EDDSA_PRIVATEKEY_TYPE:
  20570. if (header) *header = BEGIN_EDDSA_PRIV;
  20571. if (footer) *footer = END_EDDSA_PRIV;
  20572. ret = 0;
  20573. break;
  20574. #endif
  20575. #ifdef HAVE_PQC
  20576. #ifdef HAVE_FALCON
  20577. case FALCON_LEVEL1_TYPE:
  20578. if (header) *header = BEGIN_FALCON_LEVEL1_PRIV;
  20579. if (footer) *footer = END_FALCON_LEVEL1_PRIV;
  20580. ret = 0;
  20581. break;
  20582. case FALCON_LEVEL5_TYPE:
  20583. if (header) *header = BEGIN_FALCON_LEVEL5_PRIV;
  20584. if (footer) *footer = END_FALCON_LEVEL5_PRIV;
  20585. ret = 0;
  20586. break;
  20587. #endif /* HAVE_FALCON */
  20588. #ifdef HAVE_DILITHIUM
  20589. case DILITHIUM_LEVEL2_TYPE:
  20590. if (header) *header = BEGIN_DILITHIUM_LEVEL2_PRIV;
  20591. if (footer) *footer = END_DILITHIUM_LEVEL2_PRIV;
  20592. ret = 0;
  20593. break;
  20594. case DILITHIUM_LEVEL3_TYPE:
  20595. if (header) *header = BEGIN_DILITHIUM_LEVEL3_PRIV;
  20596. if (footer) *footer = END_DILITHIUM_LEVEL3_PRIV;
  20597. ret = 0;
  20598. break;
  20599. case DILITHIUM_LEVEL5_TYPE:
  20600. if (header) *header = BEGIN_DILITHIUM_LEVEL5_PRIV;
  20601. if (footer) *footer = END_DILITHIUM_LEVEL5_PRIV;
  20602. ret = 0;
  20603. break;
  20604. #endif /* HAVE_DILITHIUM */
  20605. #ifdef HAVE_SPHINCS
  20606. case SPHINCS_FAST_LEVEL1_TYPE:
  20607. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL1_PRIV;
  20608. if (footer) *footer = END_SPHINCS_FAST_LEVEL1_PRIV;
  20609. ret = 0;
  20610. break;
  20611. case SPHINCS_FAST_LEVEL3_TYPE:
  20612. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL3_PRIV;
  20613. if (footer) *footer = END_SPHINCS_FAST_LEVEL3_PRIV;
  20614. ret = 0;
  20615. break;
  20616. case SPHINCS_FAST_LEVEL5_TYPE:
  20617. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL5_PRIV;
  20618. if (footer) *footer = END_SPHINCS_FAST_LEVEL5_PRIV;
  20619. ret = 0;
  20620. break;
  20621. case SPHINCS_SMALL_LEVEL1_TYPE:
  20622. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL1_PRIV;
  20623. if (footer) *footer = END_SPHINCS_SMALL_LEVEL1_PRIV;
  20624. ret = 0;
  20625. break;
  20626. case SPHINCS_SMALL_LEVEL3_TYPE:
  20627. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL3_PRIV;
  20628. if (footer) *footer = END_SPHINCS_SMALL_LEVEL3_PRIV;
  20629. ret = 0;
  20630. break;
  20631. case SPHINCS_SMALL_LEVEL5_TYPE:
  20632. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL5_PRIV;
  20633. if (footer) *footer = END_SPHINCS_SMALL_LEVEL5_PRIV;
  20634. ret = 0;
  20635. break;
  20636. #endif /* HAVE_SPHINCS */
  20637. #endif /* HAVE_PQC */
  20638. case PUBLICKEY_TYPE:
  20639. case ECC_PUBLICKEY_TYPE:
  20640. if (header) *header = BEGIN_PUB_KEY;
  20641. if (footer) *footer = END_PUB_KEY;
  20642. ret = 0;
  20643. break;
  20644. case RSA_PUBLICKEY_TYPE:
  20645. if (header) *header = BEGIN_RSA_PUB;
  20646. if (footer) *footer = END_RSA_PUB;
  20647. ret = 0;
  20648. break;
  20649. #ifndef NO_DH
  20650. case DH_PRIVATEKEY_TYPE:
  20651. #endif
  20652. case PKCS8_PRIVATEKEY_TYPE:
  20653. if (header) *header = BEGIN_PRIV_KEY;
  20654. if (footer) *footer = END_PRIV_KEY;
  20655. ret = 0;
  20656. break;
  20657. case PKCS8_ENC_PRIVATEKEY_TYPE:
  20658. if (header) *header = BEGIN_ENC_PRIV_KEY;
  20659. if (footer) *footer = END_ENC_PRIV_KEY;
  20660. ret = 0;
  20661. break;
  20662. default:
  20663. break;
  20664. }
  20665. return ret;
  20666. }
  20667. #ifdef WOLFSSL_ENCRYPTED_KEYS
  20668. static wcchar kProcTypeHeader = "Proc-Type";
  20669. static wcchar kDecInfoHeader = "DEK-Info";
  20670. #ifdef WOLFSSL_PEM_TO_DER
  20671. #ifndef NO_DES3
  20672. static wcchar kEncTypeDes = "DES-CBC";
  20673. static wcchar kEncTypeDes3 = "DES-EDE3-CBC";
  20674. #endif
  20675. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  20676. static wcchar kEncTypeAesCbc128 = "AES-128-CBC";
  20677. #endif
  20678. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  20679. static wcchar kEncTypeAesCbc192 = "AES-192-CBC";
  20680. #endif
  20681. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  20682. static wcchar kEncTypeAesCbc256 = "AES-256-CBC";
  20683. #endif
  20684. int wc_EncryptedInfoGet(EncryptedInfo* info, const char* cipherInfo)
  20685. {
  20686. int ret = 0;
  20687. if (info == NULL || cipherInfo == NULL)
  20688. return BAD_FUNC_ARG;
  20689. /* determine cipher information */
  20690. #ifndef NO_DES3
  20691. if (XSTRCMP(cipherInfo, kEncTypeDes) == 0) {
  20692. info->cipherType = WC_CIPHER_DES;
  20693. info->keySz = DES_KEY_SIZE;
  20694. /* DES_IV_SIZE is incorrectly 16 in FIPS v2. It should be 8, same as the
  20695. * block size. */
  20696. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  20697. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  20698. #else
  20699. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  20700. #endif
  20701. }
  20702. else if (XSTRCMP(cipherInfo, kEncTypeDes3) == 0) {
  20703. info->cipherType = WC_CIPHER_DES3;
  20704. info->keySz = DES3_KEY_SIZE;
  20705. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  20706. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  20707. #else
  20708. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  20709. #endif
  20710. }
  20711. else
  20712. #endif /* !NO_DES3 */
  20713. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  20714. if (XSTRCMP(cipherInfo, kEncTypeAesCbc128) == 0) {
  20715. info->cipherType = WC_CIPHER_AES_CBC;
  20716. info->keySz = AES_128_KEY_SIZE;
  20717. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  20718. }
  20719. else
  20720. #endif
  20721. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  20722. if (XSTRCMP(cipherInfo, kEncTypeAesCbc192) == 0) {
  20723. info->cipherType = WC_CIPHER_AES_CBC;
  20724. info->keySz = AES_192_KEY_SIZE;
  20725. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  20726. }
  20727. else
  20728. #endif
  20729. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  20730. if (XSTRCMP(cipherInfo, kEncTypeAesCbc256) == 0) {
  20731. info->cipherType = WC_CIPHER_AES_CBC;
  20732. info->keySz = AES_256_KEY_SIZE;
  20733. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  20734. }
  20735. else
  20736. #endif
  20737. {
  20738. ret = NOT_COMPILED_IN;
  20739. }
  20740. return ret;
  20741. }
  20742. int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer,
  20743. size_t bufSz)
  20744. {
  20745. int err = 0;
  20746. const char* bufferStart;
  20747. const char* bufferEnd;
  20748. char* line;
  20749. if (info == NULL || pBuffer == NULL || bufSz == 0)
  20750. return BAD_FUNC_ARG;
  20751. bufferStart = *pBuffer;
  20752. bufferEnd = bufferStart + bufSz;
  20753. /* find encrypted info marker */
  20754. line = XSTRNSTR(bufferStart, kProcTypeHeader,
  20755. min((word32)bufSz, PEM_LINE_LEN));
  20756. if (line != NULL) {
  20757. word32 lineSz;
  20758. char* finish;
  20759. word32 finishSz;
  20760. char* start;
  20761. word32 startSz;
  20762. const char* newline = NULL;
  20763. if (line >= bufferEnd) {
  20764. return BUFFER_E;
  20765. }
  20766. lineSz = (word32)(bufferEnd - line);
  20767. /* find DEC-Info marker */
  20768. start = XSTRNSTR(line, kDecInfoHeader, min(lineSz, PEM_LINE_LEN));
  20769. if (start == NULL)
  20770. return BUFFER_E;
  20771. /* skip dec-info and ": " */
  20772. start += XSTRLEN(kDecInfoHeader);
  20773. if (start >= bufferEnd)
  20774. return BUFFER_E;
  20775. if (start[0] == ':') {
  20776. start++;
  20777. if (start >= bufferEnd)
  20778. return BUFFER_E;
  20779. }
  20780. if (start[0] == ' ')
  20781. start++;
  20782. startSz = (word32)(bufferEnd - start);
  20783. finish = XSTRNSTR(start, ",", min(startSz, PEM_LINE_LEN));
  20784. if ((start != NULL) && (finish != NULL) && (start < finish)) {
  20785. if (finish >= bufferEnd) {
  20786. return BUFFER_E;
  20787. }
  20788. finishSz = (word32)(bufferEnd - finish);
  20789. newline = XSTRNSTR(finish, "\r", min(finishSz, PEM_LINE_LEN));
  20790. /* get cipher name */
  20791. if (NAME_SZ < (finish - start)) /* buffer size of info->name */
  20792. return BUFFER_E;
  20793. if (XMEMCPY(info->name, start, (size_t)(finish - start)) == NULL)
  20794. return BUFFER_E;
  20795. info->name[finish - start] = '\0'; /* null term */
  20796. /* populate info */
  20797. err = wc_EncryptedInfoGet(info, info->name);
  20798. if (err != 0)
  20799. return err;
  20800. /* get IV */
  20801. if (finishSz < info->ivSz + 1)
  20802. return BUFFER_E;
  20803. if (newline == NULL) {
  20804. newline = XSTRNSTR(finish, "\n", min(finishSz,
  20805. PEM_LINE_LEN));
  20806. }
  20807. if ((newline != NULL) && (newline > finish)) {
  20808. finish++;
  20809. info->ivSz = (word32)(newline - finish);
  20810. if (info->ivSz > IV_SZ)
  20811. return BUFFER_E;
  20812. if (XMEMCPY(info->iv, finish, info->ivSz) == NULL)
  20813. return BUFFER_E;
  20814. info->set = 1;
  20815. }
  20816. else
  20817. return BUFFER_E;
  20818. }
  20819. else
  20820. return BUFFER_E;
  20821. /* eat end of line characters */
  20822. newline = SkipEndOfLineChars(newline, bufferEnd);
  20823. /* return new headerEnd */
  20824. *pBuffer = newline;
  20825. }
  20826. return err;
  20827. }
  20828. #endif /* WOLFSSL_PEM_TO_DER */
  20829. #ifdef WOLFSSL_DER_TO_PEM
  20830. static int wc_EncryptedInfoAppend(char* dest, int destSz, char* cipherInfo)
  20831. {
  20832. if (cipherInfo != NULL) {
  20833. int cipherInfoStrLen = (int)XSTRLEN((char*)cipherInfo);
  20834. if (cipherInfoStrLen > HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3))
  20835. cipherInfoStrLen = HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3);
  20836. if (destSz - (int)XSTRLEN(dest) >= cipherInfoStrLen + (9+14+8+2+2+1)) {
  20837. /* strncat's src length needs to include the NULL */
  20838. XSTRNCAT(dest, kProcTypeHeader, 10);
  20839. XSTRNCAT(dest, ": 4,ENCRYPTED\n", 15);
  20840. XSTRNCAT(dest, kDecInfoHeader, 9);
  20841. XSTRNCAT(dest, ": ", 3);
  20842. XSTRNCAT(dest, cipherInfo, (size_t)destSz - XSTRLEN(dest) - 1);
  20843. XSTRNCAT(dest, "\n\n", 4);
  20844. }
  20845. }
  20846. return 0;
  20847. }
  20848. #endif /* WOLFSSL_DER_TO_PEM */
  20849. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  20850. #ifdef WOLFSSL_DER_TO_PEM
  20851. /* Used for compatibility API */
  20852. WOLFSSL_ABI
  20853. int wc_DerToPem(const byte* der, word32 derSz,
  20854. byte* output, word32 outSz, int type)
  20855. {
  20856. return wc_DerToPemEx(der, derSz, output, outSz, NULL, type);
  20857. }
  20858. /* convert der buffer to pem into output, can't do inplace, der and output
  20859. need to be different */
  20860. int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz,
  20861. byte *cipher_info, int type)
  20862. {
  20863. const char* headerStr = NULL;
  20864. const char* footerStr = NULL;
  20865. #ifdef WOLFSSL_SMALL_STACK
  20866. char* header = NULL;
  20867. char* footer = NULL;
  20868. #else
  20869. char header[MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE];
  20870. char footer[MAX_X509_HEADER_SZ];
  20871. #endif
  20872. int headerLen = MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE;
  20873. int footerLen = MAX_X509_HEADER_SZ;
  20874. int i;
  20875. int err;
  20876. int outLen; /* return length or error */
  20877. (void)cipher_info;
  20878. if (der == output) /* no in place conversion */
  20879. return BAD_FUNC_ARG;
  20880. err = wc_PemGetHeaderFooter(type, &headerStr, &footerStr);
  20881. if (err != 0)
  20882. return err;
  20883. #ifdef WOLFSSL_SMALL_STACK
  20884. header = (char*)XMALLOC(headerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20885. if (header == NULL)
  20886. return MEMORY_E;
  20887. footer = (char*)XMALLOC(footerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20888. if (footer == NULL) {
  20889. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20890. return MEMORY_E;
  20891. }
  20892. #endif
  20893. /* build header and footer based on type */
  20894. XSTRNCPY(header, headerStr, (size_t)headerLen - 1);
  20895. header[headerLen - 2] = 0;
  20896. XSTRNCPY(footer, footerStr, (size_t)footerLen - 1);
  20897. footer[footerLen - 2] = 0;
  20898. /* add new line to end */
  20899. XSTRNCAT(header, "\n", 2);
  20900. XSTRNCAT(footer, "\n", 2);
  20901. #ifdef WOLFSSL_ENCRYPTED_KEYS
  20902. err = wc_EncryptedInfoAppend(header, headerLen, (char*)cipher_info);
  20903. if (err != 0) {
  20904. #ifdef WOLFSSL_SMALL_STACK
  20905. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20906. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20907. #endif
  20908. return err;
  20909. }
  20910. #endif
  20911. headerLen = (int)XSTRLEN(header);
  20912. footerLen = (int)XSTRLEN(footer);
  20913. /* if null output and 0 size passed in then return size needed */
  20914. if (!output && outSz == 0) {
  20915. #ifdef WOLFSSL_SMALL_STACK
  20916. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20917. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20918. #endif
  20919. outLen = 0;
  20920. if ((err = Base64_Encode(der, derSz, NULL, (word32*)&outLen))
  20921. != LENGTH_ONLY_E) {
  20922. WOLFSSL_ERROR_VERBOSE(err);
  20923. return err;
  20924. }
  20925. return headerLen + footerLen + outLen;
  20926. }
  20927. if (!der || !output) {
  20928. #ifdef WOLFSSL_SMALL_STACK
  20929. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20930. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20931. #endif
  20932. return BAD_FUNC_ARG;
  20933. }
  20934. /* don't even try if outSz too short */
  20935. if (outSz < (word32)headerLen + (word32)footerLen + derSz) {
  20936. #ifdef WOLFSSL_SMALL_STACK
  20937. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20938. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20939. #endif
  20940. return BAD_FUNC_ARG;
  20941. }
  20942. /* header */
  20943. XMEMCPY(output, header, (size_t)headerLen);
  20944. i = headerLen;
  20945. #ifdef WOLFSSL_SMALL_STACK
  20946. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20947. #endif
  20948. /* body */
  20949. outLen = (int)outSz - (headerLen + footerLen); /* input to Base64_Encode */
  20950. if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0) {
  20951. #ifdef WOLFSSL_SMALL_STACK
  20952. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20953. #endif
  20954. WOLFSSL_ERROR_VERBOSE(err);
  20955. return err;
  20956. }
  20957. i += outLen;
  20958. /* footer */
  20959. if ( (i + footerLen) > (int)outSz) {
  20960. #ifdef WOLFSSL_SMALL_STACK
  20961. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20962. #endif
  20963. return BAD_FUNC_ARG;
  20964. }
  20965. XMEMCPY(output + i, footer, (size_t)footerLen);
  20966. #ifdef WOLFSSL_SMALL_STACK
  20967. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20968. #endif
  20969. return outLen + headerLen + footerLen;
  20970. }
  20971. #endif /* WOLFSSL_DER_TO_PEM */
  20972. #ifdef WOLFSSL_PEM_TO_DER
  20973. /* Remove PEM header/footer, convert to ASN1, store any encrypted data
  20974. info->consumed tracks of PEM bytes consumed in case multiple parts */
  20975. int PemToDer(const unsigned char* buff, long longSz, int type,
  20976. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  20977. {
  20978. const char* header = NULL;
  20979. const char* footer = NULL;
  20980. const char* headerEnd;
  20981. const char* footerEnd;
  20982. const char* consumedEnd;
  20983. const char* bufferEnd = (const char*)(buff + longSz);
  20984. long neededSz;
  20985. int ret = 0;
  20986. int sz = (int)longSz;
  20987. int encrypted_key = 0;
  20988. DerBuffer* der;
  20989. word32 algId = 0;
  20990. word32 idx;
  20991. #ifdef OPENSSL_EXTRA
  20992. char beginBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  20993. char endBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  20994. #endif
  20995. WOLFSSL_ENTER("PemToDer");
  20996. /* get PEM header and footer based on type */
  20997. ret = wc_PemGetHeaderFooter(type, &header, &footer);
  20998. if (ret != 0)
  20999. return ret;
  21000. /* map header if not found for type */
  21001. for (;;) {
  21002. headerEnd = XSTRNSTR((char*)buff, header, (word32)sz);
  21003. if (headerEnd) {
  21004. break;
  21005. }
  21006. if (type == PRIVATEKEY_TYPE) {
  21007. if (header == BEGIN_RSA_PRIV) {
  21008. header = BEGIN_PRIV_KEY;
  21009. footer = END_PRIV_KEY;
  21010. }
  21011. else if (header == BEGIN_PRIV_KEY) {
  21012. header = BEGIN_ENC_PRIV_KEY;
  21013. footer = END_ENC_PRIV_KEY;
  21014. }
  21015. #ifdef HAVE_ECC
  21016. else if (header == BEGIN_ENC_PRIV_KEY) {
  21017. header = BEGIN_EC_PRIV;
  21018. footer = END_EC_PRIV;
  21019. }
  21020. else if (header == BEGIN_EC_PRIV) {
  21021. header = BEGIN_DSA_PRIV;
  21022. footer = END_DSA_PRIV;
  21023. }
  21024. #endif
  21025. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  21026. #ifdef HAVE_ECC
  21027. else if (header == BEGIN_DSA_PRIV) {
  21028. #else
  21029. else if (header == BEGIN_ENC_PRIV_KEY) {
  21030. #endif
  21031. header = BEGIN_EDDSA_PRIV;
  21032. footer = END_EDDSA_PRIV;
  21033. }
  21034. #endif
  21035. else {
  21036. #ifdef WOLF_PRIVATE_KEY_ID
  21037. /* allow loading a public key for use with crypto or PK callbacks */
  21038. type = PUBLICKEY_TYPE;
  21039. header = BEGIN_PUB_KEY;
  21040. footer = END_PUB_KEY;
  21041. #else
  21042. break;
  21043. #endif
  21044. }
  21045. }
  21046. else if (type == PUBLICKEY_TYPE) {
  21047. if (header == BEGIN_PUB_KEY) {
  21048. header = BEGIN_RSA_PUB;
  21049. footer = END_RSA_PUB;
  21050. }
  21051. else {
  21052. break;
  21053. }
  21054. }
  21055. #if defined(HAVE_ECC) && defined(OPENSSL_EXTRA)
  21056. else if (type == ECC_PARAM_TYPE) {
  21057. if (header == BEGIN_EC_PARAM) {
  21058. header = BEGIN_EC_PARAM;
  21059. footer = END_EC_PARAM;
  21060. }
  21061. else {
  21062. break;
  21063. }
  21064. }
  21065. #endif
  21066. #ifdef HAVE_CRL
  21067. else if ((type == CRL_TYPE) && (header != BEGIN_X509_CRL)) {
  21068. header = BEGIN_X509_CRL;
  21069. footer = END_X509_CRL;
  21070. }
  21071. #endif
  21072. else {
  21073. break;
  21074. }
  21075. }
  21076. if (!headerEnd) {
  21077. #ifdef OPENSSL_EXTRA
  21078. if (type == PRIVATEKEY_TYPE) {
  21079. /* see if there is a -----BEGIN * PRIVATE KEY----- header */
  21080. headerEnd = XSTRNSTR((char*)buff, PRIV_KEY_SUFFIX, sz);
  21081. if (headerEnd) {
  21082. const char* beginEnd;
  21083. int endLen;
  21084. beginEnd = headerEnd + XSTR_SIZEOF(PRIV_KEY_SUFFIX);
  21085. if (beginEnd >= (char*)buff + sz) {
  21086. return BUFFER_E;
  21087. }
  21088. /* back up to BEGIN_PRIV_KEY_PREFIX */
  21089. while (headerEnd > (char*)buff &&
  21090. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  21091. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 &&
  21092. *headerEnd != '\n') {
  21093. headerEnd--;
  21094. }
  21095. if (headerEnd <= (char*)buff ||
  21096. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  21097. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 ||
  21098. beginEnd - headerEnd > PEM_LINE_LEN) {
  21099. WOLFSSL_MSG("Couldn't find PEM header");
  21100. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21101. return ASN_NO_PEM_HEADER;
  21102. }
  21103. /* headerEnd now points to beginning of header */
  21104. XMEMCPY(beginBuf, headerEnd, beginEnd - headerEnd);
  21105. beginBuf[beginEnd - headerEnd] = '\0';
  21106. /* look for matching footer */
  21107. footer = XSTRNSTR(beginEnd,
  21108. beginBuf + XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX),
  21109. (unsigned int)((char*)buff + sz - beginEnd));
  21110. if (!footer) {
  21111. WOLFSSL_MSG("Couldn't find PEM footer");
  21112. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21113. return ASN_NO_PEM_HEADER;
  21114. }
  21115. footer -= XSTR_SIZEOF(END_PRIV_KEY_PREFIX);
  21116. if (footer > (char*)buff + sz - XSTR_SIZEOF(END_PRIV_KEY_PREFIX)
  21117. || XSTRNCMP(footer, END_PRIV_KEY_PREFIX,
  21118. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)) != 0) {
  21119. WOLFSSL_MSG("Unexpected footer for PEM");
  21120. return BUFFER_E;
  21121. }
  21122. endLen = (unsigned int)(beginEnd - headerEnd -
  21123. (XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX) -
  21124. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)));
  21125. XMEMCPY(endBuf, footer, endLen);
  21126. endBuf[endLen] = '\0';
  21127. header = beginBuf;
  21128. footer = endBuf;
  21129. headerEnd = beginEnd;
  21130. }
  21131. }
  21132. if (!headerEnd) {
  21133. WOLFSSL_MSG("Couldn't find PEM header");
  21134. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21135. return ASN_NO_PEM_HEADER;
  21136. }
  21137. #else
  21138. WOLFSSL_MSG("Couldn't find PEM header");
  21139. return ASN_NO_PEM_HEADER;
  21140. #endif
  21141. } else {
  21142. headerEnd += XSTRLEN(header);
  21143. }
  21144. /* eat end of line characters */
  21145. headerEnd = SkipEndOfLineChars(headerEnd, bufferEnd);
  21146. if (keyFormat) {
  21147. /* keyFormat is Key_Sum enum */
  21148. if (type == PRIVATEKEY_TYPE) {
  21149. #ifndef NO_RSA
  21150. if (header == BEGIN_RSA_PRIV)
  21151. *keyFormat = RSAk;
  21152. #endif
  21153. #ifdef HAVE_ECC
  21154. if (header == BEGIN_EC_PRIV)
  21155. *keyFormat = ECDSAk;
  21156. #endif
  21157. #ifndef NO_DSA
  21158. if (header == BEGIN_DSA_PRIV)
  21159. *keyFormat = DSAk;
  21160. #endif
  21161. }
  21162. #ifdef WOLF_PRIVATE_KEY_ID
  21163. else if (type == PUBLICKEY_TYPE) {
  21164. #ifndef NO_RSA
  21165. if (header == BEGIN_RSA_PUB)
  21166. *keyFormat = RSAk;
  21167. #endif
  21168. }
  21169. #endif
  21170. }
  21171. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21172. if (info) {
  21173. ret = wc_EncryptedInfoParse(info, &headerEnd,
  21174. (size_t)(bufferEnd - headerEnd));
  21175. if (ret < 0)
  21176. return ret;
  21177. if (info->set)
  21178. encrypted_key = 1;
  21179. }
  21180. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  21181. /* find footer */
  21182. footerEnd = XSTRNSTR(headerEnd, footer, (unsigned int)((char*)buff +
  21183. sz - headerEnd));
  21184. if (!footerEnd) {
  21185. if (info)
  21186. info->consumed = longSz; /* No more certs if no footer */
  21187. return BUFFER_E;
  21188. }
  21189. consumedEnd = footerEnd + XSTRLEN(footer);
  21190. if (consumedEnd < bufferEnd) { /* handle no end of line on last line */
  21191. /* eat end of line characters */
  21192. consumedEnd = SkipEndOfLineChars(consumedEnd, bufferEnd);
  21193. /* skip possible null term */
  21194. if (consumedEnd < bufferEnd && consumedEnd[0] == '\0')
  21195. consumedEnd++;
  21196. }
  21197. if (info)
  21198. info->consumed = (long)(consumedEnd - (const char*)buff);
  21199. /* set up der buffer */
  21200. neededSz = (long)(footerEnd - headerEnd);
  21201. if (neededSz > sz || neededSz <= 0)
  21202. return BUFFER_E;
  21203. ret = AllocDer(pDer, (word32)neededSz, type, heap);
  21204. if (ret < 0) {
  21205. return ret;
  21206. }
  21207. der = *pDer;
  21208. if (Base64_Decode((byte*)headerEnd, (word32)neededSz,
  21209. der->buffer, &der->length) < 0) {
  21210. WOLFSSL_ERROR(BUFFER_E);
  21211. return BUFFER_E;
  21212. }
  21213. if ((header == BEGIN_PRIV_KEY
  21214. #ifdef OPENSSL_EXTRA
  21215. || header == beginBuf
  21216. #endif
  21217. #ifdef HAVE_ECC
  21218. || header == BEGIN_EC_PRIV
  21219. #endif
  21220. ) && !encrypted_key)
  21221. {
  21222. /* detect pkcs8 key and get alg type */
  21223. /* keep PKCS8 header */
  21224. idx = 0;
  21225. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length, &algId);
  21226. if (ret > 0) {
  21227. if (keyFormat)
  21228. *keyFormat = (int)algId;
  21229. }
  21230. else {
  21231. /* ignore failure here and assume key is not pkcs8 wrapped */
  21232. }
  21233. return 0;
  21234. }
  21235. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21236. if (encrypted_key || header == BEGIN_ENC_PRIV_KEY) {
  21237. int passwordSz = NAME_SZ;
  21238. #ifdef WOLFSSL_SMALL_STACK
  21239. char* password = NULL;
  21240. #else
  21241. char password[NAME_SZ];
  21242. #endif
  21243. if (!info || !info->passwd_cb) {
  21244. WOLFSSL_MSG("No password callback set");
  21245. WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
  21246. return NO_PASSWORD;
  21247. }
  21248. #ifdef WOLFSSL_SMALL_STACK
  21249. password = (char*)XMALLOC(passwordSz, heap, DYNAMIC_TYPE_STRING);
  21250. if (password == NULL) {
  21251. return MEMORY_E;
  21252. }
  21253. #endif
  21254. /* get password */
  21255. ret = info->passwd_cb(password, passwordSz, PEM_PASS_READ,
  21256. info->passwd_userdata);
  21257. if (ret >= 0) {
  21258. passwordSz = ret;
  21259. #ifdef WOLFSSL_CHECK_MEM_ZERO
  21260. wc_MemZero_Add("PEM password", password, passwordSz);
  21261. #endif
  21262. /* convert and adjust length */
  21263. if (header == BEGIN_ENC_PRIV_KEY) {
  21264. #ifndef NO_PWDBASED
  21265. ret = wc_DecryptPKCS8Key(der->buffer, der->length,
  21266. password, passwordSz);
  21267. if (ret > 0) {
  21268. /* update length by decrypted content */
  21269. der->length = (word32)ret;
  21270. idx = 0;
  21271. /* detect pkcs8 key and get alg type */
  21272. /* keep PKCS8 header */
  21273. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length,
  21274. &algId);
  21275. if (ret >= 0) {
  21276. if (keyFormat)
  21277. *keyFormat = (int)algId;
  21278. ret = 0;
  21279. }
  21280. }
  21281. #else
  21282. WOLFSSL_ERROR_VERBOSE(NOT_COMPILED_IN);
  21283. ret = NOT_COMPILED_IN;
  21284. #endif
  21285. }
  21286. /* decrypt the key */
  21287. else {
  21288. if (passwordSz == 0) {
  21289. /* The key is encrypted but does not have a password */
  21290. WOLFSSL_MSG("No password for encrypted key");
  21291. WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
  21292. ret = NO_PASSWORD;
  21293. }
  21294. else {
  21295. #if ((defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_DES3)) || \
  21296. (!defined(NO_AES) && defined(HAVE_AES_CBC) && \
  21297. defined(HAVE_AES_DECRYPT))) && \
  21298. !defined(NO_WOLFSSL_SKIP_TRAILING_PAD)
  21299. int padVal = 0;
  21300. #endif
  21301. ret = wc_BufferKeyDecrypt(info, der->buffer, der->length,
  21302. (byte*)password, passwordSz, WC_MD5);
  21303. #ifndef NO_WOLFSSL_SKIP_TRAILING_PAD
  21304. #ifndef NO_DES3
  21305. if (info->cipherType == WC_CIPHER_DES3) {
  21306. /* Assuming there is padding:
  21307. * (der->length > 0 && der->length > DES_BLOCK_SIZE &&
  21308. * (der->length % DES_BLOCK_SIZE) != 0)
  21309. * and assuming the last value signifies the number of
  21310. * padded bytes IE if last value is 0x08 then there are
  21311. * 8 bytes of padding:
  21312. * padVal = der->buffer[der->length-1];
  21313. * then strip this padding before proceeding:
  21314. * der->length -= padVal;
  21315. */
  21316. if (der->length > DES_BLOCK_SIZE &&
  21317. (der->length % DES_BLOCK_SIZE) != 0) {
  21318. padVal = der->buffer[der->length-1];
  21319. if (padVal < DES_BLOCK_SIZE) {
  21320. der->length -= (word32)padVal;
  21321. }
  21322. }
  21323. }
  21324. #endif /* !NO_DES3 */
  21325. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && \
  21326. defined(HAVE_AES_DECRYPT)
  21327. if (info->cipherType == WC_CIPHER_AES_CBC) {
  21328. if (der->length > AES_BLOCK_SIZE) {
  21329. padVal = der->buffer[der->length-1];
  21330. if (padVal <= AES_BLOCK_SIZE) {
  21331. der->length -= (word32)padVal;
  21332. }
  21333. }
  21334. }
  21335. #endif
  21336. #endif /* !NO_WOLFSSL_SKIP_TRAILING_PAD */
  21337. }
  21338. }
  21339. #ifdef OPENSSL_EXTRA
  21340. if (ret) {
  21341. PEMerr(0, PEM_R_BAD_DECRYPT);
  21342. }
  21343. #endif
  21344. ForceZero(password, (word32)passwordSz);
  21345. }
  21346. #ifdef OPENSSL_EXTRA
  21347. else {
  21348. PEMerr(0, PEM_R_BAD_PASSWORD_READ);
  21349. }
  21350. #endif
  21351. #ifdef WOLFSSL_SMALL_STACK
  21352. XFREE(password, heap, DYNAMIC_TYPE_STRING);
  21353. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  21354. wc_MemZero_Check(password, NAME_SZ);
  21355. #endif
  21356. }
  21357. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  21358. return ret;
  21359. }
  21360. int wc_PemToDer(const unsigned char* buff, long longSz, int type,
  21361. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  21362. {
  21363. int ret = PemToDer(buff, longSz, type, pDer, heap, info, keyFormat);
  21364. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  21365. if (ret == 0 && type == PRIVATEKEY_TYPE) {
  21366. DerBuffer* der = *pDer;
  21367. /* if a PKCS8 key header exists remove it */
  21368. ret = ToTraditional(der->buffer, der->length);
  21369. if (ret > 0) {
  21370. der->length = (word32)ret;
  21371. }
  21372. ret = 0; /* ignore error removing PKCS8 header */
  21373. }
  21374. #endif
  21375. return ret;
  21376. }
  21377. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21378. /* our KeyPemToDer password callback, password in userData */
  21379. static int KeyPemToDerPassCb(char* passwd, int sz, int rw, void* userdata)
  21380. {
  21381. (void)rw;
  21382. if (userdata == NULL)
  21383. return 0;
  21384. XSTRNCPY(passwd, (char*)userdata, (size_t)sz);
  21385. return (int)min((word32)sz, (word32)XSTRLEN((char*)userdata));
  21386. }
  21387. #endif
  21388. /* Return bytes written to buff or < 0 for error */
  21389. int wc_KeyPemToDer(const unsigned char* pem, int pemSz,
  21390. unsigned char* buff, int buffSz, const char* pass)
  21391. {
  21392. int ret;
  21393. DerBuffer* der = NULL;
  21394. #ifdef WOLFSSL_SMALL_STACK
  21395. EncryptedInfo* info = NULL;
  21396. #else
  21397. EncryptedInfo info[1];
  21398. #endif
  21399. WOLFSSL_ENTER("wc_KeyPemToDer");
  21400. if (pem == NULL || (buff != NULL && buffSz <= 0)) {
  21401. WOLFSSL_MSG("Bad pem der args");
  21402. return BAD_FUNC_ARG;
  21403. }
  21404. #ifdef WOLFSSL_SMALL_STACK
  21405. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  21406. DYNAMIC_TYPE_ENCRYPTEDINFO);
  21407. if (info == NULL)
  21408. return MEMORY_E;
  21409. #endif
  21410. XMEMSET(info, 0, sizeof(EncryptedInfo));
  21411. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21412. info->passwd_cb = KeyPemToDerPassCb;
  21413. info->passwd_userdata = (void*)pass;
  21414. #else
  21415. (void)pass;
  21416. #endif
  21417. ret = PemToDer(pem, pemSz, PRIVATEKEY_TYPE, &der, NULL, info, NULL);
  21418. #ifdef WOLFSSL_SMALL_STACK
  21419. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  21420. #endif
  21421. if (ret < 0 || der == NULL) {
  21422. WOLFSSL_MSG("Bad Pem To Der");
  21423. }
  21424. else if (buff == NULL) {
  21425. WOLFSSL_MSG("Return needed der buff length");
  21426. ret = (int)der->length;
  21427. }
  21428. else if (der->length <= (word32)buffSz) {
  21429. XMEMCPY(buff, der->buffer, der->length);
  21430. ret = (int)der->length;
  21431. }
  21432. else {
  21433. WOLFSSL_MSG("Bad der length");
  21434. ret = BAD_FUNC_ARG;
  21435. }
  21436. FreeDer(&der);
  21437. return ret;
  21438. }
  21439. /* Return bytes written to buff or < 0 for error */
  21440. int wc_CertPemToDer(const unsigned char* pem, int pemSz,
  21441. unsigned char* buff, int buffSz, int type)
  21442. {
  21443. int ret;
  21444. DerBuffer* der = NULL;
  21445. WOLFSSL_ENTER("wc_CertPemToDer");
  21446. if (pem == NULL || buff == NULL || buffSz <= 0) {
  21447. WOLFSSL_MSG("Bad pem der args");
  21448. return BAD_FUNC_ARG;
  21449. }
  21450. if (type != CERT_TYPE && type != CA_TYPE && type != CERTREQ_TYPE) {
  21451. WOLFSSL_MSG("Bad cert type");
  21452. return BAD_FUNC_ARG;
  21453. }
  21454. ret = PemToDer(pem, pemSz, type, &der, NULL, NULL, NULL);
  21455. if (ret < 0 || der == NULL) {
  21456. WOLFSSL_MSG("Bad Pem To Der");
  21457. }
  21458. else {
  21459. if (der->length <= (word32)buffSz) {
  21460. XMEMCPY(buff, der->buffer, der->length);
  21461. ret = (int)der->length;
  21462. }
  21463. else {
  21464. WOLFSSL_MSG("Bad der length");
  21465. ret = BAD_FUNC_ARG;
  21466. }
  21467. }
  21468. FreeDer(&der);
  21469. return ret;
  21470. }
  21471. #endif /* WOLFSSL_PEM_TO_DER */
  21472. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  21473. #ifdef WOLFSSL_PEM_TO_DER
  21474. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  21475. /* Return bytes written to buff, needed buff size if buff is NULL, or less than
  21476. zero for error */
  21477. int wc_PubKeyPemToDer(const unsigned char* pem, int pemSz,
  21478. unsigned char* buff, int buffSz)
  21479. {
  21480. int ret;
  21481. DerBuffer* der = NULL;
  21482. WOLFSSL_ENTER("wc_PubKeyPemToDer");
  21483. if (pem == NULL || (buff != NULL && buffSz <= 0)) {
  21484. WOLFSSL_MSG("Bad pem der args");
  21485. return BAD_FUNC_ARG;
  21486. }
  21487. ret = PemToDer(pem, pemSz, PUBLICKEY_TYPE, &der, NULL, NULL, NULL);
  21488. if (ret < 0 || der == NULL) {
  21489. WOLFSSL_MSG("Bad Pem To Der");
  21490. }
  21491. else if (buff == NULL) {
  21492. WOLFSSL_MSG("Return needed der buff length");
  21493. ret = (int)der->length;
  21494. }
  21495. else if (der->length <= (word32)buffSz) {
  21496. XMEMCPY(buff, der->buffer, der->length);
  21497. ret = (int)der->length;
  21498. }
  21499. else {
  21500. WOLFSSL_MSG("Bad der length");
  21501. ret = BAD_FUNC_ARG;
  21502. }
  21503. FreeDer(&der);
  21504. return ret;
  21505. }
  21506. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  21507. #endif /* WOLFSSL_PEM_TO_DER */
  21508. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_PEM_TO_DER)
  21509. #ifdef WOLFSSL_CERT_GEN
  21510. int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der)
  21511. {
  21512. #ifndef WOLFSSL_SMALL_STACK
  21513. byte staticBuffer[FILE_BUFFER_SIZE];
  21514. #endif
  21515. byte* fileBuf = NULL;
  21516. int ret = 0;
  21517. XFILE file = XBADFILE;
  21518. int dynamic = 0;
  21519. long sz = 0;
  21520. WOLFSSL_ENTER("wc_PemCertToDer");
  21521. if (fileName == NULL) {
  21522. ret = BAD_FUNC_ARG;
  21523. }
  21524. else {
  21525. file = XFOPEN(fileName, "rb");
  21526. if (file == XBADFILE) {
  21527. ret = IO_FAILED_E;
  21528. }
  21529. }
  21530. if (ret == 0) {
  21531. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  21532. ret = IO_FAILED_E;
  21533. }
  21534. }
  21535. if (ret == 0) {
  21536. sz = XFTELL(file);
  21537. if (sz <= 0) {
  21538. ret = IO_FAILED_E;
  21539. }
  21540. }
  21541. if (ret == 0) {
  21542. if (XFSEEK(file, 0, XSEEK_SET) != 0) {
  21543. ret = IO_FAILED_E;
  21544. }
  21545. }
  21546. if (ret == 0) {
  21547. #ifndef WOLFSSL_SMALL_STACK
  21548. if (sz <= (long)sizeof(staticBuffer))
  21549. fileBuf = staticBuffer;
  21550. else
  21551. #endif
  21552. {
  21553. fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
  21554. if (fileBuf == NULL)
  21555. ret = MEMORY_E;
  21556. else
  21557. dynamic = 1;
  21558. }
  21559. }
  21560. if (ret == 0) {
  21561. if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
  21562. ret = IO_FAILED_E;
  21563. }
  21564. else {
  21565. ret = PemToDer(fileBuf, sz, CA_TYPE, der, 0, NULL,NULL);
  21566. }
  21567. }
  21568. if (file != XBADFILE)
  21569. XFCLOSE(file);
  21570. if (dynamic)
  21571. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  21572. return ret;
  21573. }
  21574. /* load pem cert from file into der buffer, return der size or error */
  21575. int wc_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz)
  21576. {
  21577. int ret;
  21578. DerBuffer* converted = NULL;
  21579. ret = wc_PemCertToDer_ex(fileName, &converted);
  21580. if (ret == 0) {
  21581. if (converted->length < (word32)derSz) {
  21582. XMEMCPY(derBuf, converted->buffer, converted->length);
  21583. ret = (int)converted->length;
  21584. }
  21585. else
  21586. ret = BUFFER_E;
  21587. FreeDer(&converted);
  21588. }
  21589. return ret;
  21590. }
  21591. #endif /* WOLFSSL_CERT_GEN */
  21592. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  21593. /* load pem public key from file into der buffer, return der size or error */
  21594. int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der)
  21595. {
  21596. #ifndef WOLFSSL_SMALL_STACK
  21597. byte staticBuffer[FILE_BUFFER_SIZE];
  21598. #endif
  21599. byte* fileBuf = NULL;
  21600. int dynamic = 0;
  21601. int ret = 0;
  21602. long sz = 0;
  21603. XFILE file = XBADFILE;
  21604. WOLFSSL_ENTER("wc_PemPubKeyToDer");
  21605. if (fileName == NULL) {
  21606. ret = BAD_FUNC_ARG;
  21607. }
  21608. else {
  21609. file = XFOPEN(fileName, "rb");
  21610. if (file == XBADFILE) {
  21611. ret = IO_FAILED_E;
  21612. }
  21613. }
  21614. if (ret == 0) {
  21615. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  21616. ret = IO_FAILED_E;
  21617. }
  21618. }
  21619. if (ret == 0) {
  21620. sz = XFTELL(file);
  21621. if (sz <= 0) {
  21622. ret = IO_FAILED_E;
  21623. }
  21624. }
  21625. if (ret == 0) {
  21626. if (XFSEEK(file, 0, XSEEK_SET) != 0) {
  21627. ret = IO_FAILED_E;
  21628. }
  21629. }
  21630. if (ret == 0) {
  21631. #ifndef WOLFSSL_SMALL_STACK
  21632. if (sz <= (long)sizeof(staticBuffer))
  21633. fileBuf = staticBuffer;
  21634. else
  21635. #endif
  21636. {
  21637. fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
  21638. if (fileBuf == NULL)
  21639. ret = MEMORY_E;
  21640. else
  21641. dynamic = 1;
  21642. }
  21643. }
  21644. if (ret == 0) {
  21645. if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
  21646. ret = BUFFER_E;
  21647. }
  21648. else {
  21649. ret = PemToDer(fileBuf, sz, PUBLICKEY_TYPE, der,
  21650. 0, NULL, NULL);
  21651. }
  21652. }
  21653. if (file != XBADFILE)
  21654. XFCLOSE(file);
  21655. if (dynamic)
  21656. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  21657. return ret;
  21658. }
  21659. /* load pem public key from file into der buffer, return der size or error */
  21660. int wc_PemPubKeyToDer(const char* fileName,
  21661. unsigned char* derBuf, int derSz)
  21662. {
  21663. int ret;
  21664. DerBuffer* converted = NULL;
  21665. ret = wc_PemPubKeyToDer_ex(fileName, &converted);
  21666. if (ret == 0) {
  21667. if (converted->length < (word32)derSz) {
  21668. XMEMCPY(derBuf, converted->buffer, converted->length);
  21669. ret = (int)converted->length;
  21670. }
  21671. else
  21672. ret = BUFFER_E;
  21673. FreeDer(&converted);
  21674. }
  21675. return ret;
  21676. }
  21677. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  21678. #endif /* !NO_FILESYSTEM && WOLFSSL_PEM_TO_DER */
  21679. /* Get public key in DER format from a populated DecodedCert struct.
  21680. *
  21681. * Users must call wc_InitDecodedCert() and wc_ParseCert() before calling
  21682. * this API. wc_InitDecodedCert() accepts a DER/ASN.1 encoded certificate.
  21683. * To convert a PEM cert to DER first use wc_CertPemToDer() before calling
  21684. * wc_InitDecodedCert().
  21685. *
  21686. * cert - populated DecodedCert struct holding X.509 certificate
  21687. * derKey - output buffer to place DER/ASN.1 encoded public key
  21688. * derKeySz [IN/OUT] - size of derKey buffer on input, size of public key
  21689. * on return. If derKey is passed in as NULL, derKeySz
  21690. * will be set to required buffer size for public key
  21691. * and LENGTH_ONLY_E will be returned from function.
  21692. * Returns 0 on success, or negative error code on failure. LENGTH_ONLY_E
  21693. * if derKey is NULL and returning length only.
  21694. */
  21695. int wc_GetPubKeyDerFromCert(struct DecodedCert* cert,
  21696. byte* derKey, word32* derKeySz)
  21697. {
  21698. int ret = 0;
  21699. /* derKey may be NULL to return length only */
  21700. if (cert == NULL || derKeySz == NULL ||
  21701. (derKey != NULL && *derKeySz == 0)) {
  21702. return BAD_FUNC_ARG;
  21703. }
  21704. if (cert->publicKey == NULL) {
  21705. WOLFSSL_MSG("DecodedCert does not contain public key\n");
  21706. return BAD_FUNC_ARG;
  21707. }
  21708. /* if derKey is NULL, return required output buffer size in derKeySz */
  21709. if (derKey == NULL) {
  21710. *derKeySz = cert->pubKeySize;
  21711. ret = LENGTH_ONLY_E;
  21712. }
  21713. if (ret == 0) {
  21714. if (cert->pubKeySize > *derKeySz) {
  21715. WOLFSSL_MSG("Output buffer not large enough for public key DER");
  21716. ret = BAD_FUNC_ARG;
  21717. }
  21718. else {
  21719. XMEMCPY(derKey, cert->publicKey, cert->pubKeySize);
  21720. *derKeySz = cert->pubKeySize;
  21721. }
  21722. }
  21723. return ret;
  21724. }
  21725. #ifdef WOLFSSL_FPKI
  21726. /* Search through list for first matching alt name of the same type
  21727. * If 'current' is null then the search starts at the head of the list
  21728. * otherwise the search starts from the node after 'current' alt name.
  21729. * Returns 0 on success
  21730. */
  21731. static DNS_entry* FindAltName(struct DecodedCert* cert, int nameType,
  21732. DNS_entry* current)
  21733. {
  21734. DNS_entry* entry;
  21735. if (current == NULL) {
  21736. entry = cert->altNames;
  21737. }
  21738. else {
  21739. entry = current->next;
  21740. }
  21741. /* cycle through alt names to check for needed types */
  21742. while (entry != NULL) {
  21743. if (entry->type == nameType) {
  21744. break;
  21745. }
  21746. entry = entry->next;
  21747. }
  21748. return entry;
  21749. }
  21750. /* returns 0 on success */
  21751. int wc_GetUUIDFromCert(struct DecodedCert* cert, byte* uuid, word32* uuidSz)
  21752. {
  21753. int ret = ALT_NAME_E;
  21754. DNS_entry* id = NULL;
  21755. do {
  21756. id = FindAltName(cert, ASN_URI_TYPE, id);
  21757. if (id != NULL) {
  21758. /* check if URI string matches expected format for UUID */
  21759. if (id->len != DEFAULT_UUID_SZ) {
  21760. continue; /* size not right not a UUID URI */
  21761. }
  21762. if (XMEMCMP(id->name, "urn:uuid:", 9) != 0) {
  21763. continue; /* beginning text not right for a UUID URI */
  21764. }
  21765. if (uuid == NULL) {
  21766. *uuidSz = id->len;
  21767. return LENGTH_ONLY_E;
  21768. }
  21769. if ((int)*uuidSz < id->len) {
  21770. return BUFFER_E;
  21771. }
  21772. XMEMCPY(uuid, id->name, id->len);
  21773. ret = 0; /* success */
  21774. break;
  21775. }
  21776. } while (id != NULL);
  21777. return ret;
  21778. }
  21779. /* reutrns 0 on success */
  21780. int wc_GetFASCNFromCert(struct DecodedCert* cert, byte* fascn, word32* fascnSz)
  21781. {
  21782. int ret = ALT_NAME_E;
  21783. DNS_entry* id = NULL;
  21784. do {
  21785. id = FindAltName(cert, ASN_OTHER_TYPE, id);
  21786. if (id != NULL && id->oidSum == FASCN_OID) {
  21787. if (fascn == NULL) {
  21788. *fascnSz = id->len;
  21789. return LENGTH_ONLY_E;
  21790. }
  21791. if ((int)*fascnSz < id->len) {
  21792. return BUFFER_E;
  21793. }
  21794. XMEMCPY(fascn, id->name, id->len);
  21795. ret = 0; /* success */
  21796. }
  21797. } while (id != NULL);
  21798. return ret;
  21799. }
  21800. #endif /* WOLFSSL_FPKI */
  21801. #if !defined(NO_RSA) && (defined(WOLFSSL_CERT_GEN) || \
  21802. defined(WOLFSSL_KCAPI_RSA) || \
  21803. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA)))
  21804. /* USER RSA ifdef portions used instead of refactor in consideration for
  21805. possible fips build */
  21806. /* Encode a public RSA key to output.
  21807. *
  21808. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  21809. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  21810. *
  21811. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  21812. * (RSAPublicKey).
  21813. *
  21814. * @param [out] output Buffer to put encoded data in.
  21815. * @param [in] key RSA key object.
  21816. * @param [in] outLen Size of the output buffer in bytes.
  21817. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  21818. * @return Size of encoded data in bytes on success.
  21819. * @return BAD_FUNC_ARG when output or key is NULL, or outLen is less than
  21820. * minimum length (5 bytes).
  21821. * @return MEMORY_E when dynamic memory allocation failed.
  21822. */
  21823. static int SetRsaPublicKey(byte* output, RsaKey* key, int outLen,
  21824. int with_header)
  21825. {
  21826. #ifndef WOLFSSL_ASN_TEMPLATE
  21827. int nSz, eSz;
  21828. word32 seqSz, algoSz = 0, headSz = 0, bitStringSz = 0, idx;
  21829. byte seq[MAX_SEQ_SZ];
  21830. byte headSeq[MAX_SEQ_SZ];
  21831. byte bitString[1 + MAX_LENGTH_SZ + 1];
  21832. byte algo[MAX_ALGO_SZ]; /* 20 bytes */
  21833. if (key == NULL) {
  21834. return BAD_FUNC_ARG;
  21835. }
  21836. #ifdef HAVE_USER_RSA
  21837. nSz = SetASNIntRSA(key->n, NULL);
  21838. #else
  21839. nSz = SetASNIntMP(&key->n, MAX_RSA_INT_SZ, NULL);
  21840. #endif
  21841. if (nSz < 0)
  21842. return nSz;
  21843. #ifdef HAVE_USER_RSA
  21844. eSz = SetASNIntRSA(key->e, NULL);
  21845. #else
  21846. eSz = SetASNIntMP(&key->e, MAX_RSA_INT_SZ, NULL);
  21847. #endif
  21848. if (eSz < 0)
  21849. return eSz;
  21850. seqSz = SetSequence((word32)(nSz + eSz), seq);
  21851. /* headers */
  21852. if (with_header) {
  21853. algoSz = SetAlgoID(RSAk, algo, oidKeyType, 0);
  21854. bitStringSz = SetBitString(seqSz + (word32)(nSz + eSz), 0, bitString);
  21855. headSz = SetSequence((word32)(nSz + eSz) + seqSz + bitStringSz + algoSz,
  21856. headSeq);
  21857. }
  21858. /* if getting length only */
  21859. if (output == NULL) {
  21860. return (int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz;
  21861. }
  21862. /* check output size */
  21863. if (((int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz) > outLen) {
  21864. return BUFFER_E;
  21865. }
  21866. /* write output */
  21867. idx = 0;
  21868. if (with_header) {
  21869. /* header size */
  21870. XMEMCPY(output + idx, headSeq, headSz);
  21871. idx += headSz;
  21872. /* algo */
  21873. XMEMCPY(output + idx, algo, algoSz);
  21874. idx += algoSz;
  21875. /* bit string */
  21876. XMEMCPY(output + idx, bitString, bitStringSz);
  21877. idx += bitStringSz;
  21878. }
  21879. /* seq */
  21880. XMEMCPY(output + idx, seq, seqSz);
  21881. idx += seqSz;
  21882. /* n */
  21883. #ifdef HAVE_USER_RSA
  21884. nSz = SetASNIntRSA(key->n, output + idx);
  21885. #else
  21886. nSz = SetASNIntMP(&key->n, nSz, output + idx);
  21887. #endif
  21888. idx += (word32)nSz;
  21889. /* e */
  21890. #ifdef HAVE_USER_RSA
  21891. eSz = SetASNIntRSA(key->e, output + idx);
  21892. #else
  21893. eSz = SetASNIntMP(&key->e, eSz, output + idx);
  21894. #endif
  21895. idx += (word32)eSz;
  21896. return (int)idx;
  21897. #else
  21898. DECL_ASNSETDATA(dataASN, rsaPublicKeyASN_Length);
  21899. int sz = 0;
  21900. int ret = 0;
  21901. int o = 0;
  21902. /* Check parameter validity. */
  21903. if ((key == NULL) || ((output != NULL) && (outLen < MAX_SEQ_SZ))) {
  21904. ret = BAD_FUNC_ARG;
  21905. }
  21906. CALLOC_ASNSETDATA(dataASN, rsaPublicKeyASN_Length, ret, key->heap);
  21907. if (ret == 0) {
  21908. if (!with_header) {
  21909. /* Start encoding with items after header. */
  21910. o = RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ;
  21911. }
  21912. /* Set OID for RSA key. */
  21913. SetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], RSAk, oidKeyType);
  21914. #ifdef WC_RSA_PSS
  21915. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].noOut = 1;
  21916. #endif
  21917. /* Set public key mp_ints. */
  21918. #ifdef HAVE_USER_RSA
  21919. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], key->n);
  21920. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], key->e);
  21921. #else
  21922. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], &key->n);
  21923. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], &key->e);
  21924. #endif
  21925. /* Calculate size of RSA public key. */
  21926. ret = SizeASN_Items(rsaPublicKeyASN + o, dataASN + o,
  21927. (int)rsaPublicKeyASN_Length - o, &sz);
  21928. }
  21929. /* Check output buffer is big enough for encoding. */
  21930. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  21931. ret = BUFFER_E;
  21932. }
  21933. if ((ret == 0) && (output != NULL)) {
  21934. /* Encode RSA public key. */
  21935. SetASN_Items(rsaPublicKeyASN + o, dataASN + o,
  21936. (int)rsaPublicKeyASN_Length - o, output);
  21937. }
  21938. if (ret == 0) {
  21939. /* Return size of encoding. */
  21940. ret = sz;
  21941. }
  21942. FREE_ASNSETDATA(dataASN, key->heap);
  21943. return ret;
  21944. #endif /* WOLFSSL_ASN_TEMPLATE */
  21945. }
  21946. /* Calculate size of encoded public RSA key in bytes.
  21947. *
  21948. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  21949. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  21950. *
  21951. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  21952. * (RSAPublicKey).
  21953. *
  21954. * @param [in] key RSA key object.
  21955. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  21956. * @return Size of encoded data in bytes on success.
  21957. * @return BAD_FUNC_ARG when key is NULL.
  21958. * @return MEMORY_E when dynamic memory allocation failed.
  21959. */
  21960. int wc_RsaPublicKeyDerSize(RsaKey* key, int with_header)
  21961. {
  21962. return SetRsaPublicKey(NULL, key, 0, with_header);
  21963. }
  21964. /* Encode public RSA key in DER format.
  21965. *
  21966. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  21967. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  21968. *
  21969. * @param [in] key RSA key object.
  21970. * @param [out] output Buffer to put encoded data in.
  21971. * @param [in] inLen Size of buffer in bytes.
  21972. * @return Size of encoded data in bytes on success.
  21973. * @return BAD_FUNC_ARG when key or output is NULL.
  21974. * @return MEMORY_E when dynamic memory allocation failed.
  21975. */
  21976. int wc_RsaKeyToPublicDer(RsaKey* key, byte* output, word32 inLen)
  21977. {
  21978. return SetRsaPublicKey(output, key, (int)inLen, 1);
  21979. }
  21980. /* Returns public DER version of the RSA key. If with_header is 0 then only a
  21981. * seq + n + e is returned in ASN.1 DER format */
  21982. int wc_RsaKeyToPublicDer_ex(RsaKey* key, byte* output, word32 inLen,
  21983. int with_header)
  21984. {
  21985. return SetRsaPublicKey(output, key, (int)inLen, with_header);
  21986. }
  21987. #endif /* !NO_RSA && (WOLFSSL_CERT_GEN || WOLFSSL_KCAPI_RSA ||
  21988. ((OPENSSL_EXTRA || WOLFSSL_KEY_GEN) && !HAVE_USER_RSA))) */
  21989. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  21990. defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)) && \
  21991. !defined(NO_RSA) && !defined(HAVE_USER_RSA)
  21992. /* Encode private RSA key in DER format.
  21993. *
  21994. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  21995. *
  21996. * @param [in] key RSA key object.
  21997. * @param [out] output Buffer to put encoded data in.
  21998. * @param [in] inLen Size of buffer in bytes.
  21999. * @return Size of encoded data in bytes on success.
  22000. * @return BAD_FUNC_ARG when key is NULL or not a private key.
  22001. * @return MEMORY_E when dynamic memory allocation failed.
  22002. */
  22003. int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
  22004. {
  22005. #ifndef WOLFSSL_ASN_TEMPLATE
  22006. int ret = 0, i, mpSz;
  22007. word32 j, seqSz = 0, verSz = 0, rawLen, intTotalLen = 0, outLen = 0;
  22008. word32 sizes[RSA_INTS];
  22009. byte seq[MAX_SEQ_SZ];
  22010. byte ver[MAX_VERSION_SZ];
  22011. byte* tmps[RSA_INTS];
  22012. if (key == NULL)
  22013. return BAD_FUNC_ARG;
  22014. if (key->type != RSA_PRIVATE)
  22015. return BAD_FUNC_ARG;
  22016. for (i = 0; i < RSA_INTS; i++)
  22017. tmps[i] = NULL;
  22018. /* write all big ints from key to DER tmps */
  22019. for (i = 0; i < RSA_INTS; i++) {
  22020. mp_int* keyInt = GetRsaInt(key, i);
  22021. ret = mp_unsigned_bin_size(keyInt);
  22022. if (ret < 0)
  22023. return ret;
  22024. rawLen = (word32)ret + 1;
  22025. ret = 0;
  22026. if (output != NULL) {
  22027. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  22028. DYNAMIC_TYPE_RSA);
  22029. if (tmps[i] == NULL) {
  22030. ret = MEMORY_E;
  22031. break;
  22032. }
  22033. }
  22034. mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, tmps[i]);
  22035. if (mpSz < 0) {
  22036. ret = mpSz;
  22037. break;
  22038. }
  22039. sizes[i] = (word32)mpSz;
  22040. intTotalLen += (word32)mpSz;
  22041. }
  22042. if (ret == 0) {
  22043. /* make headers */
  22044. ret = SetMyVersion(0, ver, FALSE);
  22045. }
  22046. if (ret >= 0) {
  22047. verSz = (word32)ret;
  22048. ret = 0;
  22049. seqSz = SetSequence(verSz + intTotalLen, seq);
  22050. outLen = seqSz + verSz + intTotalLen;
  22051. if (output != NULL && outLen > inLen)
  22052. ret = BUFFER_E;
  22053. }
  22054. if (ret == 0 && output != NULL) {
  22055. /* write to output */
  22056. XMEMCPY(output, seq, seqSz);
  22057. j = seqSz;
  22058. XMEMCPY(output + j, ver, verSz);
  22059. j += verSz;
  22060. for (i = 0; i < RSA_INTS; i++) {
  22061. XMEMCPY(output + j, tmps[i], sizes[i]);
  22062. j += sizes[i];
  22063. }
  22064. }
  22065. for (i = 0; i < RSA_INTS; i++) {
  22066. if (tmps[i])
  22067. XFREE(tmps[i], key->heap, DYNAMIC_TYPE_RSA);
  22068. }
  22069. if (ret == 0)
  22070. ret = (int)outLen;
  22071. return ret;
  22072. #else
  22073. DECL_ASNSETDATA(dataASN, rsaKeyASN_Length);
  22074. int i;
  22075. int sz = 0;
  22076. int ret = 0;
  22077. if ((key == NULL) || (key->type != RSA_PRIVATE)) {
  22078. ret = BAD_FUNC_ARG;
  22079. }
  22080. CALLOC_ASNSETDATA(dataASN, rsaKeyASN_Length, ret, key->heap);
  22081. if (ret == 0) {
  22082. /* Set the version. */
  22083. SetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], 0);
  22084. /* Set all the mp_ints in private key. */
  22085. for (i = 0; i < RSA_INTS; i++) {
  22086. SetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i], GetRsaInt(key, i));
  22087. }
  22088. /* Calculate size of RSA private key encoding. */
  22089. ret = SizeASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, &sz);
  22090. }
  22091. /* Check output buffer has enough space for encoding. */
  22092. if ((ret == 0) && (output != NULL) && (sz > (int)inLen)) {
  22093. ret = BAD_FUNC_ARG;
  22094. }
  22095. if ((ret == 0) && (output != NULL)) {
  22096. /* Encode RSA private key. */
  22097. SetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, output);
  22098. }
  22099. if (ret == 0) {
  22100. /* Return size of encoding. */
  22101. ret = sz;
  22102. }
  22103. FREE_ASNSETDATA(dataASN, key->heap);
  22104. return ret;
  22105. #endif
  22106. }
  22107. #endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA && !HAVE_USER_RSA */
  22108. #ifdef WOLFSSL_CERT_GEN
  22109. /* Initialize and Set Certificate defaults:
  22110. version = 3 (0x2)
  22111. serial = 0
  22112. sigType = SHA_WITH_RSA
  22113. issuer = blank
  22114. daysValid = 500
  22115. selfSigned = 1 (true) use subject as issuer
  22116. subject = blank
  22117. */
  22118. int wc_InitCert_ex(Cert* cert, void* heap, int devId)
  22119. {
  22120. #ifdef WOLFSSL_MULTI_ATTRIB
  22121. int i = 0;
  22122. #endif
  22123. if (cert == NULL) {
  22124. return BAD_FUNC_ARG;
  22125. }
  22126. XMEMSET(cert, 0, sizeof(Cert));
  22127. cert->version = 2; /* version 3 is hex 2 */
  22128. #ifndef NO_SHA
  22129. cert->sigType = CTC_SHAwRSA;
  22130. #elif !defined(NO_SHA256)
  22131. cert->sigType = CTC_SHA256wRSA;
  22132. #else
  22133. cert->sigType = 0;
  22134. #endif
  22135. cert->daysValid = 500;
  22136. cert->selfSigned = 1;
  22137. cert->keyType = RSA_KEY;
  22138. cert->issuer.countryEnc = CTC_PRINTABLE;
  22139. cert->issuer.stateEnc = CTC_UTF8;
  22140. cert->issuer.streetEnc = CTC_UTF8;
  22141. cert->issuer.localityEnc = CTC_UTF8;
  22142. cert->issuer.surEnc = CTC_UTF8;
  22143. #ifdef WOLFSSL_CERT_NAME_ALL
  22144. cert->issuer.givenNameEnc = CTC_UTF8;
  22145. cert->issuer.initialsEnc = CTC_UTF8;
  22146. cert->issuer.dnQualifierEnc = CTC_UTF8;
  22147. cert->issuer.dnNameEnc = CTC_UTF8;
  22148. #endif
  22149. cert->issuer.orgEnc = CTC_UTF8;
  22150. cert->issuer.unitEnc = CTC_UTF8;
  22151. cert->issuer.commonNameEnc = CTC_UTF8;
  22152. cert->issuer.serialDevEnc = CTC_PRINTABLE;
  22153. cert->issuer.userIdEnc = CTC_UTF8;
  22154. cert->issuer.postalCodeEnc = CTC_UTF8;
  22155. #ifdef WOLFSSL_CERT_EXT
  22156. cert->issuer.busCatEnc = CTC_UTF8;
  22157. cert->issuer.joiCEnc = CTC_UTF8;
  22158. cert->issuer.joiStEnc = CTC_UTF8;
  22159. #endif
  22160. cert->subject.countryEnc = CTC_PRINTABLE;
  22161. cert->subject.stateEnc = CTC_UTF8;
  22162. cert->subject.streetEnc = CTC_UTF8;
  22163. cert->subject.localityEnc = CTC_UTF8;
  22164. cert->subject.surEnc = CTC_UTF8;
  22165. #ifdef WOLFSSL_CERT_NAME_ALL
  22166. cert->subject.givenNameEnc = CTC_UTF8;
  22167. cert->subject.initialsEnc = CTC_UTF8;
  22168. cert->subject.dnQualifierEnc = CTC_UTF8;
  22169. cert->subject.dnNameEnc = CTC_UTF8;
  22170. #endif
  22171. cert->subject.orgEnc = CTC_UTF8;
  22172. cert->subject.unitEnc = CTC_UTF8;
  22173. cert->subject.commonNameEnc = CTC_UTF8;
  22174. cert->subject.serialDevEnc = CTC_PRINTABLE;
  22175. cert->subject.userIdEnc = CTC_UTF8;
  22176. cert->subject.postalCodeEnc = CTC_UTF8;
  22177. #ifdef WOLFSSL_CERT_EXT
  22178. cert->subject.busCatEnc = CTC_UTF8;
  22179. cert->subject.joiCEnc = CTC_UTF8;
  22180. cert->subject.joiStEnc = CTC_UTF8;
  22181. #endif
  22182. #ifdef WOLFSSL_MULTI_ATTRIB
  22183. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  22184. cert->issuer.name[i].type = CTC_UTF8;
  22185. cert->subject.name[i].type = CTC_UTF8;
  22186. }
  22187. #endif /* WOLFSSL_MULTI_ATTRIB */
  22188. cert->heap = heap;
  22189. (void)devId; /* future */
  22190. return 0;
  22191. }
  22192. WOLFSSL_ABI
  22193. int wc_InitCert(Cert* cert)
  22194. {
  22195. return wc_InitCert_ex(cert, NULL, INVALID_DEVID);
  22196. }
  22197. WOLFSSL_ABI
  22198. Cert* wc_CertNew(void* heap)
  22199. {
  22200. Cert* certNew;
  22201. certNew = (Cert*)XMALLOC(sizeof(Cert), heap, DYNAMIC_TYPE_CERT);
  22202. if (certNew) {
  22203. if (wc_InitCert_ex(certNew, heap, INVALID_DEVID) != 0) {
  22204. XFREE(certNew, heap, DYNAMIC_TYPE_CERT);
  22205. certNew = NULL;
  22206. }
  22207. }
  22208. return certNew;
  22209. }
  22210. WOLFSSL_ABI
  22211. void wc_CertFree(Cert* cert)
  22212. {
  22213. if (cert) {
  22214. void* heap = cert->heap;
  22215. ForceZero(cert, sizeof(Cert));
  22216. XFREE(cert, heap, DYNAMIC_TYPE_CERT);
  22217. (void)heap;
  22218. }
  22219. }
  22220. /* DER encoded x509 Certificate */
  22221. typedef struct DerCert {
  22222. byte size[MAX_LENGTH_SZ]; /* length encoded */
  22223. byte version[MAX_VERSION_SZ]; /* version encoded */
  22224. byte serial[(int)CTC_SERIAL_SIZE + (int)MAX_LENGTH_SZ]; /* serial number encoded */
  22225. byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
  22226. byte issuer[WC_ASN_NAME_MAX]; /* issuer encoded */
  22227. byte subject[WC_ASN_NAME_MAX]; /* subject encoded */
  22228. byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
  22229. byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa public key encoded */
  22230. byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
  22231. byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
  22232. #ifdef WOLFSSL_CERT_EXT
  22233. byte skid[MAX_KID_SZ]; /* Subject Key Identifier extension */
  22234. byte akid[MAX_KID_SZ
  22235. #ifdef WOLFSSL_AKID_NAME
  22236. + sizeof(CertName) + CTC_SERIAL_SIZE
  22237. #endif
  22238. ]; /* Authority Key Identifier extension */
  22239. byte keyUsage[MAX_KEYUSAGE_SZ]; /* Key Usage extension */
  22240. byte extKeyUsage[MAX_EXTKEYUSAGE_SZ]; /* Extended Key Usage extension */
  22241. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  22242. byte nsCertType[MAX_NSCERTTYPE_SZ]; /* Extended Key Usage extension */
  22243. #endif
  22244. byte certPolicies[MAX_CERTPOL_NB*MAX_CERTPOL_SZ]; /* Certificate Policies */
  22245. byte crlInfo[CTC_MAX_CRLINFO_SZ]; /* CRL Distribution Points */
  22246. #endif
  22247. #ifdef WOLFSSL_CERT_REQ
  22248. byte attrib[MAX_ATTRIB_SZ]; /* Cert req attributes encoded */
  22249. #ifdef WOLFSSL_CUSTOM_OID
  22250. byte extCustom[MAX_ATTRIB_SZ]; /* Encoded user oid and value */
  22251. #endif
  22252. #endif
  22253. #ifdef WOLFSSL_ALT_NAMES
  22254. byte altNames[CTC_MAX_ALT_SIZE]; /* Alternative Names encoded */
  22255. #endif
  22256. int sizeSz; /* encoded size length */
  22257. int versionSz; /* encoded version length */
  22258. int serialSz; /* encoded serial length */
  22259. int sigAlgoSz; /* encoded sig algo length */
  22260. int issuerSz; /* encoded issuer length */
  22261. int subjectSz; /* encoded subject length */
  22262. int validitySz; /* encoded validity length */
  22263. int publicKeySz; /* encoded public key length */
  22264. int caSz; /* encoded CA extension length */
  22265. #ifdef WOLFSSL_CERT_EXT
  22266. int skidSz; /* encoded SKID extension length */
  22267. int akidSz; /* encoded SKID extension length */
  22268. int keyUsageSz; /* encoded KeyUsage extension length */
  22269. int extKeyUsageSz; /* encoded ExtendedKeyUsage extension length */
  22270. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  22271. int nsCertTypeSz; /* encoded Netscape Certifcate Type
  22272. * extension length */
  22273. #endif
  22274. int certPoliciesSz; /* encoded CertPolicies extension length*/
  22275. int crlInfoSz; /* encoded CRL Dist Points length */
  22276. #endif
  22277. #ifdef WOLFSSL_ALT_NAMES
  22278. int altNamesSz; /* encoded AltNames extension length */
  22279. #endif
  22280. int extensionsSz; /* encoded extensions total length */
  22281. int total; /* total encoded lengths */
  22282. #ifdef WOLFSSL_CERT_REQ
  22283. int attribSz;
  22284. #ifdef WOLFSSL_CUSTOM_OID
  22285. int extCustomSz;
  22286. #endif
  22287. #endif
  22288. } DerCert;
  22289. #ifdef WOLFSSL_CERT_REQ
  22290. #ifndef WOLFSSL_ASN_TEMPLATE
  22291. /* Write a set header to output */
  22292. static word32 SetPrintableString(word32 len, byte* output)
  22293. {
  22294. output[0] = ASN_PRINTABLE_STRING;
  22295. return SetLength(len, output + 1) + 1;
  22296. }
  22297. static word32 SetUTF8String(word32 len, byte* output)
  22298. {
  22299. output[0] = ASN_UTF8STRING;
  22300. return SetLength(len, output + 1) + 1;
  22301. }
  22302. #endif
  22303. #endif /* WOLFSSL_CERT_REQ */
  22304. #ifndef WOLFSSL_CERT_GEN_CACHE
  22305. /* wc_SetCert_Free is only public when WOLFSSL_CERT_GEN_CACHE is not defined */
  22306. static
  22307. #endif
  22308. WOLFSSL_ABI
  22309. void wc_SetCert_Free(Cert* cert)
  22310. {
  22311. if (cert != NULL) {
  22312. cert->der = NULL;
  22313. if (cert->decodedCert) {
  22314. FreeDecodedCert((DecodedCert*)cert->decodedCert);
  22315. XFREE(cert->decodedCert, cert->heap, DYNAMIC_TYPE_DCERT);
  22316. cert->decodedCert = NULL;
  22317. }
  22318. }
  22319. }
  22320. static int wc_SetCert_LoadDer(Cert* cert, const byte* der, word32 derSz,
  22321. int devId)
  22322. {
  22323. int ret;
  22324. if (cert == NULL) {
  22325. ret = BAD_FUNC_ARG;
  22326. }
  22327. else {
  22328. /* Allocate DecodedCert struct and Zero */
  22329. cert->decodedCert = (void*)XMALLOC(sizeof(DecodedCert), cert->heap,
  22330. DYNAMIC_TYPE_DCERT);
  22331. if (cert->decodedCert == NULL) {
  22332. ret = MEMORY_E;
  22333. }
  22334. else {
  22335. XMEMSET(cert->decodedCert, 0, sizeof(DecodedCert));
  22336. InitDecodedCert_ex((DecodedCert*)cert->decodedCert, der, derSz,
  22337. cert->heap, devId);
  22338. ret = ParseCertRelative((DecodedCert*)cert->decodedCert,
  22339. CERT_TYPE, 0, NULL);
  22340. if (ret >= 0) {
  22341. cert->der = (byte*)der;
  22342. }
  22343. else {
  22344. wc_SetCert_Free(cert);
  22345. }
  22346. }
  22347. }
  22348. return ret;
  22349. }
  22350. #endif /* WOLFSSL_CERT_GEN */
  22351. #ifdef HAVE_ECC
  22352. #ifdef WOLFSSL_ASN_TEMPLATE
  22353. /* ASN.1 template for ECC public key (SubjectPublicKeyInfo).
  22354. * RFC 5480, 2 - Subject Public Key Information Fields
  22355. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  22356. * X9.62 ECC point format.
  22357. * See ASN.1 template 'eccSpecifiedASN' for specifiedCurve.
  22358. */
  22359. static const ASNItem eccPublicKeyASN[] = {
  22360. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  22361. /* AlgorithmIdentifier */
  22362. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  22363. /* algorithm */
  22364. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  22365. /* namedCurve */
  22366. /* ALGOID_CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  22367. /* specifiedCurve - explicit parameters */
  22368. /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  22369. /* Public Key */
  22370. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  22371. };
  22372. enum {
  22373. ECCPUBLICKEYASN_IDX_SEQ = 0,
  22374. ECCPUBLICKEYASN_IDX_ALGOID_SEQ,
  22375. ECCPUBLICKEYASN_IDX_ALGOID_OID,
  22376. ECCPUBLICKEYASN_IDX_ALGOID_CURVEID,
  22377. ECCPUBLICKEYASN_IDX_ALGOID_PARAMS,
  22378. ECCPUBLICKEYASN_IDX_PUBKEY
  22379. };
  22380. /* Number of items in ASN.1 template for ECC public key. */
  22381. #define eccPublicKeyASN_Length (sizeof(eccPublicKeyASN) / sizeof(ASNItem))
  22382. #endif /* WOLFSSL_ASN_TEMPLATE */
  22383. #endif /* HAVE_ECC */
  22384. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  22385. /* Encode public ECC key in DER format.
  22386. *
  22387. * RFC 5480, 2 - Subject Public Key Information Fields
  22388. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  22389. * X9.62 ECC point format.
  22390. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  22391. *
  22392. * @param [out] output Buffer to put encoded data in.
  22393. * @param [in] key ECC key object.
  22394. * @param [in] outLen Size of buffer in bytes.
  22395. * @param [in] with_header Whether to use SubjectPublicKeyInfo format.
  22396. * @return Size of encoded data in bytes on success.
  22397. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  22398. * @return MEMORY_E when dynamic memory allocation failed.
  22399. */
  22400. static int SetEccPublicKey(byte* output, ecc_key* key, int outLen,
  22401. int with_header, int comp)
  22402. {
  22403. #ifndef WOLFSSL_ASN_TEMPLATE
  22404. int ret;
  22405. word32 idx = 0, curveSz, algoSz, pubSz, bitStringSz;
  22406. byte bitString[1 + MAX_LENGTH_SZ + 1]; /* 6 */
  22407. byte algo[MAX_ALGO_SZ]; /* 20 */
  22408. /* public size */
  22409. pubSz = key->dp ? (word32)key->dp->size : MAX_ECC_BYTES;
  22410. if (comp)
  22411. pubSz = 1 + pubSz;
  22412. else
  22413. pubSz = 1 + 2 * pubSz;
  22414. /* check for buffer overflow */
  22415. if (output != NULL && pubSz > (word32)outLen) {
  22416. return BUFFER_E;
  22417. }
  22418. /* headers */
  22419. if (with_header) {
  22420. ret = SetCurve(key, NULL, 0);
  22421. if (ret <= 0) {
  22422. return ret;
  22423. }
  22424. curveSz = (word32)ret;
  22425. ret = 0;
  22426. /* calculate size */
  22427. algoSz = SetAlgoID(ECDSAk, algo, oidKeyType, (int)curveSz);
  22428. bitStringSz = SetBitString(pubSz, 0, bitString);
  22429. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz, NULL);
  22430. /* check for buffer overflow */
  22431. if (output != NULL &&
  22432. curveSz + algoSz + bitStringSz + idx + pubSz > (word32)outLen) {
  22433. return BUFFER_E;
  22434. }
  22435. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz,
  22436. output);
  22437. /* algo */
  22438. if (output)
  22439. XMEMCPY(output + idx, algo, algoSz);
  22440. idx += algoSz;
  22441. /* curve */
  22442. if (output)
  22443. (void)SetCurve(key, output + idx, curveSz);
  22444. idx += curveSz;
  22445. /* bit string */
  22446. if (output)
  22447. XMEMCPY(output + idx, bitString, bitStringSz);
  22448. idx += bitStringSz;
  22449. }
  22450. /* pub */
  22451. if (output) {
  22452. PRIVATE_KEY_UNLOCK();
  22453. ret = wc_ecc_export_x963_ex(key, output + idx, &pubSz, comp);
  22454. PRIVATE_KEY_LOCK();
  22455. if (ret != 0) {
  22456. return ret;
  22457. }
  22458. }
  22459. idx += pubSz;
  22460. return (int)idx;
  22461. #else
  22462. word32 pubSz = 0;
  22463. int sz = 0;
  22464. int ret = 0;
  22465. int curveIdSz = 0;
  22466. byte* curveOid = NULL;
  22467. /* Check key validity. */
  22468. if ((key == NULL) || (key->dp == NULL)) {
  22469. ret = BAD_FUNC_ARG;
  22470. }
  22471. if (ret == 0) {
  22472. /* Calculate the size of the encoded public point. */
  22473. PRIVATE_KEY_UNLOCK();
  22474. #if defined(HAVE_COMP_KEY) && defined(HAVE_FIPS) && \
  22475. defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  22476. /* in earlier versions of FIPS the get length functionality is not
  22477. * available with compressed keys */
  22478. pubSz = key->dp ? key->dp->size : MAX_ECC_BYTES;
  22479. if (comp)
  22480. pubSz = 1 + pubSz;
  22481. else
  22482. pubSz = 1 + 2 * pubSz;
  22483. ret = LENGTH_ONLY_E;
  22484. #else
  22485. ret = wc_ecc_export_x963_ex(key, NULL, &pubSz, comp);
  22486. #endif
  22487. PRIVATE_KEY_LOCK();
  22488. /* LENGTH_ONLY_E on success. */
  22489. if (ret == LENGTH_ONLY_E) {
  22490. ret = 0;
  22491. }
  22492. }
  22493. if ((ret == 0) && with_header) {
  22494. /* Including SubjectPublicKeyInfo header. */
  22495. DECL_ASNSETDATA(dataASN, eccPublicKeyASN_Length);
  22496. CALLOC_ASNSETDATA(dataASN, eccPublicKeyASN_Length, ret, key->heap);
  22497. /* Get the length of the named curve OID to put into the encoding. */
  22498. curveIdSz = SetCurve(key, NULL, 0);
  22499. if (curveIdSz < 0) {
  22500. ret = curveIdSz;
  22501. }
  22502. if (ret == 0) {
  22503. /* Set the key type OID. */
  22504. SetASN_OID(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], ECDSAk,
  22505. oidKeyType);
  22506. /* Set the curve OID. */
  22507. SetASN_ReplaceBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID],
  22508. NULL, (word32)curveIdSz);
  22509. /* Don't try to write out explicit parameters. */
  22510. dataASN[ECCPUBLICKEYASN_IDX_ALGOID_PARAMS].noOut = 1;
  22511. /* Set size of public point to ensure space is made for it. */
  22512. SetASN_Buffer(&dataASN[ECCPUBLICKEYASN_IDX_PUBKEY], NULL, pubSz);
  22513. /* Calculate size of ECC public key. */
  22514. ret = SizeASN_Items(eccPublicKeyASN, dataASN,
  22515. eccPublicKeyASN_Length, &sz);
  22516. }
  22517. /* Check buffer, if passed in, is big enough for encoded data. */
  22518. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  22519. ret = BUFFER_E;
  22520. }
  22521. if ((ret == 0) && (output != NULL)) {
  22522. /* Encode ECC public key. */
  22523. SetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length,
  22524. output);
  22525. /* Skip to where public point is to be encoded. */
  22526. output += sz - (int)pubSz;
  22527. /* Cache the location to place the name curve OID. */
  22528. curveOid = (byte*)
  22529. dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID].data.buffer.data;
  22530. }
  22531. FREE_ASNSETDATA(dataASN, key->heap);
  22532. }
  22533. else if ((ret == 0) && (output != NULL) && (pubSz > (word32)outLen)) {
  22534. ret = BUFFER_E;
  22535. }
  22536. else {
  22537. /* Total size is the public point size. */
  22538. sz = (int)pubSz;
  22539. }
  22540. if ((ret == 0) && (output != NULL)) {
  22541. /* Put named curve OID data into encoding. */
  22542. curveIdSz = SetCurve(key, curveOid, (size_t)curveIdSz);
  22543. if (curveIdSz < 0) {
  22544. ret = curveIdSz;
  22545. }
  22546. }
  22547. if ((ret == 0) && (output != NULL)) {
  22548. /* Encode public point. */
  22549. PRIVATE_KEY_UNLOCK();
  22550. ret = wc_ecc_export_x963_ex(key, output, &pubSz, comp);
  22551. PRIVATE_KEY_LOCK();
  22552. }
  22553. if (ret == 0) {
  22554. /* Return the size of the encoding. */
  22555. ret = sz;
  22556. }
  22557. return ret;
  22558. #endif
  22559. }
  22560. /* Encode the public part of an ECC key in a DER.
  22561. *
  22562. * Pass NULL for output to get the size of the encoding.
  22563. *
  22564. * @param [in] key ECC key object.
  22565. * @param [out] output Buffer to hold DER encoding.
  22566. * @param [in] inLen Size of buffer in bytes.
  22567. * @param [in] with_AlgCurve Whether to use SubjectPublicKeyInfo format.
  22568. * @return Size of encoded data in bytes on success.
  22569. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  22570. * @return MEMORY_E when dynamic memory allocation failed.
  22571. */
  22572. WOLFSSL_ABI
  22573. int wc_EccPublicKeyToDer(ecc_key* key, byte* output, word32 inLen,
  22574. int with_AlgCurve)
  22575. {
  22576. return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, 0);
  22577. }
  22578. int wc_EccPublicKeyToDer_ex(ecc_key* key, byte* output, word32 inLen,
  22579. int with_AlgCurve, int comp)
  22580. {
  22581. return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, comp);
  22582. }
  22583. int wc_EccPublicKeyDerSize(ecc_key* key, int with_AlgCurve)
  22584. {
  22585. return SetEccPublicKey(NULL, key, 0, with_AlgCurve, 0);
  22586. }
  22587. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  22588. #ifdef WOLFSSL_ASN_TEMPLATE
  22589. #if defined(WC_ENABLE_ASYM_KEY_EXPORT) || defined(WC_ENABLE_ASYM_KEY_IMPORT)
  22590. /* ASN.1 template for Ed25519 and Ed448 public key (SubkectPublicKeyInfo).
  22591. * RFC 8410, 4 - Subject Public Key Fields
  22592. */
  22593. static const ASNItem edPubKeyASN[] = {
  22594. /* SubjectPublicKeyInfo */
  22595. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  22596. /* AlgorithmIdentifier */
  22597. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  22598. /* Ed25519/Ed448 OID */
  22599. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  22600. /* Public key stream */
  22601. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  22602. };
  22603. enum {
  22604. EDPUBKEYASN_IDX_SEQ = 0,
  22605. EDPUBKEYASN_IDX_ALGOID_SEQ,
  22606. EDPUBKEYASN_IDX_ALGOID_OID,
  22607. EDPUBKEYASN_IDX_PUBKEY
  22608. };
  22609. /* Number of items in ASN.1 template for Ed25519 and Ed448 public key. */
  22610. #define edPubKeyASN_Length (sizeof(edPubKeyASN) / sizeof(ASNItem))
  22611. #endif /* WC_ENABLE_ASYM_KEY_EXPORT || WC_ENABLE_ASYM_KEY_IMPORT */
  22612. #endif /* WOLFSSL_ASN_TEMPLATE */
  22613. #ifdef WC_ENABLE_ASYM_KEY_EXPORT
  22614. /* Build ASN.1 formatted public key based on RFC 8410
  22615. *
  22616. * Pass NULL for output to get the size of the encoding.
  22617. *
  22618. * @param [in] pubKey public key buffer
  22619. * @param [in] pubKeyLen public ket buffer length
  22620. * @param [out] output Buffer to put encoded data in (optional)
  22621. * @param [in] outLen Size of buffer in bytes
  22622. * @param [in] keyType is "enum Key_Sum" like ED25519k
  22623. * @param [in] withHeader Whether to include SubjectPublicKeyInfo around key.
  22624. * @return Size of encoded data in bytes on success
  22625. * @return BAD_FUNC_ARG when key is NULL.
  22626. * @return MEMORY_E when dynamic memory allocation failed.
  22627. */
  22628. int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen,
  22629. byte* output, word32 outLen, int keyType, int withHeader)
  22630. {
  22631. int ret = 0;
  22632. #ifndef WOLFSSL_ASN_TEMPLATE
  22633. word32 idx = 0;
  22634. word32 seqDataSz = 0;
  22635. word32 sz;
  22636. #else
  22637. int sz = 0;
  22638. DECL_ASNSETDATA(dataASN, edPubKeyASN_Length);
  22639. #endif
  22640. if (pubKey == NULL) {
  22641. return BAD_FUNC_ARG;
  22642. }
  22643. #ifndef WOLFSSL_ASN_TEMPLATE
  22644. /* calculate size */
  22645. if (withHeader) {
  22646. word32 algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
  22647. word32 bitStringSz = SetBitString(pubKeyLen, 0, NULL);
  22648. seqDataSz = algoSz + bitStringSz + pubKeyLen;
  22649. sz = SetSequence(seqDataSz, NULL) + seqDataSz;
  22650. }
  22651. else {
  22652. sz = pubKeyLen;
  22653. }
  22654. /* checkout output size */
  22655. if (output != NULL && sz > outLen) {
  22656. ret = BUFFER_E;
  22657. }
  22658. /* headers */
  22659. if (ret == 0 && output != NULL && withHeader) {
  22660. /* sequence */
  22661. idx = SetSequence(seqDataSz, output);
  22662. /* algo */
  22663. idx += SetAlgoID(keyType, output + idx, oidKeyType, 0);
  22664. /* bit string */
  22665. idx += SetBitString(pubKeyLen, 0, output + idx);
  22666. }
  22667. if (ret == 0 && output != NULL) {
  22668. /* pub */
  22669. XMEMCPY(output + idx, pubKey, pubKeyLen);
  22670. idx += pubKeyLen;
  22671. sz = idx;
  22672. }
  22673. if (ret == 0) {
  22674. ret = (int)sz;
  22675. }
  22676. #else
  22677. if (withHeader) {
  22678. CALLOC_ASNSETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
  22679. if (ret == 0) {
  22680. /* Set the OID. */
  22681. SetASN_OID(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], (word32)keyType,
  22682. oidKeyType);
  22683. /* Leave space for public point. */
  22684. SetASN_Buffer(&dataASN[EDPUBKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
  22685. /* Calculate size of public key encoding. */
  22686. ret = SizeASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, &sz);
  22687. }
  22688. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  22689. ret = BUFFER_E;
  22690. }
  22691. if ((ret == 0) && (output != NULL)) {
  22692. /* Encode public key. */
  22693. SetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, output);
  22694. /* Set location to encode public point. */
  22695. output = (byte*)dataASN[EDPUBKEYASN_IDX_PUBKEY].data.buffer.data;
  22696. }
  22697. FREE_ASNSETDATA(dataASN, NULL);
  22698. }
  22699. else if ((output != NULL) && (pubKeyLen > outLen)) {
  22700. ret = BUFFER_E;
  22701. }
  22702. else if (ret == 0) {
  22703. sz = (int)pubKeyLen;
  22704. }
  22705. if ((ret == 0) && (output != NULL)) {
  22706. /* Put public key into space provided. */
  22707. XMEMCPY(output, pubKey, pubKeyLen);
  22708. }
  22709. if (ret == 0) {
  22710. ret = sz;
  22711. }
  22712. #endif /* WOLFSSL_ASN_TEMPLATE */
  22713. return ret;
  22714. }
  22715. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  22716. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  22717. /* Encode the public part of an Ed25519 key in DER.
  22718. *
  22719. * Pass NULL for output to get the size of the encoding.
  22720. *
  22721. * @param [in] key Ed25519 key object.
  22722. * @param [out] output Buffer to put encoded data in.
  22723. * @param [in] outLen Size of buffer in bytes.
  22724. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  22725. * @return Size of encoded data in bytes on success.
  22726. * @return BAD_FUNC_ARG when key is NULL.
  22727. * @return MEMORY_E when dynamic memory allocation failed.
  22728. */
  22729. int wc_Ed25519PublicKeyToDer(ed25519_key* key, byte* output, word32 inLen,
  22730. int withAlg)
  22731. {
  22732. int ret;
  22733. byte pubKey[ED25519_PUB_KEY_SIZE];
  22734. word32 pubKeyLen = (word32)sizeof(pubKey);
  22735. if (key == NULL) {
  22736. return BAD_FUNC_ARG;
  22737. }
  22738. ret = wc_ed25519_export_public(key, pubKey, &pubKeyLen);
  22739. if (ret == 0) {
  22740. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  22741. ED25519k, withAlg);
  22742. }
  22743. return ret;
  22744. }
  22745. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  22746. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  22747. /* Encode the public part of an Ed448 key in DER.
  22748. *
  22749. * Pass NULL for output to get the size of the encoding.
  22750. *
  22751. * @param [in] key Ed448 key object.
  22752. * @param [out] output Buffer to put encoded data in.
  22753. * @param [in] outLen Size of buffer in bytes.
  22754. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  22755. * @return Size of encoded data in bytes on success.
  22756. * @return BAD_FUNC_ARG when key is NULL.
  22757. * @return MEMORY_E when dynamic memory allocation failed.
  22758. */
  22759. int wc_Ed448PublicKeyToDer(ed448_key* key, byte* output, word32 inLen,
  22760. int withAlg)
  22761. {
  22762. int ret;
  22763. byte pubKey[ED448_PUB_KEY_SIZE];
  22764. word32 pubKeyLen = (word32)sizeof(pubKey);
  22765. if (key == NULL) {
  22766. return BAD_FUNC_ARG;
  22767. }
  22768. ret = wc_ed448_export_public(key, pubKey, &pubKeyLen);
  22769. if (ret == 0) {
  22770. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  22771. ED448k, withAlg);
  22772. }
  22773. return ret;
  22774. }
  22775. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  22776. #ifdef WOLFSSL_CERT_GEN
  22777. #ifndef NO_ASN_TIME
  22778. static WC_INLINE byte itob(int number)
  22779. {
  22780. return (byte)number + 0x30;
  22781. }
  22782. /* write time to output, format */
  22783. static void SetTime(struct tm* date, byte* output)
  22784. {
  22785. int i = 0;
  22786. output[i++] = itob((date->tm_year % 10000) / 1000);
  22787. output[i++] = itob((date->tm_year % 1000) / 100);
  22788. output[i++] = itob((date->tm_year % 100) / 10);
  22789. output[i++] = itob( date->tm_year % 10);
  22790. output[i++] = itob(date->tm_mon / 10);
  22791. output[i++] = itob(date->tm_mon % 10);
  22792. output[i++] = itob(date->tm_mday / 10);
  22793. output[i++] = itob(date->tm_mday % 10);
  22794. output[i++] = itob(date->tm_hour / 10);
  22795. output[i++] = itob(date->tm_hour % 10);
  22796. output[i++] = itob(date->tm_min / 10);
  22797. output[i++] = itob(date->tm_min % 10);
  22798. output[i++] = itob(date->tm_sec / 10);
  22799. output[i++] = itob(date->tm_sec % 10);
  22800. output[i] = 'Z'; /* Zulu profile */
  22801. }
  22802. #endif
  22803. #ifndef WOLFSSL_ASN_TEMPLATE
  22804. /* Copy Dates from cert, return bytes written */
  22805. static int CopyValidity(byte* output, Cert* cert)
  22806. {
  22807. word32 seqSz;
  22808. WOLFSSL_ENTER("CopyValidity");
  22809. /* headers and output */
  22810. seqSz = SetSequence((word32)(cert->beforeDateSz + cert->afterDateSz),
  22811. output);
  22812. if (output) {
  22813. XMEMCPY(output + seqSz, cert->beforeDate, (size_t)cert->beforeDateSz);
  22814. XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
  22815. (size_t)cert->afterDateSz);
  22816. }
  22817. return (int)seqSz + cert->beforeDateSz + cert->afterDateSz;
  22818. }
  22819. #endif /* !WOLFSSL_ASN_TEMPLATE */
  22820. /* Simple name OID size. */
  22821. #define NAME_OID_SZ 3
  22822. /* Domain name OIDs. */
  22823. static const byte nameOid[][NAME_OID_SZ] = {
  22824. { 0x55, 0x04, ASN_COUNTRY_NAME },
  22825. { 0x55, 0x04, ASN_STATE_NAME },
  22826. { 0x55, 0x04, ASN_STREET_ADDR },
  22827. { 0x55, 0x04, ASN_LOCALITY_NAME },
  22828. #ifdef WOLFSSL_CERT_NAME_ALL
  22829. { 0x55, 0x04, ASN_NAME },
  22830. { 0x55, 0x04, ASN_GIVEN_NAME },
  22831. { 0x55, 0x04, ASN_INITIALS },
  22832. { 0x55, 0x04, ASN_DNQUALIFIER },
  22833. #endif
  22834. { 0x55, 0x04, ASN_SUR_NAME },
  22835. { 0x55, 0x04, ASN_ORG_NAME },
  22836. { 0x00, 0x00, ASN_DOMAIN_COMPONENT}, /* not actual OID - see dcOid */
  22837. /* list all DC values before OUs */
  22838. { 0x55, 0x04, ASN_ORGUNIT_NAME },
  22839. { 0x55, 0x04, ASN_COMMON_NAME },
  22840. { 0x55, 0x04, ASN_SERIAL_NUMBER },
  22841. #ifdef WOLFSSL_CERT_EXT
  22842. { 0x55, 0x04, ASN_BUS_CAT },
  22843. #endif
  22844. { 0x55, 0x04, ASN_POSTAL_CODE },
  22845. { 0x00, 0x00, ASN_EMAIL_NAME}, /* not actual OID - see attrEmailOid */
  22846. { 0x00, 0x00, ASN_USER_ID}, /* not actual OID - see uidOid */
  22847. #ifdef WOLFSSL_CUSTOM_OID
  22848. { 0x00, 0x00, ASN_CUSTOM_NAME} /* OID comes from CertOidField */
  22849. #endif
  22850. };
  22851. #define NAME_ENTRIES (int)(sizeof(nameOid)/NAME_OID_SZ)
  22852. /* Get ASN Name from index */
  22853. byte GetCertNameId(int idx)
  22854. {
  22855. if (idx < NAME_ENTRIES)
  22856. return nameOid[idx][2];
  22857. return 0;
  22858. }
  22859. /* Get Which Name from index */
  22860. const char* GetOneCertName(CertName* name, int idx)
  22861. {
  22862. byte type = GetCertNameId(idx);
  22863. switch (type) {
  22864. case ASN_COUNTRY_NAME:
  22865. return name->country;
  22866. case ASN_STATE_NAME:
  22867. return name->state;
  22868. case ASN_STREET_ADDR:
  22869. return name->street;
  22870. case ASN_LOCALITY_NAME:
  22871. return name->locality;
  22872. #ifdef WOLFSSL_CERT_NAME_ALL
  22873. case ASN_NAME:
  22874. return name->dnName;
  22875. case ASN_GIVEN_NAME:
  22876. return name->givenName;
  22877. case ASN_INITIALS:
  22878. return name->initials;
  22879. case ASN_DNQUALIFIER:
  22880. return name->dnQualifier;
  22881. #endif /* WOLFSSL_CERT_NAME_ALL */
  22882. case ASN_SUR_NAME:
  22883. return name->sur;
  22884. case ASN_ORG_NAME:
  22885. return name->org;
  22886. case ASN_ORGUNIT_NAME:
  22887. return name->unit;
  22888. case ASN_COMMON_NAME:
  22889. return name->commonName;
  22890. case ASN_SERIAL_NUMBER:
  22891. return name->serialDev;
  22892. case ASN_USER_ID:
  22893. return name->userId;
  22894. case ASN_POSTAL_CODE:
  22895. return name->postalCode;
  22896. case ASN_EMAIL_NAME:
  22897. return name->email;
  22898. #ifdef WOLFSSL_CERT_EXT
  22899. case ASN_BUS_CAT:
  22900. return name->busCat;
  22901. #endif
  22902. #ifdef WOLFSSL_CUSTOM_OID
  22903. case ASN_CUSTOM_NAME:
  22904. return (const char*)name->custom.val;
  22905. #endif
  22906. default:
  22907. return NULL;
  22908. }
  22909. }
  22910. /* Get Which Name Encoding from index */
  22911. static char GetNameType(CertName* name, int idx)
  22912. {
  22913. byte type = GetCertNameId(idx);
  22914. switch (type) {
  22915. case ASN_COUNTRY_NAME:
  22916. return name->countryEnc;
  22917. case ASN_STATE_NAME:
  22918. return name->stateEnc;
  22919. case ASN_STREET_ADDR:
  22920. return name->streetEnc;
  22921. case ASN_LOCALITY_NAME:
  22922. return name->localityEnc;
  22923. #ifdef WOLFSSL_CERT_NAME_ALL
  22924. case ASN_NAME:
  22925. return name->dnNameEnc;
  22926. case ASN_GIVEN_NAME:
  22927. return name->givenNameEnc;
  22928. case ASN_INITIALS:
  22929. return name->initialsEnc;
  22930. case ASN_DNQUALIFIER:
  22931. return name->dnQualifierEnc;
  22932. #endif /* WOLFSSL_CERT_NAME_ALL */
  22933. case ASN_SUR_NAME:
  22934. return name->surEnc;
  22935. case ASN_ORG_NAME:
  22936. return name->orgEnc;
  22937. case ASN_ORGUNIT_NAME:
  22938. return name->unitEnc;
  22939. case ASN_COMMON_NAME:
  22940. return name->commonNameEnc;
  22941. case ASN_SERIAL_NUMBER:
  22942. return name->serialDevEnc;
  22943. case ASN_USER_ID:
  22944. return name->userIdEnc;
  22945. case ASN_POSTAL_CODE:
  22946. return name->postalCodeEnc;
  22947. case ASN_EMAIL_NAME:
  22948. return 0; /* special */
  22949. #ifdef WOLFSSL_CERT_EXT
  22950. case ASN_BUS_CAT:
  22951. return name->busCatEnc;
  22952. #endif
  22953. #ifdef WOLFSSL_CUSTOM_OID
  22954. case ASN_CUSTOM_NAME:
  22955. return name->custom.enc;
  22956. #endif
  22957. default:
  22958. return 0;
  22959. }
  22960. }
  22961. #ifndef WOLFSSL_ASN_TEMPLATE
  22962. /*
  22963. Extensions ::= SEQUENCE OF Extension
  22964. Extension ::= SEQUENCE {
  22965. extnId OBJECT IDENTIFIER,
  22966. critical BOOLEAN DEFAULT FALSE,
  22967. extnValue OCTET STRING }
  22968. */
  22969. /* encode all extensions, return total bytes written */
  22970. static int SetExtensions(byte* out, word32 outSz, int *IdxInOut,
  22971. const byte* ext, int extSz)
  22972. {
  22973. if (out == NULL || IdxInOut == NULL || ext == NULL)
  22974. return BAD_FUNC_ARG;
  22975. if (outSz < (word32)(*IdxInOut+extSz))
  22976. return BUFFER_E;
  22977. XMEMCPY(&out[*IdxInOut], ext, (size_t)extSz); /* extensions */
  22978. *IdxInOut += extSz;
  22979. return *IdxInOut;
  22980. }
  22981. /* encode extensions header, return total bytes written */
  22982. static int SetExtensionsHeader(byte* out, word32 outSz, word32 extSz)
  22983. {
  22984. byte sequence[MAX_SEQ_SZ];
  22985. byte len[MAX_LENGTH_SZ];
  22986. word32 seqSz, lenSz, idx = 0;
  22987. if (out == NULL)
  22988. return BAD_FUNC_ARG;
  22989. if (outSz < 3)
  22990. return BUFFER_E;
  22991. seqSz = SetSequence(extSz, sequence);
  22992. /* encode extensions length provided */
  22993. lenSz = SetLength(extSz+seqSz, len);
  22994. if (outSz < (word32)(lenSz+seqSz+1))
  22995. return BUFFER_E;
  22996. out[idx++] = ASN_EXTENSIONS; /* extensions id */
  22997. XMEMCPY(&out[idx], len, lenSz); /* length */
  22998. idx += lenSz;
  22999. XMEMCPY(&out[idx], sequence, seqSz); /* sequence */
  23000. idx += seqSz;
  23001. return (int)idx;
  23002. }
  23003. /* encode CA basic constraints true with path length
  23004. * return total bytes written */
  23005. static int SetCaWithPathLen(byte* out, word32 outSz, byte pathLen)
  23006. {
  23007. /* ASN1->DER sequence for Basic Constraints True and path length */
  23008. const byte caPathLenBasicConstASN1[] = {
  23009. 0x30, 0x0F, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04,
  23010. 0x08, 0x30, 0x06, 0x01, 0x01, 0xFF, 0x02, 0x01,
  23011. 0x00
  23012. };
  23013. if (out == NULL)
  23014. return BAD_FUNC_ARG;
  23015. if (outSz < sizeof(caPathLenBasicConstASN1))
  23016. return BUFFER_E;
  23017. XMEMCPY(out, caPathLenBasicConstASN1, sizeof(caPathLenBasicConstASN1));
  23018. out[sizeof(caPathLenBasicConstASN1)-1] = pathLen;
  23019. return (int)sizeof(caPathLenBasicConstASN1);
  23020. }
  23021. /* encode CA basic constraints true
  23022. * return total bytes written */
  23023. static int SetCa(byte* out, word32 outSz)
  23024. {
  23025. /* ASN1->DER sequence for Basic Constraints True */
  23026. const byte caBasicConstASN1[] = {
  23027. 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  23028. 0x05, 0x30, 0x03, 0x01, 0x01, 0xff
  23029. };
  23030. if (out == NULL)
  23031. return BAD_FUNC_ARG;
  23032. if (outSz < sizeof(caBasicConstASN1))
  23033. return BUFFER_E;
  23034. XMEMCPY(out, caBasicConstASN1, sizeof(caBasicConstASN1));
  23035. return (int)sizeof(caBasicConstASN1);
  23036. }
  23037. /* encode basic constraints without CA Boolean
  23038. * return total bytes written */
  23039. static int SetBC(byte* out, word32 outSz)
  23040. {
  23041. /* ASN1->DER sequence for Basic Constraint without CA Boolean */
  23042. const byte BasicConstASN1[] = {
  23043. 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  23044. 0x02, 0x30, 0x00
  23045. };
  23046. if (out == NULL)
  23047. return BAD_FUNC_ARG;
  23048. if (outSz < sizeof(BasicConstASN1))
  23049. return BUFFER_E;
  23050. XMEMCPY(out, BasicConstASN1, sizeof(BasicConstASN1));
  23051. return (int)sizeof(BasicConstASN1);
  23052. }
  23053. #endif
  23054. #ifdef WOLFSSL_CERT_EXT
  23055. #ifndef WOLFSSL_ASN_TEMPLATE
  23056. /* encode OID and associated value, return total bytes written */
  23057. static int SetOidValue(byte* out, word32 outSz, const byte *oid, word32 oidSz,
  23058. byte *in, word32 inSz)
  23059. {
  23060. word32 idx = 0;
  23061. if (out == NULL || oid == NULL || in == NULL)
  23062. return BAD_FUNC_ARG;
  23063. if (outSz < 3)
  23064. return BUFFER_E;
  23065. /* sequence, + 1 => byte to put value size */
  23066. idx = SetSequence(inSz + oidSz + 1, out);
  23067. if ((idx + inSz + oidSz + 1) > outSz)
  23068. return BUFFER_E;
  23069. XMEMCPY(out+idx, oid, oidSz);
  23070. idx += oidSz;
  23071. out[idx++] = (byte)inSz;
  23072. XMEMCPY(out+idx, in, inSz);
  23073. return (int)(idx+inSz);
  23074. }
  23075. /* encode Subject Key Identifier, return total bytes written
  23076. * RFC5280 : non-critical */
  23077. static int SetSKID(byte* output, word32 outSz, const byte *input, word32 length)
  23078. {
  23079. byte skid_len[1 + MAX_LENGTH_SZ];
  23080. byte skid_enc_len[MAX_LENGTH_SZ];
  23081. word32 idx = 0, skid_lenSz, skid_enc_lenSz;
  23082. const byte skid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04 };
  23083. if (output == NULL || input == NULL)
  23084. return BAD_FUNC_ARG;
  23085. /* Octet String header */
  23086. skid_lenSz = SetOctetString(length, skid_len);
  23087. /* length of encoded value */
  23088. skid_enc_lenSz = SetLength(length + skid_lenSz, skid_enc_len);
  23089. if (outSz < 3)
  23090. return BUFFER_E;
  23091. idx = SetSequence(length + (word32)sizeof(skid_oid) + skid_lenSz +
  23092. skid_enc_lenSz, output);
  23093. if ((length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz) > outSz)
  23094. return BUFFER_E;
  23095. /* put oid */
  23096. XMEMCPY(output+idx, skid_oid, sizeof(skid_oid));
  23097. idx += sizeof(skid_oid);
  23098. /* put encoded len */
  23099. XMEMCPY(output+idx, skid_enc_len, skid_enc_lenSz);
  23100. idx += skid_enc_lenSz;
  23101. /* put octet header */
  23102. XMEMCPY(output+idx, skid_len, skid_lenSz);
  23103. idx += skid_lenSz;
  23104. /* put value */
  23105. XMEMCPY(output+idx, input, length);
  23106. idx += length;
  23107. return (int)idx;
  23108. }
  23109. /* encode Authority Key Identifier, return total bytes written
  23110. * RFC5280 : non-critical */
  23111. static int SetAKID(byte* output, word32 outSz, byte *input, word32 length,
  23112. byte rawAkid)
  23113. {
  23114. int enc_valSz;
  23115. byte enc_val_buf[MAX_KID_SZ];
  23116. byte* enc_val;
  23117. const byte akid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x23 };
  23118. const byte akid_cs[] = { 0x80 };
  23119. word32 inSeqSz, idx;
  23120. (void)rawAkid;
  23121. if (output == NULL || input == NULL)
  23122. return BAD_FUNC_ARG;
  23123. #ifdef WOLFSSL_AKID_NAME
  23124. if (rawAkid) {
  23125. enc_val = input;
  23126. enc_valSz = length;
  23127. }
  23128. else
  23129. #endif
  23130. {
  23131. enc_val = enc_val_buf;
  23132. enc_valSz = (int)length + 3 + (int)sizeof(akid_cs);
  23133. if (enc_valSz > (int)sizeof(enc_val_buf))
  23134. return BAD_FUNC_ARG;
  23135. /* sequence for ContentSpec & value */
  23136. enc_valSz = SetOidValue(enc_val, (word32)enc_valSz, akid_cs,
  23137. sizeof(akid_cs), input, length);
  23138. if (enc_valSz <= 0)
  23139. return enc_valSz;
  23140. }
  23141. /* The size of the extension sequence contents */
  23142. inSeqSz = (word32)sizeof(akid_oid) +
  23143. SetOctetString((word32)enc_valSz, NULL) + (word32)enc_valSz;
  23144. if (SetSequence(inSeqSz, NULL) + inSeqSz > outSz)
  23145. return BAD_FUNC_ARG;
  23146. /* Write out the sequence header */
  23147. idx = SetSequence(inSeqSz, output);
  23148. /* Write out OID */
  23149. XMEMCPY(output + idx, akid_oid, sizeof(akid_oid));
  23150. idx += sizeof(akid_oid);
  23151. /* Write out AKID */
  23152. idx += SetOctetString((word32)enc_valSz, output + idx);
  23153. XMEMCPY(output + idx, enc_val, (size_t)enc_valSz);
  23154. return (int)idx + enc_valSz;
  23155. }
  23156. /* encode Key Usage, return total bytes written
  23157. * RFC5280 : critical */
  23158. static int SetKeyUsage(byte* output, word32 outSz, word16 input)
  23159. {
  23160. byte ku[5];
  23161. word32 idx;
  23162. const byte keyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0f,
  23163. 0x01, 0x01, 0xff, 0x04};
  23164. if (output == NULL)
  23165. return BAD_FUNC_ARG;
  23166. idx = SetBitString16Bit(input, ku);
  23167. return SetOidValue(output, outSz, keyusage_oid, sizeof(keyusage_oid),
  23168. ku, idx);
  23169. }
  23170. static int SetOjectIdValue(byte* output, word32 outSz, word32* idx,
  23171. const byte* oid, word32 oidSz)
  23172. {
  23173. /* verify room */
  23174. if (*idx + 2 + oidSz >= outSz)
  23175. return ASN_PARSE_E;
  23176. *idx += (word32)SetObjectId((int)oidSz, &output[*idx]);
  23177. XMEMCPY(&output[*idx], oid, oidSz);
  23178. *idx += oidSz;
  23179. return 0;
  23180. }
  23181. #endif
  23182. #ifdef WOLFSSL_ASN_TEMPLATE
  23183. /* ASN.1 template for extended key usage.
  23184. * X.509: RFC 5280, 4.2.12 - Extended Key Usage
  23185. * Dynamic creation of template for encoding.
  23186. */
  23187. static const ASNItem ekuASN[] = {
  23188. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  23189. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  23190. };
  23191. enum {
  23192. EKUASN_IDX_SEQ = 0,
  23193. EKUASN_IDX_OID
  23194. };
  23195. /* OIDs corresponding to extended key usage. */
  23196. struct {
  23197. const byte* oid;
  23198. word32 oidSz;
  23199. } ekuOid[] = {
  23200. { extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid) },
  23201. { extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid) },
  23202. { extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid) },
  23203. { extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid) },
  23204. { extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid) },
  23205. { extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid) },
  23206. };
  23207. #define EKU_OID_LO 1
  23208. #define EKU_OID_HI 6
  23209. #endif /* WOLFSSL_ASN_TEMPLATE */
  23210. /* encode Extended Key Usage (RFC 5280 4.2.1.12), return total bytes written */
  23211. static int SetExtKeyUsage(Cert* cert, byte* output, word32 outSz, byte input)
  23212. {
  23213. #ifndef WOLFSSL_ASN_TEMPLATE
  23214. word32 idx = 0, oidListSz = 0, totalSz;
  23215. int ret = 0;
  23216. const byte extkeyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x25 };
  23217. if (output == NULL)
  23218. return BAD_FUNC_ARG;
  23219. /* Skip to OID List */
  23220. totalSz = 2 + sizeof(extkeyusage_oid) + 4;
  23221. idx = totalSz;
  23222. /* Build OID List */
  23223. /* If any set, then just use it */
  23224. if (input & EXTKEYUSE_ANY) {
  23225. ret |= SetOjectIdValue(output, outSz, &idx,
  23226. extExtKeyUsageAnyOid, sizeof(extExtKeyUsageAnyOid));
  23227. }
  23228. else {
  23229. if (input & EXTKEYUSE_SERVER_AUTH)
  23230. ret |= SetOjectIdValue(output, outSz, &idx,
  23231. extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid));
  23232. if (input & EXTKEYUSE_CLIENT_AUTH)
  23233. ret |= SetOjectIdValue(output, outSz, &idx,
  23234. extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid));
  23235. if (input & EXTKEYUSE_CODESIGN)
  23236. ret |= SetOjectIdValue(output, outSz, &idx,
  23237. extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid));
  23238. if (input & EXTKEYUSE_EMAILPROT)
  23239. ret |= SetOjectIdValue(output, outSz, &idx,
  23240. extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid));
  23241. if (input & EXTKEYUSE_TIMESTAMP)
  23242. ret |= SetOjectIdValue(output, outSz, &idx,
  23243. extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid));
  23244. if (input & EXTKEYUSE_OCSP_SIGN)
  23245. ret |= SetOjectIdValue(output, outSz, &idx,
  23246. extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid));
  23247. #ifdef WOLFSSL_EKU_OID
  23248. /* iterate through OID values */
  23249. if (input & EXTKEYUSE_USER) {
  23250. int i, sz;
  23251. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  23252. sz = cert->extKeyUsageOIDSz[i];
  23253. if (sz > 0) {
  23254. ret |= SetOjectIdValue(output, outSz, &idx,
  23255. cert->extKeyUsageOID[i], sz);
  23256. }
  23257. }
  23258. }
  23259. #endif /* WOLFSSL_EKU_OID */
  23260. }
  23261. if (ret != 0)
  23262. return ASN_PARSE_E;
  23263. /* Calculate Sizes */
  23264. oidListSz = idx - totalSz;
  23265. totalSz = idx - 2; /* exclude first seq/len (2) */
  23266. /* 1. Seq + Total Len (2) */
  23267. idx = SetSequence(totalSz, output);
  23268. /* 2. Object ID (2) */
  23269. XMEMCPY(&output[idx], extkeyusage_oid, sizeof(extkeyusage_oid));
  23270. idx += sizeof(extkeyusage_oid);
  23271. /* 3. Octet String (2) */
  23272. idx += SetOctetString(totalSz - idx, &output[idx]);
  23273. /* 4. Seq + OidListLen (2) */
  23274. idx += SetSequence(oidListSz, &output[idx]);
  23275. /* 5. Oid List (already set in-place above) */
  23276. idx += oidListSz;
  23277. (void)cert;
  23278. return (int)idx;
  23279. #else
  23280. /* TODO: consider calculating size of OBJECT_IDs, setting length into
  23281. * SEQUENCE, encode SEQUENCE, encode OBJECT_IDs into buffer. */
  23282. ASNSetData* dataASN;
  23283. ASNItem* extKuASN = NULL;
  23284. int asnIdx = 1;
  23285. size_t cnt = 1 + EKU_OID_HI;
  23286. int i;
  23287. int ret = 0;
  23288. int sz = 0;
  23289. #ifdef WOLFSSL_EKU_OID
  23290. cnt += CTC_MAX_EKU_NB;
  23291. #endif
  23292. /* Allocate memory for dynamic data items. */
  23293. dataASN = (ASNSetData*)XMALLOC(cnt * sizeof(ASNSetData), cert->heap,
  23294. DYNAMIC_TYPE_TMP_BUFFER);
  23295. if (dataASN == NULL) {
  23296. ret = MEMORY_E;
  23297. }
  23298. if (ret == 0) {
  23299. /* Allocate memory for dynamic ASN.1 template. */
  23300. extKuASN = (ASNItem*)XMALLOC(cnt * sizeof(ASNItem), cert->heap,
  23301. DYNAMIC_TYPE_TMP_BUFFER);
  23302. if (extKuASN == NULL) {
  23303. ret = MEMORY_E;
  23304. }
  23305. }
  23306. if (ret == 0) {
  23307. /* Copy Sequence into dynamic ASN.1 template. */
  23308. XMEMCPY(&extKuASN[EKUASN_IDX_SEQ], ekuASN, sizeof(ASNItem));
  23309. /* Clear dynamic data. */
  23310. XMEMSET(dataASN, 0, cnt * sizeof(ASNSetData));
  23311. /* Build up the template and data. */
  23312. /* If 'any' set, then just use it. */
  23313. if ((input & EXTKEYUSE_ANY) == EXTKEYUSE_ANY) {
  23314. /* Set template item. */
  23315. XMEMCPY(&extKuASN[EKUASN_IDX_OID], &ekuASN[EKUASN_IDX_OID],
  23316. sizeof(ASNItem));
  23317. /* Set data item. */
  23318. SetASN_Buffer(&dataASN[asnIdx], extExtKeyUsageAnyOid,
  23319. sizeof(extExtKeyUsageAnyOid));
  23320. asnIdx++;
  23321. }
  23322. else {
  23323. /* Step through the flagged purposes. */
  23324. for (i = EKU_OID_LO; i <= EKU_OID_HI; i++) {
  23325. if ((input & (1 << i)) != 0) {
  23326. /* Set template item. */
  23327. XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
  23328. sizeof(ASNItem));
  23329. /* Set data item. */
  23330. SetASN_Buffer(&dataASN[asnIdx], ekuOid[i - 1].oid,
  23331. ekuOid[i - 1].oidSz);
  23332. asnIdx++;
  23333. }
  23334. }
  23335. #ifdef WOLFSSL_EKU_OID
  23336. if (input & EXTKEYUSE_USER) {
  23337. /* Iterate through OID values */
  23338. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  23339. sz = cert->extKeyUsageOIDSz[i];
  23340. if (sz > 0) {
  23341. /* Set template item. */
  23342. XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
  23343. sizeof(ASNItem));
  23344. /* Set data item. */
  23345. SetASN_Buffer(&dataASN[asnIdx], cert->extKeyUsageOID[i],
  23346. sz);
  23347. asnIdx++;
  23348. }
  23349. }
  23350. }
  23351. #endif /* WOLFSSL_EKU_OID */
  23352. (void)cert;
  23353. }
  23354. /* Calculate size of encoding. */
  23355. sz = 0;
  23356. ret = SizeASN_Items(extKuASN, dataASN, asnIdx, &sz);
  23357. }
  23358. /* When buffer to write to, ensure it's big enough. */
  23359. if ((ret == 0) && (output != NULL) && (sz > (int)outSz)) {
  23360. ret = BUFFER_E;
  23361. }
  23362. if ((ret == 0) && (output != NULL)) {
  23363. /* Encode extended key usage. */
  23364. SetASN_Items(extKuASN, dataASN, asnIdx, output);
  23365. }
  23366. if (ret == 0) {
  23367. /* Return the encoding size. */
  23368. ret = sz;
  23369. }
  23370. /* Dispose of allocated data. */
  23371. if (extKuASN != NULL) {
  23372. XFREE(extKuASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23373. }
  23374. if (dataASN != NULL) {
  23375. XFREE(dataASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23376. }
  23377. return ret;
  23378. #endif
  23379. }
  23380. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  23381. #ifndef WOLFSSL_ASN_TEMPLATE
  23382. static int SetNsCertType(Cert* cert, byte* output, word32 outSz, byte input)
  23383. {
  23384. word32 idx;
  23385. byte unusedBits = 0;
  23386. byte nsCertType = input;
  23387. word32 totalSz;
  23388. word32 bitStrSz;
  23389. const byte nscerttype_oid[] = { 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
  23390. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  23391. if (cert == NULL || output == NULL ||
  23392. input == 0)
  23393. return BAD_FUNC_ARG;
  23394. totalSz = sizeof(nscerttype_oid);
  23395. /* Get amount of lsb zero's */
  23396. for (;(input & 1) == 0; input >>= 1)
  23397. unusedBits++;
  23398. /* 1 byte of NS Cert Type extension */
  23399. bitStrSz = SetBitString(1, unusedBits, NULL) + 1;
  23400. totalSz += SetOctetString(bitStrSz, NULL) + bitStrSz;
  23401. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  23402. return BAD_FUNC_ARG;
  23403. /* 1. Seq + Total Len */
  23404. idx = SetSequence(totalSz, output);
  23405. /* 2. Object ID */
  23406. XMEMCPY(&output[idx], nscerttype_oid, sizeof(nscerttype_oid));
  23407. idx += sizeof(nscerttype_oid);
  23408. /* 3. Octet String */
  23409. idx += SetOctetString(bitStrSz, &output[idx]);
  23410. /* 4. Bit String */
  23411. idx += SetBitString(1, unusedBits, &output[idx]);
  23412. output[idx++] = nsCertType;
  23413. return (int)idx;
  23414. }
  23415. #endif
  23416. #endif
  23417. #ifndef WOLFSSL_ASN_TEMPLATE
  23418. static int SetCRLInfo(Cert* cert, byte* output, word32 outSz, byte* input,
  23419. int inSz)
  23420. {
  23421. word32 idx;
  23422. word32 totalSz;
  23423. const byte crlinfo_oid[] = { 0x06, 0x03, 0x55, 0x1D, 0x1F };
  23424. if (cert == NULL || output == NULL ||
  23425. input == 0 || inSz <= 0)
  23426. return BAD_FUNC_ARG;
  23427. totalSz = (word32)sizeof(crlinfo_oid) + SetOctetString((word32)inSz, NULL) +
  23428. (word32)inSz;
  23429. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  23430. return BAD_FUNC_ARG;
  23431. /* 1. Seq + Total Len */
  23432. idx = SetSequence(totalSz, output);
  23433. /* 2. Object ID */
  23434. XMEMCPY(&output[idx], crlinfo_oid, sizeof(crlinfo_oid));
  23435. idx += sizeof(crlinfo_oid);
  23436. /* 3. Octet String */
  23437. idx += SetOctetString((word32)inSz, &output[idx]);
  23438. /* 4. CRL Info */
  23439. XMEMCPY(&output[idx], input, (size_t)inSz);
  23440. idx += (word32)inSz;
  23441. return (int)idx;
  23442. }
  23443. #endif
  23444. /* encode Certificate Policies, return total bytes written
  23445. * each input value must be ITU-T X.690 formatted : a.b.c...
  23446. * input must be an array of values with a NULL terminated for the latest
  23447. * RFC5280 : non-critical */
  23448. static int SetCertificatePolicies(byte *output,
  23449. word32 outputSz,
  23450. char input[MAX_CERTPOL_NB][MAX_CERTPOL_SZ],
  23451. word16 nb_certpol,
  23452. void* heap)
  23453. {
  23454. #ifndef WOLFSSL_ASN_TEMPLATE
  23455. byte oid[MAX_OID_SZ];
  23456. byte der_oid[MAX_CERTPOL_NB][MAX_OID_SZ];
  23457. byte out[MAX_CERTPOL_SZ];
  23458. word32 oidSz;
  23459. word32 outSz;
  23460. word32 i = 0;
  23461. word32 der_oidSz[MAX_CERTPOL_NB];
  23462. int ret;
  23463. const byte certpol_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x20, 0x04 };
  23464. const byte oid_oid[] = { 0x06 };
  23465. if (output == NULL || input == NULL || nb_certpol > MAX_CERTPOL_NB)
  23466. return BAD_FUNC_ARG;
  23467. for (i = 0; i < nb_certpol; i++) {
  23468. oidSz = sizeof(oid);
  23469. XMEMSET(oid, 0, oidSz);
  23470. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  23471. if (ret != 0)
  23472. return ret;
  23473. /* compute sequence value for the oid */
  23474. ret = SetOidValue(der_oid[i], MAX_OID_SZ, oid_oid,
  23475. sizeof(oid_oid), oid, oidSz);
  23476. if (ret <= 0)
  23477. return ret;
  23478. else
  23479. der_oidSz[i] = (word32)ret;
  23480. }
  23481. /* concatenate oid, keep two byte for sequence/size of the created value */
  23482. for (i = 0, outSz = 2; i < nb_certpol; i++) {
  23483. XMEMCPY(out+outSz, der_oid[i], der_oidSz[i]);
  23484. outSz += der_oidSz[i];
  23485. }
  23486. /* add sequence */
  23487. ret = (int)SetSequence(outSz-2, out);
  23488. if (ret <= 0)
  23489. return ret;
  23490. /* add Policy OID to compute final value */
  23491. return SetOidValue(output, outputSz, certpol_oid, sizeof(certpol_oid),
  23492. out, outSz);
  23493. #else
  23494. int i;
  23495. int ret = 0;
  23496. byte oid[MAX_OID_SZ];
  23497. word32 oidSz;
  23498. word32 sz = 0;
  23499. int piSz;
  23500. if ((input == NULL) || (nb_certpol > MAX_CERTPOL_NB)) {
  23501. ret = BAD_FUNC_ARG;
  23502. }
  23503. /* Put in policyIdentifier but not policyQualifiers. */
  23504. for (i = 0; (ret == 0) && (i < nb_certpol); i++) {
  23505. ASNSetData dataASN[policyInfoASN_Length];
  23506. oidSz = sizeof(oid);
  23507. XMEMSET(oid, 0, oidSz);
  23508. dataASN[POLICYINFOASN_IDX_QUALI].noOut = 1;
  23509. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  23510. if (ret == 0) {
  23511. XMEMSET(dataASN, 0, sizeof(dataASN));
  23512. SetASN_Buffer(&dataASN[POLICYINFOASN_IDX_ID], oid, oidSz);
  23513. ret = SizeASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  23514. &piSz);
  23515. }
  23516. if ((ret == 0) && (output != NULL) && (sz + (word32)piSz > outputSz)) {
  23517. ret = BUFFER_E;
  23518. }
  23519. if (ret == 0) {
  23520. if (output != NULL) {
  23521. SetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  23522. output);
  23523. output += piSz;
  23524. }
  23525. sz += (word32)piSz;
  23526. }
  23527. }
  23528. if (ret == 0) {
  23529. ret = (int)sz;
  23530. }
  23531. return ret;
  23532. #endif
  23533. }
  23534. #endif /* WOLFSSL_CERT_EXT */
  23535. #ifdef WOLFSSL_ALT_NAMES
  23536. #ifndef WOLFSSL_ASN_TEMPLATE
  23537. /* encode Alternative Names, return total bytes written */
  23538. static int SetAltNames(byte *output, word32 outSz,
  23539. const byte *input, word32 length, int critical)
  23540. {
  23541. byte san_len[1 + MAX_LENGTH_SZ];
  23542. const byte san_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x11 };
  23543. const byte san_crit[] = { 0x01, 0x01, 0xff };
  23544. word32 seqSz, san_lenSz, idx = 0;
  23545. if (output == NULL || input == NULL)
  23546. return BAD_FUNC_ARG;
  23547. if (outSz < length)
  23548. return BUFFER_E;
  23549. /* Octet String header */
  23550. san_lenSz = SetOctetString(length, san_len);
  23551. if (outSz < MAX_SEQ_SZ)
  23552. return BUFFER_E;
  23553. seqSz = length + (word32)sizeof(san_oid) + san_lenSz;
  23554. if (critical)
  23555. seqSz += sizeof(san_crit);
  23556. idx = SetSequence(seqSz, output);
  23557. if (seqSz > outSz)
  23558. return BUFFER_E;
  23559. /* put oid */
  23560. XMEMCPY(output+idx, san_oid, sizeof(san_oid));
  23561. idx += sizeof(san_oid);
  23562. if (critical) {
  23563. XMEMCPY(output+idx, san_crit, sizeof(san_crit));
  23564. idx += sizeof(san_crit);
  23565. }
  23566. /* put octet header */
  23567. XMEMCPY(output+idx, san_len, san_lenSz);
  23568. idx += san_lenSz;
  23569. /* put value */
  23570. XMEMCPY(output+idx, input, length);
  23571. idx += length;
  23572. return (int)idx;
  23573. }
  23574. #endif /* WOLFSSL_ASN_TEMPLATE */
  23575. int FlattenAltNames(byte* output, word32 outputSz, const DNS_entry* names)
  23576. {
  23577. word32 idx;
  23578. const DNS_entry* curName;
  23579. word32 namesSz = 0;
  23580. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23581. word32 i;
  23582. #endif
  23583. if (output == NULL)
  23584. return BAD_FUNC_ARG;
  23585. if (names == NULL)
  23586. return 0;
  23587. curName = names;
  23588. do {
  23589. namesSz += (word32)curName->len + 2 +
  23590. ((curName->len < ASN_LONG_LENGTH) ? 0
  23591. : BytePrecision((word32)curName->len));
  23592. curName = curName->next;
  23593. } while (curName != NULL);
  23594. if (outputSz < MAX_SEQ_SZ + namesSz)
  23595. return BUFFER_E;
  23596. idx = SetSequence(namesSz, output);
  23597. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23598. namesSz += idx;
  23599. i = namesSz;
  23600. #endif
  23601. curName = names;
  23602. do {
  23603. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23604. word32 len = SetLength(curName->len, NULL);
  23605. idx = i - curName->len - len - 1;
  23606. i = idx;
  23607. #endif
  23608. output[idx] = (byte) (ASN_CONTEXT_SPECIFIC | curName->type);
  23609. if (curName->type == ASN_DIR_TYPE || curName->type == ASN_OTHER_TYPE) {
  23610. output[idx] |= ASN_CONSTRUCTED;
  23611. }
  23612. idx++;
  23613. idx += SetLength((word32)curName->len, output + idx);
  23614. XMEMCPY(output + idx, curName->name, (size_t)curName->len);
  23615. #ifndef WOLFSSL_ALT_NAMES_NO_REV
  23616. idx += (word32)curName->len;
  23617. #endif
  23618. curName = curName->next;
  23619. } while (curName != NULL);
  23620. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23621. idx = namesSz;
  23622. #endif
  23623. return (int)idx;
  23624. }
  23625. #endif /* WOLFSSL_ALT_NAMES */
  23626. #endif /* WOLFSSL_CERT_GEN */
  23627. #if defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  23628. /* Simple domain name OID size. */
  23629. #define DN_OID_SZ 3
  23630. /* Encodes one attribute of the name (issuer/subject)
  23631. *
  23632. * name structure to hold result of encoding
  23633. * nameStr value to be encoded
  23634. * nameTag tag of encoding i.e CTC_UTF8
  23635. * type id of attribute i.e ASN_COMMON_NAME
  23636. * emailTag tag of email i.e CTC_UTF8
  23637. * returns length on success
  23638. */
  23639. static int EncodeName(EncodedName* name, const char* nameStr,
  23640. byte nameTag, byte type, byte emailTag, CertName* cname)
  23641. {
  23642. #if !defined(WOLFSSL_ASN_TEMPLATE)
  23643. word32 idx = 0;
  23644. /* bottom up */
  23645. byte firstLen[1 + MAX_LENGTH_SZ];
  23646. byte secondLen[MAX_LENGTH_SZ];
  23647. byte sequence[MAX_SEQ_SZ];
  23648. byte set[MAX_SET_SZ];
  23649. word32 strLen;
  23650. word32 thisLen;
  23651. word32 firstSz, secondSz, seqSz, setSz;
  23652. if (nameStr == NULL) {
  23653. name->used = 0;
  23654. return 0;
  23655. }
  23656. thisLen = strLen = (word32)XSTRLEN(nameStr);
  23657. #ifdef WOLFSSL_CUSTOM_OID
  23658. if (type == ASN_CUSTOM_NAME) {
  23659. if (cname == NULL || cname->custom.oidSz == 0) {
  23660. name->used = 0;
  23661. return 0;
  23662. }
  23663. thisLen = strLen = (word32)cname->custom.valSz;
  23664. }
  23665. #else
  23666. (void)cname;
  23667. #endif
  23668. if (strLen == 0) { /* no user data for this item */
  23669. name->used = 0;
  23670. return 0;
  23671. }
  23672. /* Restrict country code size */
  23673. if (type == ASN_COUNTRY_NAME && strLen != CTC_COUNTRY_SIZE) {
  23674. WOLFSSL_MSG("Country code size error");
  23675. WOLFSSL_ERROR_VERBOSE(ASN_COUNTRY_SIZE_E);
  23676. return ASN_COUNTRY_SIZE_E;
  23677. }
  23678. secondSz = SetLength(strLen, secondLen);
  23679. thisLen += secondSz;
  23680. switch (type) {
  23681. case ASN_EMAIL_NAME: /* email */
  23682. thisLen += (int)sizeof(attrEmailOid);
  23683. firstSz = (int)sizeof(attrEmailOid);
  23684. break;
  23685. case ASN_DOMAIN_COMPONENT:
  23686. thisLen += (int)sizeof(dcOid);
  23687. firstSz = (int)sizeof(dcOid);
  23688. break;
  23689. case ASN_USER_ID:
  23690. thisLen += (int)sizeof(uidOid);
  23691. firstSz = (int)sizeof(uidOid);
  23692. break;
  23693. case ASN_FAVOURITE_DRINK:
  23694. thisLen += (int)sizeof(fvrtDrk);
  23695. firstSz = (int)sizeof(fvrtDrk);
  23696. break;
  23697. #ifdef WOLFSSL_CUSTOM_OID
  23698. case ASN_CUSTOM_NAME:
  23699. thisLen += cname->custom.oidSz;
  23700. firstSz = cname->custom.oidSz;
  23701. break;
  23702. #endif
  23703. default:
  23704. thisLen += DN_OID_SZ;
  23705. firstSz = DN_OID_SZ;
  23706. }
  23707. thisLen++; /* id type */
  23708. firstSz = (word32)SetObjectId((int)firstSz, firstLen);
  23709. thisLen += firstSz;
  23710. seqSz = SetSequence(thisLen, sequence);
  23711. thisLen += seqSz;
  23712. setSz = SetSet(thisLen, set);
  23713. thisLen += setSz;
  23714. if (thisLen > (int)sizeof(name->encoded)) {
  23715. return BUFFER_E;
  23716. }
  23717. /* store it */
  23718. idx = 0;
  23719. /* set */
  23720. XMEMCPY(name->encoded, set, setSz);
  23721. idx += setSz;
  23722. /* seq */
  23723. XMEMCPY(name->encoded + idx, sequence, seqSz);
  23724. idx += seqSz;
  23725. /* asn object id */
  23726. XMEMCPY(name->encoded + idx, firstLen, firstSz);
  23727. idx += firstSz;
  23728. switch (type) {
  23729. case ASN_EMAIL_NAME:
  23730. /* email joint id */
  23731. XMEMCPY(name->encoded + idx, attrEmailOid, sizeof(attrEmailOid));
  23732. idx += (int)sizeof(attrEmailOid);
  23733. name->encoded[idx++] = emailTag;
  23734. break;
  23735. case ASN_DOMAIN_COMPONENT:
  23736. XMEMCPY(name->encoded + idx, dcOid, sizeof(dcOid)-1);
  23737. idx += (int)sizeof(dcOid)-1;
  23738. /* id type */
  23739. name->encoded[idx++] = type;
  23740. /* str type */
  23741. name->encoded[idx++] = nameTag;
  23742. break;
  23743. case ASN_USER_ID:
  23744. XMEMCPY(name->encoded + idx, uidOid, sizeof(uidOid));
  23745. idx += (int)sizeof(uidOid);
  23746. /* str type */
  23747. name->encoded[idx++] = nameTag;
  23748. break;
  23749. case ASN_FAVOURITE_DRINK:
  23750. XMEMCPY(name->encoded + idx, fvrtDrk, sizeof(fvrtDrk));
  23751. idx += (int)sizeof(fvrtDrk);
  23752. /* str type */
  23753. name->encoded[idx++] = nameTag;
  23754. break;
  23755. #ifdef WOLFSSL_CUSTOM_OID
  23756. case ASN_CUSTOM_NAME:
  23757. XMEMCPY(name->encoded + idx, cname->custom.oid,
  23758. cname->custom.oidSz);
  23759. idx += cname->custom.oidSz;
  23760. /* str type */
  23761. name->encoded[idx++] = nameTag;
  23762. break;
  23763. #endif
  23764. default:
  23765. name->encoded[idx++] = 0x55;
  23766. name->encoded[idx++] = 0x04;
  23767. /* id type */
  23768. name->encoded[idx++] = type;
  23769. /* str type */
  23770. name->encoded[idx++] = nameTag;
  23771. }
  23772. /* second length */
  23773. XMEMCPY(name->encoded + idx, secondLen, secondSz);
  23774. idx += secondSz;
  23775. /* str value */
  23776. XMEMCPY(name->encoded + idx, nameStr, strLen);
  23777. idx += strLen;
  23778. name->type = type;
  23779. name->totalLen = (int)idx;
  23780. name->used = 1;
  23781. return (int)idx;
  23782. #else
  23783. DECL_ASNSETDATA(dataASN, rdnASN_Length);
  23784. ASNItem namesASN[rdnASN_Length];
  23785. byte dnOid[DN_OID_SZ] = { 0x55, 0x04, 0x00 };
  23786. int ret = 0;
  23787. int sz = 0;
  23788. const byte* oid;
  23789. word32 oidSz;
  23790. word32 nameSz;
  23791. /* Validate input parameters. */
  23792. if ((name == NULL) || (nameStr == NULL)) {
  23793. ret = BAD_FUNC_ARG;
  23794. }
  23795. CALLOC_ASNSETDATA(dataASN, rdnASN_Length, ret, NULL);
  23796. if (ret == 0) {
  23797. nameSz = (word32)XSTRLEN(nameStr);
  23798. /* Copy the RDN encoding template. ASN.1 tag for the name string is set
  23799. * based on type. */
  23800. XMEMCPY(namesASN, rdnASN, sizeof(namesASN));
  23801. /* Set OID and ASN.1 tag for name depending on type. */
  23802. switch (type) {
  23803. case ASN_EMAIL_NAME:
  23804. /* email OID different to standard types. */
  23805. oid = attrEmailOid;
  23806. oidSz = sizeof(attrEmailOid);
  23807. /* Use email specific type/tag. */
  23808. nameTag = emailTag;
  23809. break;
  23810. case ASN_DOMAIN_COMPONENT:
  23811. /* Domain component OID different to standard types. */
  23812. oid = dcOid;
  23813. oidSz = sizeof(dcOid);
  23814. break;
  23815. case ASN_USER_ID:
  23816. /* Domain component OID different to standard types. */
  23817. oid = uidOid;
  23818. oidSz = sizeof(uidOid);
  23819. break;
  23820. case ASN_FAVOURITE_DRINK:
  23821. oid = fvrtDrk;
  23822. oidSz = sizeof(fvrtDrk);
  23823. break;
  23824. #ifdef WOLFSSL_CUSTOM_OID
  23825. case ASN_CUSTOM_NAME:
  23826. nameSz = cname->custom.valSz;
  23827. oid = cname->custom.oid;
  23828. oidSz = cname->custom.oidSz;
  23829. break;
  23830. #endif
  23831. default:
  23832. /* Construct OID using type. */
  23833. dnOid[2] = type;
  23834. oid = dnOid;
  23835. oidSz = DN_OID_SZ;
  23836. break;
  23837. }
  23838. /* Set OID corresponding to the name type. */
  23839. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
  23840. /* Set name string. */
  23841. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], (const byte *)nameStr, nameSz);
  23842. /* Set the ASN.1 tag for the name string. */
  23843. namesASN[RDNASN_IDX_ATTR_VAL].tag = nameTag;
  23844. /* Calculate size of encoded name and indexes of components. */
  23845. ret = SizeASN_Items(namesASN, dataASN, rdnASN_Length, &sz);
  23846. }
  23847. /* Check if name's buffer is big enough. */
  23848. if ((ret == 0) && (sz > (int)sizeof(name->encoded))) {
  23849. ret = BUFFER_E;
  23850. }
  23851. if (ret == 0) {
  23852. /* Encode name into the buffer. */
  23853. SetASN_Items(namesASN, dataASN, rdnASN_Length, name->encoded);
  23854. /* Cache the type and size, and set that it is used. */
  23855. name->type = type;
  23856. name->totalLen = sz;
  23857. name->used = 1;
  23858. /* Return size of encoding. */
  23859. ret = sz;
  23860. }
  23861. (void)cname;
  23862. FREE_ASNSETDATA(dataASN, NULL);
  23863. return ret;
  23864. #endif /* WOLFSSL_ASN_TEMPLATE */
  23865. }
  23866. /* canonical encoding one attribute of the name (issuer/subject)
  23867. * call EncodeName with CTC_UTF8 for email type
  23868. *
  23869. * name structure to hold result of encoding
  23870. * nameStr value to be encoded
  23871. * nameType type of encoding i.e CTC_UTF8
  23872. * type id of attribute i.e ASN_COMMON_NAME
  23873. *
  23874. * returns length on success
  23875. */
  23876. int wc_EncodeNameCanonical(EncodedName* name, const char* nameStr,
  23877. char nameType, byte type)
  23878. {
  23879. return EncodeName(name, nameStr, (byte)nameType, type,
  23880. ASN_UTF8STRING, NULL);
  23881. }
  23882. #endif /* WOLFSSL_CERT_GEN || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  23883. #ifdef WOLFSSL_CERT_GEN
  23884. /* Encodes one attribute of the name (issuer/subject)
  23885. * call we_EncodeName_ex with 0x16, IA5String for email type
  23886. * name structure to hold result of encoding
  23887. * nameStr value to be encoded
  23888. * nameType type of encoding i.e CTC_UTF8
  23889. * type id of attribute i.e ASN_COMMON_NAME
  23890. *
  23891. * returns length on success
  23892. */
  23893. int wc_EncodeName(EncodedName* name, const char* nameStr, char nameType,
  23894. byte type)
  23895. {
  23896. return EncodeName(name, nameStr, (byte)nameType, type,
  23897. ASN_IA5_STRING, NULL);
  23898. }
  23899. #ifdef WOLFSSL_ASN_TEMPLATE
  23900. static void SetRdnItems(ASNItem* namesASN, ASNSetData* dataASN, const byte* oid,
  23901. word32 oidSz, byte tag, const byte* data, word32 sz)
  23902. {
  23903. XMEMCPY(namesASN, rdnASN, sizeof(rdnASN));
  23904. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
  23905. namesASN[RDNASN_IDX_ATTR_VAL].tag = tag;
  23906. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], data, sz);
  23907. }
  23908. #ifdef WOLFSSL_MULTI_ATTRIB
  23909. static int FindMultiAttrib(CertName* name, int id, int* idx)
  23910. {
  23911. int i;
  23912. for (i = *idx + 1; i < CTC_MAX_ATTRIB; i++) {
  23913. if (name->name[i].sz > 0 && name->name[i].id == id) {
  23914. break;
  23915. }
  23916. }
  23917. if (i == CTC_MAX_ATTRIB) {
  23918. i = -1;
  23919. }
  23920. *idx = i;
  23921. return i >= 0;
  23922. }
  23923. #endif
  23924. /* ASN.1 template for the SEQUENCE around the RDNs.
  23925. * X.509: RFC 5280, 4.1.2.4 - RDNSequence
  23926. */
  23927. static const ASNItem nameASN[] = {
  23928. { 0, ASN_SEQUENCE, 1, 1, 0 },
  23929. };
  23930. enum {
  23931. NAMEASN_IDX_SEQ = 0
  23932. };
  23933. /* Number of items in ASN.1 template for the SEQUENCE around the RDNs. */
  23934. #define nameASN_Length (sizeof(nameASN) / sizeof(ASNItem))
  23935. static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN,
  23936. int maxIdx, CertName* name)
  23937. {
  23938. int i;
  23939. int idx;
  23940. int ret = 0;
  23941. word32 nameLen[NAME_ENTRIES];
  23942. #ifdef WOLFSSL_MULTI_ATTRIB
  23943. int j;
  23944. #endif
  23945. for (i = 0; i < NAME_ENTRIES; i++) {
  23946. /* Keep name length to identify component is to be encoded. */
  23947. const char* nameStr = GetOneCertName(name, i);
  23948. nameLen[i] = nameStr ? (word32)XSTRLEN(nameStr) : 0;
  23949. }
  23950. idx = nameASN_Length;
  23951. for (i = 0; i < NAME_ENTRIES; i++) {
  23952. int type = GetCertNameId(i);
  23953. #ifdef WOLFSSL_MULTI_ATTRIB
  23954. j = -1;
  23955. /* Put DomainComponents before OrgUnitName. */
  23956. while (FindMultiAttrib(name, type, &j)) {
  23957. if (GetCertNameId(i) != ASN_DOMAIN_COMPONENT) {
  23958. continue;
  23959. }
  23960. if (dataASN != NULL && namesASN != NULL) {
  23961. if (idx > maxIdx - (int)rdnASN_Length) {
  23962. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  23963. ret = BUFFER_E;
  23964. break;
  23965. }
  23966. /* Copy data into dynamic vars. */
  23967. SetRdnItems(namesASN + idx, dataASN + idx, dcOid,
  23968. sizeof(dcOid), (byte)name->name[j].type,
  23969. (byte*)name->name[j].value,
  23970. (word32)name->name[j].sz);
  23971. }
  23972. idx += (int)rdnASN_Length;
  23973. }
  23974. if (ret != 0)
  23975. break;
  23976. #endif
  23977. if (nameLen[i] > 0) {
  23978. if (dataASN != NULL) {
  23979. if (idx > maxIdx - (int)rdnASN_Length) {
  23980. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  23981. ret = BUFFER_E;
  23982. break;
  23983. }
  23984. /* Write out first instance of attribute type. */
  23985. if (type == ASN_EMAIL_NAME) {
  23986. /* Copy email data into dynamic vars. */
  23987. SetRdnItems(namesASN + idx, dataASN + idx, attrEmailOid,
  23988. sizeof(attrEmailOid), ASN_IA5_STRING,
  23989. (const byte*)GetOneCertName(name, i), nameLen[i]);
  23990. }
  23991. else if (type == ASN_USER_ID) {
  23992. /* Copy userID data into dynamic vars. */
  23993. SetRdnItems(namesASN + idx, dataASN + idx, uidOid,
  23994. sizeof(uidOid), (byte)GetNameType(name, i),
  23995. (const byte*)GetOneCertName(name, i), nameLen[i]);
  23996. }
  23997. else if (type == ASN_FAVOURITE_DRINK) {
  23998. /* Copy favourite drink data into dynamic vars. */
  23999. SetRdnItems(namesASN + idx, dataASN + idx, fvrtDrk,
  24000. sizeof(fvrtDrk), (byte)GetNameType(name, i),
  24001. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24002. }
  24003. else if (type == ASN_CUSTOM_NAME) {
  24004. #ifdef WOLFSSL_CUSTOM_OID
  24005. SetRdnItems(namesASN + idx, dataASN + idx, name->custom.oid,
  24006. name->custom.oidSz, name->custom.enc,
  24007. name->custom.val, name->custom.valSz);
  24008. #endif
  24009. }
  24010. else {
  24011. /* Copy name data into dynamic vars. */
  24012. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
  24013. NAME_OID_SZ, (byte)GetNameType(name, i),
  24014. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24015. }
  24016. }
  24017. idx += (int)rdnASN_Length;
  24018. }
  24019. #ifdef WOLFSSL_MULTI_ATTRIB
  24020. j = -1;
  24021. /* Write all other attributes of this type. */
  24022. while (FindMultiAttrib(name, type, &j)) {
  24023. if (GetCertNameId(i) == ASN_DOMAIN_COMPONENT) {
  24024. continue;
  24025. }
  24026. if (dataASN != NULL && namesASN != NULL) {
  24027. if (idx > maxIdx - (int)rdnASN_Length) {
  24028. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  24029. ret = BUFFER_E;
  24030. break;
  24031. }
  24032. /* Copy data into dynamic vars. */
  24033. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
  24034. NAME_OID_SZ, (byte)name->name[j].type,
  24035. (byte*)name->name[j].value, (word32)name->name[j].sz);
  24036. }
  24037. idx += (int)rdnASN_Length;
  24038. }
  24039. if (ret != 0)
  24040. break;
  24041. #endif
  24042. }
  24043. if (ret == 0)
  24044. ret = idx;
  24045. return ret;
  24046. }
  24047. #endif
  24048. /* encode CertName into output, return total bytes written */
  24049. int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap)
  24050. {
  24051. #ifndef WOLFSSL_ASN_TEMPLATE
  24052. int ret;
  24053. int i;
  24054. word32 idx, totalBytes = 0;
  24055. #ifdef WOLFSSL_SMALL_STACK
  24056. EncodedName* names = NULL;
  24057. #else
  24058. EncodedName names[NAME_ENTRIES];
  24059. #endif
  24060. #ifdef WOLFSSL_MULTI_ATTRIB
  24061. EncodedName addNames[CTC_MAX_ATTRIB];
  24062. int j, type;
  24063. #endif
  24064. if (output == NULL || name == NULL)
  24065. return BAD_FUNC_ARG;
  24066. if (outputSz < 3)
  24067. return BUFFER_E;
  24068. #ifdef WOLFSSL_SMALL_STACK
  24069. names = (EncodedName*)XMALLOC(sizeof(EncodedName) * NAME_ENTRIES, NULL,
  24070. DYNAMIC_TYPE_TMP_BUFFER);
  24071. if (names == NULL)
  24072. return MEMORY_E;
  24073. #endif
  24074. for (i = 0; i < NAME_ENTRIES; i++) {
  24075. const char* nameStr = GetOneCertName(name, i);
  24076. ret = EncodeName(&names[i], nameStr, (byte)GetNameType(name, i),
  24077. GetCertNameId(i), ASN_IA5_STRING, name);
  24078. if (ret < 0) {
  24079. #ifdef WOLFSSL_SMALL_STACK
  24080. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24081. #endif
  24082. WOLFSSL_MSG("EncodeName failed");
  24083. return BUFFER_E;
  24084. }
  24085. totalBytes += (word32)ret;
  24086. }
  24087. #ifdef WOLFSSL_MULTI_ATTRIB
  24088. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  24089. if (name->name[i].sz > 0) {
  24090. ret = EncodeName(&addNames[i], name->name[i].value,
  24091. (byte)name->name[i].type, (byte)name->name[i].id,
  24092. ASN_IA5_STRING, NULL);
  24093. if (ret < 0) {
  24094. #ifdef WOLFSSL_SMALL_STACK
  24095. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24096. #endif
  24097. WOLFSSL_MSG("EncodeName on multiple attributes failed");
  24098. return BUFFER_E;
  24099. }
  24100. totalBytes += (word32)ret;
  24101. }
  24102. else {
  24103. addNames[i].used = 0;
  24104. }
  24105. }
  24106. #endif /* WOLFSSL_MULTI_ATTRIB */
  24107. /* header */
  24108. idx = SetSequence(totalBytes, output);
  24109. totalBytes += idx;
  24110. if (totalBytes > WC_ASN_NAME_MAX) {
  24111. #ifdef WOLFSSL_SMALL_STACK
  24112. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24113. #endif
  24114. WOLFSSL_MSG("Total Bytes is greater than WC_ASN_NAME_MAX");
  24115. return BUFFER_E;
  24116. }
  24117. for (i = 0; i < NAME_ENTRIES; i++) {
  24118. #ifdef WOLFSSL_MULTI_ATTRIB
  24119. type = GetCertNameId(i);
  24120. for (j = 0; j < CTC_MAX_ATTRIB; j++) {
  24121. if (name->name[j].sz > 0 && type == name->name[j].id) {
  24122. if (outputSz < idx + (word32)addNames[j].totalLen) {
  24123. #ifdef WOLFSSL_SMALL_STACK
  24124. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24125. #endif
  24126. WOLFSSL_MSG("Not enough space left for DC value");
  24127. return BUFFER_E;
  24128. }
  24129. XMEMCPY(output + idx, addNames[j].encoded,
  24130. (size_t)addNames[j].totalLen);
  24131. idx += (word32)addNames[j].totalLen;
  24132. }
  24133. }
  24134. #endif /* WOLFSSL_MULTI_ATTRIB */
  24135. if (names[i].used) {
  24136. if (outputSz < idx + (word32)names[i].totalLen) {
  24137. #ifdef WOLFSSL_SMALL_STACK
  24138. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24139. #endif
  24140. return BUFFER_E;
  24141. }
  24142. XMEMCPY(output + idx, names[i].encoded, (size_t)names[i].totalLen);
  24143. idx += (word32)names[i].totalLen;
  24144. }
  24145. }
  24146. #ifdef WOLFSSL_SMALL_STACK
  24147. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24148. #endif
  24149. (void)heap;
  24150. return (int)totalBytes;
  24151. #else
  24152. /* TODO: consider calculating size of entries, putting length into
  24153. * SEQUENCE, encode SEQUENCE, encode entries into buffer. */
  24154. ASNSetData* dataASN = NULL; /* Can't use DECL_ASNSETDATA. Always dynamic. */
  24155. ASNItem* namesASN = NULL;
  24156. word32 items = 0;
  24157. int ret = 0;
  24158. int sz = 0;
  24159. /* Calculate length of name entries and size for allocating. */
  24160. ret = SetNameRdnItems(NULL, NULL, 0, name);
  24161. if (ret > 0) {
  24162. items = (word32)ret;
  24163. ret = 0;
  24164. }
  24165. /* Allocate dynamic data items. */
  24166. dataASN = (ASNSetData*)XMALLOC(items * sizeof(ASNSetData), heap,
  24167. DYNAMIC_TYPE_TMP_BUFFER);
  24168. if (dataASN == NULL) {
  24169. ret = MEMORY_E;
  24170. }
  24171. else {
  24172. /* Allocate dynamic ASN.1 template items. */
  24173. namesASN = (ASNItem*)XMALLOC(items * sizeof(ASNItem), heap,
  24174. DYNAMIC_TYPE_TMP_BUFFER);
  24175. if (namesASN == NULL) {
  24176. ret = MEMORY_E;
  24177. }
  24178. }
  24179. if (ret == 0) {
  24180. /* Clear the dynamic data. */
  24181. XMEMSET(dataASN, 0, items * sizeof(ASNSetData));
  24182. /* Copy in the outer sequence. */
  24183. XMEMCPY(namesASN, nameASN, sizeof(nameASN));
  24184. ret = SetNameRdnItems(dataASN, namesASN, (int)items, name);
  24185. if (ret == (int)items)
  24186. ret = 0;
  24187. else if (ret > 0) {
  24188. WOLFSSL_MSG("SetNameRdnItems returned different length");
  24189. ret = BUFFER_E;
  24190. }
  24191. }
  24192. if (ret == 0) {
  24193. /* Calculate size of encoding. */
  24194. ret = SizeASN_Items(namesASN, dataASN, (int)items, &sz);
  24195. }
  24196. /* Check buffer size if passed in. */
  24197. if (ret == 0 && output != NULL && sz > (int)outputSz) {
  24198. ret = BUFFER_E;
  24199. }
  24200. if (ret == 0) {
  24201. if (output != NULL) {
  24202. /* Encode Name. */
  24203. ret = SetASN_Items(namesASN, dataASN, (int)items, output);
  24204. }
  24205. else {
  24206. /* Return the encoding size. */
  24207. ret = sz;
  24208. }
  24209. }
  24210. if (namesASN != NULL)
  24211. XFREE(namesASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24212. if (dataASN != NULL)
  24213. XFREE(dataASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24214. (void)heap;
  24215. return ret;
  24216. #endif
  24217. }
  24218. int SetName(byte* output, word32 outputSz, CertName* name)
  24219. {
  24220. return SetNameEx(output, outputSz, name, NULL);
  24221. }
  24222. #ifdef WOLFSSL_ASN_TEMPLATE
  24223. static int EncodePublicKey(int keyType, byte* output, int outLen,
  24224. RsaKey* rsaKey, ecc_key* eccKey,
  24225. ed25519_key* ed25519Key, ed448_key* ed448Key,
  24226. DsaKey* dsaKey)
  24227. {
  24228. int ret = 0;
  24229. (void)outLen;
  24230. (void)rsaKey;
  24231. (void)eccKey;
  24232. (void)ed25519Key;
  24233. (void)ed448Key;
  24234. (void)dsaKey;
  24235. switch (keyType) {
  24236. #ifndef NO_RSA
  24237. case RSA_KEY:
  24238. ret = SetRsaPublicKey(output, rsaKey, outLen, 1);
  24239. if (ret <= 0) {
  24240. ret = PUBLIC_KEY_E;
  24241. }
  24242. break;
  24243. #endif
  24244. #ifdef HAVE_ECC
  24245. case ECC_KEY:
  24246. ret = SetEccPublicKey(output, eccKey, outLen, 1, 0);
  24247. if (ret <= 0) {
  24248. ret = PUBLIC_KEY_E;
  24249. }
  24250. break;
  24251. #endif /* HAVE_ECC */
  24252. #ifdef HAVE_ED25519
  24253. case ED25519_KEY:
  24254. ret = wc_Ed25519PublicKeyToDer(ed25519Key, output,
  24255. (word32)outLen, 1);
  24256. if (ret <= 0) {
  24257. ret = PUBLIC_KEY_E;
  24258. }
  24259. break;
  24260. #endif
  24261. #ifdef HAVE_ED448
  24262. case ED448_KEY:
  24263. ret = wc_Ed448PublicKeyToDer(ed448Key, output, (word32)outLen, 1);
  24264. if (ret <= 0) {
  24265. ret = PUBLIC_KEY_E;
  24266. }
  24267. break;
  24268. #endif
  24269. default:
  24270. ret = PUBLIC_KEY_E;
  24271. break;
  24272. }
  24273. return ret;
  24274. }
  24275. /* ASN.1 template for certificate extensions.
  24276. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  24277. * All extensions supported for encoding are described.
  24278. */
  24279. static const ASNItem static_certExtsASN[] = {
  24280. /* Basic Constraints Extension - 4.2.1.9 */
  24281. /* BC_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24282. /* BC_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24283. /* BC_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24284. /* BC_STR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  24285. /* cA */
  24286. /* BC_CA */ { 3, ASN_BOOLEAN, 0, 0, 0 },
  24287. /* pathLenConstraint */
  24288. /* BC_PATHLEN */ { 3, ASN_INTEGER, 0, 0, 1 },
  24289. /* Subject Alternative Name - 4.2.1.6 */
  24290. /* SAN_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24291. /* SAN_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24292. /* SAN_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24293. /* SAN_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24294. /* Subject Key Identifier - 4.2.1.2 */
  24295. /* SKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24296. /* SKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24297. /* SKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24298. /* SKID_KEYID */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  24299. /* Authority Key Identifier - 4.2.1.1 */
  24300. /* AKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24301. /* AKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24302. /* AKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24303. /* AKID_STR_SEQ, */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  24304. /* AKID_KEYID */ { 3, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  24305. /* Key Usage - 4.2.1.3 */
  24306. /* KU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24307. /* KU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24308. /* KU_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24309. /* KU_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24310. /* KU_USAGE */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  24311. /* Extended Key Usage - 4,2,1,12 */
  24312. /* EKU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24313. /* EKU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24314. /* EKU_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24315. /* Certificate Policies - 4.2.1.4 */
  24316. /* POLICIES_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24317. /* POLICIES_OID, */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24318. /* POLICIES_STR, */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24319. /* POLICIES_INFO */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  24320. /* Netscape Certificate Type */
  24321. /* NSTYPE_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24322. /* NSTYPE_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24323. /* NSTYPE_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24324. /* NSTYPE_USAGE, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  24325. /* CRLINFO_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24326. /* CRLINFO_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24327. /* CRLINFO_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24328. /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24329. /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24330. /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24331. };
  24332. enum {
  24333. CERTEXTSASN_IDX_BC_SEQ = 0,
  24334. CERTEXTSASN_IDX_BC_OID,
  24335. CERTEXTSASN_IDX_BC_STR,
  24336. CERTEXTSASN_IDX_BC_STR_SEQ,
  24337. CERTEXTSASN_IDX_BC_CA,
  24338. CERTEXTSASN_IDX_BC_PATHLEN,
  24339. CERTEXTSASN_IDX_SAN_SEQ,
  24340. CERTEXTSASN_IDX_SAN_OID,
  24341. CERTEXTSASN_IDX_SAN_CRIT,
  24342. CERTEXTSASN_IDX_SAN_STR,
  24343. CERTEXTSASN_IDX_SKID_SEQ,
  24344. CERTEXTSASN_IDX_SKID_OID,
  24345. CERTEXTSASN_IDX_SKID_STR,
  24346. CERTEXTSASN_IDX_SKID_KEYID,
  24347. CERTEXTSASN_IDX_AKID_SEQ,
  24348. CERTEXTSASN_IDX_AKID_OID,
  24349. CERTEXTSASN_IDX_AKID_STR,
  24350. CERTEXTSASN_IDX_AKID_STR_SEQ,
  24351. CERTEXTSASN_IDX_AKID_KEYID,
  24352. CERTEXTSASN_IDX_KU_SEQ,
  24353. CERTEXTSASN_IDX_KU_OID,
  24354. CERTEXTSASN_IDX_KU_CRIT,
  24355. CERTEXTSASN_IDX_KU_STR,
  24356. CERTEXTSASN_IDX_KU_USAGE,
  24357. CERTEXTSASN_IDX_EKU_SEQ,
  24358. CERTEXTSASN_IDX_EKU_OID,
  24359. CERTEXTSASN_IDX_EKU_STR,
  24360. CERTEXTSASN_IDX_POLICIES_SEQ,
  24361. CERTEXTSASN_IDX_POLICIES_OID,
  24362. CERTEXTSASN_IDX_POLICIES_STR,
  24363. CERTEXTSASN_IDX_POLICIES_INFO,
  24364. CERTEXTSASN_IDX_NSTYPE_SEQ,
  24365. CERTEXTSASN_IDX_NSTYPE_OID,
  24366. CERTEXTSASN_IDX_NSTYPE_STR,
  24367. CERTEXTSASN_IDX_NSTYPE_USAGE,
  24368. CERTEXTSASN_IDX_CRLINFO_SEQ,
  24369. CERTEXTSASN_IDX_CRLINFO_OID,
  24370. CERTEXTSASN_IDX_CRLINFO_STR,
  24371. CERTEXTSASN_IDX_CUSTOM_SEQ,
  24372. CERTEXTSASN_IDX_CUSTOM_OID,
  24373. CERTEXTSASN_IDX_CUSTOM_STR,
  24374. CERTEXTSASN_IDX_START_CUSTOM
  24375. };
  24376. /* Number of items in ASN.1 template for certificate extensions. We multiply
  24377. * by 4 because there are 4 things (seq, OID, crit flag, octet string). */
  24378. #define certExtsASN_Length ((sizeof(static_certExtsASN) / sizeof(ASNItem)) \
  24379. + (NUM_CUSTOM_EXT * 4))
  24380. static const ASNItem customExtASN[] = {
  24381. /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24382. /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24383. /* CUSTOM_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24384. /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24385. };
  24386. static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz,
  24387. int forRequest)
  24388. {
  24389. DECL_ASNSETDATA(dataASN, certExtsASN_Length);
  24390. int sz;
  24391. int ret = 0;
  24392. int i = 0;
  24393. static const byte bcOID[] = { 0x55, 0x1d, 0x13 };
  24394. #ifdef WOLFSSL_ALT_NAMES
  24395. static const byte sanOID[] = { 0x55, 0x1d, 0x11 };
  24396. #endif
  24397. #ifdef WOLFSSL_CERT_EXT
  24398. static const byte skidOID[] = { 0x55, 0x1d, 0x0e };
  24399. static const byte akidOID[] = { 0x55, 0x1d, 0x23 };
  24400. static const byte kuOID[] = { 0x55, 0x1d, 0x0f };
  24401. static const byte ekuOID[] = { 0x55, 0x1d, 0x25 };
  24402. static const byte cpOID[] = { 0x55, 0x1d, 0x20 };
  24403. static const byte nsCertOID[] = { 0x60, 0x86, 0x48, 0x01,
  24404. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  24405. static const byte crlInfoOID[] = { 0x55, 0x1D, 0x1F };
  24406. #endif
  24407. #ifdef WOLFSSL_SMALL_STACK
  24408. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24409. byte *encodedOids;
  24410. #endif
  24411. ASNItem *certExtsASN = (ASNItem *)XMALLOC(certExtsASN_Length *
  24412. sizeof(ASNItem), cert->heap,
  24413. DYNAMIC_TYPE_TMP_BUFFER);
  24414. if (certExtsASN == NULL) {
  24415. return MEMORY_E;
  24416. }
  24417. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24418. encodedOids = (byte *)XMALLOC(NUM_CUSTOM_EXT * MAX_OID_SZ, cert->heap,
  24419. DYNAMIC_TYPE_TMP_BUFFER);
  24420. if (encodedOids == NULL) {
  24421. XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24422. return MEMORY_E;
  24423. }
  24424. #endif
  24425. #else
  24426. ASNItem certExtsASN[certExtsASN_Length];
  24427. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24428. byte encodedOids[NUM_CUSTOM_EXT * MAX_OID_SZ];
  24429. #endif
  24430. #endif
  24431. /* Clone static_certExtsASN into a certExtsASN and then fill the rest of it
  24432. * with (NUM_CUSTOM_EXT*4) more ASNItems specifying extensions. See comment
  24433. * above definition of certExtsASN_Length. */
  24434. XMEMCPY(certExtsASN, static_certExtsASN, sizeof(static_certExtsASN));
  24435. for (i = sizeof(static_certExtsASN) / sizeof(ASNItem);
  24436. i < (int)certExtsASN_Length; i += 4) {
  24437. XMEMCPY(&certExtsASN[i], customExtASN, sizeof(customExtASN));
  24438. }
  24439. (void)forRequest;
  24440. CALLOC_ASNSETDATA(dataASN, certExtsASN_Length, ret, cert->heap);
  24441. if (ret == 0) {
  24442. if (cert->isCA) {
  24443. /* Set Basic Constraints to be a Certificate Authority. */
  24444. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_BC_CA], 1);
  24445. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
  24446. if (cert->pathLenSet
  24447. #ifdef WOLFSSL_CERT_EXT
  24448. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  24449. #endif
  24450. ) {
  24451. SetASN_Int8Bit(&dataASN[CERTEXTSASN_IDX_BC_PATHLEN],
  24452. cert->pathLen);
  24453. }
  24454. else {
  24455. dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
  24456. }
  24457. }
  24458. else if (cert->basicConstSet) {
  24459. /* Set Basic Constraints to be a non Certificate Authority. */
  24460. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
  24461. dataASN[CERTEXTSASN_IDX_BC_CA].noOut = 1;
  24462. dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
  24463. }
  24464. else {
  24465. /* Don't write out Basic Constraints extension items. */
  24466. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_BC_SEQ,
  24467. CERTEXTSASN_IDX_BC_PATHLEN);
  24468. }
  24469. #ifdef WOLFSSL_ALT_NAMES
  24470. if (cert->altNamesSz > 0) {
  24471. /* Set Subject Alternative Name OID and data. */
  24472. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_OID],
  24473. sanOID, sizeof(sanOID));
  24474. if (cert->altNamesCrit) {
  24475. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_SAN_CRIT], 1);
  24476. }
  24477. else {
  24478. dataASN[CERTEXTSASN_IDX_SAN_CRIT].noOut = 1;
  24479. }
  24480. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_STR],
  24481. cert->altNames, (word32)cert->altNamesSz);
  24482. }
  24483. else
  24484. #endif
  24485. {
  24486. /* Don't write out Subject Alternative Name extension items. */
  24487. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SAN_SEQ,
  24488. CERTEXTSASN_IDX_SAN_STR);
  24489. }
  24490. #ifdef WOLFSSL_CERT_EXT
  24491. if (cert->skidSz > 0) {
  24492. /* Set Subject Key Identifier OID and data. */
  24493. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_OID],
  24494. skidOID, sizeof(skidOID));
  24495. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_KEYID],
  24496. cert->skid, (word32)cert->skidSz);
  24497. }
  24498. else
  24499. #endif
  24500. {
  24501. /* Don't write out Subject Key Identifier extension items. */
  24502. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SKID_SEQ,
  24503. CERTEXTSASN_IDX_SKID_KEYID);
  24504. }
  24505. #ifdef WOLFSSL_CERT_EXT
  24506. if (cert->akidSz > 0) {
  24507. /* Set Authority Key Identifier OID and data. */
  24508. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_OID],
  24509. akidOID, sizeof(akidOID));
  24510. #ifdef WOLFSSL_AKID_NAME
  24511. if (cert->rawAkid) {
  24512. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_STR],
  24513. cert->akid, cert->akidSz);
  24514. /* cert->akid contains the internal ext structure */
  24515. SetASNItem_NoOutBelow(dataASN, certExtsASN,
  24516. CERTEXTSASN_IDX_AKID_STR, certExtsASN_Length);
  24517. }
  24518. else
  24519. #endif
  24520. {
  24521. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_KEYID],
  24522. cert->akid, (word32)cert->akidSz);
  24523. }
  24524. }
  24525. else
  24526. #endif
  24527. {
  24528. /* Don't write out Authority Key Identifier extension items. */
  24529. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_AKID_SEQ,
  24530. CERTEXTSASN_IDX_AKID_KEYID);
  24531. }
  24532. #ifdef WOLFSSL_CERT_EXT
  24533. if (cert->keyUsage != 0) {
  24534. /* Set Key Usage OID, critical and value. */
  24535. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_KU_OID],
  24536. kuOID, sizeof(kuOID));
  24537. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_KU_CRIT], 1);
  24538. SetASN_Int16Bit(&dataASN[CERTEXTSASN_IDX_KU_USAGE],
  24539. cert->keyUsage);
  24540. }
  24541. else
  24542. #endif
  24543. {
  24544. /* Don't write out Key Usage extension items. */
  24545. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_KU_SEQ,
  24546. CERTEXTSASN_IDX_KU_USAGE);
  24547. }
  24548. #ifdef WOLFSSL_CERT_EXT
  24549. if (cert->extKeyUsage != 0) {
  24550. /* Calculate size of Extended Key Usage data. */
  24551. sz = SetExtKeyUsage(cert, NULL, 0, cert->extKeyUsage);
  24552. if (sz <= 0) {
  24553. ret = KEYUSAGE_E;
  24554. }
  24555. /* Set Extended Key Usage OID and data. */
  24556. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_OID],
  24557. ekuOID, sizeof(ekuOID));
  24558. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_STR],
  24559. NULL, (word32)sz);
  24560. }
  24561. else
  24562. #endif
  24563. {
  24564. /* Don't write out Extended Key Usage extension items. */
  24565. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_EKU_SEQ,
  24566. CERTEXTSASN_IDX_EKU_STR);
  24567. }
  24568. #ifdef WOLFSSL_CERT_EXT
  24569. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  24570. /* Calculate size of certificate policies. */
  24571. sz = SetCertificatePolicies(NULL, 0, cert->certPolicies,
  24572. cert->certPoliciesNb, cert->heap);
  24573. if (sz > 0) {
  24574. /* Set Certificate Policies OID. */
  24575. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_OID],
  24576. cpOID, sizeof(cpOID));
  24577. /* Make space for data. */
  24578. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_INFO],
  24579. NULL, (word32)sz);
  24580. }
  24581. else {
  24582. ret = CERTPOLICIES_E;
  24583. }
  24584. }
  24585. else
  24586. #endif
  24587. {
  24588. /* Don't write out Certificate Policies extension items. */
  24589. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_POLICIES_SEQ,
  24590. CERTEXTSASN_IDX_POLICIES_INFO);
  24591. }
  24592. #if defined(WOLFSSL_CERT_EXT) && !defined(IGNORE_NETSCAPE_CERT_TYPE)
  24593. /* Netscape Certificate Type */
  24594. if (cert->nsCertType != 0) {
  24595. /* Set Netscape Certificate Type OID and data. */
  24596. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_OID],
  24597. nsCertOID, sizeof(nsCertOID));
  24598. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_USAGE],
  24599. &cert->nsCertType, 1);
  24600. }
  24601. else
  24602. #endif
  24603. {
  24604. /* Don't write out Netscape Certificate Type. */
  24605. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_NSTYPE_SEQ,
  24606. CERTEXTSASN_IDX_NSTYPE_USAGE);
  24607. }
  24608. #ifdef WOLFSSL_CERT_EXT
  24609. if (cert->crlInfoSz > 0) {
  24610. /* Set CRL Distribution Points OID and data. */
  24611. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_OID],
  24612. crlInfoOID, sizeof(crlInfoOID));
  24613. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_STR],
  24614. cert->crlInfo, (word32)cert->crlInfoSz);
  24615. }
  24616. else
  24617. #endif
  24618. {
  24619. /* Don't write out CRL Distribution Points. */
  24620. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CRLINFO_SEQ,
  24621. CERTEXTSASN_IDX_CRLINFO_STR);
  24622. }
  24623. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
  24624. /* encode a custom oid and value */
  24625. if (cert->extCustom.oidSz > 0) {
  24626. /* Set CRL Distribution Points OID and data. */
  24627. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_OID],
  24628. cert->extCustom.oid, cert->extCustom.oidSz);
  24629. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_STR],
  24630. cert->extCustom.val, cert->extCustom.valSz);
  24631. }
  24632. else
  24633. #endif
  24634. {
  24635. /* Don't write out custom OID. */
  24636. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CUSTOM_SEQ,
  24637. CERTEXTSASN_IDX_CUSTOM_STR);
  24638. }
  24639. i = 0;
  24640. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
  24641. for (; i < cert->customCertExtCount; i++) {
  24642. int idx = CERTEXTSASN_IDX_START_CUSTOM + (i * 4);
  24643. word32 encodedOidSz = MAX_OID_SZ;
  24644. idx++; /* Skip one for for SEQ. */
  24645. /* EncodePolicyOID() will never return error since we parsed this
  24646. * OID when it was set. */
  24647. EncodePolicyOID(&encodedOids[i * MAX_OID_SZ], &encodedOidSz,
  24648. cert->customCertExt[i].oid, NULL);
  24649. SetASN_Buffer(&dataASN[idx], &encodedOids[i * MAX_OID_SZ],
  24650. encodedOidSz);
  24651. idx++;
  24652. if (cert->customCertExt[i].crit) {
  24653. SetASN_Boolean(&dataASN[idx], 1);
  24654. } else {
  24655. dataASN[idx].noOut = 1;
  24656. }
  24657. idx++;
  24658. SetASN_Buffer(&dataASN[idx], cert->customCertExt[i].val,
  24659. cert->customCertExt[i].valSz);
  24660. }
  24661. #endif
  24662. while (i < NUM_CUSTOM_EXT) {
  24663. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_START_CUSTOM + (i * 4),
  24664. CERTEXTSASN_IDX_START_CUSTOM + (i * 4) + 3);
  24665. i++;
  24666. }
  24667. }
  24668. if (ret == 0) {
  24669. /* Calculate size of encoded extensions. */
  24670. ret = SizeASN_Items(certExtsASN, dataASN, certExtsASN_Length, &sz);
  24671. }
  24672. if (ret == 0) {
  24673. /* Only SEQUENCE - don't encode extensions. */
  24674. if (sz == 2) {
  24675. sz = 0;
  24676. }
  24677. /* Check buffer is big enough. */
  24678. else if ((output != NULL) && (sz > (int)maxSz)) {
  24679. ret = BUFFER_E;
  24680. }
  24681. }
  24682. if ((ret == 0) && (output != NULL) && (sz > 0)) {
  24683. /* Encode certificate extensions into buffer. */
  24684. SetASN_Items(certExtsASN, dataASN, certExtsASN_Length, output);
  24685. #ifdef WOLFSSL_CERT_EXT
  24686. if (cert->extKeyUsage != 0){
  24687. /* Encode Extended Key Usage into space provided. */
  24688. if (SetExtKeyUsage(cert,
  24689. (byte*)dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.data,
  24690. dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.length,
  24691. cert->extKeyUsage) <= 0) {
  24692. ret = KEYUSAGE_E;
  24693. }
  24694. }
  24695. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  24696. /* Encode Certificate Policies into space provided. */
  24697. if (SetCertificatePolicies(
  24698. (byte*)dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.data,
  24699. dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.length,
  24700. cert->certPolicies, cert->certPoliciesNb, cert->heap) <= 0) {
  24701. ret = CERTPOLICIES_E;
  24702. }
  24703. }
  24704. #endif
  24705. }
  24706. if (ret == 0) {
  24707. /* Return the encoding size. */
  24708. ret = sz;
  24709. }
  24710. FREE_ASNSETDATA(dataASN, cert->heap);
  24711. #ifdef WOLFSSL_SMALL_STACK
  24712. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24713. XFREE(encodedOids, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24714. #endif
  24715. XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24716. #endif
  24717. return ret;
  24718. }
  24719. #endif /* WOLFSSL_ASN_TEMPLATE */
  24720. #ifndef WOLFSSL_ASN_TEMPLATE
  24721. /* Set Date validity from now until now + daysValid
  24722. * return size in bytes written to output, 0 on error */
  24723. /* TODO https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.5
  24724. * "MUST always encode certificate validity dates through the year 2049 as
  24725. * UTCTime; certificate validity dates in 2050 or later MUST be encoded as
  24726. * GeneralizedTime." */
  24727. static int SetValidity(byte* output, int daysValid)
  24728. {
  24729. #ifndef NO_ASN_TIME
  24730. byte before[MAX_DATE_SIZE];
  24731. byte after[MAX_DATE_SIZE];
  24732. word32 beforeSz, afterSz, seqSz;
  24733. time_t now;
  24734. time_t then;
  24735. struct tm* tmpTime;
  24736. struct tm* expandedTime;
  24737. struct tm localTime;
  24738. #if defined(NEED_TMP_TIME)
  24739. /* for use with gmtime_r */
  24740. struct tm tmpTimeStorage;
  24741. tmpTime = &tmpTimeStorage;
  24742. #else
  24743. tmpTime = NULL;
  24744. #endif
  24745. (void)tmpTime;
  24746. now = wc_Time(0);
  24747. /* before now */
  24748. before[0] = ASN_GENERALIZED_TIME;
  24749. beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
  24750. /* subtract 1 day of seconds for more compliance */
  24751. then = now - 86400;
  24752. expandedTime = XGMTIME(&then, tmpTime);
  24753. if (expandedTime == NULL) {
  24754. WOLFSSL_MSG("XGMTIME failed");
  24755. return 0; /* error */
  24756. }
  24757. localTime = *expandedTime;
  24758. /* adjust */
  24759. localTime.tm_year += 1900;
  24760. localTime.tm_mon += 1;
  24761. SetTime(&localTime, before + beforeSz);
  24762. beforeSz += ASN_GEN_TIME_SZ;
  24763. after[0] = ASN_GENERALIZED_TIME;
  24764. afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
  24765. /* add daysValid of seconds */
  24766. then = now + (daysValid * (time_t)86400);
  24767. expandedTime = XGMTIME(&then, tmpTime);
  24768. if (expandedTime == NULL) {
  24769. WOLFSSL_MSG("XGMTIME failed");
  24770. return 0; /* error */
  24771. }
  24772. localTime = *expandedTime;
  24773. /* adjust */
  24774. localTime.tm_year += 1900;
  24775. localTime.tm_mon += 1;
  24776. SetTime(&localTime, after + afterSz);
  24777. afterSz += ASN_GEN_TIME_SZ;
  24778. /* headers and output */
  24779. seqSz = SetSequence(beforeSz + afterSz, output);
  24780. XMEMCPY(output + seqSz, before, beforeSz);
  24781. XMEMCPY(output + seqSz + beforeSz, after, afterSz);
  24782. return (int)(seqSz + beforeSz + afterSz);
  24783. #else
  24784. (void)output;
  24785. (void)daysValid;
  24786. return NOT_COMPILED_IN;
  24787. #endif
  24788. }
  24789. #else
  24790. static int SetValidity(byte* before, byte* after, int daysValid)
  24791. {
  24792. #ifndef NO_ASN_TIME
  24793. int ret = 0;
  24794. time_t now;
  24795. time_t then;
  24796. struct tm* tmpTime;
  24797. struct tm* expandedTime;
  24798. struct tm localTime;
  24799. #if defined(NEED_TMP_TIME)
  24800. /* for use with gmtime_r */
  24801. struct tm tmpTimeStorage;
  24802. tmpTime = &tmpTimeStorage;
  24803. #else
  24804. tmpTime = NULL;
  24805. #endif
  24806. (void)tmpTime;
  24807. now = wc_Time(0);
  24808. /* subtract 1 day of seconds for more compliance */
  24809. then = now - 86400;
  24810. expandedTime = XGMTIME(&then, tmpTime);
  24811. if (expandedTime == NULL) {
  24812. WOLFSSL_MSG("XGMTIME failed");
  24813. ret = DATE_E;
  24814. }
  24815. if (ret == 0) {
  24816. localTime = *expandedTime;
  24817. /* adjust */
  24818. localTime.tm_year += 1900;
  24819. localTime.tm_mon += 1;
  24820. SetTime(&localTime, before);
  24821. /* add daysValid of seconds */
  24822. then = now + (daysValid * (time_t)86400);
  24823. expandedTime = XGMTIME(&then, tmpTime);
  24824. if (expandedTime == NULL) {
  24825. WOLFSSL_MSG("XGMTIME failed");
  24826. ret = DATE_E;
  24827. }
  24828. }
  24829. if (ret == 0) {
  24830. localTime = *expandedTime;
  24831. /* adjust */
  24832. localTime.tm_year += 1900;
  24833. localTime.tm_mon += 1;
  24834. SetTime(&localTime, after);
  24835. }
  24836. return ret;
  24837. #else
  24838. (void)before;
  24839. (void)after;
  24840. (void)daysValid;
  24841. return NOT_COMPILED_IN;
  24842. #endif
  24843. }
  24844. #endif /* WOLFSSL_ASN_TEMPLATE */
  24845. #ifndef WOLFSSL_ASN_TEMPLATE
  24846. /* encode info from cert into DER encoded format */
  24847. static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey,
  24848. WC_RNG* rng, DsaKey* dsaKey, ed25519_key* ed25519Key,
  24849. ed448_key* ed448Key, falcon_key* falconKey,
  24850. dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
  24851. {
  24852. int ret;
  24853. if (cert == NULL || der == NULL || rng == NULL)
  24854. return BAD_FUNC_ARG;
  24855. /* make sure at least one key type is provided */
  24856. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  24857. dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
  24858. dilithiumKey == NULL && sphincsKey == NULL) {
  24859. return PUBLIC_KEY_E;
  24860. }
  24861. /* init */
  24862. XMEMSET(der, 0, sizeof(DerCert));
  24863. /* version */
  24864. der->versionSz = SetMyVersion((word32)cert->version, der->version, TRUE);
  24865. /* serial number (must be positive) */
  24866. if (cert->serialSz == 0) {
  24867. /* generate random serial */
  24868. cert->serialSz = CTC_GEN_SERIAL_SZ;
  24869. ret = wc_RNG_GenerateBlock(rng, cert->serial, (word32)cert->serialSz);
  24870. if (ret != 0)
  24871. return ret;
  24872. /* Clear the top bit to avoid a negative value */
  24873. cert->serial[0] &= 0x7f;
  24874. }
  24875. der->serialSz = SetSerialNumber(cert->serial, (word32)cert->serialSz,
  24876. der->serial, sizeof(der->serial),
  24877. CTC_SERIAL_SIZE);
  24878. if (der->serialSz < 0)
  24879. return der->serialSz;
  24880. /* signature algo */
  24881. der->sigAlgoSz = (int)SetAlgoID(cert->sigType, der->sigAlgo, oidSigType, 0);
  24882. if (der->sigAlgoSz <= 0)
  24883. return ALGO_ID_E;
  24884. /* public key */
  24885. #ifndef NO_RSA
  24886. if (cert->keyType == RSA_KEY) {
  24887. if (rsaKey == NULL)
  24888. return PUBLIC_KEY_E;
  24889. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  24890. sizeof(der->publicKey), 1);
  24891. }
  24892. #endif
  24893. #ifdef HAVE_ECC
  24894. if (cert->keyType == ECC_KEY) {
  24895. if (eccKey == NULL)
  24896. return PUBLIC_KEY_E;
  24897. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  24898. sizeof(der->publicKey), 1, 0);
  24899. }
  24900. #endif
  24901. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  24902. if (cert->keyType == DSA_KEY) {
  24903. if (dsaKey == NULL)
  24904. return PUBLIC_KEY_E;
  24905. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  24906. sizeof(der->publicKey), 1);
  24907. }
  24908. #endif
  24909. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  24910. if (cert->keyType == ED25519_KEY) {
  24911. if (ed25519Key == NULL)
  24912. return PUBLIC_KEY_E;
  24913. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  24914. (word32)sizeof(der->publicKey), 1);
  24915. }
  24916. #endif
  24917. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  24918. if (cert->keyType == ED448_KEY) {
  24919. if (ed448Key == NULL)
  24920. return PUBLIC_KEY_E;
  24921. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  24922. (word32)sizeof(der->publicKey), 1);
  24923. }
  24924. #endif
  24925. #if defined(HAVE_PQC)
  24926. #if defined(HAVE_FALCON)
  24927. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  24928. (cert->keyType == FALCON_LEVEL5_KEY)) {
  24929. if (falconKey == NULL)
  24930. return PUBLIC_KEY_E;
  24931. der->publicKeySz =
  24932. wc_Falcon_PublicKeyToDer(falconKey, der->publicKey,
  24933. (word32)sizeof(der->publicKey), 1);
  24934. }
  24935. #endif /* HAVE_FALCON */
  24936. #if defined(HAVE_DILITHIUM)
  24937. if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
  24938. (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
  24939. (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
  24940. if (dilithiumKey == NULL)
  24941. return PUBLIC_KEY_E;
  24942. der->publicKeySz =
  24943. wc_Dilithium_PublicKeyToDer(dilithiumKey, der->publicKey,
  24944. (word32)sizeof(der->publicKey), 1);
  24945. }
  24946. #endif /* HAVE_DILITHIUM */
  24947. #if defined(HAVE_SPHINCS)
  24948. if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
  24949. (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
  24950. (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
  24951. (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
  24952. (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
  24953. (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
  24954. if (sphincsKey == NULL)
  24955. return PUBLIC_KEY_E;
  24956. der->publicKeySz =
  24957. wc_Sphincs_PublicKeyToDer(sphincsKey, der->publicKey,
  24958. (word32)sizeof(der->publicKey), 1);
  24959. }
  24960. #endif /* HAVE_SPHINCS */
  24961. #endif /* HAVE_PQC */
  24962. if (der->publicKeySz <= 0)
  24963. return PUBLIC_KEY_E;
  24964. der->validitySz = 0;
  24965. /* copy date validity if already set in cert struct */
  24966. if (cert->beforeDateSz && cert->afterDateSz) {
  24967. der->validitySz = CopyValidity(der->validity, cert);
  24968. if (der->validitySz <= 0)
  24969. return DATE_E;
  24970. }
  24971. /* set date validity using daysValid if not set already */
  24972. if (der->validitySz == 0) {
  24973. der->validitySz = SetValidity(der->validity, cert->daysValid);
  24974. if (der->validitySz <= 0)
  24975. return DATE_E;
  24976. }
  24977. /* subject name */
  24978. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  24979. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  24980. /* Use the raw subject */
  24981. word32 idx;
  24982. der->subjectSz = (int)min((word32)sizeof(der->subject),
  24983. (word32)XSTRLEN((const char*)cert->sbjRaw));
  24984. /* header */
  24985. idx = SetSequence((word32)der->subjectSz, der->subject);
  24986. if ((word32)der->subjectSz + idx > (word32)sizeof(der->subject)) {
  24987. return SUBJECT_E;
  24988. }
  24989. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  24990. (size_t)der->subjectSz);
  24991. der->subjectSz += (int)idx;
  24992. }
  24993. else
  24994. #endif
  24995. {
  24996. /* Use the name structure */
  24997. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  24998. &cert->subject, cert->heap);
  24999. }
  25000. if (der->subjectSz <= 0)
  25001. return SUBJECT_E;
  25002. /* issuer name */
  25003. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  25004. if (XSTRLEN((const char*)cert->issRaw) > 0) {
  25005. /* Use the raw issuer */
  25006. word32 idx;
  25007. der->issuerSz = (int)min((word32)sizeof(der->issuer),
  25008. (word32)XSTRLEN((const char*)cert->issRaw));
  25009. /* header */
  25010. idx = SetSequence((word32)der->issuerSz, der->issuer);
  25011. if ((word32)der->issuerSz + idx > (word32)sizeof(der->issuer)) {
  25012. return ISSUER_E;
  25013. }
  25014. XMEMCPY((char*)der->issuer + idx, (const char*)cert->issRaw,
  25015. (size_t)der->issuerSz);
  25016. der->issuerSz += (int)idx;
  25017. }
  25018. else
  25019. #endif
  25020. {
  25021. /* Use the name structure */
  25022. der->issuerSz = SetNameEx(der->issuer, sizeof(der->issuer),
  25023. cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
  25024. }
  25025. if (der->issuerSz <= 0)
  25026. return ISSUER_E;
  25027. /* set the extensions */
  25028. der->extensionsSz = 0;
  25029. /* RFC 5280 : 4.2.1.9. Basic Constraints
  25030. * The pathLenConstraint field is meaningful only if the CA boolean is
  25031. * asserted and the key usage extension, if present, asserts the
  25032. * keyCertSign bit */
  25033. /* Set CA and path length */
  25034. if ((cert->isCA) && (cert->pathLenSet)
  25035. #ifdef WOLFSSL_CERT_EXT
  25036. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  25037. #endif
  25038. ) {
  25039. der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
  25040. if (der->caSz <= 0)
  25041. return CA_TRUE_E;
  25042. der->extensionsSz += der->caSz;
  25043. }
  25044. /* Set CA */
  25045. else if (cert->isCA) {
  25046. der->caSz = SetCa(der->ca, sizeof(der->ca));
  25047. if (der->caSz <= 0)
  25048. return CA_TRUE_E;
  25049. der->extensionsSz += der->caSz;
  25050. }
  25051. /* Set Basic Constraint */
  25052. else if (cert->basicConstSet) {
  25053. der->caSz = SetBC(der->ca, sizeof(der->ca));
  25054. if (der->caSz <= 0)
  25055. return EXTENSIONS_E;
  25056. der->extensionsSz += der->caSz;
  25057. }
  25058. else
  25059. der->caSz = 0;
  25060. #ifdef WOLFSSL_ALT_NAMES
  25061. /* Alternative Name */
  25062. if (cert->altNamesSz) {
  25063. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  25064. cert->altNames, (word32)cert->altNamesSz,
  25065. cert->altNamesCrit);
  25066. if (der->altNamesSz <= 0)
  25067. return ALT_NAME_E;
  25068. der->extensionsSz += der->altNamesSz;
  25069. }
  25070. else
  25071. der->altNamesSz = 0;
  25072. #endif
  25073. #ifdef WOLFSSL_CERT_EXT
  25074. /* SKID */
  25075. if (cert->skidSz) {
  25076. /* check the provided SKID size */
  25077. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  25078. return SKID_E;
  25079. /* Note: different skid buffers sizes for der (MAX_KID_SZ) and
  25080. cert (CTC_MAX_SKID_SIZE). */
  25081. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  25082. cert->skid, (word32)cert->skidSz);
  25083. if (der->skidSz <= 0)
  25084. return SKID_E;
  25085. der->extensionsSz += der->skidSz;
  25086. }
  25087. else
  25088. der->skidSz = 0;
  25089. /* AKID */
  25090. if (cert->akidSz) {
  25091. /* check the provided AKID size */
  25092. if ((
  25093. #ifdef WOLFSSL_AKID_NAME
  25094. !cert->rawAkid &&
  25095. #endif
  25096. cert->akidSz > (int)min(CTC_MAX_AKID_SIZE, sizeof(der->akid)))
  25097. #ifdef WOLFSSL_AKID_NAME
  25098. || (cert->rawAkid && cert->akidSz > (int)sizeof(der->akid))
  25099. #endif
  25100. )
  25101. return AKID_E;
  25102. der->akidSz = SetAKID(der->akid, sizeof(der->akid), cert->akid,
  25103. (word32)cert->akidSz,
  25104. #ifdef WOLFSSL_AKID_NAME
  25105. cert->rawAkid
  25106. #else
  25107. 0
  25108. #endif
  25109. );
  25110. if (der->akidSz <= 0)
  25111. return AKID_E;
  25112. der->extensionsSz += der->akidSz;
  25113. }
  25114. else
  25115. der->akidSz = 0;
  25116. /* Key Usage */
  25117. if (cert->keyUsage != 0){
  25118. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  25119. cert->keyUsage);
  25120. if (der->keyUsageSz <= 0)
  25121. return KEYUSAGE_E;
  25122. der->extensionsSz += der->keyUsageSz;
  25123. }
  25124. else
  25125. der->keyUsageSz = 0;
  25126. /* Extended Key Usage */
  25127. if (cert->extKeyUsage != 0){
  25128. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  25129. sizeof(der->extKeyUsage), cert->extKeyUsage);
  25130. if (der->extKeyUsageSz <= 0)
  25131. return EXTKEYUSAGE_E;
  25132. der->extensionsSz += der->extKeyUsageSz;
  25133. }
  25134. else
  25135. der->extKeyUsageSz = 0;
  25136. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  25137. /* Netscape Certificate Type */
  25138. if (cert->nsCertType != 0) {
  25139. der->nsCertTypeSz = SetNsCertType(cert, der->nsCertType,
  25140. sizeof(der->nsCertType), cert->nsCertType);
  25141. if (der->nsCertTypeSz <= 0)
  25142. return EXTENSIONS_E;
  25143. der->extensionsSz += der->nsCertTypeSz;
  25144. }
  25145. else
  25146. der->nsCertTypeSz = 0;
  25147. #endif
  25148. if (cert->crlInfoSz > 0) {
  25149. der->crlInfoSz = SetCRLInfo(cert, der->crlInfo, sizeof(der->crlInfo),
  25150. cert->crlInfo, cert->crlInfoSz);
  25151. if (der->crlInfoSz <= 0)
  25152. return EXTENSIONS_E;
  25153. der->extensionsSz += der->crlInfoSz;
  25154. }
  25155. else
  25156. der->crlInfoSz = 0;
  25157. /* Certificate Policies */
  25158. if (cert->certPoliciesNb != 0) {
  25159. der->certPoliciesSz = SetCertificatePolicies(der->certPolicies,
  25160. sizeof(der->certPolicies),
  25161. cert->certPolicies,
  25162. cert->certPoliciesNb,
  25163. cert->heap);
  25164. if (der->certPoliciesSz <= 0)
  25165. return CERTPOLICIES_E;
  25166. der->extensionsSz += der->certPoliciesSz;
  25167. }
  25168. else
  25169. der->certPoliciesSz = 0;
  25170. #endif /* WOLFSSL_CERT_EXT */
  25171. /* put extensions */
  25172. if (der->extensionsSz > 0) {
  25173. /* put the start of extensions sequence (ID, Size) */
  25174. der->extensionsSz = SetExtensionsHeader(der->extensions,
  25175. sizeof(der->extensions),
  25176. (word32)der->extensionsSz);
  25177. if (der->extensionsSz <= 0)
  25178. return EXTENSIONS_E;
  25179. /* put CA */
  25180. if (der->caSz) {
  25181. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25182. &der->extensionsSz,
  25183. der->ca, der->caSz);
  25184. if (ret == 0)
  25185. return EXTENSIONS_E;
  25186. }
  25187. #ifdef WOLFSSL_ALT_NAMES
  25188. /* put Alternative Names */
  25189. if (der->altNamesSz) {
  25190. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25191. &der->extensionsSz,
  25192. der->altNames, der->altNamesSz);
  25193. if (ret <= 0)
  25194. return EXTENSIONS_E;
  25195. }
  25196. #endif
  25197. #ifdef WOLFSSL_CERT_EXT
  25198. /* put SKID */
  25199. if (der->skidSz) {
  25200. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25201. &der->extensionsSz,
  25202. der->skid, der->skidSz);
  25203. if (ret <= 0)
  25204. return EXTENSIONS_E;
  25205. }
  25206. /* put AKID */
  25207. if (der->akidSz) {
  25208. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25209. &der->extensionsSz,
  25210. der->akid, der->akidSz);
  25211. if (ret <= 0)
  25212. return EXTENSIONS_E;
  25213. }
  25214. /* put CRL Distribution Points */
  25215. if (der->crlInfoSz) {
  25216. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25217. &der->extensionsSz,
  25218. der->crlInfo, der->crlInfoSz);
  25219. if (ret <= 0)
  25220. return EXTENSIONS_E;
  25221. }
  25222. /* put KeyUsage */
  25223. if (der->keyUsageSz) {
  25224. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25225. &der->extensionsSz,
  25226. der->keyUsage, der->keyUsageSz);
  25227. if (ret <= 0)
  25228. return EXTENSIONS_E;
  25229. }
  25230. /* put ExtendedKeyUsage */
  25231. if (der->extKeyUsageSz) {
  25232. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25233. &der->extensionsSz,
  25234. der->extKeyUsage, der->extKeyUsageSz);
  25235. if (ret <= 0)
  25236. return EXTENSIONS_E;
  25237. }
  25238. /* put Netscape Cert Type */
  25239. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  25240. if (der->nsCertTypeSz) {
  25241. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25242. &der->extensionsSz,
  25243. der->nsCertType, der->nsCertTypeSz);
  25244. if (ret <= 0)
  25245. return EXTENSIONS_E;
  25246. }
  25247. #endif
  25248. /* put Certificate Policies */
  25249. if (der->certPoliciesSz) {
  25250. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25251. &der->extensionsSz,
  25252. der->certPolicies, der->certPoliciesSz);
  25253. if (ret <= 0)
  25254. return EXTENSIONS_E;
  25255. }
  25256. #endif /* WOLFSSL_CERT_EXT */
  25257. }
  25258. der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
  25259. der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
  25260. der->extensionsSz;
  25261. return 0;
  25262. }
  25263. /* write DER encoded cert to buffer, size already checked */
  25264. static int WriteCertBody(DerCert* der, byte* buf)
  25265. {
  25266. word32 idx;
  25267. /* signed part header */
  25268. idx = SetSequence((word32)der->total, buf);
  25269. /* version */
  25270. XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
  25271. idx += (word32)der->versionSz;
  25272. /* serial */
  25273. XMEMCPY(buf + idx, der->serial, (size_t)der->serialSz);
  25274. idx += (word32)der->serialSz;
  25275. /* sig algo */
  25276. XMEMCPY(buf + idx, der->sigAlgo, (size_t)der->sigAlgoSz);
  25277. idx += (word32)der->sigAlgoSz;
  25278. /* issuer */
  25279. XMEMCPY(buf + idx, der->issuer, (size_t)der->issuerSz);
  25280. idx += (word32)der->issuerSz;
  25281. /* validity */
  25282. XMEMCPY(buf + idx, der->validity, (size_t)der->validitySz);
  25283. idx += (word32)der->validitySz;
  25284. /* subject */
  25285. XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
  25286. idx += (word32)der->subjectSz;
  25287. /* public key */
  25288. XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
  25289. idx += (word32)der->publicKeySz;
  25290. if (der->extensionsSz) {
  25291. /* extensions */
  25292. XMEMCPY(buf + idx, der->extensions,
  25293. min((word32)der->extensionsSz,
  25294. (word32)sizeof(der->extensions)));
  25295. idx += (word32)der->extensionsSz;
  25296. }
  25297. return (int)idx;
  25298. }
  25299. #endif /* !WOLFSSL_ASN_TEMPLATE */
  25300. /* Make signature from buffer (sz), write to sig (sigSz) */
  25301. static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz,
  25302. byte* sig, word32 sigSz, RsaKey* rsaKey, ecc_key* eccKey,
  25303. ed25519_key* ed25519Key, ed448_key* ed448Key, falcon_key* falconKey,
  25304. dilithium_key* dilithiumKey, sphincs_key* sphincsKey, WC_RNG* rng,
  25305. word32 sigAlgoType, void* heap)
  25306. {
  25307. int digestSz = 0, typeH = 0, ret = 0;
  25308. (void)digestSz;
  25309. (void)typeH;
  25310. (void)buf;
  25311. (void)sz;
  25312. (void)sig;
  25313. (void)sigSz;
  25314. (void)rsaKey;
  25315. (void)eccKey;
  25316. (void)ed25519Key;
  25317. (void)ed448Key;
  25318. (void)falconKey;
  25319. (void)dilithiumKey;
  25320. (void)sphincsKey;
  25321. (void)rng;
  25322. (void)heap;
  25323. switch (certSignCtx->state) {
  25324. case CERTSIGN_STATE_BEGIN:
  25325. case CERTSIGN_STATE_DIGEST:
  25326. certSignCtx->state = CERTSIGN_STATE_DIGEST;
  25327. certSignCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, heap,
  25328. DYNAMIC_TYPE_TMP_BUFFER);
  25329. if (certSignCtx->digest == NULL) {
  25330. ret = MEMORY_E; goto exit_ms;
  25331. }
  25332. ret = HashForSignature(buf, sz, sigAlgoType, certSignCtx->digest,
  25333. &typeH, &digestSz, 0);
  25334. /* set next state, since WC_PENDING_E rentry for these are not "call again" */
  25335. certSignCtx->state = CERTSIGN_STATE_ENCODE;
  25336. if (ret != 0) {
  25337. goto exit_ms;
  25338. }
  25339. FALL_THROUGH;
  25340. case CERTSIGN_STATE_ENCODE:
  25341. #ifndef NO_RSA
  25342. if (rsaKey) {
  25343. certSignCtx->encSig = (byte*)XMALLOC(MAX_DER_DIGEST_SZ, heap,
  25344. DYNAMIC_TYPE_TMP_BUFFER);
  25345. if (certSignCtx->encSig == NULL) {
  25346. ret = MEMORY_E; goto exit_ms;
  25347. }
  25348. /* signature */
  25349. certSignCtx->encSigSz = (int)wc_EncodeSignature(certSignCtx->encSig,
  25350. certSignCtx->digest, (word32)digestSz, typeH);
  25351. }
  25352. #endif /* !NO_RSA */
  25353. FALL_THROUGH;
  25354. case CERTSIGN_STATE_DO:
  25355. certSignCtx->state = CERTSIGN_STATE_DO;
  25356. ret = ALGO_ID_E; /* default to error */
  25357. #ifndef NO_RSA
  25358. if (rsaKey) {
  25359. /* signature */
  25360. ret = wc_RsaSSL_Sign(certSignCtx->encSig,
  25361. (word32)certSignCtx->encSigSz,
  25362. sig, sigSz, rsaKey, rng);
  25363. }
  25364. #endif /* !NO_RSA */
  25365. #if defined(HAVE_ECC) && defined(HAVE_ECC_SIGN)
  25366. if (!rsaKey && eccKey) {
  25367. word32 outSz = sigSz;
  25368. ret = wc_ecc_sign_hash(certSignCtx->digest, (word32)digestSz,
  25369. sig, &outSz, rng, eccKey);
  25370. if (ret == 0)
  25371. ret = (int)outSz;
  25372. }
  25373. #endif /* HAVE_ECC && HAVE_ECC_SIGN */
  25374. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_SIGN)
  25375. if (!rsaKey && !eccKey && ed25519Key) {
  25376. word32 outSz = sigSz;
  25377. ret = wc_ed25519_sign_msg(buf, sz, sig, &outSz, ed25519Key);
  25378. if (ret == 0)
  25379. ret = (int)outSz;
  25380. }
  25381. #endif /* HAVE_ED25519 && HAVE_ED25519_SIGN */
  25382. #if defined(HAVE_ED448) && defined(HAVE_ED448_SIGN)
  25383. if (!rsaKey && !eccKey && !ed25519Key && ed448Key) {
  25384. word32 outSz = sigSz;
  25385. ret = wc_ed448_sign_msg(buf, sz, sig, &outSz, ed448Key, NULL, 0);
  25386. if (ret == 0)
  25387. ret = (int)outSz;
  25388. }
  25389. #endif /* HAVE_ED448 && HAVE_ED448_SIGN */
  25390. #if defined(HAVE_PQC)
  25391. #if defined(HAVE_FALCON)
  25392. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && falconKey) {
  25393. word32 outSz = sigSz;
  25394. ret = wc_falcon_sign_msg(buf, sz, sig, &outSz, falconKey);
  25395. if (ret == 0)
  25396. ret = outSz;
  25397. }
  25398. #endif /* HAVE_FALCON */
  25399. #if defined(HAVE_DILITHIUM)
  25400. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
  25401. dilithiumKey) {
  25402. word32 outSz = sigSz;
  25403. ret = wc_dilithium_sign_msg(buf, sz, sig, &outSz, dilithiumKey);
  25404. if (ret == 0)
  25405. ret = outSz;
  25406. }
  25407. #endif /* HAVE_DILITHIUM */
  25408. #if defined(HAVE_SPHINCS)
  25409. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
  25410. !dilithiumKey && sphincsKey) {
  25411. word32 outSz = sigSz;
  25412. ret = wc_sphincs_sign_msg(buf, sz, sig, &outSz, sphincsKey);
  25413. if (ret == 0)
  25414. ret = outSz;
  25415. }
  25416. #endif /* HAVE_SPHINCS */
  25417. #endif /* HAVE_PQC */
  25418. break;
  25419. }
  25420. exit_ms:
  25421. #ifdef WOLFSSL_ASYNC_CRYPT
  25422. if (ret == WC_PENDING_E) {
  25423. return ret;
  25424. }
  25425. #endif
  25426. #ifndef NO_RSA
  25427. if (rsaKey) {
  25428. XFREE(certSignCtx->encSig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25429. }
  25430. #endif /* !NO_RSA */
  25431. XFREE(certSignCtx->digest, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25432. certSignCtx->digest = NULL;
  25433. /* reset state */
  25434. certSignCtx->state = CERTSIGN_STATE_BEGIN;
  25435. if (ret < 0) {
  25436. WOLFSSL_ERROR_VERBOSE(ret);
  25437. }
  25438. return ret;
  25439. }
  25440. #ifdef WOLFSSL_ASN_TEMPLATE
  25441. /* Generate a random integer value of at most len bytes.
  25442. *
  25443. * Most-significant bit will not be set when maximum size.
  25444. * Random value may be smaller than maximum size in bytes.
  25445. *
  25446. * @param [in] rng Random number generator.
  25447. * @param [out] out Buffer to hold integer value.
  25448. * @param [in] len Maximum number of bytes of integer.
  25449. * @return 0 on success.
  25450. * @return -ve when random number generation failed.
  25451. */
  25452. static int GenerateInteger(WC_RNG* rng, byte* out, word32 len)
  25453. {
  25454. int ret;
  25455. /* Generate random number. */
  25456. ret = wc_RNG_GenerateBlock(rng, out, len);
  25457. if (ret == 0) {
  25458. int i;
  25459. /* Clear the top bit to make positive. */
  25460. out[0] &= 0x7f;
  25461. /* Find first non-zero byte. One zero byte is valid though. */
  25462. for (i = 0; i < (int)len - 1; i++) {
  25463. if (out[i] != 0) {
  25464. break;
  25465. }
  25466. }
  25467. if (i != 0) {
  25468. /* Remove leading zeros. */
  25469. XMEMMOVE(out, out + i, (size_t)len - (size_t)i);
  25470. }
  25471. }
  25472. return ret;
  25473. }
  25474. /* ASN.1 template for a Certificate.
  25475. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  25476. */
  25477. static const ASNItem sigASN[] = {
  25478. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25479. /* tbsCertificate */
  25480. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  25481. /* signatureAlgorithm */
  25482. /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  25483. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  25484. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  25485. /* signatureValue */
  25486. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  25487. };
  25488. enum {
  25489. SIGASN_IDX_SEQ = 0,
  25490. SIGASN_IDX_TBS_SEQ,
  25491. SIGASN_IDX_SIGALGO_SEQ,
  25492. SIGASN_IDX_SIGALGO_OID,
  25493. SIGASN_IDX_SIGALGO_NULL,
  25494. SIGASN_IDX_SIGNATURE
  25495. };
  25496. /* Number of items in ASN.1 template for a Certificate. */
  25497. #define sigASN_Length (sizeof(sigASN) / sizeof(ASNItem))
  25498. #endif
  25499. /* add signature to end of buffer, size of buffer assumed checked, return
  25500. new length */
  25501. int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz,
  25502. int sigAlgoType)
  25503. {
  25504. #ifndef WOLFSSL_ASN_TEMPLATE
  25505. byte seq[MAX_SEQ_SZ];
  25506. word32 idx, seqSz;
  25507. if ((bodySz < 0) || (sigSz < 0))
  25508. return BUFFER_E;
  25509. idx = (word32)bodySz;
  25510. /* algo */
  25511. idx += SetAlgoID(sigAlgoType, buf ? buf + idx : NULL, oidSigType, 0);
  25512. /* bit string */
  25513. idx += SetBitString((word32)sigSz, 0, buf ? buf + idx : NULL);
  25514. /* signature */
  25515. if (buf)
  25516. XMEMCPY(buf + idx, sig, (size_t)sigSz);
  25517. idx += (word32)sigSz;
  25518. /* make room for overall header */
  25519. seqSz = SetSequence(idx, seq);
  25520. if (buf) {
  25521. XMEMMOVE(buf + seqSz, buf, idx);
  25522. XMEMCPY(buf, seq, seqSz);
  25523. }
  25524. return (int)(idx + seqSz);
  25525. #else
  25526. DECL_ASNSETDATA(dataASN, sigASN_Length);
  25527. word32 seqSz;
  25528. int sz;
  25529. int ret = 0;
  25530. CALLOC_ASNSETDATA(dataASN, sigASN_Length, ret, NULL);
  25531. /* In place, put body between SEQUENCE and signature. */
  25532. if (ret == 0) {
  25533. /* Set sigature OID and signature data. */
  25534. SetASN_OID(&dataASN[SIGASN_IDX_SIGALGO_OID], (word32)sigAlgoType,
  25535. oidSigType);
  25536. if (IsSigAlgoECC((word32)sigAlgoType)) {
  25537. /* ECDSA and EdDSA doesn't have NULL tagged item. */
  25538. dataASN[SIGASN_IDX_SIGALGO_NULL].noOut = 1;
  25539. }
  25540. SetASN_Buffer(&dataASN[SIGASN_IDX_SIGNATURE], sig, (word32)sigSz);
  25541. /* Calculate size of signature data. */
  25542. ret = SizeASN_Items(&sigASN[SIGASN_IDX_SIGALGO_SEQ],
  25543. &dataASN[SIGASN_IDX_SIGALGO_SEQ], sigASN_Length - 2, &sz);
  25544. }
  25545. if (ret == 0) {
  25546. /* Calculate size of outer sequence by calculating size of the encoded
  25547. * length and adding 1 for tag. */
  25548. seqSz = SizeASNHeader((word32)bodySz + (word32)sz);
  25549. if (buf != NULL) {
  25550. /* Move body to after sequence. */
  25551. XMEMMOVE(buf + seqSz, buf, (size_t)bodySz);
  25552. }
  25553. /* Leave space for body in encoding. */
  25554. SetASN_ReplaceBuffer(&dataASN[SIGASN_IDX_TBS_SEQ], NULL,
  25555. (word32)bodySz);
  25556. /* Calculate overall size and put in offsets and lengths. */
  25557. ret = SizeASN_Items(sigASN, dataASN, sigASN_Length, &sz);
  25558. }
  25559. if ((ret == 0) && (buf != NULL)) {
  25560. /* Write SEQUENCE and signature around body. */
  25561. SetASN_Items(sigASN, dataASN, sigASN_Length, buf);
  25562. }
  25563. if (ret == 0) {
  25564. /* Return the encoding size. */
  25565. ret = sz;
  25566. }
  25567. FREE_ASNSETDATA(dataASN, NULL);
  25568. return ret;
  25569. #endif /* WOLFSSL_ASN_TEMPLATE */
  25570. }
  25571. /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
  25572. static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
  25573. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng,
  25574. DsaKey* dsaKey, ed25519_key* ed25519Key,
  25575. ed448_key* ed448Key, falcon_key* falconKey,
  25576. dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
  25577. {
  25578. #ifndef WOLFSSL_ASN_TEMPLATE
  25579. int ret;
  25580. #ifdef WOLFSSL_SMALL_STACK
  25581. DerCert* der;
  25582. #else
  25583. DerCert der[1];
  25584. #endif
  25585. if (derBuffer == NULL)
  25586. return BAD_FUNC_ARG;
  25587. if (eccKey)
  25588. cert->keyType = ECC_KEY;
  25589. else if (rsaKey)
  25590. cert->keyType = RSA_KEY;
  25591. else if (dsaKey)
  25592. cert->keyType = DSA_KEY;
  25593. else if (ed25519Key)
  25594. cert->keyType = ED25519_KEY;
  25595. else if (ed448Key)
  25596. cert->keyType = ED448_KEY;
  25597. #ifdef HAVE_PQC
  25598. #ifdef HAVE_FALCON
  25599. else if ((falconKey != NULL) && (falconKey->level == 1))
  25600. cert->keyType = FALCON_LEVEL1_KEY;
  25601. else if ((falconKey != NULL) && (falconKey->level == 5))
  25602. cert->keyType = FALCON_LEVEL5_KEY;
  25603. #endif /* HAVE_FALCON */
  25604. #ifdef HAVE_DILITHIUM
  25605. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
  25606. cert->keyType = DILITHIUM_LEVEL2_KEY;
  25607. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
  25608. cert->keyType = DILITHIUM_LEVEL3_KEY;
  25609. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
  25610. cert->keyType = DILITHIUM_LEVEL5_KEY;
  25611. #endif /* HAVE_DILITHIUM */
  25612. #ifdef HAVE_SPHINCS
  25613. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25614. && (sphincsKey->optim == FAST_VARIANT))
  25615. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  25616. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25617. && (sphincsKey->optim == FAST_VARIANT))
  25618. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  25619. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25620. && (sphincsKey->optim == FAST_VARIANT))
  25621. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  25622. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25623. && (sphincsKey->optim == SMALL_VARIANT))
  25624. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  25625. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25626. && (sphincsKey->optim == SMALL_VARIANT))
  25627. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  25628. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25629. && (sphincsKey->optim == SMALL_VARIANT))
  25630. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  25631. #endif /* HAVE_SPHINCS */
  25632. #endif /* HAVE_PQC */
  25633. else
  25634. return BAD_FUNC_ARG;
  25635. #ifdef WOLFSSL_SMALL_STACK
  25636. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25637. if (der == NULL)
  25638. return MEMORY_E;
  25639. #endif
  25640. ret = EncodeCert(cert, der, rsaKey, eccKey, rng, dsaKey, ed25519Key,
  25641. ed448Key, falconKey, dilithiumKey, sphincsKey);
  25642. if (ret == 0) {
  25643. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  25644. ret = BUFFER_E;
  25645. else
  25646. ret = cert->bodySz = WriteCertBody(der, derBuffer);
  25647. }
  25648. #ifdef WOLFSSL_SMALL_STACK
  25649. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25650. #endif
  25651. return ret;
  25652. #else
  25653. /* TODO: issRaw and sbjRaw should be NUL terminated. */
  25654. DECL_ASNSETDATA(dataASN, x509CertASN_Length);
  25655. word32 publicKeySz = 0;
  25656. word32 issuerSz = 0;
  25657. word32 subjectSz = 0;
  25658. word32 extSz = 0;
  25659. int sz = 0;
  25660. int ret = 0;
  25661. word32 issRawLen = 0;
  25662. word32 sbjRawLen = 0;
  25663. /* Unused without OQS */
  25664. (void)falconKey;
  25665. (void)dilithiumKey;
  25666. (void)sphincsKey;
  25667. CALLOC_ASNSETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  25668. if (ret == 0) {
  25669. /* Set key type into certificate object based on key passed in. */
  25670. if (rsaKey) {
  25671. cert->keyType = RSA_KEY;
  25672. }
  25673. else if (eccKey) {
  25674. cert->keyType = ECC_KEY;
  25675. }
  25676. else if (dsaKey) {
  25677. cert->keyType = DSA_KEY;
  25678. }
  25679. else if (ed25519Key) {
  25680. cert->keyType = ED25519_KEY;
  25681. }
  25682. else if (ed448Key) {
  25683. cert->keyType = ED448_KEY;
  25684. }
  25685. #ifdef HAVE_PQC
  25686. #ifdef HAVE_FALCON
  25687. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  25688. cert->keyType = FALCON_LEVEL1_KEY;
  25689. }
  25690. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  25691. cert->keyType = FALCON_LEVEL5_KEY;
  25692. }
  25693. #endif /* HAVE_FALCON */
  25694. #ifdef HAVE_DILITHIUM
  25695. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
  25696. cert->keyType = DILITHIUM_LEVEL2_KEY;
  25697. }
  25698. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
  25699. cert->keyType = DILITHIUM_LEVEL3_KEY;
  25700. }
  25701. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
  25702. cert->keyType = DILITHIUM_LEVEL5_KEY;
  25703. }
  25704. #endif /* HAVE_DILITHIUM */
  25705. #ifdef HAVE_SPHINCS
  25706. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25707. && (sphincsKey->optim == FAST_VARIANT)) {
  25708. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  25709. }
  25710. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25711. && (sphincsKey->optim == FAST_VARIANT)) {
  25712. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  25713. }
  25714. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25715. && (sphincsKey->optim == FAST_VARIANT)) {
  25716. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  25717. }
  25718. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25719. && (sphincsKey->optim == SMALL_VARIANT)) {
  25720. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  25721. }
  25722. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25723. && (sphincsKey->optim == SMALL_VARIANT)) {
  25724. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  25725. }
  25726. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25727. && (sphincsKey->optim == SMALL_VARIANT)) {
  25728. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  25729. }
  25730. #endif /* HAVE_SPHINCS */
  25731. #endif /* HAVE_PQC */
  25732. else {
  25733. ret = BAD_FUNC_ARG;
  25734. }
  25735. }
  25736. if ((ret == 0) && (cert->serialSz == 0)) {
  25737. /* Generate random serial number. */
  25738. cert->serialSz = CTC_GEN_SERIAL_SZ;
  25739. ret = GenerateInteger(rng, cert->serial, CTC_GEN_SERIAL_SZ);
  25740. }
  25741. if (ret == 0) {
  25742. /* Determine issuer name size. */
  25743. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25744. defined(WOLFSSL_CERT_REQ)
  25745. issRawLen = (word32)XSTRLEN((const char*)cert->issRaw);
  25746. if (issRawLen > 0) {
  25747. issuerSz = min(sizeof(cert->issRaw), issRawLen);
  25748. }
  25749. else
  25750. #endif
  25751. {
  25752. /* Calculate issuer name encoding size. If the cert is self-signed
  25753. * use the subject instead of the issuer. */
  25754. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, cert->selfSigned ?
  25755. &cert->subject : &cert->issuer, cert->heap);
  25756. issuerSz = (word32)ret;
  25757. }
  25758. }
  25759. if (ret >= 0) {
  25760. /* Determine subject name size. */
  25761. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25762. defined(WOLFSSL_CERT_REQ)
  25763. sbjRawLen = (word32)XSTRLEN((const char*)cert->sbjRaw);
  25764. if (sbjRawLen > 0) {
  25765. subjectSz = min(sizeof(cert->sbjRaw), sbjRawLen);
  25766. }
  25767. else
  25768. #endif
  25769. {
  25770. /* Calculate subject name encoding size. */
  25771. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject,
  25772. cert->heap);
  25773. subjectSz = (word32)ret;
  25774. }
  25775. }
  25776. if (ret >= 0) {
  25777. /* Calculate public key encoding size. */
  25778. ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  25779. eccKey, ed25519Key, ed448Key, dsaKey);
  25780. publicKeySz = (word32)ret;
  25781. }
  25782. if (ret >= 0) {
  25783. /* Calculate extensions encoding size - may be 0. */
  25784. ret = EncodeExtensions(cert, NULL, 0, 0);
  25785. extSz = (word32)ret;
  25786. }
  25787. if (ret >= 0) {
  25788. /* Don't write out outer sequence - only doing body. */
  25789. dataASN[X509CERTASN_IDX_SEQ].noOut = 1;
  25790. /* Set version, serial number and signature OID */
  25791. SetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT],
  25792. (byte)cert->version);
  25793. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
  25794. (word32)cert->serialSz);
  25795. SetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID],
  25796. (word32)cert->sigType, oidSigType);
  25797. if (IsSigAlgoECC((word32)cert->sigType)) {
  25798. /* No NULL tagged item with ECDSA and EdDSA signature OIDs. */
  25799. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL].noOut = 1;
  25800. }
  25801. #ifdef WC_RSA_PSS
  25802. /* TODO: Encode RSA PSS parameters. */
  25803. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].noOut = 1;
  25804. #endif
  25805. if (issRawLen > 0) {
  25806. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25807. defined(WOLFSSL_CERT_REQ)
  25808. /* Put in encoded issuer name. */
  25809. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  25810. cert->issRaw, issuerSz);
  25811. #endif
  25812. }
  25813. else {
  25814. /* Leave space for issuer name. */
  25815. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  25816. NULL, issuerSz);
  25817. }
  25818. if (cert->beforeDateSz && cert->afterDateSz) {
  25819. if (cert->beforeDate[0] == ASN_UTC_TIME) {
  25820. /* Make space for before date data. */
  25821. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC],
  25822. cert->beforeDate + 2, ASN_UTC_TIME_SIZE - 1);
  25823. /* Don't put out Generalized Time before data. */
  25824. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT].noOut = 1;
  25825. }
  25826. else {
  25827. /* Don't put out UTC before data. */
  25828. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
  25829. /* Make space for before date data. */
  25830. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
  25831. cert->beforeDate + 2, ASN_GEN_TIME_SZ);
  25832. }
  25833. if (cert->afterDate[0] == ASN_UTC_TIME) {
  25834. /* Make space for after date data. */
  25835. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC],
  25836. cert->afterDate + 2, ASN_UTC_TIME_SIZE - 1);
  25837. /* Don't put out UTC Generalized Time after data. */
  25838. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT].noOut = 1;
  25839. }
  25840. else {
  25841. /* Don't put out UTC after data. */
  25842. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
  25843. /* Make space for after date data. */
  25844. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
  25845. cert->afterDate + 2, ASN_GEN_TIME_SZ);
  25846. }
  25847. }
  25848. else
  25849. {
  25850. /* Don't put out UTC before data. */
  25851. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
  25852. /* Make space for before date data. */
  25853. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
  25854. NULL, ASN_GEN_TIME_SZ);
  25855. /* Don't put out UTC after data. */
  25856. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
  25857. /* Make space for after date data. */
  25858. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
  25859. NULL, ASN_GEN_TIME_SZ);
  25860. }
  25861. if (sbjRawLen > 0) {
  25862. /* Put in encoded subject name. */
  25863. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25864. defined(WOLFSSL_CERT_REQ)
  25865. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
  25866. cert->sbjRaw, subjectSz);
  25867. #endif
  25868. }
  25869. else {
  25870. /* Leave space for subject name. */
  25871. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
  25872. NULL, subjectSz);
  25873. }
  25874. /* Leave space for public key. */
  25875. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ],
  25876. NULL, publicKeySz);
  25877. /* Replacement buffer instead of algorithm identifier items. */
  25878. SetASNItem_NoOut(dataASN,
  25879. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
  25880. X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY);
  25881. /* issuerUniqueID and subjectUniqueID not supported. */
  25882. dataASN[X509CERTASN_IDX_TBS_ISSUERUID].noOut = 1;
  25883. dataASN[X509CERTASN_IDX_TBS_SUBJECTUID].noOut = 1;
  25884. /* Leave space for extensions if any set into certificate object. */
  25885. if (extSz > 0) {
  25886. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_EXT_SEQ], NULL, extSz);
  25887. }
  25888. else {
  25889. SetASNItem_NoOutNode(dataASN, x509CertASN,
  25890. X509CERTASN_IDX_TBS_EXT, x509CertASN_Length);
  25891. }
  25892. /* No signature - added later. */
  25893. SetASNItem_NoOut(dataASN, X509CERTASN_IDX_SIGALGO_SEQ,
  25894. X509CERTASN_IDX_SIGNATURE);
  25895. /* Calculate encoded certificate body size. */
  25896. ret = SizeASN_Items(x509CertASN, dataASN, x509CertASN_Length, &sz);
  25897. }
  25898. /* Check buffer is big enough for encoded data. */
  25899. if ((ret == 0) && (sz > (int)derSz)) {
  25900. ret = BUFFER_E;
  25901. }
  25902. if (ret == 0) {
  25903. /* Encode certificate body into buffer. */
  25904. SetASN_Items(x509CertASN, dataASN, x509CertASN_Length, derBuffer);
  25905. if (issRawLen == 0) {
  25906. /* Encode issuer name into buffer. Use the subject as the issuer
  25907. * if it is self-signed. Size will be correct because we did the
  25908. * same for size. */
  25909. ret = SetNameEx(
  25910. (byte*)dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.data,
  25911. dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.length,
  25912. cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
  25913. }
  25914. }
  25915. if ((ret >= 0) && (sbjRawLen == 0)) {
  25916. /* Encode subject name into buffer. */
  25917. ret = SetNameEx(
  25918. (byte*)dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.data,
  25919. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.length,
  25920. &cert->subject, cert->heap);
  25921. }
  25922. if (ret >= 0) {
  25923. if (cert->beforeDateSz == 0 || cert->afterDateSz == 0)
  25924. {
  25925. /* Encode validity into buffer. */
  25926. ret = SetValidity(
  25927. (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT]
  25928. .data.buffer.data,
  25929. (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT]
  25930. .data.buffer.data, cert->daysValid);
  25931. }
  25932. }
  25933. if (ret >= 0) {
  25934. /* Encode public key into buffer. */
  25935. ret = EncodePublicKey(cert->keyType,
  25936. (byte*)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
  25937. .data.buffer.data,
  25938. (int)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
  25939. .data.buffer.length,
  25940. rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
  25941. }
  25942. if ((ret >= 0) && (!dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].noOut)) {
  25943. /* Encode extensions into buffer. */
  25944. ret = EncodeExtensions(cert,
  25945. (byte*)dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.data,
  25946. dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.length, 0);
  25947. }
  25948. if (ret >= 0) {
  25949. /* Store encoded certifcate body size. */
  25950. cert->bodySz = sz;
  25951. /* Return the encoding size. */
  25952. ret = sz;
  25953. }
  25954. FREE_ASNSETDATA(dataASN, cert->heap);
  25955. return ret;
  25956. #endif
  25957. }
  25958. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  25959. int wc_MakeCert_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  25960. void* key, WC_RNG* rng)
  25961. {
  25962. RsaKey* rsaKey = NULL;
  25963. DsaKey* dsaKey = NULL;
  25964. ecc_key* eccKey = NULL;
  25965. ed25519_key* ed25519Key = NULL;
  25966. ed448_key* ed448Key = NULL;
  25967. falcon_key* falconKey = NULL;
  25968. dilithium_key* dilithiumKey = NULL;
  25969. sphincs_key* sphincsKey = NULL;
  25970. if (keyType == RSA_TYPE)
  25971. rsaKey = (RsaKey*)key;
  25972. else if (keyType == DSA_TYPE)
  25973. dsaKey = (DsaKey*)key;
  25974. else if (keyType == ECC_TYPE)
  25975. eccKey = (ecc_key*)key;
  25976. else if (keyType == ED25519_TYPE)
  25977. ed25519Key = (ed25519_key*)key;
  25978. else if (keyType == ED448_TYPE)
  25979. ed448Key = (ed448_key*)key;
  25980. else if (keyType == FALCON_LEVEL1_TYPE)
  25981. falconKey = (falcon_key*)key;
  25982. else if (keyType == FALCON_LEVEL5_TYPE)
  25983. falconKey = (falcon_key*)key;
  25984. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  25985. dilithiumKey = (dilithium_key*)key;
  25986. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  25987. dilithiumKey = (dilithium_key*)key;
  25988. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  25989. dilithiumKey = (dilithium_key*)key;
  25990. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  25991. sphincsKey = (sphincs_key*)key;
  25992. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  25993. sphincsKey = (sphincs_key*)key;
  25994. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  25995. sphincsKey = (sphincs_key*)key;
  25996. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  25997. sphincsKey = (sphincs_key*)key;
  25998. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  25999. sphincsKey = (sphincs_key*)key;
  26000. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  26001. sphincsKey = (sphincs_key*)key;
  26002. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, dsaKey,
  26003. ed25519Key, ed448Key, falconKey, dilithiumKey,
  26004. sphincsKey);
  26005. }
  26006. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  26007. WOLFSSL_ABI
  26008. int wc_MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,
  26009. ecc_key* eccKey, WC_RNG* rng)
  26010. {
  26011. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, NULL,
  26012. NULL, NULL, NULL, NULL);
  26013. }
  26014. #ifdef WOLFSSL_CERT_REQ
  26015. #ifndef WOLFSSL_ASN_TEMPLATE
  26016. /* return size of data set on success
  26017. * if getting size only then attr and oid should be NULL
  26018. */
  26019. static word32 SetReqAttribSingle(byte* output, word32* idx, char* attr,
  26020. word32 attrSz, const byte* oid, word32 oidSz, byte printable,
  26021. word32 extSz)
  26022. {
  26023. word32 totalSz = 0;
  26024. word32 seqSz = 0;
  26025. word32 setSz = 0;
  26026. word32 strSz = 0;
  26027. byte seq[MAX_SEQ_SZ];
  26028. byte set[MAX_SET_SZ];
  26029. byte str[MAX_PRSTR_SZ];
  26030. totalSz = (word32)SetObjectId((int)oidSz, NULL);
  26031. totalSz += oidSz;
  26032. if (extSz > 0) {
  26033. totalSz += setSz = SetSet(extSz, set);
  26034. totalSz += seqSz = SetSequence(totalSz + extSz, seq);
  26035. totalSz += extSz;
  26036. }
  26037. else {
  26038. if (printable) {
  26039. strSz = SetPrintableString(attrSz, str);
  26040. totalSz += strSz;
  26041. }
  26042. else {
  26043. totalSz += strSz = SetUTF8String(attrSz, str);
  26044. }
  26045. totalSz += setSz = SetSet(strSz + attrSz, set);
  26046. totalSz += seqSz = SetSequence(totalSz + attrSz, seq);
  26047. totalSz += attrSz;
  26048. }
  26049. if (oid) {
  26050. XMEMCPY(&output[*idx], seq, seqSz);
  26051. *idx += seqSz;
  26052. *idx += (word32)SetObjectId((int)oidSz, output + *idx);
  26053. XMEMCPY(&output[*idx], oid, oidSz);
  26054. *idx += oidSz;
  26055. XMEMCPY(&output[*idx], set, setSz);
  26056. *idx += setSz;
  26057. if (strSz > 0) {
  26058. XMEMCPY(&output[*idx], str, strSz);
  26059. *idx += strSz;
  26060. if (attrSz > 0) {
  26061. XMEMCPY(&output[*idx], attr, attrSz);
  26062. *idx += attrSz;
  26063. }
  26064. }
  26065. }
  26066. return totalSz;
  26067. }
  26068. static int SetReqAttrib(byte* output, Cert* cert, word32 extSz)
  26069. {
  26070. word32 sz = 0; /* overall size */
  26071. word32 setSz = 0;
  26072. output[0] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  26073. sz++;
  26074. if (cert->challengePw[0]) {
  26075. setSz += SetReqAttribSingle(output, &sz, NULL,
  26076. (word32)XSTRLEN(cert->challengePw), NULL,
  26077. sizeof(attrChallengePasswordOid),
  26078. (byte)cert->challengePwPrintableString, 0);
  26079. }
  26080. if (cert->unstructuredName[0]) {
  26081. setSz += SetReqAttribSingle(output, &sz, NULL,
  26082. (word32)XSTRLEN(cert->unstructuredName), NULL,
  26083. sizeof(attrUnstructuredNameOid), 1, 0);
  26084. }
  26085. if (extSz) {
  26086. setSz += SetReqAttribSingle(output, &sz, NULL, 0, NULL,
  26087. sizeof(attrExtensionRequestOid), 1, extSz);
  26088. }
  26089. /* Put the pieces together. */
  26090. sz += SetLength(setSz, &output[sz]);
  26091. if (sz + setSz - extSz > MAX_ATTRIB_SZ) {
  26092. WOLFSSL_MSG("Attribute Buffer is not big enough!");
  26093. return REQ_ATTRIBUTE_E;
  26094. }
  26095. if (cert->challengePw[0]) {
  26096. SetReqAttribSingle(output, &sz, cert->challengePw,
  26097. (word32)XSTRLEN(cert->challengePw),
  26098. &attrChallengePasswordOid[0],
  26099. sizeof(attrChallengePasswordOid),
  26100. (byte)cert->challengePwPrintableString, 0);
  26101. }
  26102. if (cert->unstructuredName[0]) {
  26103. SetReqAttribSingle(output, &sz, cert->unstructuredName,
  26104. (word32)XSTRLEN(cert->unstructuredName),
  26105. &attrUnstructuredNameOid[0],
  26106. sizeof(attrUnstructuredNameOid), 1, 0);
  26107. }
  26108. if (extSz) {
  26109. SetReqAttribSingle(output, &sz, NULL, 0, &attrExtensionRequestOid[0],
  26110. sizeof(attrExtensionRequestOid), 1, extSz);
  26111. /* The actual extension data will be tacked onto the output later. */
  26112. }
  26113. return (int)sz;
  26114. }
  26115. #ifdef WOLFSSL_CUSTOM_OID
  26116. /* encode a custom oid and value */
  26117. static int SetCustomObjectId(Cert* cert, byte* output, word32 outSz,
  26118. CertOidField* custom)
  26119. {
  26120. int idx = 0, cust_lenSz, cust_oidSz;
  26121. if (cert == NULL || output == NULL || custom == NULL) {
  26122. return BAD_FUNC_ARG;
  26123. }
  26124. if (custom->oid == NULL || custom->oidSz <= 0) {
  26125. return 0; /* none set */
  26126. }
  26127. /* Octet String header */
  26128. cust_lenSz = SetOctetString(custom->valSz, NULL);
  26129. cust_oidSz = SetObjectId(custom->oidSz, NULL);
  26130. /* check for output buffer room */
  26131. if ((word32)(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz) >
  26132. outSz) {
  26133. return BUFFER_E;
  26134. }
  26135. /* put sequence with total */
  26136. idx = SetSequence(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz,
  26137. output);
  26138. /* put oid header */
  26139. idx += SetObjectId(custom->oidSz, output+idx);
  26140. XMEMCPY(output+idx, custom->oid, custom->oidSz);
  26141. idx += custom->oidSz;
  26142. /* put value */
  26143. idx += SetOctetString(custom->valSz, output+idx);
  26144. XMEMCPY(output+idx, custom->val, custom->valSz);
  26145. idx += custom->valSz;
  26146. return idx;
  26147. }
  26148. #endif /* WOLFSSL_CUSTOM_OID */
  26149. /* encode info from cert into DER encoded format */
  26150. static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey,
  26151. DsaKey* dsaKey, ecc_key* eccKey,
  26152. ed25519_key* ed25519Key, ed448_key* ed448Key,
  26153. falcon_key* falconKey, dilithium_key* dilithiumKey,
  26154. sphincs_key* sphincsKey)
  26155. {
  26156. int ret;
  26157. (void)eccKey;
  26158. (void)ed25519Key;
  26159. (void)ed448Key;
  26160. (void)falconKey;
  26161. (void)dilithiumKey;
  26162. (void)sphincsKey;
  26163. if (cert == NULL || der == NULL)
  26164. return BAD_FUNC_ARG;
  26165. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  26166. dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
  26167. falconKey == NULL) {
  26168. return PUBLIC_KEY_E;
  26169. }
  26170. /* init */
  26171. XMEMSET(der, 0, sizeof(DerCert));
  26172. /* version */
  26173. der->versionSz = SetMyVersion((word32)cert->version, der->version, FALSE);
  26174. /* subject name */
  26175. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26176. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  26177. /* Use the raw subject */
  26178. int idx;
  26179. der->subjectSz = (int)min(sizeof(der->subject),
  26180. (word32)XSTRLEN((const char*)cert->sbjRaw));
  26181. /* header */
  26182. idx = (int)SetSequence((word32)der->subjectSz, der->subject);
  26183. if (der->subjectSz + idx > (int)sizeof(der->subject)) {
  26184. return SUBJECT_E;
  26185. }
  26186. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  26187. (size_t)der->subjectSz);
  26188. der->subjectSz += idx;
  26189. }
  26190. else
  26191. #endif
  26192. {
  26193. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  26194. &cert->subject, cert->heap);
  26195. }
  26196. if (der->subjectSz <= 0)
  26197. return SUBJECT_E;
  26198. /* public key */
  26199. #ifndef NO_RSA
  26200. if (cert->keyType == RSA_KEY) {
  26201. if (rsaKey == NULL)
  26202. return PUBLIC_KEY_E;
  26203. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  26204. sizeof(der->publicKey), 1);
  26205. }
  26206. #endif
  26207. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  26208. if (cert->keyType == DSA_KEY) {
  26209. if (dsaKey == NULL)
  26210. return PUBLIC_KEY_E;
  26211. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  26212. sizeof(der->publicKey), 1);
  26213. }
  26214. #endif
  26215. #ifdef HAVE_ECC
  26216. if (cert->keyType == ECC_KEY) {
  26217. if (eccKey == NULL)
  26218. return PUBLIC_KEY_E;
  26219. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  26220. sizeof(der->publicKey), 1, 0);
  26221. }
  26222. #endif
  26223. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  26224. if (cert->keyType == ED25519_KEY) {
  26225. if (ed25519Key == NULL)
  26226. return PUBLIC_KEY_E;
  26227. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  26228. (word32)sizeof(der->publicKey), 1);
  26229. }
  26230. #endif
  26231. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  26232. if (cert->keyType == ED448_KEY) {
  26233. if (ed448Key == NULL)
  26234. return PUBLIC_KEY_E;
  26235. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  26236. (word32)sizeof(der->publicKey), 1);
  26237. }
  26238. #endif
  26239. #if defined(HAVE_PQC)
  26240. #if defined(HAVE_FALCON)
  26241. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  26242. (cert->keyType == FALCON_LEVEL5_KEY)) {
  26243. if (falconKey == NULL)
  26244. return PUBLIC_KEY_E;
  26245. der->publicKeySz = wc_Falcon_PublicKeyToDer(falconKey,
  26246. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26247. }
  26248. #endif
  26249. #if defined(HAVE_DILITHIUM)
  26250. if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
  26251. (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
  26252. (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
  26253. if (dilithiumKey == NULL)
  26254. return PUBLIC_KEY_E;
  26255. der->publicKeySz = wc_Dilithium_PublicKeyToDer(dilithiumKey,
  26256. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26257. }
  26258. #endif
  26259. #if defined(HAVE_SPHINCS)
  26260. if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
  26261. (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
  26262. (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
  26263. (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
  26264. (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
  26265. (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
  26266. if (sphincsKey == NULL)
  26267. return PUBLIC_KEY_E;
  26268. der->publicKeySz = wc_Sphincs_PublicKeyToDer(sphincsKey,
  26269. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26270. }
  26271. #endif
  26272. #endif /* HAVE_PQC */
  26273. if (der->publicKeySz <= 0)
  26274. return PUBLIC_KEY_E;
  26275. /* set the extensions */
  26276. der->extensionsSz = 0;
  26277. /* RFC 5280 : 4.2.1.9. Basic Constraints
  26278. * The pathLenConstraint field is meaningful only if the CA boolean is
  26279. * asserted and the key usage extension, if present, asserts the
  26280. * keyCertSign bit */
  26281. /* Set CA and path length */
  26282. if ((cert->isCA) && (cert->pathLenSet)
  26283. #ifdef WOLFSSL_CERT_EXT
  26284. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  26285. #endif
  26286. ) {
  26287. der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
  26288. if (der->caSz <= 0)
  26289. return CA_TRUE_E;
  26290. der->extensionsSz += der->caSz;
  26291. }
  26292. /* Set CA */
  26293. else if (cert->isCA) {
  26294. der->caSz = SetCa(der->ca, sizeof(der->ca));
  26295. if (der->caSz <= 0)
  26296. return CA_TRUE_E;
  26297. der->extensionsSz += der->caSz;
  26298. }
  26299. /* Set Basic Constraint */
  26300. else if (cert->basicConstSet) {
  26301. der->caSz = SetBC(der->ca, sizeof(der->ca));
  26302. if (der->caSz <= 0)
  26303. return EXTENSIONS_E;
  26304. der->extensionsSz += der->caSz;
  26305. }
  26306. else
  26307. der->caSz = 0;
  26308. #ifdef WOLFSSL_ALT_NAMES
  26309. /* Alternative Name */
  26310. if (cert->altNamesSz) {
  26311. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  26312. cert->altNames, (word32)cert->altNamesSz,
  26313. cert->altNamesCrit);
  26314. if (der->altNamesSz <= 0)
  26315. return ALT_NAME_E;
  26316. der->extensionsSz += der->altNamesSz;
  26317. }
  26318. else
  26319. der->altNamesSz = 0;
  26320. #endif
  26321. #ifdef WOLFSSL_CERT_EXT
  26322. /* SKID */
  26323. if (cert->skidSz) {
  26324. /* check the provided SKID size */
  26325. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  26326. return SKID_E;
  26327. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  26328. cert->skid, (word32)cert->skidSz);
  26329. if (der->skidSz <= 0)
  26330. return SKID_E;
  26331. der->extensionsSz += der->skidSz;
  26332. }
  26333. else
  26334. der->skidSz = 0;
  26335. /* Key Usage */
  26336. if (cert->keyUsage != 0) {
  26337. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  26338. cert->keyUsage);
  26339. if (der->keyUsageSz <= 0)
  26340. return KEYUSAGE_E;
  26341. der->extensionsSz += der->keyUsageSz;
  26342. }
  26343. else
  26344. der->keyUsageSz = 0;
  26345. /* Extended Key Usage */
  26346. if (cert->extKeyUsage != 0) {
  26347. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  26348. sizeof(der->extKeyUsage), cert->extKeyUsage);
  26349. if (der->extKeyUsageSz <= 0)
  26350. return EXTKEYUSAGE_E;
  26351. der->extensionsSz += der->extKeyUsageSz;
  26352. }
  26353. else
  26354. der->extKeyUsageSz = 0;
  26355. #endif /* WOLFSSL_CERT_EXT */
  26356. #ifdef WOLFSSL_CUSTOM_OID
  26357. /* encode a custom oid and value */
  26358. /* zero returns, means none set */
  26359. ret = SetCustomObjectId(cert, der->extCustom,
  26360. sizeof(der->extCustom), &cert->extCustom);
  26361. if (ret < 0)
  26362. return ret;
  26363. der->extCustomSz = ret;
  26364. der->extensionsSz += der->extCustomSz;
  26365. #endif
  26366. /* put extensions */
  26367. if (der->extensionsSz > 0) {
  26368. /* put the start of sequence (ID, Size) */
  26369. der->extensionsSz = (int)SetSequence((word32)der->extensionsSz,
  26370. der->extensions);
  26371. if (der->extensionsSz <= 0)
  26372. return EXTENSIONS_E;
  26373. /* put CA */
  26374. if (der->caSz) {
  26375. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26376. &der->extensionsSz,
  26377. der->ca, der->caSz);
  26378. if (ret <= 0)
  26379. return EXTENSIONS_E;
  26380. }
  26381. #ifdef WOLFSSL_ALT_NAMES
  26382. /* put Alternative Names */
  26383. if (der->altNamesSz) {
  26384. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26385. &der->extensionsSz,
  26386. der->altNames, der->altNamesSz);
  26387. if (ret <= 0)
  26388. return EXTENSIONS_E;
  26389. }
  26390. #endif
  26391. #ifdef WOLFSSL_CERT_EXT
  26392. /* put SKID */
  26393. if (der->skidSz) {
  26394. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26395. &der->extensionsSz,
  26396. der->skid, der->skidSz);
  26397. if (ret <= 0)
  26398. return EXTENSIONS_E;
  26399. }
  26400. /* put AKID */
  26401. if (der->akidSz) {
  26402. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26403. &der->extensionsSz,
  26404. der->akid, der->akidSz);
  26405. if (ret <= 0)
  26406. return EXTENSIONS_E;
  26407. }
  26408. /* put KeyUsage */
  26409. if (der->keyUsageSz) {
  26410. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26411. &der->extensionsSz,
  26412. der->keyUsage, der->keyUsageSz);
  26413. if (ret <= 0)
  26414. return EXTENSIONS_E;
  26415. }
  26416. /* put ExtendedKeyUsage */
  26417. if (der->extKeyUsageSz) {
  26418. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26419. &der->extensionsSz,
  26420. der->extKeyUsage, der->extKeyUsageSz);
  26421. if (ret <= 0)
  26422. return EXTENSIONS_E;
  26423. }
  26424. #ifdef WOLFSSL_CUSTOM_OID
  26425. if (der->extCustomSz) {
  26426. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26427. &der->extensionsSz,
  26428. der->extCustom, der->extCustomSz);
  26429. if (ret <= 0)
  26430. return EXTENSIONS_E;
  26431. }
  26432. #endif
  26433. #endif /* WOLFSSL_CERT_EXT */
  26434. }
  26435. der->attribSz = SetReqAttrib(der->attrib, cert, (word32)der->extensionsSz);
  26436. if (der->attribSz <= 0)
  26437. return REQ_ATTRIBUTE_E;
  26438. der->total = der->versionSz + der->subjectSz + der->publicKeySz +
  26439. der->extensionsSz + der->attribSz;
  26440. return 0;
  26441. }
  26442. /* write DER encoded cert req to buffer, size already checked */
  26443. static int WriteCertReqBody(DerCert* der, byte* buf)
  26444. {
  26445. int idx;
  26446. /* signed part header */
  26447. idx = (int)SetSequence((word32)der->total, buf);
  26448. /* version */
  26449. if (buf)
  26450. XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
  26451. idx += der->versionSz;
  26452. /* subject */
  26453. if (buf)
  26454. XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
  26455. idx += der->subjectSz;
  26456. /* public key */
  26457. if (buf)
  26458. XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
  26459. idx += der->publicKeySz;
  26460. /* attributes */
  26461. if (buf)
  26462. XMEMCPY(buf + idx, der->attrib, (size_t)der->attribSz);
  26463. idx += der->attribSz;
  26464. /* extensions */
  26465. if (der->extensionsSz) {
  26466. if (buf)
  26467. XMEMCPY(buf + idx, der->extensions, min((word32)der->extensionsSz,
  26468. sizeof(der->extensions)));
  26469. idx += der->extensionsSz;
  26470. }
  26471. return idx;
  26472. }
  26473. #endif
  26474. #ifdef WOLFSSL_ASN_TEMPLATE
  26475. /* ASN.1 template for Certificate Request body.
  26476. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  26477. */
  26478. static const ASNItem certReqBodyASN[] = {
  26479. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  26480. /* version */
  26481. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  26482. /* subject */
  26483. /* SUBJ_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  26484. /* subjectPKInfo */
  26485. /* SPUBKEYINFO_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  26486. /* attributes*/
  26487. /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  26488. /* Challenge Password Attribute */
  26489. /* ATTRS_CPW_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  26490. /* ATTRS_CPW_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  26491. /* ATTRS_CPW_SET */ { 3, ASN_SET, 1, 1, 0 },
  26492. /* ATTRS_CPW_PS */ { 4, ASN_PRINTABLE_STRING, 0, 0, 0 },
  26493. /* ATTRS_CPW_UTF */ { 4, ASN_UTF8STRING, 0, 0, 0 },
  26494. /* Extensions Attribute */
  26495. /* EXT_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  26496. /* EXT_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  26497. /* EXT_SET */ { 3, ASN_SET, 1, 1, 0 },
  26498. /* EXT_BODY */ { 4, ASN_SEQUENCE, 1, 0, 0 },
  26499. };
  26500. enum {
  26501. CERTREQBODYASN_IDX_SEQ = 0,
  26502. CERTREQBODYASN_IDX_VER,
  26503. CERTREQBODYASN_IDX_SUBJ_SEQ,
  26504. CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ,
  26505. CERTREQBODYASN_IDX_ATTRS,
  26506. CERTREQBODYASN_IDX_ATTRS_CPW_SEQ,
  26507. CERTREQBODYASN_IDX_ATTRS_CPW_OID,
  26508. CERTREQBODYASN_IDX_ATTRS_CPW_SET,
  26509. CERTREQBODYASN_IDX_ATTRS_CPW_PS,
  26510. CERTREQBODYASN_IDX_ATTRS_CPW_UTF,
  26511. CERTREQBODYASN_IDX_EXT_SEQ,
  26512. CERTREQBODYASN_IDX_EXT_OID,
  26513. CERTREQBODYASN_IDX_EXT_SET,
  26514. CERTREQBODYASN_IDX_EXT_BODY
  26515. };
  26516. /* Number of items in ASN.1 template for Certificate Request body. */
  26517. #define certReqBodyASN_Length (sizeof(certReqBodyASN) / sizeof(ASNItem))
  26518. #endif
  26519. static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  26520. RsaKey* rsaKey, DsaKey* dsaKey, ecc_key* eccKey,
  26521. ed25519_key* ed25519Key, ed448_key* ed448Key,
  26522. falcon_key* falconKey, dilithium_key* dilithiumKey,
  26523. sphincs_key* sphincsKey)
  26524. {
  26525. #ifndef WOLFSSL_ASN_TEMPLATE
  26526. int ret;
  26527. #ifdef WOLFSSL_SMALL_STACK
  26528. DerCert* der;
  26529. #else
  26530. DerCert der[1];
  26531. #endif
  26532. if (eccKey)
  26533. cert->keyType = ECC_KEY;
  26534. else if (rsaKey)
  26535. cert->keyType = RSA_KEY;
  26536. else if (dsaKey)
  26537. cert->keyType = DSA_KEY;
  26538. else if (ed25519Key)
  26539. cert->keyType = ED25519_KEY;
  26540. else if (ed448Key)
  26541. cert->keyType = ED448_KEY;
  26542. #ifdef HAVE_PQC
  26543. #ifdef HAVE_FALCON
  26544. else if ((falconKey != NULL) && (falconKey->level == 1))
  26545. cert->keyType = FALCON_LEVEL1_KEY;
  26546. else if ((falconKey != NULL) && (falconKey->level == 5))
  26547. cert->keyType = FALCON_LEVEL5_KEY;
  26548. #endif /* HAVE_FALCON */
  26549. #ifdef HAVE_DILITHIUM
  26550. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
  26551. cert->keyType = DILITHIUM_LEVEL2_KEY;
  26552. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
  26553. cert->keyType = DILITHIUM_LEVEL3_KEY;
  26554. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
  26555. cert->keyType = DILITHIUM_LEVEL5_KEY;
  26556. #endif /* HAVE_DILITHIUM */
  26557. #ifdef HAVE_SPHINCS
  26558. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26559. && (sphincsKey->optim == FAST_VARIANT))
  26560. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  26561. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26562. && (sphincsKey->optim == FAST_VARIANT))
  26563. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  26564. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26565. && (sphincsKey->optim == FAST_VARIANT))
  26566. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  26567. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26568. && (sphincsKey->optim == SMALL_VARIANT))
  26569. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  26570. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26571. && (sphincsKey->optim == SMALL_VARIANT))
  26572. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  26573. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26574. && (sphincsKey->optim == SMALL_VARIANT))
  26575. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  26576. #endif /* HAVE_SPHINCS */
  26577. #endif /* HAVE_PQC */
  26578. else
  26579. return BAD_FUNC_ARG;
  26580. #ifdef WOLFSSL_SMALL_STACK
  26581. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap,
  26582. DYNAMIC_TYPE_TMP_BUFFER);
  26583. if (der == NULL)
  26584. return MEMORY_E;
  26585. #endif
  26586. ret = EncodeCertReq(cert, der, rsaKey, dsaKey, eccKey, ed25519Key, ed448Key,
  26587. falconKey, dilithiumKey, sphincsKey);
  26588. if (ret == 0) {
  26589. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  26590. ret = BUFFER_E;
  26591. else
  26592. ret = cert->bodySz = WriteCertReqBody(der, derBuffer);
  26593. }
  26594. #ifdef WOLFSSL_SMALL_STACK
  26595. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  26596. #endif
  26597. return ret;
  26598. #else
  26599. DECL_ASNSETDATA(dataASN, certReqBodyASN_Length);
  26600. word32 publicKeySz = 0;
  26601. word32 subjectSz = 0;
  26602. word32 extSz = 0;
  26603. int sz = 0;
  26604. int ret = 0;
  26605. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26606. word32 sbjRawSz = 0;
  26607. #endif
  26608. /* Unused without OQS */
  26609. (void)falconKey;
  26610. (void)dilithiumKey;
  26611. (void)sphincsKey;
  26612. CALLOC_ASNSETDATA(dataASN, certReqBodyASN_Length, ret, cert->heap);
  26613. if (ret == 0) {
  26614. /* Set key type into certificate object based on key passed in. */
  26615. if (rsaKey != NULL) {
  26616. cert->keyType = RSA_KEY;
  26617. }
  26618. else if (eccKey != NULL) {
  26619. cert->keyType = ECC_KEY;
  26620. }
  26621. else if (dsaKey != NULL) {
  26622. cert->keyType = DSA_KEY;
  26623. }
  26624. else if (ed25519Key != NULL) {
  26625. cert->keyType = ED25519_KEY;
  26626. }
  26627. else if (ed448Key != NULL) {
  26628. cert->keyType = ED448_KEY;
  26629. }
  26630. #ifdef HAVE_PQC
  26631. #ifdef HAVE_FALCON
  26632. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  26633. cert->keyType = FALCON_LEVEL1_KEY;
  26634. }
  26635. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  26636. cert->keyType = FALCON_LEVEL5_KEY;
  26637. }
  26638. #endif /* HAVE_FALCON */
  26639. #ifdef HAVE_DILITHIUM
  26640. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
  26641. cert->keyType = DILITHIUM_LEVEL2_KEY;
  26642. }
  26643. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
  26644. cert->keyType = DILITHIUM_LEVEL3_KEY;
  26645. }
  26646. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
  26647. cert->keyType = DILITHIUM_LEVEL5_KEY;
  26648. }
  26649. #endif /* HAVE_DILITHIUM */
  26650. #ifdef HAVE_SPHINCS
  26651. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26652. && (sphincsKey->optim == FAST_VARIANT)) {
  26653. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  26654. }
  26655. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26656. && (sphincsKey->optim == FAST_VARIANT)) {
  26657. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  26658. }
  26659. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26660. && (sphincsKey->optim == FAST_VARIANT)) {
  26661. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  26662. }
  26663. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26664. && (sphincsKey->optim == SMALL_VARIANT)) {
  26665. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  26666. }
  26667. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26668. && (sphincsKey->optim == SMALL_VARIANT)) {
  26669. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  26670. }
  26671. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26672. && (sphincsKey->optim == SMALL_VARIANT)) {
  26673. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  26674. }
  26675. #endif /* HAVE_SPHINCS */
  26676. #endif /* HAVE_PQC */
  26677. else {
  26678. ret = BAD_FUNC_ARG;
  26679. }
  26680. }
  26681. if (ret == 0) {
  26682. /* Determine subject name size. */
  26683. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26684. sbjRawSz = (word32)XSTRLEN((const char*)cert->sbjRaw);
  26685. if (sbjRawSz > 0) {
  26686. subjectSz = min(sizeof(cert->sbjRaw), sbjRawSz);
  26687. }
  26688. else
  26689. #endif
  26690. {
  26691. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject, cert->heap);
  26692. subjectSz = (word32)ret;
  26693. }
  26694. }
  26695. if (ret >= 0) {
  26696. /* Determine encode public key size. */
  26697. ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  26698. eccKey, ed25519Key, ed448Key, dsaKey);
  26699. publicKeySz = (word32)ret;
  26700. }
  26701. if (ret >= 0) {
  26702. /* Determine encode extensions size. */
  26703. ret = EncodeExtensions(cert, NULL, 0, 1);
  26704. extSz = (word32)ret;
  26705. }
  26706. if (ret >= 0) {
  26707. /* Set version. */
  26708. SetASN_Int8Bit(&dataASN[CERTREQBODYASN_IDX_VER], (byte)cert->version);
  26709. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26710. if (sbjRawSz > 0) {
  26711. /* Put in encoded subject name. */
  26712. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], cert->sbjRaw,
  26713. subjectSz);
  26714. }
  26715. else
  26716. #endif
  26717. {
  26718. /* Leave space for subject name. */
  26719. SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], NULL,
  26720. subjectSz);
  26721. }
  26722. /* Leave space for public key. */
  26723. SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ],
  26724. NULL, publicKeySz);
  26725. if (cert->challengePw[0] != '\0') {
  26726. /* Add challenge password attribute. */
  26727. /* Set challenge password OID. */
  26728. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_OID],
  26729. attrChallengePasswordOid, sizeof(attrChallengePasswordOid));
  26730. /* Enable the ASN template item with the appropriate tag. */
  26731. if (cert->challengePwPrintableString) {
  26732. /* PRINTABLE_STRING - set buffer */
  26733. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS],
  26734. (byte*)cert->challengePw,
  26735. (word32)XSTRLEN(cert->challengePw));
  26736. /* UTF8STRING - don't encode */
  26737. dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF].noOut = 1;
  26738. }
  26739. else {
  26740. /* PRINTABLE_STRING - don't encode */
  26741. dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS].noOut = 1;
  26742. /* UTF8STRING - set buffer */
  26743. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF],
  26744. (byte*)cert->challengePw,
  26745. (word32)XSTRLEN(cert->challengePw));
  26746. }
  26747. }
  26748. else {
  26749. /* Leave out challenge password attribute items. */
  26750. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  26751. CERTREQBODYASN_IDX_ATTRS_CPW_SEQ, certReqBodyASN_Length);
  26752. }
  26753. if (extSz > 0) {
  26754. /* Set extension attribute OID. */
  26755. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_OID], attrExtensionRequestOid,
  26756. sizeof(attrExtensionRequestOid));
  26757. /* Leave space for data. */
  26758. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_BODY], NULL, extSz);
  26759. }
  26760. else {
  26761. /* Leave out extension attribute items. */
  26762. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  26763. CERTREQBODYASN_IDX_EXT_SEQ, certReqBodyASN_Length);
  26764. }
  26765. /* Calculate size of encoded certificate request body. */
  26766. ret = SizeASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length,
  26767. &sz);
  26768. }
  26769. /* Check buffer is big enough for encoded data. */
  26770. if ((ret == 0) && (sz > (int)derSz)) {
  26771. ret = BUFFER_E;
  26772. }
  26773. if (ret == 0 && derBuffer != NULL) {
  26774. /* Encode certificate request body into buffer. */
  26775. SetASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length, derBuffer);
  26776. /* Put in generated data */
  26777. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26778. if (sbjRawSz == 0)
  26779. #endif
  26780. {
  26781. /* Encode subject name into space in buffer. */
  26782. ret = SetNameEx(
  26783. (byte*)dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.data,
  26784. dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.length,
  26785. &cert->subject, cert->heap);
  26786. }
  26787. }
  26788. if (ret >= 0 && derBuffer != NULL) {
  26789. /* Encode public key into space in buffer. */
  26790. ret = EncodePublicKey(cert->keyType,
  26791. (byte*)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.data,
  26792. (int)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.length,
  26793. rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
  26794. }
  26795. if ((ret >= 0 && derBuffer != NULL) &&
  26796. (!dataASN[CERTREQBODYASN_IDX_EXT_BODY].noOut)) {
  26797. /* Encode extensions into space in buffer. */
  26798. ret = EncodeExtensions(cert,
  26799. (byte*)dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.data,
  26800. dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.length, 1);
  26801. }
  26802. if (ret >= 0) {
  26803. /* Store encoded certifcate request body size. */
  26804. cert->bodySz = sz;
  26805. /* Return the encoding size. */
  26806. ret = sz;
  26807. }
  26808. FREE_ASNSETDATA(dataASN, cert->heap);
  26809. return ret;
  26810. #endif /* WOLFSSL_ASN_TEMPLATE */
  26811. }
  26812. int wc_MakeCertReq_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  26813. void* key)
  26814. {
  26815. RsaKey* rsaKey = NULL;
  26816. DsaKey* dsaKey = NULL;
  26817. ecc_key* eccKey = NULL;
  26818. ed25519_key* ed25519Key = NULL;
  26819. ed448_key* ed448Key = NULL;
  26820. falcon_key* falconKey = NULL;
  26821. dilithium_key* dilithiumKey = NULL;
  26822. sphincs_key* sphincsKey = NULL;
  26823. if (keyType == RSA_TYPE)
  26824. rsaKey = (RsaKey*)key;
  26825. else if (keyType == DSA_TYPE)
  26826. dsaKey = (DsaKey*)key;
  26827. else if (keyType == ECC_TYPE)
  26828. eccKey = (ecc_key*)key;
  26829. else if (keyType == ED25519_TYPE)
  26830. ed25519Key = (ed25519_key*)key;
  26831. else if (keyType == ED448_TYPE)
  26832. ed448Key = (ed448_key*)key;
  26833. else if (keyType == FALCON_LEVEL1_TYPE)
  26834. falconKey = (falcon_key*)key;
  26835. else if (keyType == FALCON_LEVEL5_TYPE)
  26836. falconKey = (falcon_key*)key;
  26837. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  26838. dilithiumKey = (dilithium_key*)key;
  26839. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  26840. dilithiumKey = (dilithium_key*)key;
  26841. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  26842. dilithiumKey = (dilithium_key*)key;
  26843. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  26844. sphincsKey = (sphincs_key*)key;
  26845. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  26846. sphincsKey = (sphincs_key*)key;
  26847. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  26848. sphincsKey = (sphincs_key*)key;
  26849. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  26850. sphincsKey = (sphincs_key*)key;
  26851. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  26852. sphincsKey = (sphincs_key*)key;
  26853. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  26854. sphincsKey = (sphincs_key*)key;
  26855. return MakeCertReq(cert, derBuffer, derSz, rsaKey, dsaKey, eccKey,
  26856. ed25519Key, ed448Key, falconKey, dilithiumKey,
  26857. sphincsKey);
  26858. }
  26859. WOLFSSL_ABI
  26860. int wc_MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  26861. RsaKey* rsaKey, ecc_key* eccKey)
  26862. {
  26863. return MakeCertReq(cert, derBuffer, derSz, rsaKey, NULL, eccKey, NULL,
  26864. NULL, NULL, NULL, NULL);
  26865. }
  26866. #endif /* WOLFSSL_CERT_REQ */
  26867. static int SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  26868. RsaKey* rsaKey, ecc_key* eccKey, ed25519_key* ed25519Key,
  26869. ed448_key* ed448Key, falcon_key* falconKey,
  26870. dilithium_key* dilithiumKey, sphincs_key* sphincsKey,
  26871. WC_RNG* rng)
  26872. {
  26873. int sigSz = 0;
  26874. void* heap = NULL;
  26875. CertSignCtx certSignCtx_lcl;
  26876. CertSignCtx* certSignCtx = &certSignCtx_lcl;
  26877. XMEMSET(certSignCtx, 0, sizeof(*certSignCtx));
  26878. if (requestSz < 0)
  26879. return requestSz;
  26880. /* locate ctx */
  26881. if (rsaKey) {
  26882. #ifndef NO_RSA
  26883. #ifdef WOLFSSL_ASYNC_CRYPT
  26884. certSignCtx = &rsaKey->certSignCtx;
  26885. #endif
  26886. heap = rsaKey->heap;
  26887. #else
  26888. return NOT_COMPILED_IN;
  26889. #endif /* NO_RSA */
  26890. }
  26891. else if (eccKey) {
  26892. #ifdef HAVE_ECC
  26893. #ifdef WOLFSSL_ASYNC_CRYPT
  26894. certSignCtx = &eccKey->certSignCtx;
  26895. #endif
  26896. heap = eccKey->heap;
  26897. #else
  26898. return NOT_COMPILED_IN;
  26899. #endif /* HAVE_ECC */
  26900. }
  26901. if (certSignCtx->sig == NULL) {
  26902. certSignCtx->sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, heap,
  26903. DYNAMIC_TYPE_TMP_BUFFER);
  26904. if (certSignCtx->sig == NULL)
  26905. return MEMORY_E;
  26906. }
  26907. sigSz = MakeSignature(certSignCtx, buf, (word32)requestSz, certSignCtx->sig,
  26908. MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key,
  26909. falconKey, dilithiumKey, sphincsKey, rng, (word32)sType, heap);
  26910. #ifdef WOLFSSL_ASYNC_CRYPT
  26911. if (sigSz == WC_PENDING_E) {
  26912. /* Not free'ing certSignCtx->sig here because it could still be in use
  26913. * with async operations. */
  26914. return sigSz;
  26915. }
  26916. #endif
  26917. if (sigSz >= 0) {
  26918. if (requestSz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
  26919. sigSz = BUFFER_E;
  26920. else
  26921. sigSz = AddSignature(buf, requestSz, certSignCtx->sig, sigSz,
  26922. sType);
  26923. }
  26924. XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  26925. certSignCtx->sig = NULL;
  26926. return sigSz;
  26927. }
  26928. int wc_SignCert_ex(int requestSz, int sType, byte* buf, word32 buffSz,
  26929. int keyType, void* key, WC_RNG* rng)
  26930. {
  26931. RsaKey* rsaKey = NULL;
  26932. ecc_key* eccKey = NULL;
  26933. ed25519_key* ed25519Key = NULL;
  26934. ed448_key* ed448Key = NULL;
  26935. falcon_key* falconKey = NULL;
  26936. dilithium_key* dilithiumKey = NULL;
  26937. sphincs_key* sphincsKey = NULL;
  26938. if (keyType == RSA_TYPE)
  26939. rsaKey = (RsaKey*)key;
  26940. else if (keyType == ECC_TYPE)
  26941. eccKey = (ecc_key*)key;
  26942. else if (keyType == ED25519_TYPE)
  26943. ed25519Key = (ed25519_key*)key;
  26944. else if (keyType == ED448_TYPE)
  26945. ed448Key = (ed448_key*)key;
  26946. else if (keyType == FALCON_LEVEL1_TYPE)
  26947. falconKey = (falcon_key*)key;
  26948. else if (keyType == FALCON_LEVEL5_TYPE)
  26949. falconKey = (falcon_key*)key;
  26950. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  26951. dilithiumKey = (dilithium_key*)key;
  26952. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  26953. dilithiumKey = (dilithium_key*)key;
  26954. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  26955. dilithiumKey = (dilithium_key*)key;
  26956. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  26957. sphincsKey = (sphincs_key*)key;
  26958. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  26959. sphincsKey = (sphincs_key*)key;
  26960. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  26961. sphincsKey = (sphincs_key*)key;
  26962. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  26963. sphincsKey = (sphincs_key*)key;
  26964. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  26965. sphincsKey = (sphincs_key*)key;
  26966. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  26967. sphincsKey = (sphincs_key*)key;
  26968. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, ed25519Key,
  26969. ed448Key, falconKey, dilithiumKey, sphincsKey, rng);
  26970. }
  26971. int wc_SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  26972. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng)
  26973. {
  26974. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, NULL, NULL,
  26975. NULL, NULL, NULL, rng);
  26976. }
  26977. WOLFSSL_ABI
  26978. int wc_MakeSelfCert(Cert* cert, byte* buf, word32 buffSz,
  26979. RsaKey* key, WC_RNG* rng)
  26980. {
  26981. int ret;
  26982. ret = wc_MakeCert(cert, buf, buffSz, key, NULL, rng);
  26983. if (ret < 0)
  26984. return ret;
  26985. return wc_SignCert(cert->bodySz, cert->sigType,
  26986. buf, buffSz, key, NULL, rng);
  26987. }
  26988. #ifdef WOLFSSL_CERT_EXT
  26989. /* Get raw subject from cert, which may contain OIDs not parsed by Decode.
  26990. The raw subject pointer will only be valid while "cert" is valid. */
  26991. WOLFSSL_ABI
  26992. int wc_GetSubjectRaw(byte **subjectRaw, Cert *cert)
  26993. {
  26994. int rc = BAD_FUNC_ARG;
  26995. if ((subjectRaw != NULL) && (cert != NULL)) {
  26996. *subjectRaw = cert->sbjRaw;
  26997. rc = 0;
  26998. }
  26999. return rc;
  27000. }
  27001. /* Set KID from public key */
  27002. static int SetKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey,
  27003. ed25519_key* ed25519Key, ed448_key* ed448Key,
  27004. falcon_key* falconKey,
  27005. dilithium_key* dilithiumKey,
  27006. sphincs_key *sphincsKey, int kid_type)
  27007. {
  27008. byte *buf;
  27009. int bufferSz, ret;
  27010. if (cert == NULL ||
  27011. (rsakey == NULL && eckey == NULL && ed25519Key == NULL &&
  27012. ed448Key == NULL && falconKey == NULL && dilithiumKey == NULL &&
  27013. sphincsKey == NULL) ||
  27014. (kid_type != SKID_TYPE && kid_type != AKID_TYPE))
  27015. return BAD_FUNC_ARG;
  27016. buf = (byte *)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap,
  27017. DYNAMIC_TYPE_TMP_BUFFER);
  27018. if (buf == NULL)
  27019. return MEMORY_E;
  27020. /* Public Key */
  27021. bufferSz = -1;
  27022. #ifndef NO_RSA
  27023. /* RSA public key */
  27024. if (rsakey != NULL)
  27025. bufferSz = SetRsaPublicKey(buf, rsakey, MAX_PUBLIC_KEY_SZ, 0);
  27026. #endif
  27027. #ifdef HAVE_ECC
  27028. /* ECC public key */
  27029. if (eckey != NULL)
  27030. bufferSz = SetEccPublicKey(buf, eckey, MAX_PUBLIC_KEY_SZ, 0, 0);
  27031. #endif
  27032. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  27033. /* ED25519 public key */
  27034. if (ed25519Key != NULL) {
  27035. bufferSz = wc_Ed25519PublicKeyToDer(ed25519Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  27036. }
  27037. #endif
  27038. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  27039. /* ED448 public key */
  27040. if (ed448Key != NULL) {
  27041. bufferSz = wc_Ed448PublicKeyToDer(ed448Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  27042. }
  27043. #endif
  27044. #if defined(HAVE_PQC)
  27045. #if defined(HAVE_FALCON)
  27046. if (falconKey != NULL) {
  27047. bufferSz = wc_Falcon_PublicKeyToDer(falconKey, buf, MAX_PUBLIC_KEY_SZ,
  27048. 0);
  27049. }
  27050. #endif
  27051. #if defined(HAVE_DILITHIUM)
  27052. if (dilithiumKey != NULL) {
  27053. bufferSz = wc_Dilithium_PublicKeyToDer(dilithiumKey, buf,
  27054. MAX_PUBLIC_KEY_SZ, 0);
  27055. }
  27056. #endif
  27057. #if defined(HAVE_SPHINCS)
  27058. if (sphincsKey != NULL) {
  27059. bufferSz = wc_Sphincs_PublicKeyToDer(sphincsKey, buf,
  27060. MAX_PUBLIC_KEY_SZ, 0);
  27061. }
  27062. #endif
  27063. #endif /* HAVE_PQC */
  27064. if (bufferSz <= 0) {
  27065. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27066. return PUBLIC_KEY_E;
  27067. }
  27068. /* Compute SKID by hashing public key */
  27069. if (kid_type == SKID_TYPE) {
  27070. ret = CalcHashId(buf, (word32)bufferSz, cert->skid);
  27071. cert->skidSz = KEYID_SIZE;
  27072. }
  27073. else if (kid_type == AKID_TYPE) {
  27074. ret = CalcHashId(buf, (word32)bufferSz, cert->akid);
  27075. cert->akidSz = KEYID_SIZE;
  27076. }
  27077. else
  27078. ret = BAD_FUNC_ARG;
  27079. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27080. return ret;
  27081. }
  27082. int wc_SetSubjectKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  27083. {
  27084. RsaKey* rsaKey = NULL;
  27085. ecc_key* eccKey = NULL;
  27086. ed25519_key* ed25519Key = NULL;
  27087. ed448_key* ed448Key = NULL;
  27088. falcon_key* falconKey = NULL;
  27089. dilithium_key* dilithiumKey = NULL;
  27090. sphincs_key* sphincsKey = NULL;
  27091. if (keyType == RSA_TYPE)
  27092. rsaKey = (RsaKey*)key;
  27093. else if (keyType == ECC_TYPE)
  27094. eccKey = (ecc_key*)key;
  27095. else if (keyType == ED25519_TYPE)
  27096. ed25519Key = (ed25519_key*)key;
  27097. else if (keyType == ED448_TYPE)
  27098. ed448Key = (ed448_key*)key;
  27099. else if (keyType == FALCON_LEVEL1_TYPE)
  27100. falconKey = (falcon_key*)key;
  27101. else if (keyType == FALCON_LEVEL5_TYPE)
  27102. falconKey = (falcon_key*)key;
  27103. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27104. dilithiumKey = (dilithium_key*)key;
  27105. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27106. dilithiumKey = (dilithium_key*)key;
  27107. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27108. dilithiumKey = (dilithium_key*)key;
  27109. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27110. sphincsKey = (sphincs_key*)key;
  27111. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27112. sphincsKey = (sphincs_key*)key;
  27113. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27114. sphincsKey = (sphincs_key*)key;
  27115. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27116. sphincsKey = (sphincs_key*)key;
  27117. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27118. sphincsKey = (sphincs_key*)key;
  27119. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27120. sphincsKey = (sphincs_key*)key;
  27121. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  27122. falconKey, dilithiumKey, sphincsKey,
  27123. SKID_TYPE);
  27124. }
  27125. /* Set SKID from RSA or ECC public key */
  27126. int wc_SetSubjectKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  27127. {
  27128. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
  27129. NULL, SKID_TYPE);
  27130. }
  27131. int wc_SetAuthKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  27132. {
  27133. RsaKey* rsaKey = NULL;
  27134. ecc_key* eccKey = NULL;
  27135. ed25519_key* ed25519Key = NULL;
  27136. ed448_key* ed448Key = NULL;
  27137. falcon_key* falconKey = NULL;
  27138. dilithium_key* dilithiumKey = NULL;
  27139. sphincs_key* sphincsKey = NULL;
  27140. if (keyType == RSA_TYPE)
  27141. rsaKey = (RsaKey*)key;
  27142. else if (keyType == ECC_TYPE)
  27143. eccKey = (ecc_key*)key;
  27144. else if (keyType == ED25519_TYPE)
  27145. ed25519Key = (ed25519_key*)key;
  27146. else if (keyType == ED448_TYPE)
  27147. ed448Key = (ed448_key*)key;
  27148. else if (keyType == FALCON_LEVEL1_TYPE)
  27149. falconKey = (falcon_key*)key;
  27150. else if (keyType == FALCON_LEVEL5_TYPE)
  27151. falconKey = (falcon_key*)key;
  27152. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27153. dilithiumKey = (dilithium_key*)key;
  27154. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27155. dilithiumKey = (dilithium_key*)key;
  27156. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27157. dilithiumKey = (dilithium_key*)key;
  27158. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27159. sphincsKey = (sphincs_key*)key;
  27160. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27161. sphincsKey = (sphincs_key*)key;
  27162. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27163. sphincsKey = (sphincs_key*)key;
  27164. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27165. sphincsKey = (sphincs_key*)key;
  27166. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27167. sphincsKey = (sphincs_key*)key;
  27168. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27169. sphincsKey = (sphincs_key*)key;
  27170. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  27171. falconKey, dilithiumKey, sphincsKey,
  27172. AKID_TYPE);
  27173. }
  27174. /* Set SKID from RSA or ECC public key */
  27175. int wc_SetAuthKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  27176. {
  27177. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
  27178. NULL, AKID_TYPE);
  27179. }
  27180. #if !defined(NO_FILESYSTEM) && !defined(NO_ASN_CRYPT)
  27181. /* Set SKID from public key file in PEM */
  27182. int wc_SetSubjectKeyId(Cert *cert, const char* file)
  27183. {
  27184. int ret, derSz;
  27185. byte* der;
  27186. word32 idx;
  27187. RsaKey *rsakey = NULL;
  27188. ecc_key *eckey = NULL;
  27189. if (cert == NULL || file == NULL)
  27190. return BAD_FUNC_ARG;
  27191. der = (byte*)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap, DYNAMIC_TYPE_CERT);
  27192. if (der == NULL) {
  27193. WOLFSSL_MSG("wc_SetSubjectKeyId memory Problem");
  27194. return MEMORY_E;
  27195. }
  27196. derSz = MAX_PUBLIC_KEY_SZ;
  27197. XMEMSET(der, 0, (size_t)derSz);
  27198. derSz = wc_PemPubKeyToDer(file, der, derSz);
  27199. if (derSz <= 0) {
  27200. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27201. return derSz;
  27202. }
  27203. /* Load PubKey in internal structure */
  27204. #ifndef NO_RSA
  27205. rsakey = (RsaKey*) XMALLOC(sizeof(RsaKey), cert->heap, DYNAMIC_TYPE_RSA);
  27206. if (rsakey == NULL) {
  27207. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27208. return MEMORY_E;
  27209. }
  27210. if (wc_InitRsaKey(rsakey, cert->heap) != 0) {
  27211. WOLFSSL_MSG("wc_InitRsaKey failure");
  27212. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27213. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27214. return MEMORY_E;
  27215. }
  27216. idx = 0;
  27217. ret = wc_RsaPublicKeyDecode(der, &idx, rsakey, (word32)derSz);
  27218. if (ret != 0)
  27219. #endif
  27220. {
  27221. #ifndef NO_RSA
  27222. WOLFSSL_MSG("wc_RsaPublicKeyDecode failed");
  27223. wc_FreeRsaKey(rsakey);
  27224. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27225. rsakey = NULL;
  27226. #endif
  27227. #ifdef HAVE_ECC
  27228. /* Check to load ecc public key */
  27229. eckey = (ecc_key*) XMALLOC(sizeof(ecc_key), cert->heap,
  27230. DYNAMIC_TYPE_ECC);
  27231. if (eckey == NULL) {
  27232. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27233. return MEMORY_E;
  27234. }
  27235. if (wc_ecc_init(eckey) != 0) {
  27236. WOLFSSL_MSG("wc_ecc_init failure");
  27237. wc_ecc_free(eckey);
  27238. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27239. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27240. return MEMORY_E;
  27241. }
  27242. idx = 0;
  27243. ret = wc_EccPublicKeyDecode(der, &idx, eckey, (word32)derSz);
  27244. if (ret != 0) {
  27245. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  27246. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27247. wc_ecc_free(eckey);
  27248. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27249. return PUBLIC_KEY_E;
  27250. }
  27251. #else
  27252. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27253. return PUBLIC_KEY_E;
  27254. #endif /* HAVE_ECC */
  27255. }
  27256. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27257. ret = wc_SetSubjectKeyIdFromPublicKey(cert, rsakey, eckey);
  27258. #ifndef NO_RSA
  27259. wc_FreeRsaKey(rsakey);
  27260. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27261. #endif
  27262. #ifdef HAVE_ECC
  27263. wc_ecc_free(eckey);
  27264. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27265. #endif
  27266. return ret;
  27267. }
  27268. #endif /* !NO_FILESYSTEM && !NO_ASN_CRYPT */
  27269. static int SetAuthKeyIdFromDcert(Cert* cert, DecodedCert* decoded)
  27270. {
  27271. int ret = 0;
  27272. /* Subject Key Id not found !! */
  27273. if (decoded->extSubjKeyIdSet == 0) {
  27274. ret = ASN_NO_SKID;
  27275. }
  27276. /* SKID invalid size */
  27277. else if (sizeof(cert->akid) < sizeof(decoded->extSubjKeyId)) {
  27278. ret = MEMORY_E;
  27279. }
  27280. else {
  27281. /* Put the SKID of CA to AKID of certificate */
  27282. XMEMCPY(cert->akid, decoded->extSubjKeyId, KEYID_SIZE);
  27283. cert->akidSz = KEYID_SIZE;
  27284. }
  27285. return ret;
  27286. }
  27287. /* Set AKID from certificate contains in buffer (DER encoded) */
  27288. int wc_SetAuthKeyIdFromCert(Cert *cert, const byte *der, int derSz)
  27289. {
  27290. int ret = 0;
  27291. if (cert == NULL) {
  27292. ret = BAD_FUNC_ARG;
  27293. }
  27294. else {
  27295. /* Check if decodedCert is cached */
  27296. if (cert->der != der) {
  27297. /* Allocate cache for the decoded cert */
  27298. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27299. }
  27300. if (ret >= 0) {
  27301. ret = SetAuthKeyIdFromDcert(cert, (DecodedCert*)cert->decodedCert);
  27302. #ifndef WOLFSSL_CERT_GEN_CACHE
  27303. wc_SetCert_Free(cert);
  27304. #endif
  27305. }
  27306. }
  27307. return ret;
  27308. }
  27309. #ifndef NO_FILESYSTEM
  27310. /* Set AKID from certificate file in PEM */
  27311. int wc_SetAuthKeyId(Cert *cert, const char* file)
  27312. {
  27313. int ret;
  27314. DerBuffer* der = NULL;
  27315. if (cert == NULL || file == NULL)
  27316. return BAD_FUNC_ARG;
  27317. ret = wc_PemCertToDer_ex(file, &der);
  27318. if (ret == 0)
  27319. {
  27320. ret = wc_SetAuthKeyIdFromCert(cert, der->buffer, (int)der->length);
  27321. FreeDer(&der);
  27322. }
  27323. return ret;
  27324. }
  27325. #endif /* !NO_FILESYSTEM */
  27326. /* Set KeyUsage from human readable string */
  27327. int wc_SetKeyUsage(Cert *cert, const char *value)
  27328. {
  27329. int ret = 0;
  27330. char *token, *str, *ptr;
  27331. word32 len;
  27332. if (cert == NULL || value == NULL)
  27333. return BAD_FUNC_ARG;
  27334. cert->keyUsage = 0;
  27335. /* duplicate string (including terminator) */
  27336. len = (word32)XSTRLEN(value);
  27337. str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27338. if (str == NULL)
  27339. return MEMORY_E;
  27340. XMEMCPY(str, value, len+1);
  27341. /* parse value, and set corresponding Key Usage value */
  27342. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  27343. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27344. return KEYUSAGE_E;
  27345. }
  27346. while (token != NULL)
  27347. {
  27348. if (!XSTRCASECMP(token, "digitalSignature"))
  27349. cert->keyUsage |= KEYUSE_DIGITAL_SIG;
  27350. else if (!XSTRCASECMP(token, "nonRepudiation") ||
  27351. !XSTRCASECMP(token, "contentCommitment"))
  27352. cert->keyUsage |= KEYUSE_CONTENT_COMMIT;
  27353. else if (!XSTRCASECMP(token, "keyEncipherment"))
  27354. cert->keyUsage |= KEYUSE_KEY_ENCIPHER;
  27355. else if (!XSTRCASECMP(token, "dataEncipherment"))
  27356. cert->keyUsage |= KEYUSE_DATA_ENCIPHER;
  27357. else if (!XSTRCASECMP(token, "keyAgreement"))
  27358. cert->keyUsage |= KEYUSE_KEY_AGREE;
  27359. else if (!XSTRCASECMP(token, "keyCertSign"))
  27360. cert->keyUsage |= KEYUSE_KEY_CERT_SIGN;
  27361. else if (!XSTRCASECMP(token, "cRLSign"))
  27362. cert->keyUsage |= KEYUSE_CRL_SIGN;
  27363. else if (!XSTRCASECMP(token, "encipherOnly"))
  27364. cert->keyUsage |= KEYUSE_ENCIPHER_ONLY;
  27365. else if (!XSTRCASECMP(token, "decipherOnly"))
  27366. cert->keyUsage |= KEYUSE_DECIPHER_ONLY;
  27367. else {
  27368. ret = KEYUSAGE_E;
  27369. break;
  27370. }
  27371. token = XSTRTOK(NULL, ",", &ptr);
  27372. }
  27373. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27374. return ret;
  27375. }
  27376. /* Set ExtendedKeyUsage from human readable string */
  27377. int wc_SetExtKeyUsage(Cert *cert, const char *value)
  27378. {
  27379. int ret = 0;
  27380. char *token, *str, *ptr;
  27381. word32 len;
  27382. if (cert == NULL || value == NULL)
  27383. return BAD_FUNC_ARG;
  27384. cert->extKeyUsage = 0;
  27385. /* duplicate string (including terminator) */
  27386. len = (word32)XSTRLEN(value);
  27387. str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27388. if (str == NULL)
  27389. return MEMORY_E;
  27390. XMEMCPY(str, value, len+1);
  27391. /* parse value, and set corresponding Key Usage value */
  27392. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  27393. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27394. return EXTKEYUSAGE_E;
  27395. }
  27396. while (token != NULL)
  27397. {
  27398. if (!XSTRCASECMP(token, "any"))
  27399. cert->extKeyUsage |= EXTKEYUSE_ANY;
  27400. else if (!XSTRCASECMP(token, "serverAuth"))
  27401. cert->extKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  27402. else if (!XSTRCASECMP(token, "clientAuth"))
  27403. cert->extKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  27404. else if (!XSTRCASECMP(token, "codeSigning"))
  27405. cert->extKeyUsage |= EXTKEYUSE_CODESIGN;
  27406. else if (!XSTRCASECMP(token, "emailProtection"))
  27407. cert->extKeyUsage |= EXTKEYUSE_EMAILPROT;
  27408. else if (!XSTRCASECMP(token, "timeStamping"))
  27409. cert->extKeyUsage |= EXTKEYUSE_TIMESTAMP;
  27410. else if (!XSTRCASECMP(token, "OCSPSigning"))
  27411. cert->extKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  27412. else {
  27413. ret = EXTKEYUSAGE_E;
  27414. break;
  27415. }
  27416. token = XSTRTOK(NULL, ",", &ptr);
  27417. }
  27418. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27419. return ret;
  27420. }
  27421. #ifdef WOLFSSL_EKU_OID
  27422. /*
  27423. * cert structure to set EKU oid in
  27424. * oid the oid in byte representation
  27425. * sz size of oid buffer
  27426. * idx index of array to place oid
  27427. *
  27428. * returns 0 on success
  27429. */
  27430. int wc_SetExtKeyUsageOID(Cert *cert, const char *in, word32 sz, byte idx,
  27431. void* heap)
  27432. {
  27433. byte oid[MAX_OID_SZ];
  27434. word32 oidSz = MAX_OID_SZ;
  27435. if (idx >= CTC_MAX_EKU_NB || sz >= CTC_MAX_EKU_OID_SZ) {
  27436. WOLFSSL_MSG("Either idx or sz was too large");
  27437. return BAD_FUNC_ARG;
  27438. }
  27439. if (EncodePolicyOID(oid, &oidSz, in, heap) != 0) {
  27440. return BUFFER_E;
  27441. }
  27442. XMEMCPY(cert->extKeyUsageOID[idx], oid, oidSz);
  27443. cert->extKeyUsageOIDSz[idx] = oidSz;
  27444. cert->extKeyUsage |= EXTKEYUSE_USER;
  27445. return 0;
  27446. }
  27447. #endif /* WOLFSSL_EKU_OID */
  27448. #if defined(WOLFSSL_ASN_TEMPLATE) && defined(WOLFSSL_CERT_GEN) && \
  27449. defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_ENCODING) && \
  27450. defined(WOLFSSL_CERT_EXT)
  27451. int wc_SetCustomExtension(Cert *cert, int critical, const char *oid,
  27452. const byte *der, word32 derSz) {
  27453. CertExtension *ext;
  27454. byte encodedOid[MAX_OID_SZ];
  27455. word32 encodedOidSz = MAX_OID_SZ;
  27456. int ret;
  27457. if (cert == NULL || oid == NULL || der == NULL || derSz == 0) {
  27458. return BAD_FUNC_ARG;
  27459. }
  27460. if (cert->customCertExtCount >= NUM_CUSTOM_EXT) {
  27461. return MEMORY_E;
  27462. }
  27463. /* Make sure we can properly parse the OID. */
  27464. ret = EncodePolicyOID(encodedOid, &encodedOidSz, oid, NULL);
  27465. if (ret != 0) {
  27466. return ret;
  27467. }
  27468. ext = &cert->customCertExt[cert->customCertExtCount];
  27469. ext->oid = oid;
  27470. ext->crit = (critical == 0) ? 0 : 1;
  27471. ext->val = der;
  27472. ext->valSz = derSz;
  27473. cert->customCertExtCount++;
  27474. return 0;
  27475. }
  27476. #endif
  27477. #endif /* WOLFSSL_CERT_EXT */
  27478. #ifdef WOLFSSL_ALT_NAMES
  27479. static int SetAltNamesFromDcert(Cert* cert, DecodedCert* decoded)
  27480. {
  27481. int ret = 0;
  27482. cert->altNamesSz = 0;
  27483. if (decoded->altNames) {
  27484. ret = FlattenAltNames(cert->altNames,
  27485. sizeof(cert->altNames), decoded->altNames);
  27486. if (ret >= 0) {
  27487. cert->altNamesSz = ret;
  27488. ret = 0;
  27489. }
  27490. }
  27491. return ret;
  27492. }
  27493. #ifndef NO_FILESYSTEM
  27494. /* Set Alt Names from der cert, return 0 on success */
  27495. static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz,
  27496. int devId)
  27497. {
  27498. int ret;
  27499. #ifdef WOLFSSL_SMALL_STACK
  27500. DecodedCert* decoded;
  27501. #else
  27502. DecodedCert decoded[1];
  27503. #endif
  27504. if (derSz < 0)
  27505. return derSz;
  27506. #ifdef WOLFSSL_SMALL_STACK
  27507. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), cert->heap,
  27508. DYNAMIC_TYPE_TMP_BUFFER);
  27509. if (decoded == NULL)
  27510. return MEMORY_E;
  27511. #endif
  27512. InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
  27513. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  27514. if (ret < 0) {
  27515. WOLFSSL_MSG("ParseCertRelative error");
  27516. }
  27517. else {
  27518. ret = SetAltNamesFromDcert(cert, decoded);
  27519. }
  27520. FreeDecodedCert(decoded);
  27521. #ifdef WOLFSSL_SMALL_STACK
  27522. XFREE(decoded, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27523. #endif
  27524. return ret < 0 ? ret : 0;
  27525. }
  27526. #endif
  27527. static int SetDatesFromDcert(Cert* cert, DecodedCert* decoded)
  27528. {
  27529. int ret = 0;
  27530. if (decoded->beforeDate == NULL || decoded->afterDate == NULL) {
  27531. WOLFSSL_MSG("Couldn't extract dates");
  27532. ret = -1;
  27533. }
  27534. else if (decoded->beforeDateLen > MAX_DATE_SIZE ||
  27535. decoded->afterDateLen > MAX_DATE_SIZE) {
  27536. WOLFSSL_MSG("Bad date size");
  27537. ret = -1;
  27538. }
  27539. else {
  27540. XMEMCPY(cert->beforeDate, decoded->beforeDate,
  27541. (size_t)decoded->beforeDateLen);
  27542. XMEMCPY(cert->afterDate, decoded->afterDate,
  27543. (size_t)decoded->afterDateLen);
  27544. cert->beforeDateSz = decoded->beforeDateLen;
  27545. cert->afterDateSz = decoded->afterDateLen;
  27546. }
  27547. return ret;
  27548. }
  27549. #endif /* WOLFSSL_ALT_NAMES */
  27550. static void SetNameFromDcert(CertName* cn, DecodedCert* decoded)
  27551. {
  27552. int sz;
  27553. if (decoded->subjectCN) {
  27554. sz = (decoded->subjectCNLen < CTC_NAME_SIZE) ? decoded->subjectCNLen
  27555. : CTC_NAME_SIZE - 1;
  27556. XSTRNCPY(cn->commonName, decoded->subjectCN, (size_t)sz);
  27557. cn->commonName[sz] = '\0';
  27558. cn->commonNameEnc = decoded->subjectCNEnc;
  27559. }
  27560. if (decoded->subjectC) {
  27561. sz = (decoded->subjectCLen < CTC_NAME_SIZE) ? decoded->subjectCLen
  27562. : CTC_NAME_SIZE - 1;
  27563. XSTRNCPY(cn->country, decoded->subjectC, (size_t)sz);
  27564. cn->country[sz] = '\0';
  27565. cn->countryEnc = decoded->subjectCEnc;
  27566. }
  27567. if (decoded->subjectST) {
  27568. sz = (decoded->subjectSTLen < CTC_NAME_SIZE) ? decoded->subjectSTLen
  27569. : CTC_NAME_SIZE - 1;
  27570. XSTRNCPY(cn->state, decoded->subjectST, (size_t)sz);
  27571. cn->state[sz] = '\0';
  27572. cn->stateEnc = decoded->subjectSTEnc;
  27573. }
  27574. if (decoded->subjectL) {
  27575. sz = (decoded->subjectLLen < CTC_NAME_SIZE) ? decoded->subjectLLen
  27576. : CTC_NAME_SIZE - 1;
  27577. XSTRNCPY(cn->locality, decoded->subjectL, (size_t)sz);
  27578. cn->locality[sz] = '\0';
  27579. cn->localityEnc = decoded->subjectLEnc;
  27580. }
  27581. if (decoded->subjectO) {
  27582. sz = (decoded->subjectOLen < CTC_NAME_SIZE) ? decoded->subjectOLen
  27583. : CTC_NAME_SIZE - 1;
  27584. XSTRNCPY(cn->org, decoded->subjectO, (size_t)sz);
  27585. cn->org[sz] = '\0';
  27586. cn->orgEnc = decoded->subjectOEnc;
  27587. }
  27588. if (decoded->subjectOU) {
  27589. sz = (decoded->subjectOULen < CTC_NAME_SIZE) ? decoded->subjectOULen
  27590. : CTC_NAME_SIZE - 1;
  27591. XSTRNCPY(cn->unit, decoded->subjectOU, (size_t)sz);
  27592. cn->unit[sz] = '\0';
  27593. cn->unitEnc = decoded->subjectOUEnc;
  27594. }
  27595. if (decoded->subjectSN) {
  27596. sz = (decoded->subjectSNLen < CTC_NAME_SIZE) ? decoded->subjectSNLen
  27597. : CTC_NAME_SIZE - 1;
  27598. XSTRNCPY(cn->sur, decoded->subjectSN, (size_t)sz);
  27599. cn->sur[sz] = '\0';
  27600. cn->surEnc = decoded->subjectSNEnc;
  27601. }
  27602. if (decoded->subjectSND) {
  27603. sz = (decoded->subjectSNDLen < CTC_NAME_SIZE) ? decoded->subjectSNDLen
  27604. : CTC_NAME_SIZE - 1;
  27605. XSTRNCPY(cn->serialDev, decoded->subjectSND, (size_t)sz);
  27606. cn->serialDev[sz] = '\0';
  27607. cn->serialDevEnc = decoded->subjectSNDEnc;
  27608. }
  27609. if (decoded->subjectUID) {
  27610. sz = (decoded->subjectUIDLen < CTC_NAME_SIZE) ? decoded->subjectUIDLen
  27611. : CTC_NAME_SIZE - 1;
  27612. XSTRNCPY(cn->userId, decoded->subjectUID, (size_t)sz);
  27613. cn->userId[sz] = '\0';
  27614. cn->userIdEnc = decoded->subjectUIDEnc;
  27615. }
  27616. #ifdef WOLFSSL_CERT_EXT
  27617. if (decoded->subjectBC) {
  27618. sz = (decoded->subjectBCLen < CTC_NAME_SIZE) ? decoded->subjectBCLen
  27619. : CTC_NAME_SIZE - 1;
  27620. XSTRNCPY(cn->busCat, decoded->subjectBC, (size_t)sz);
  27621. cn->busCat[sz] = '\0';
  27622. cn->busCatEnc = decoded->subjectBCEnc;
  27623. }
  27624. if (decoded->subjectJC) {
  27625. sz = (decoded->subjectJCLen < CTC_NAME_SIZE) ? decoded->subjectJCLen
  27626. : CTC_NAME_SIZE - 1;
  27627. XSTRNCPY(cn->joiC, decoded->subjectJC, (size_t)sz);
  27628. cn->joiC[sz] = '\0';
  27629. cn->joiCEnc = decoded->subjectJCEnc;
  27630. }
  27631. if (decoded->subjectJS) {
  27632. sz = (decoded->subjectJSLen < CTC_NAME_SIZE) ? decoded->subjectJSLen
  27633. : CTC_NAME_SIZE - 1;
  27634. XSTRNCPY(cn->joiSt, decoded->subjectJS, (size_t)sz);
  27635. cn->joiSt[sz] = '\0';
  27636. cn->joiStEnc = decoded->subjectJSEnc;
  27637. }
  27638. #endif
  27639. if (decoded->subjectEmail) {
  27640. sz = (decoded->subjectEmailLen < CTC_NAME_SIZE)
  27641. ? decoded->subjectEmailLen : CTC_NAME_SIZE - 1;
  27642. XSTRNCPY(cn->email, decoded->subjectEmail, (size_t)sz);
  27643. cn->email[sz] = '\0';
  27644. }
  27645. #if defined(WOLFSSL_CERT_NAME_ALL) && \
  27646. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
  27647. if (decoded->subjectN) {
  27648. sz = (decoded->subjectNLen < CTC_NAME_SIZE) ? decoded->subjectNLen
  27649. : CTC_NAME_SIZE - 1;
  27650. XSTRNCPY(cn->dnName, decoded->subjectN, (size_t)sz);
  27651. cn->dnName[sz] = '\0';
  27652. cn->dnNameEnc = decoded->subjectNEnc;
  27653. }
  27654. if (decoded->subjectI) {
  27655. sz = (decoded->subjectILen < CTC_NAME_SIZE) ? decoded->subjectILen
  27656. : CTC_NAME_SIZE - 1;
  27657. XSTRNCPY(cn->initials, decoded->subjectI, (size_t)sz);
  27658. cn->initials[sz] = '\0';
  27659. cn->initialsEnc = decoded->subjectIEnc;
  27660. }
  27661. if (decoded->subjectGN) {
  27662. sz = (decoded->subjectGNLen < CTC_NAME_SIZE) ? decoded->subjectGNLen
  27663. : CTC_NAME_SIZE - 1;
  27664. XSTRNCPY(cn->givenName, decoded->subjectGN, (size_t)sz);
  27665. cn->givenName[sz] = '\0';
  27666. cn->givenNameEnc = decoded->subjectGNEnc;
  27667. }
  27668. if (decoded->subjectDNQ) {
  27669. sz = (decoded->subjectDNQLen < CTC_NAME_SIZE) ? decoded->subjectDNQLen
  27670. : CTC_NAME_SIZE - 1;
  27671. XSTRNCPY(cn->dnQualifier, decoded->subjectDNQ, (size_t)sz);
  27672. cn->dnQualifier[sz] = '\0';
  27673. cn->dnQualifierEnc = decoded->subjectDNQEnc;
  27674. }
  27675. #endif /* WOLFSSL_CERT_NAME_ALL */
  27676. }
  27677. #ifndef NO_FILESYSTEM
  27678. /* Set cn name from der buffer, return 0 on success */
  27679. static int SetNameFromCert(CertName* cn, const byte* der, int derSz, int devId)
  27680. {
  27681. int ret;
  27682. #ifdef WOLFSSL_SMALL_STACK
  27683. DecodedCert* decoded;
  27684. #else
  27685. DecodedCert decoded[1];
  27686. #endif
  27687. if (derSz < 0)
  27688. return derSz;
  27689. #ifdef WOLFSSL_SMALL_STACK
  27690. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  27691. DYNAMIC_TYPE_TMP_BUFFER);
  27692. if (decoded == NULL)
  27693. return MEMORY_E;
  27694. #endif
  27695. InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
  27696. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  27697. if (ret < 0) {
  27698. WOLFSSL_MSG("ParseCertRelative error");
  27699. }
  27700. else {
  27701. SetNameFromDcert(cn, decoded);
  27702. }
  27703. FreeDecodedCert(decoded);
  27704. #ifdef WOLFSSL_SMALL_STACK
  27705. XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  27706. #endif
  27707. return ret < 0 ? ret : 0;
  27708. }
  27709. /* Set cert issuer from issuerFile in PEM */
  27710. WOLFSSL_ABI
  27711. int wc_SetIssuer(Cert* cert, const char* issuerFile)
  27712. {
  27713. int ret;
  27714. DerBuffer* der = NULL;
  27715. if (cert == NULL || issuerFile == NULL)
  27716. return BAD_FUNC_ARG;
  27717. ret = wc_PemCertToDer_ex(issuerFile, &der);
  27718. if (ret == 0) {
  27719. cert->selfSigned = 0;
  27720. ret = SetNameFromCert(&cert->issuer, der->buffer, (int)der->length,
  27721. INVALID_DEVID);
  27722. FreeDer(&der);
  27723. }
  27724. return ret;
  27725. }
  27726. /* Set cert subject from subjectFile in PEM */
  27727. WOLFSSL_ABI
  27728. int wc_SetSubject(Cert* cert, const char* subjectFile)
  27729. {
  27730. int ret;
  27731. DerBuffer* der = NULL;
  27732. if (cert == NULL || subjectFile == NULL)
  27733. return BAD_FUNC_ARG;
  27734. ret = wc_PemCertToDer_ex(subjectFile, &der);
  27735. if (ret == 0) {
  27736. ret = SetNameFromCert(&cert->subject, der->buffer, (int)der->length,
  27737. INVALID_DEVID);
  27738. FreeDer(&der);
  27739. }
  27740. return ret;
  27741. }
  27742. #ifdef WOLFSSL_ALT_NAMES
  27743. /* Set alt names from file in PEM */
  27744. WOLFSSL_ABI
  27745. int wc_SetAltNames(Cert* cert, const char* file)
  27746. {
  27747. int ret;
  27748. DerBuffer* der = NULL;
  27749. if (cert == NULL) {
  27750. return BAD_FUNC_ARG;
  27751. }
  27752. ret = wc_PemCertToDer_ex(file, &der);
  27753. if (ret == 0) {
  27754. ret = SetAltNamesFromCert(cert, der->buffer, (int)der->length,
  27755. INVALID_DEVID);
  27756. FreeDer(&der);
  27757. }
  27758. return ret;
  27759. }
  27760. #endif /* WOLFSSL_ALT_NAMES */
  27761. #endif /* !NO_FILESYSTEM */
  27762. /* Set cert issuer from DER buffer */
  27763. WOLFSSL_ABI
  27764. int wc_SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
  27765. {
  27766. int ret = 0;
  27767. if (cert == NULL) {
  27768. ret = BAD_FUNC_ARG;
  27769. }
  27770. else {
  27771. cert->selfSigned = 0;
  27772. /* Check if decodedCert is cached */
  27773. if (cert->der != der) {
  27774. /* Allocate cache for the decoded cert */
  27775. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27776. }
  27777. if (ret >= 0) {
  27778. SetNameFromDcert(&cert->issuer, (DecodedCert*)cert->decodedCert);
  27779. #ifndef WOLFSSL_CERT_GEN_CACHE
  27780. wc_SetCert_Free(cert);
  27781. #endif
  27782. }
  27783. }
  27784. return ret;
  27785. }
  27786. /* Set cert subject from DER buffer */
  27787. WOLFSSL_ABI
  27788. int wc_SetSubjectBuffer(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. /* Check if decodedCert is cached */
  27796. if (cert->der != der) {
  27797. /* Allocate cache for the decoded cert */
  27798. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27799. }
  27800. if (ret >= 0) {
  27801. SetNameFromDcert(&cert->subject, (DecodedCert*)cert->decodedCert);
  27802. #ifndef WOLFSSL_CERT_GEN_CACHE
  27803. wc_SetCert_Free(cert);
  27804. #endif
  27805. }
  27806. }
  27807. return ret;
  27808. }
  27809. #ifdef WOLFSSL_CERT_EXT
  27810. /* Set cert raw subject from DER buffer */
  27811. WOLFSSL_ABI
  27812. int wc_SetSubjectRaw(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, (word32)derSz, INVALID_DEVID);
  27823. }
  27824. if (ret >= 0) {
  27825. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  27826. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  27827. (int)sizeof(CertName))) {
  27828. XMEMCPY(cert->sbjRaw,
  27829. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  27830. (size_t)((DecodedCert*)cert->decodedCert)->
  27831. subjectRawLen);
  27832. }
  27833. #ifndef WOLFSSL_CERT_GEN_CACHE
  27834. wc_SetCert_Free(cert);
  27835. #endif
  27836. }
  27837. }
  27838. return ret;
  27839. }
  27840. /* Set cert raw issuer from DER buffer */
  27841. WOLFSSL_ABI
  27842. int wc_SetIssuerRaw(Cert* cert, const byte* der, int derSz)
  27843. {
  27844. int ret = 0;
  27845. if (cert == NULL) {
  27846. ret = BAD_FUNC_ARG;
  27847. }
  27848. else {
  27849. /* Check if decodedCert is cached */
  27850. if (cert->der != der) {
  27851. /* Allocate cache for the decoded cert */
  27852. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27853. }
  27854. if (ret >= 0) {
  27855. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  27856. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  27857. (int)sizeof(CertName))) {
  27858. /* Copy the subject to the issuer field */
  27859. XMEMCPY(cert->issRaw,
  27860. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  27861. (size_t)((DecodedCert*)cert->decodedCert)->
  27862. subjectRawLen);
  27863. }
  27864. #ifndef WOLFSSL_CERT_GEN_CACHE
  27865. wc_SetCert_Free(cert);
  27866. #endif
  27867. }
  27868. }
  27869. return ret;
  27870. }
  27871. #endif
  27872. #ifdef WOLFSSL_ALT_NAMES
  27873. /* Set cert alt names from DER buffer */
  27874. WOLFSSL_ABI
  27875. int wc_SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
  27876. {
  27877. int ret = 0;
  27878. if (cert == NULL) {
  27879. ret = BAD_FUNC_ARG;
  27880. }
  27881. else {
  27882. /* Check if decodedCert is cached */
  27883. if (cert->der != der) {
  27884. /* Allocate cache for the decoded cert */
  27885. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27886. }
  27887. if (ret >= 0) {
  27888. ret = SetAltNamesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  27889. #ifndef WOLFSSL_CERT_GEN_CACHE
  27890. wc_SetCert_Free(cert);
  27891. #endif
  27892. }
  27893. }
  27894. return(ret);
  27895. }
  27896. /* Set cert dates from DER buffer */
  27897. WOLFSSL_ABI
  27898. int wc_SetDatesBuffer(Cert* cert, const byte* der, int derSz)
  27899. {
  27900. int ret = 0;
  27901. if (cert == NULL) {
  27902. ret = BAD_FUNC_ARG;
  27903. }
  27904. else {
  27905. /* Check if decodedCert is cached */
  27906. if (cert->der != der) {
  27907. /* Allocate cache for the decoded cert */
  27908. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27909. }
  27910. if (ret >= 0) {
  27911. ret = SetDatesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  27912. #ifndef WOLFSSL_CERT_GEN_CACHE
  27913. wc_SetCert_Free(cert);
  27914. #endif
  27915. }
  27916. }
  27917. return(ret);
  27918. }
  27919. #endif /* WOLFSSL_ALT_NAMES */
  27920. #endif /* WOLFSSL_CERT_GEN */
  27921. #if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) \
  27922. || defined(OPENSSL_EXTRA)
  27923. /* Encode OID string representation to ITU-T X.690 format */
  27924. int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap)
  27925. {
  27926. word32 idx = 0, nb_val;
  27927. char *token, *str, *ptr;
  27928. word32 len;
  27929. (void)heap;
  27930. if (out == NULL || outSz == NULL || *outSz < 2 || in == NULL)
  27931. return BAD_FUNC_ARG;
  27932. /* duplicate string (including terminator) */
  27933. len = (word32)XSTRLEN(in);
  27934. str = (char *)XMALLOC(len+1, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27935. if (str == NULL)
  27936. return MEMORY_E;
  27937. XMEMCPY(str, in, len+1);
  27938. nb_val = 0;
  27939. /* parse value, and set corresponding Policy OID value */
  27940. token = XSTRTOK(str, ".", &ptr);
  27941. while (token != NULL)
  27942. {
  27943. word32 val = (word32)XATOI(token);
  27944. if (nb_val == 0) {
  27945. if (val > 2) {
  27946. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27947. return ASN_OBJECT_ID_E;
  27948. }
  27949. out[idx] = (byte)(40 * val);
  27950. }
  27951. else if (nb_val == 1) {
  27952. if (val > 127) {
  27953. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27954. return ASN_OBJECT_ID_E;
  27955. }
  27956. if (idx > *outSz) {
  27957. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27958. return BUFFER_E;
  27959. }
  27960. out[idx++] += (byte)val;
  27961. }
  27962. else {
  27963. word32 tb = 0;
  27964. int i = 0;
  27965. byte oid[MAX_OID_SZ];
  27966. while (val >= 128) {
  27967. word32 x = val % 128;
  27968. val /= 128;
  27969. oid[i++] = (byte) (((tb++) ? 0x80 : 0) | x);
  27970. }
  27971. if ((idx+(word32)i) >= *outSz) {
  27972. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27973. return BUFFER_E;
  27974. }
  27975. oid[i] = (byte) (((tb++) ? 0x80 : 0) | val);
  27976. /* push value in the right order */
  27977. while (i >= 0)
  27978. out[idx++] = oid[i--];
  27979. }
  27980. token = XSTRTOK(NULL, ".", &ptr);
  27981. nb_val++;
  27982. }
  27983. *outSz = idx;
  27984. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27985. return 0;
  27986. }
  27987. #endif /* WOLFSSL_CERT_EXT || OPENSSL_EXTRA */
  27988. #endif /* !NO_CERTS */
  27989. #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
  27990. /* Helper function for wolfSSL_i2d_DHparams */
  27991. int StoreDHparams(byte* out, word32* outLen, mp_int* p, mp_int* g)
  27992. {
  27993. #ifndef WOLFSSL_ASN_TEMPLATE
  27994. word32 idx = 0;
  27995. word32 total;
  27996. WOLFSSL_ENTER("StoreDHparams");
  27997. if (out == NULL) {
  27998. WOLFSSL_MSG("Null buffer error");
  27999. return BUFFER_E;
  28000. }
  28001. /* determine size */
  28002. /* integer - g */
  28003. idx = SetASNIntMP(g, -1, NULL);
  28004. /* integer - p */
  28005. idx += SetASNIntMP(p, -1, NULL);
  28006. total = idx;
  28007. /* sequence */
  28008. idx += SetSequence(idx, NULL);
  28009. /* make sure output fits in buffer */
  28010. if (idx > *outLen) {
  28011. return BUFFER_E;
  28012. }
  28013. /* write DH parameters */
  28014. /* sequence - for P and G only */
  28015. idx = SetSequence(total, out);
  28016. /* integer - p */
  28017. idx += SetASNIntMP(p, -1, out + idx);
  28018. /* integer - g */
  28019. idx += SetASNIntMP(g, -1, out + idx);
  28020. *outLen = idx;
  28021. return 0;
  28022. #else
  28023. ASNSetData dataASN[dhParamASN_Length];
  28024. int ret = 0;
  28025. int sz = 0;
  28026. WOLFSSL_ENTER("StoreDHparams");
  28027. if (out == NULL) {
  28028. ret = BUFFER_E;
  28029. }
  28030. if (ret == 0) {
  28031. XMEMSET(dataASN, 0, sizeof(dataASN));
  28032. /* Set mp_int containing p and g. */
  28033. SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], p);
  28034. SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], g);
  28035. /* privateValueLength not encoded. */
  28036. dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
  28037. /* Calculate the size of the DH parameters. */
  28038. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  28039. }
  28040. /* Check buffer is big enough for encoding. */
  28041. if ((ret == 0) && ((int)*outLen < sz)) {
  28042. ret = BUFFER_E;
  28043. }
  28044. if (ret == 0) {
  28045. /* Encode the DH parameters into buffer. */
  28046. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, out);
  28047. /* Set the actual encoding size. */
  28048. *outLen = sz;
  28049. }
  28050. return ret;
  28051. #endif /* WOLFSSL_ASN_TEMPLATE */
  28052. }
  28053. #endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
  28054. #if defined(HAVE_ECC) || !defined(NO_DSA)
  28055. #ifdef WOLFSSL_ASN_TEMPLATE
  28056. /* ASN.1 template for DSA signature.
  28057. * RFC 5912, 6 - DSA-Sig-Value
  28058. */
  28059. static const ASNItem dsaSigASN[] = {
  28060. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28061. /* r */
  28062. /* R */ { 1, ASN_INTEGER, 0, 0, 0 },
  28063. /* s */
  28064. /* S */ { 1, ASN_INTEGER, 0, 0, 0 },
  28065. };
  28066. enum {
  28067. DSASIGASN_IDX_SEQ = 0,
  28068. DSASIGASN_IDX_R,
  28069. DSASIGASN_IDX_S
  28070. };
  28071. #define dsaSigASN_Length (sizeof(dsaSigASN) / sizeof(ASNItem))
  28072. #endif
  28073. /* Der Encode r & s ints into out, outLen is (in/out) size */
  28074. int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
  28075. {
  28076. #ifndef WOLFSSL_ASN_TEMPLATE
  28077. word32 idx = 0;
  28078. int rSz; /* encoding size */
  28079. int sSz;
  28080. int headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  28081. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  28082. int rLeadingZero = mp_leading_bit(r);
  28083. int sLeadingZero = mp_leading_bit(s);
  28084. int rLen = mp_unsigned_bin_size(r); /* big int size */
  28085. int sLen = mp_unsigned_bin_size(s);
  28086. if (*outLen < (word32)((rLen + rLeadingZero + sLen + sLeadingZero +
  28087. headerSz + 2))) /* SEQ_TAG + LEN(ENUM) */
  28088. return BUFFER_E;
  28089. idx = SetSequence((word32)(rLen + rLeadingZero + sLen + sLeadingZero +
  28090. headerSz), out);
  28091. /* store r */
  28092. rSz = SetASNIntMP(r, (int)(*outLen - idx), &out[idx]);
  28093. if (rSz < 0)
  28094. return rSz;
  28095. idx += (word32)rSz;
  28096. /* store s */
  28097. sSz = SetASNIntMP(s, (int)(*outLen - idx), &out[idx]);
  28098. if (sSz < 0)
  28099. return sSz;
  28100. idx += (word32)sSz;
  28101. *outLen = idx;
  28102. return 0;
  28103. #else
  28104. ASNSetData dataASN[dsaSigASN_Length];
  28105. int ret;
  28106. int sz;
  28107. /* Clear dynamic data and set mp_ints r and s */
  28108. XMEMSET(dataASN, 0, sizeof(dataASN));
  28109. SetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
  28110. SetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
  28111. /* Calculate size of encoding. */
  28112. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  28113. /* Check buffer is big enough for encoding. */
  28114. if ((ret == 0) && ((int)*outLen < sz)) {
  28115. ret = BUFFER_E;
  28116. }
  28117. if (ret == 0) {
  28118. /* Encode DSA signature into buffer. */
  28119. SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  28120. /* Set the actual encoding size. */
  28121. *outLen = (word32)sz;
  28122. }
  28123. return ret;
  28124. #endif /* WOLFSSL_ASN_TEMPLATE */
  28125. }
  28126. #ifndef WOLFSSL_ASN_TEMPLATE
  28127. /* determine if leading bit is set */
  28128. static word32 is_leading_bit_set(const byte* input, word32 sz)
  28129. {
  28130. byte c = 0;
  28131. if (sz > 0)
  28132. c = input[0];
  28133. return (c & 0x80) != 0;
  28134. }
  28135. static word32 trim_leading_zeros(const byte** input, word32 sz)
  28136. {
  28137. int i;
  28138. word32 leadingZeroCount = 0;
  28139. const byte* tmp = *input;
  28140. for (i=0; i<(int)sz; i++) {
  28141. if (tmp[i] != 0)
  28142. break;
  28143. leadingZeroCount++;
  28144. }
  28145. /* catch all zero case */
  28146. if (sz > 0 && leadingZeroCount == sz) {
  28147. leadingZeroCount--;
  28148. }
  28149. *input += leadingZeroCount;
  28150. sz -= leadingZeroCount;
  28151. return sz;
  28152. }
  28153. #endif
  28154. /* Der Encode r & s ints into out, outLen is (in/out) size */
  28155. /* All input/outputs are assumed to be big-endian */
  28156. int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen,
  28157. const byte* s, word32 sLen)
  28158. {
  28159. #ifndef WOLFSSL_ASN_TEMPLATE
  28160. int ret;
  28161. word32 idx;
  28162. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  28163. word32 rAddLeadZero, sAddLeadZero;
  28164. if ((out == NULL) || (outLen == NULL) || (r == NULL) || (s == NULL))
  28165. return BAD_FUNC_ARG;
  28166. /* Trim leading zeros */
  28167. rLen = trim_leading_zeros(&r, rLen);
  28168. sLen = trim_leading_zeros(&s, sLen);
  28169. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  28170. /* Add leading zero if MSB is set */
  28171. rAddLeadZero = is_leading_bit_set(r, rLen);
  28172. sAddLeadZero = is_leading_bit_set(s, sLen);
  28173. if (*outLen < (rLen + rAddLeadZero + sLen + sAddLeadZero +
  28174. headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
  28175. return BUFFER_E;
  28176. idx = SetSequence(rLen+rAddLeadZero + sLen+sAddLeadZero + headerSz, out);
  28177. /* store r */
  28178. ret = SetASNInt((int)rLen, rAddLeadZero ? 0x80 : 0x00, &out[idx]);
  28179. if (ret < 0)
  28180. return ret;
  28181. idx += (word32)ret;
  28182. XMEMCPY(&out[idx], r, rLen);
  28183. idx += rLen;
  28184. /* store s */
  28185. ret = SetASNInt((int)sLen, sAddLeadZero ? 0x80 : 0x00, &out[idx]);
  28186. if (ret < 0)
  28187. return ret;
  28188. idx += (word32)ret;
  28189. XMEMCPY(&out[idx], s, sLen);
  28190. idx += sLen;
  28191. *outLen = idx;
  28192. return 0;
  28193. #else
  28194. ASNSetData dataASN[dsaSigASN_Length];
  28195. int ret;
  28196. int sz;
  28197. /* Clear dynamic data and set buffers for r and s */
  28198. XMEMSET(dataASN, 0, sizeof(dataASN));
  28199. SetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
  28200. SetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
  28201. /* Calculate size of encoding. */
  28202. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  28203. /* Check buffer is big enough for encoding. */
  28204. if ((ret == 0) && ((int)*outLen < sz)) {
  28205. ret = BUFFER_E;
  28206. }
  28207. if (ret == 0) {
  28208. /* Encode DSA signature into buffer. */
  28209. SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  28210. /* Set the actual encoding size. */
  28211. *outLen = (word32)sz;
  28212. }
  28213. return ret;
  28214. #endif /* WOLFSSL_ASN_TEMPLATE */
  28215. }
  28216. /* Der Decode ECC-DSA Signature with R/S as unsigned bin */
  28217. /* All input/outputs are assumed to be big-endian */
  28218. int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen,
  28219. byte* s, word32* sLen)
  28220. {
  28221. #ifndef WOLFSSL_ASN_TEMPLATE
  28222. int ret;
  28223. word32 idx = 0;
  28224. int len = 0;
  28225. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  28226. return ASN_ECC_KEY_E;
  28227. }
  28228. #ifndef NO_STRICT_ECDSA_LEN
  28229. /* enable strict length checking for signature */
  28230. if (sigLen != idx + (word32)len) {
  28231. return ASN_ECC_KEY_E;
  28232. }
  28233. #else
  28234. /* allow extra signature bytes at end */
  28235. if ((word32)len > (sigLen - idx)) {
  28236. return ASN_ECC_KEY_E;
  28237. }
  28238. #endif
  28239. ret = GetASNInt(sig, &idx, &len, sigLen);
  28240. if (ret != 0)
  28241. return ret;
  28242. if (rLen)
  28243. *rLen = (word32)len;
  28244. if (r)
  28245. XMEMCPY(r, (byte*)sig + idx, (size_t)len);
  28246. idx += (word32)len;
  28247. ret = GetASNInt(sig, &idx, &len, sigLen);
  28248. if (ret != 0)
  28249. return ret;
  28250. if (sLen)
  28251. *sLen = (word32)len;
  28252. if (s)
  28253. XMEMCPY(s, (byte*)sig + idx, (size_t)len);
  28254. #ifndef NO_STRICT_ECDSA_LEN
  28255. /* sanity check that the index has been advanced all the way to the end of
  28256. * the buffer */
  28257. if (idx + (word32)len != sigLen) {
  28258. ret = ASN_ECC_KEY_E;
  28259. }
  28260. #endif
  28261. return ret;
  28262. #else
  28263. ASNGetData dataASN[dsaSigASN_Length];
  28264. word32 idx = 0;
  28265. /* Clear dynamic data and set buffers to put r and s into. */
  28266. XMEMSET(dataASN, 0, sizeof(dataASN));
  28267. GetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
  28268. GetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
  28269. /* Decode the DSA signature. */
  28270. return GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 1, sig, &idx,
  28271. sigLen);
  28272. #endif /* WOLFSSL_ASN_TEMPLATE */
  28273. }
  28274. int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
  28275. {
  28276. return DecodeECC_DSA_Sig_Ex(sig, sigLen, r, s, 1);
  28277. }
  28278. int DecodeECC_DSA_Sig_Ex(const byte* sig, word32 sigLen, mp_int* r, mp_int* s,
  28279. int init)
  28280. {
  28281. #ifndef WOLFSSL_ASN_TEMPLATE
  28282. word32 idx = 0;
  28283. int len = 0;
  28284. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  28285. return ASN_ECC_KEY_E;
  28286. }
  28287. #ifndef NO_STRICT_ECDSA_LEN
  28288. /* enable strict length checking for signature */
  28289. if (sigLen != idx + (word32)len) {
  28290. return ASN_ECC_KEY_E;
  28291. }
  28292. #else
  28293. /* allow extra signature bytes at end */
  28294. if ((word32)len > (sigLen - idx)) {
  28295. return ASN_ECC_KEY_E;
  28296. }
  28297. #endif
  28298. if (GetIntPositive(r, sig, &idx, sigLen, init) < 0) {
  28299. return ASN_ECC_KEY_E;
  28300. }
  28301. if (GetIntPositive(s, sig, &idx, sigLen, init) < 0) {
  28302. mp_clear(r);
  28303. return ASN_ECC_KEY_E;
  28304. }
  28305. #ifndef NO_STRICT_ECDSA_LEN
  28306. /* sanity check that the index has been advanced all the way to the end of
  28307. * the buffer */
  28308. if (idx != sigLen) {
  28309. mp_clear(r);
  28310. mp_clear(s);
  28311. return ASN_ECC_KEY_E;
  28312. }
  28313. #endif
  28314. return 0;
  28315. #else
  28316. ASNGetData dataASN[dsaSigASN_Length];
  28317. word32 idx = 0;
  28318. int ret;
  28319. /* Clear dynamic data and set mp_ints to put r and s into. */
  28320. XMEMSET(dataASN, 0, sizeof(dataASN));
  28321. if (init) {
  28322. GetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
  28323. GetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
  28324. }
  28325. else {
  28326. GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_R], r);
  28327. GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_S], s);
  28328. }
  28329. /* Decode the DSA signature. */
  28330. ret = GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 0, sig, &idx,
  28331. sigLen);
  28332. #ifndef NO_STRICT_ECDSA_LEN
  28333. /* sanity check that the index has been advanced all the way to the end of
  28334. * the buffer */
  28335. if ((ret == 0) && (idx != sigLen)) {
  28336. ret = ASN_ECC_KEY_E;
  28337. }
  28338. #endif
  28339. if (ret != 0) {
  28340. mp_clear(r);
  28341. mp_clear(s);
  28342. }
  28343. return ret;
  28344. #endif /* WOLFSSL_ASN_TEMPLATE */
  28345. }
  28346. #endif
  28347. #ifdef WOLFSSL_ASN_TEMPLATE
  28348. #ifdef WOLFSSL_CUSTOM_CURVES
  28349. /* Convert data to hex string.
  28350. *
  28351. * Big-endian byte array is converted to big-endian hexadecimal string.
  28352. *
  28353. * @param [in] input Buffer containing data.
  28354. * @param [in] inSz Size of data in buffer.
  28355. * @param [out] out Buffer to hold hex string.
  28356. */
  28357. static void DataToHexString(const byte* input, word32 inSz, char* out)
  28358. {
  28359. static const char hexChar[] = { '0', '1', '2', '3', '4', '5', '6', '7',
  28360. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  28361. word32 i;
  28362. /* Converting a byte of data at a time to two hex characters. */
  28363. for (i = 0; i < inSz; i++) {
  28364. out[i*2 + 0] = hexChar[input[i] >> 4];
  28365. out[i*2 + 1] = hexChar[input[i] & 0xf];
  28366. }
  28367. /* NUL terminate string. */
  28368. out[i * 2] = '\0';
  28369. }
  28370. /* Convert data to hex string and place in allocated buffer.
  28371. *
  28372. * Big-endian byte array is converted to big-endian hexadecimal string.
  28373. *
  28374. * @param [in] input Buffer containing data.
  28375. * @param [in] inSz Size of data in buffer.
  28376. * @param [out] out Allocated buffer holding hex string.
  28377. * @param [in] heap Dynamic memory allocation hint.
  28378. * @param [in] heapType Type of heap to use.
  28379. * @return 0 on succcess.
  28380. * @return MEMORY_E when dynamic memory allocation fails.
  28381. */
  28382. static int DataToHexStringAlloc(const byte* input, word32 inSz, char** out,
  28383. void* heap, int heapType)
  28384. {
  28385. int ret = 0;
  28386. char* str;
  28387. /* Allocate for 2 string characters ber byte plus NUL. */
  28388. str = (char*)XMALLOC(inSz * 2 + 1, heap, heapType);
  28389. if (str == NULL) {
  28390. ret = MEMORY_E;
  28391. }
  28392. else {
  28393. /* Convert to hex string. */
  28394. DataToHexString(input, inSz, str);
  28395. *out = str;
  28396. }
  28397. (void)heap;
  28398. (void)heapType;
  28399. return ret;
  28400. }
  28401. /* ASN.1 template for SpecifiedECDomain.
  28402. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  28403. * NOTE: characteristic-two-field not supported. */
  28404. static const ASNItem eccSpecifiedASN[] = {
  28405. /* version */
  28406. /* VER */ { 0, ASN_INTEGER, 0, 0, 0 },
  28407. /* fieldID */
  28408. /* PRIME_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28409. /* prime-field or characteristic-two-field */
  28410. /* PRIME_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  28411. /* Prime-p */
  28412. /* PRIME_P */ { 1, ASN_INTEGER, 0, 0, 0 },
  28413. /* fieldID */
  28414. /* PARAM_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28415. /* a */
  28416. /* PARAM_A */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28417. /* b */
  28418. /* PARAM_B */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28419. /* seed */
  28420. /* PARAM_SEED */ { 1, ASN_BIT_STRING, 0, 0, 1 },
  28421. /* base */
  28422. /* BASE */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  28423. /* order */
  28424. /* ORDER */ { 0, ASN_INTEGER, 0, 0, 0 },
  28425. /* cofactor */
  28426. /* COFACTOR */ { 0, ASN_INTEGER, 0, 0, 1 },
  28427. /* hash */
  28428. /* HASH_SEQ */ { 0, ASN_SEQUENCE, 0, 0, 1 },
  28429. };
  28430. enum {
  28431. ECCSPECIFIEDASN_IDX_VER = 0,
  28432. ECCSPECIFIEDASN_IDX_PRIME_SEQ,
  28433. ECCSPECIFIEDASN_IDX_PRIME_OID,
  28434. ECCSPECIFIEDASN_IDX_PRIME_P,
  28435. ECCSPECIFIEDASN_IDX_PARAM_SEQ,
  28436. ECCSPECIFIEDASN_IDX_PARAM_A,
  28437. ECCSPECIFIEDASN_IDX_PARAM_B,
  28438. ECCSPECIFIEDASN_IDX_PARAM_SEED,
  28439. ECCSPECIFIEDASN_IDX_BASE,
  28440. ECCSPECIFIEDASN_IDX_ORDER,
  28441. ECCSPECIFIEDASN_IDX_COFACTOR,
  28442. ECCSPECIFIEDASN_IDX_HASH_SEQ
  28443. };
  28444. /* Number of items in ASN.1 template for SpecifiedECDomain. */
  28445. #define eccSpecifiedASN_Length (sizeof(eccSpecifiedASN) / sizeof(ASNItem))
  28446. /* OID indicating the prime field is explicity defined. */
  28447. static const byte primeFieldOID[] = {
  28448. 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01
  28449. };
  28450. static const char ecSetCustomName[] = "Custom";
  28451. /* Explicit EC parameter values. */
  28452. static int EccSpecifiedECDomainDecode(const byte* input, word32 inSz,
  28453. ecc_key* key)
  28454. {
  28455. DECL_ASNGETDATA(dataASN, eccSpecifiedASN_Length);
  28456. int ret = 0;
  28457. ecc_set_type* curve;
  28458. word32 idx = 0;
  28459. byte version;
  28460. byte cofactor;
  28461. const byte *base;
  28462. word32 baseLen;
  28463. /* Allocate a new parameter set. */
  28464. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  28465. DYNAMIC_TYPE_ECC_BUFFER);
  28466. if (curve == NULL) {
  28467. ret = MEMORY_E;
  28468. }
  28469. else {
  28470. /* Clear out parameters and set fields to indicate it is custom. */
  28471. XMEMSET(curve, 0, sizeof(*curve));
  28472. }
  28473. CALLOC_ASNGETDATA(dataASN, eccSpecifiedASN_Length, ret, key->heap);
  28474. if (ret == 0) {
  28475. /* Set name to be: "Custom" */
  28476. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28477. curve->name = ecSetCustomName;
  28478. #else
  28479. XMEMCPY((void*)curve->name, ecSetCustomName, sizeof(ecSetCustomName));
  28480. #endif
  28481. curve->id = ECC_CURVE_CUSTOM;
  28482. /* Get version, must have prime field OID and get co-factor. */
  28483. GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_VER], &version);
  28484. GetASN_ExpBuffer(&dataASN[ECCSPECIFIEDASN_IDX_PRIME_OID],
  28485. primeFieldOID, sizeof(primeFieldOID));
  28486. GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_COFACTOR], &cofactor);
  28487. /* Decode the explicit parameters. */
  28488. ret = GetASN_Items(eccSpecifiedASN, dataASN, eccSpecifiedASN_Length, 1,
  28489. input, &idx, inSz);
  28490. }
  28491. /* Version must be 1 or 2 for supporting explicit parameters. */
  28492. if ((ret == 0) && (version < 1 || version > 3)) {
  28493. ret = ASN_PARSE_E;
  28494. }
  28495. #ifndef WOLFSSL_NO_ASN_STRICT
  28496. /* Only version 2 and above can have a seed. */
  28497. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_PARAM_SEED].tag != 0) &&
  28498. (version < 2)) {
  28499. ret = ASN_PARSE_E;
  28500. }
  28501. #endif
  28502. /* Only version 2 and above can have a hash algorithm. */
  28503. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_HASH_SEQ].tag != 0) &&
  28504. (version < 2)) {
  28505. ret = ASN_PARSE_E;
  28506. }
  28507. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_COFACTOR].tag != 0)) {
  28508. /* Store optional co-factor. */
  28509. curve->cofactor = cofactor;
  28510. }
  28511. if (ret == 0) {
  28512. /* Length of the prime in bytes is the curve size. */
  28513. curve->size =
  28514. (int)dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length;
  28515. /* Base point: 0x04 <x> <y> (must be uncompressed). */
  28516. GetASN_GetConstRef(&dataASN[ECCSPECIFIEDASN_IDX_BASE], &base,
  28517. &baseLen);
  28518. if ((baseLen < (word32)curve->size * 2 + 1) || (base[0] != 0x4)) {
  28519. ret = ASN_PARSE_E;
  28520. }
  28521. }
  28522. /* Put the curve parameters into the set.
  28523. * Convert the big-endian number byte array to a big-endian string.
  28524. */
  28525. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28526. /* Allocate buffer to put hex strings into. */
  28527. if (ret == 0) {
  28528. /* Base X-ordinate */
  28529. ret = DataToHexStringAlloc(base + 1, (word32)curve->size,
  28530. (char**)&curve->Gx, key->heap,
  28531. DYNAMIC_TYPE_ECC_BUFFER);
  28532. }
  28533. if (ret == 0) {
  28534. /* Base Y-ordinate */
  28535. ret = DataToHexStringAlloc(base + 1 + curve->size, (word32)curve->size,
  28536. (char**)&curve->Gy, key->heap,
  28537. DYNAMIC_TYPE_ECC_BUFFER);
  28538. }
  28539. if (ret == 0) {
  28540. /* Prime */
  28541. ret = DataToHexStringAlloc(
  28542. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
  28543. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
  28544. (char**)&curve->prime, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28545. }
  28546. if (ret == 0) {
  28547. /* Parameter A */
  28548. ret = DataToHexStringAlloc(
  28549. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
  28550. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
  28551. (char**)&curve->Af, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28552. }
  28553. if (ret == 0) {
  28554. /* Parameter B */
  28555. ret = DataToHexStringAlloc(
  28556. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
  28557. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
  28558. (char**)&curve->Bf, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28559. }
  28560. if (ret == 0) {
  28561. /* Order of curve */
  28562. ret = DataToHexStringAlloc(
  28563. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
  28564. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
  28565. (char**)&curve->order, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28566. }
  28567. #else
  28568. if (ret == 0) {
  28569. /* Base X-ordinate */
  28570. DataToHexString(base + 1, curve->size, curve->Gx);
  28571. /* Base Y-ordinate */
  28572. DataToHexString(base + 1 + curve->size, curve->size, curve->Gy);
  28573. /* Prime */
  28574. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
  28575. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
  28576. curve->prime);
  28577. /* Parameter A */
  28578. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
  28579. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
  28580. curve->Af);
  28581. /* Parameter B */
  28582. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
  28583. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
  28584. curve->Bf);
  28585. /* Order of curve */
  28586. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
  28587. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
  28588. curve->order);
  28589. }
  28590. #endif /* WOLFSSL_ECC_CURVE_STATIC */
  28591. /* Store parameter set in key. */
  28592. if ((ret == 0) && (wc_ecc_set_custom_curve(key, curve) < 0)) {
  28593. ret = ASN_PARSE_E;
  28594. }
  28595. if (ret == 0) {
  28596. /* The parameter set was allocated.. */
  28597. key->deallocSet = 1;
  28598. }
  28599. if ((ret != 0) && (curve != NULL)) {
  28600. /* Failed to set parameters so free paramter set. */
  28601. wc_ecc_free_curve(curve, key->heap);
  28602. }
  28603. FREE_ASNGETDATA(dataASN, key->heap);
  28604. return ret;
  28605. }
  28606. #endif /* WOLFSSL_CUSTOM_CURVES */
  28607. #endif /* WOLFSSL_ASN_TEMPLATE */
  28608. #ifdef HAVE_ECC
  28609. #ifdef WOLFSSL_ASN_TEMPLATE
  28610. /* ASN.1 template for ECC private key.
  28611. * SEC.1 Ver 2.0, C.4 - Syntax for Elliptic Curve Private Keys
  28612. */
  28613. static const ASNItem eccKeyASN[] = {
  28614. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28615. /* version */
  28616. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  28617. /* privateKey */
  28618. /* PKEY */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28619. /* parameters */
  28620. /* PARAMS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PARAMS, 1, 1, 1 },
  28621. /* named */
  28622. /* CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  28623. /* specified */
  28624. /* CURVEPARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  28625. /* publicKey */
  28626. /* PUBKEY */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PUBKEY, 1, 1, 1 },
  28627. /* Uncompressed point - X9.62. */
  28628. /* PUBKEY_VAL, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  28629. };
  28630. enum {
  28631. ECCKEYASN_IDX_SEQ = 0,
  28632. ECCKEYASN_IDX_VER,
  28633. ECCKEYASN_IDX_PKEY,
  28634. ECCKEYASN_IDX_PARAMS,
  28635. ECCKEYASN_IDX_CURVEID,
  28636. ECCKEYASN_IDX_CURVEPARAMS,
  28637. ECCKEYASN_IDX_PUBKEY,
  28638. ECCKEYASN_IDX_PUBKEY_VAL
  28639. };
  28640. /* Number of items in ASN.1 template for ECC private key. */
  28641. #define eccKeyASN_Length (sizeof(eccKeyASN) / sizeof(ASNItem))
  28642. #endif
  28643. WOLFSSL_ABI
  28644. int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
  28645. word32 inSz)
  28646. {
  28647. #ifndef WOLFSSL_ASN_TEMPLATE
  28648. word32 oidSum;
  28649. int version, length;
  28650. int privSz, pubSz = 0;
  28651. byte b;
  28652. int ret = 0;
  28653. int curve_id = ECC_CURVE_DEF;
  28654. #ifdef WOLFSSL_SMALL_STACK
  28655. byte* priv;
  28656. byte* pub = NULL;
  28657. #else
  28658. byte priv[ECC_MAXSIZE+1];
  28659. byte pub[2*(ECC_MAXSIZE+1)]; /* public key has two parts plus header */
  28660. #endif
  28661. word32 algId = 0;
  28662. byte* pubData = NULL;
  28663. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  28664. return BAD_FUNC_ARG;
  28665. /* if has pkcs8 header skip it */
  28666. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  28667. /* ignore error, did not have pkcs8 header */
  28668. }
  28669. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28670. return ASN_PARSE_E;
  28671. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  28672. return ASN_PARSE_E;
  28673. if (*inOutIdx >= inSz)
  28674. return ASN_PARSE_E;
  28675. b = input[*inOutIdx];
  28676. *inOutIdx += 1;
  28677. /* priv type */
  28678. if (b != 4 && b != 6 && b != 7)
  28679. return ASN_PARSE_E;
  28680. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  28681. return ASN_PARSE_E;
  28682. privSz = length;
  28683. if (privSz > ECC_MAXSIZE)
  28684. return BUFFER_E;
  28685. #ifdef WOLFSSL_SMALL_STACK
  28686. priv = (byte*)XMALLOC(privSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28687. if (priv == NULL)
  28688. return MEMORY_E;
  28689. #endif
  28690. /* priv key */
  28691. XMEMCPY(priv, &input[*inOutIdx], (size_t)privSz);
  28692. *inOutIdx += (word32)length;
  28693. if ((*inOutIdx + 1) < inSz) {
  28694. /* prefix 0, may have */
  28695. b = input[*inOutIdx];
  28696. if (b == ECC_PREFIX_0) {
  28697. *inOutIdx += 1;
  28698. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  28699. ret = ASN_PARSE_E;
  28700. else {
  28701. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType,
  28702. inSz);
  28703. if (ret == 0) {
  28704. if ((ret = CheckCurve(oidSum)) < 0)
  28705. ret = ECC_CURVE_OID_E;
  28706. else {
  28707. curve_id = ret;
  28708. ret = 0;
  28709. }
  28710. }
  28711. }
  28712. }
  28713. }
  28714. if (ret == 0 && (*inOutIdx + 1) < inSz) {
  28715. /* prefix 1 */
  28716. b = input[*inOutIdx];
  28717. *inOutIdx += 1;
  28718. if (b != ECC_PREFIX_1) {
  28719. ret = ASN_ECC_KEY_E;
  28720. }
  28721. else if (GetLength(input, inOutIdx, &length, inSz) <= 0) {
  28722. ret = ASN_PARSE_E;
  28723. }
  28724. else {
  28725. /* key header */
  28726. ret = CheckBitString(input, inOutIdx, &length, inSz, 0, NULL);
  28727. if (ret == 0) {
  28728. /* pub key */
  28729. pubSz = length;
  28730. if (pubSz > 2*(ECC_MAXSIZE+1))
  28731. ret = BUFFER_E;
  28732. else {
  28733. #ifdef WOLFSSL_SMALL_STACK
  28734. pub = (byte*)XMALLOC(pubSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28735. if (pub == NULL)
  28736. ret = MEMORY_E;
  28737. else
  28738. #endif
  28739. {
  28740. XMEMCPY(pub, &input[*inOutIdx], (size_t)pubSz);
  28741. *inOutIdx += (word32)length;
  28742. pubData = pub;
  28743. }
  28744. }
  28745. }
  28746. }
  28747. }
  28748. if (ret == 0) {
  28749. ret = wc_ecc_import_private_key_ex(priv, (word32)privSz, pubData,
  28750. (word32)pubSz, key, curve_id);
  28751. }
  28752. #ifdef WOLFSSL_SMALL_STACK
  28753. XFREE(priv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28754. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28755. #endif
  28756. return ret;
  28757. #else
  28758. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  28759. byte version;
  28760. int ret = 0;
  28761. int curve_id = ECC_CURVE_DEF;
  28762. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  28763. word32 algId = 0;
  28764. #endif
  28765. /* Validate parameters. */
  28766. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  28767. ret = BAD_FUNC_ARG;
  28768. }
  28769. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  28770. /* if has pkcs8 header skip it */
  28771. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  28772. /* ignore error, did not have pkcs8 header */
  28773. }
  28774. #endif
  28775. CALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  28776. if (ret == 0) {
  28777. /* Get the version and set the expected OID type. */
  28778. GetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], &version);
  28779. GetASN_OID(&dataASN[ECCKEYASN_IDX_CURVEID], oidCurveType);
  28780. /* Decode the private ECC key. */
  28781. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  28782. inOutIdx, inSz);
  28783. }
  28784. /* Only version 1 supported. */
  28785. if ((ret == 0) && (version != 1)) {
  28786. ret = ASN_PARSE_E;
  28787. }
  28788. /* Curve Parameters are optional. */
  28789. if ((ret == 0) && (dataASN[ECCKEYASN_IDX_PARAMS].tag != 0)) {
  28790. if (dataASN[ECCKEYASN_IDX_CURVEID].tag != 0) {
  28791. /* Named curve - check and get id. */
  28792. curve_id = CheckCurve(dataASN[ECCKEYASN_IDX_CURVEID].data.oid.sum);
  28793. if (curve_id < 0) {
  28794. ret = ECC_CURVE_OID_E;
  28795. }
  28796. }
  28797. else {
  28798. #ifdef WOLFSSL_CUSTOM_CURVES
  28799. /* Parse explicit parameters. */
  28800. ret = EccSpecifiedECDomainDecode(
  28801. dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.data,
  28802. dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.length, key);
  28803. #else
  28804. /* Explicit parameters not supported in build configuration. */
  28805. ret = ASN_PARSE_E;
  28806. #endif
  28807. }
  28808. }
  28809. if (ret == 0) {
  28810. /* Import private key value and public point (may be NULL). */
  28811. ret = wc_ecc_import_private_key_ex(
  28812. dataASN[ECCKEYASN_IDX_PKEY].data.ref.data,
  28813. dataASN[ECCKEYASN_IDX_PKEY].data.ref.length,
  28814. dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.data,
  28815. dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.length,
  28816. key, curve_id);
  28817. }
  28818. FREE_ASNGETDATA(dataASN, key->heap);
  28819. return ret;
  28820. #endif
  28821. }
  28822. #ifdef WOLFSSL_CUSTOM_CURVES
  28823. #ifndef WOLFSSL_ASN_TEMPLATE
  28824. /* returns 0 on success */
  28825. static int ASNToHexString(const byte* input, word32* inOutIdx, char** out,
  28826. word32 inSz, void* heap, int heapType)
  28827. {
  28828. int len;
  28829. int i;
  28830. char* str;
  28831. word32 localIdx;
  28832. byte tag;
  28833. if (*inOutIdx >= inSz) {
  28834. return BUFFER_E;
  28835. }
  28836. localIdx = *inOutIdx;
  28837. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 && tag == ASN_INTEGER) {
  28838. if (GetASNInt(input, inOutIdx, &len, inSz) < 0)
  28839. return ASN_PARSE_E;
  28840. }
  28841. else {
  28842. if (GetOctetString(input, inOutIdx, &len, inSz) < 0)
  28843. return ASN_PARSE_E;
  28844. }
  28845. str = (char*)XMALLOC((size_t)len * 2 + 1, heap, heapType);
  28846. if (str == NULL) {
  28847. return MEMORY_E;
  28848. }
  28849. for (i=0; i<len; i++)
  28850. ByteToHexStr(input[*inOutIdx + (word32)i], str + i*2);
  28851. str[len*2] = '\0';
  28852. *inOutIdx += (word32)len;
  28853. *out = str;
  28854. (void)heap;
  28855. (void)heapType;
  28856. return 0;
  28857. }
  28858. static int EccKeyParamCopy(char** dst, char* src)
  28859. {
  28860. int ret = 0;
  28861. #ifdef WOLFSSL_ECC_CURVE_STATIC
  28862. word32 length;
  28863. #endif
  28864. if (dst == NULL || src == NULL)
  28865. return BAD_FUNC_ARG;
  28866. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28867. *dst = src;
  28868. #else
  28869. length = (int)XSTRLEN(src) + 1;
  28870. if (length > MAX_ECC_STRING) {
  28871. WOLFSSL_MSG("ECC Param too large for buffer");
  28872. ret = BUFFER_E;
  28873. }
  28874. else {
  28875. XSTRNCPY(*dst, src, MAX_ECC_STRING);
  28876. }
  28877. XFREE(src, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28878. #endif
  28879. return ret;
  28880. }
  28881. #endif /* !WOLFSSL_ASN_TEMPLATE */
  28882. #endif /* WOLFSSL_CUSTOM_CURVES */
  28883. WOLFSSL_ABI
  28884. int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx,
  28885. ecc_key* key, word32 inSz)
  28886. {
  28887. #ifndef WOLFSSL_ASN_TEMPLATE
  28888. int ret;
  28889. int version, length;
  28890. int curve_id = ECC_CURVE_DEF;
  28891. word32 oidSum, localIdx;
  28892. byte tag, isPrivFormat = 0;
  28893. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  28894. return BAD_FUNC_ARG;
  28895. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28896. return ASN_PARSE_E;
  28897. /* Check if ECC private key is being used and skip private portion */
  28898. if (GetMyVersion(input, inOutIdx, &version, inSz) >= 0) {
  28899. isPrivFormat = 1;
  28900. /* Type private key */
  28901. if (*inOutIdx >= inSz)
  28902. return ASN_PARSE_E;
  28903. tag = input[*inOutIdx];
  28904. *inOutIdx += 1;
  28905. if (tag != 4 && tag != 6 && tag != 7)
  28906. return ASN_PARSE_E;
  28907. /* Skip Private Key */
  28908. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  28909. return ASN_PARSE_E;
  28910. if (length > ECC_MAXSIZE)
  28911. return BUFFER_E;
  28912. *inOutIdx += (word32)length;
  28913. /* Private Curve Header */
  28914. if (*inOutIdx >= inSz)
  28915. return ASN_PARSE_E;
  28916. tag = input[*inOutIdx];
  28917. *inOutIdx += 1;
  28918. if (tag != ECC_PREFIX_0)
  28919. return ASN_ECC_KEY_E;
  28920. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  28921. return ASN_PARSE_E;
  28922. }
  28923. /* Standard ECC public key */
  28924. else {
  28925. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28926. return ASN_PARSE_E;
  28927. ret = SkipObjectId(input, inOutIdx, inSz);
  28928. if (ret != 0)
  28929. return ret;
  28930. }
  28931. if (*inOutIdx >= inSz) {
  28932. return BUFFER_E;
  28933. }
  28934. localIdx = *inOutIdx;
  28935. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 &&
  28936. tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  28937. #ifdef WOLFSSL_CUSTOM_CURVES
  28938. ecc_set_type* curve;
  28939. int len;
  28940. char* point = NULL;
  28941. ret = 0;
  28942. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  28943. DYNAMIC_TYPE_ECC_BUFFER);
  28944. if (curve == NULL)
  28945. ret = MEMORY_E;
  28946. if (ret == 0) {
  28947. static const char customName[] = "Custom";
  28948. XMEMSET(curve, 0, sizeof(*curve));
  28949. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28950. curve->name = customName;
  28951. #else
  28952. XMEMCPY((void*)curve->name, customName, sizeof(customName));
  28953. #endif
  28954. curve->id = ECC_CURVE_CUSTOM;
  28955. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28956. ret = ASN_PARSE_E;
  28957. }
  28958. if (ret == 0) {
  28959. GetInteger7Bit(input, inOutIdx, inSz);
  28960. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28961. ret = ASN_PARSE_E;
  28962. }
  28963. if (ret == 0) {
  28964. char* p = NULL;
  28965. SkipObjectId(input, inOutIdx, inSz);
  28966. ret = ASNToHexString(input, inOutIdx, &p, inSz,
  28967. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28968. if (ret == 0) {
  28969. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28970. ret = EccKeyParamCopy((char**)&curve->prime, p);
  28971. #else
  28972. const char *_tmp_ptr = &curve->prime[0];
  28973. ret = EccKeyParamCopy((char**)&_tmp_ptr, p);
  28974. #endif
  28975. }
  28976. }
  28977. if (ret == 0) {
  28978. curve->size = (int)XSTRLEN(curve->prime) / 2;
  28979. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28980. ret = ASN_PARSE_E;
  28981. }
  28982. if (ret == 0) {
  28983. char* af = NULL;
  28984. ret = ASNToHexString(input, inOutIdx, &af, inSz,
  28985. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28986. if (ret == 0) {
  28987. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28988. ret = EccKeyParamCopy((char**)&curve->Af, af);
  28989. #else
  28990. const char *_tmp_ptr = &curve->Af[0];
  28991. ret = EccKeyParamCopy((char**)&_tmp_ptr, af);
  28992. #endif
  28993. }
  28994. }
  28995. if (ret == 0) {
  28996. char* bf = NULL;
  28997. ret = ASNToHexString(input, inOutIdx, &bf, inSz,
  28998. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28999. if (ret == 0) {
  29000. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29001. ret = EccKeyParamCopy((char**)&curve->Bf, bf);
  29002. #else
  29003. const char *_tmp_ptr = &curve->Bf[0];
  29004. ret = EccKeyParamCopy((char**)&_tmp_ptr, bf);
  29005. #endif
  29006. }
  29007. }
  29008. if (ret == 0) {
  29009. localIdx = *inOutIdx;
  29010. if (*inOutIdx < inSz && GetASNTag(input, &localIdx, &tag, inSz)
  29011. == 0 && tag == ASN_BIT_STRING) {
  29012. len = 0;
  29013. ret = GetASNHeader(input, ASN_BIT_STRING, inOutIdx, &len, inSz);
  29014. if (ret > 0)
  29015. ret = 0; /* reset on success */
  29016. *inOutIdx += (word32)len;
  29017. }
  29018. }
  29019. if (ret == 0) {
  29020. ret = ASNToHexString(input, inOutIdx, (char**)&point, inSz,
  29021. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29022. /* sanity check that point buffer is not smaller than the expected
  29023. * size to hold ( 0 4 || Gx || Gy )
  29024. * where Gx and Gy are each the size of curve->size * 2 */
  29025. if (ret == 0 && (int)XSTRLEN(point) < (curve->size * 4) + 2) {
  29026. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29027. ret = BUFFER_E;
  29028. }
  29029. }
  29030. if (ret == 0) {
  29031. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29032. curve->Gx = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
  29033. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29034. curve->Gy = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
  29035. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29036. if (curve->Gx == NULL || curve->Gy == NULL) {
  29037. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29038. ret = MEMORY_E;
  29039. }
  29040. #else
  29041. if (curve->size * 2 + 2 > MAX_ECC_STRING) {
  29042. WOLFSSL_MSG("curve size is too large to fit in buffer");
  29043. ret = BUFFER_E;
  29044. }
  29045. #endif
  29046. }
  29047. if (ret == 0) {
  29048. char* o = NULL;
  29049. XMEMCPY((char*)curve->Gx, point + 2, (size_t)curve->size * 2);
  29050. XMEMCPY((char*)curve->Gy, point + curve->size * 2 + 2,
  29051. (size_t)curve->size * 2);
  29052. ((char*)curve->Gx)[curve->size * 2] = '\0';
  29053. ((char*)curve->Gy)[curve->size * 2] = '\0';
  29054. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29055. ret = ASNToHexString(input, inOutIdx, &o, inSz,
  29056. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29057. if (ret == 0) {
  29058. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29059. ret = EccKeyParamCopy((char**)&curve->order, o);
  29060. #else
  29061. const char *_tmp_ptr = &curve->order[0];
  29062. ret = EccKeyParamCopy((char**)&_tmp_ptr, o);
  29063. #endif
  29064. }
  29065. }
  29066. if (ret == 0) {
  29067. curve->cofactor = GetInteger7Bit(input, inOutIdx, inSz);
  29068. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29069. curve->oid = NULL;
  29070. #else
  29071. XMEMSET((void*)curve->oid, 0, sizeof(curve->oid));
  29072. #endif
  29073. curve->oidSz = 0;
  29074. curve->oidSum = 0;
  29075. if (wc_ecc_set_custom_curve(key, curve) < 0) {
  29076. ret = ASN_PARSE_E;
  29077. }
  29078. key->deallocSet = 1;
  29079. curve = NULL;
  29080. }
  29081. if (curve != NULL)
  29082. wc_ecc_free_curve(curve, key->heap);
  29083. if (ret < 0)
  29084. return ret;
  29085. #else
  29086. return ASN_PARSE_E;
  29087. #endif /* WOLFSSL_CUSTOM_CURVES */
  29088. }
  29089. else {
  29090. /* ecc params information */
  29091. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType, inSz);
  29092. if (ret != 0)
  29093. return ret;
  29094. /* get curve id */
  29095. if ((ret = CheckCurve(oidSum)) < 0)
  29096. return ECC_CURVE_OID_E;
  29097. else {
  29098. curve_id = ret;
  29099. }
  29100. }
  29101. if (isPrivFormat) {
  29102. /* Public Curve Header - skip */
  29103. if (*inOutIdx >= inSz)
  29104. return ASN_PARSE_E;
  29105. tag = input[*inOutIdx];
  29106. *inOutIdx += 1;
  29107. if (tag != ECC_PREFIX_1)
  29108. return ASN_ECC_KEY_E;
  29109. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  29110. return ASN_PARSE_E;
  29111. }
  29112. /* key header */
  29113. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  29114. if (ret != 0)
  29115. return ret;
  29116. /* This is the raw point data compressed or uncompressed. */
  29117. if (wc_ecc_import_x963_ex(input + *inOutIdx, (word32)length, key,
  29118. curve_id) != 0) {
  29119. return ASN_ECC_KEY_E;
  29120. }
  29121. *inOutIdx += (word32)length;
  29122. return 0;
  29123. #else
  29124. /* eccKeyASN is longer than eccPublicKeyASN. */
  29125. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  29126. int ret = 0;
  29127. int curve_id = ECC_CURVE_DEF;
  29128. int oidIdx = ECCPUBLICKEYASN_IDX_ALGOID_CURVEID;
  29129. #ifdef WOLFSSL_CUSTOM_CURVES
  29130. int specIdx = ECCPUBLICKEYASN_IDX_ALGOID_PARAMS;
  29131. #endif
  29132. int pubIdx = ECCPUBLICKEYASN_IDX_PUBKEY;
  29133. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  29134. ret = BAD_FUNC_ARG;
  29135. }
  29136. ALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  29137. if (ret == 0) {
  29138. /* Clear dynamic data for ECC public key. */
  29139. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccPublicKeyASN_Length);
  29140. /* Set required ECDSA OID and ignore the curve OID type. */
  29141. GetASN_ExpBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], keyEcdsaOid,
  29142. sizeof(keyEcdsaOid));
  29143. GetASN_OID(&dataASN[oidIdx], oidIgnoreType);
  29144. /* Decode the public ECC key. */
  29145. ret = GetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length, 1,
  29146. input, inOutIdx, inSz);
  29147. if (ret != 0) {
  29148. oidIdx = ECCKEYASN_IDX_CURVEID;
  29149. #ifdef WOLFSSL_CUSTOM_CURVES
  29150. specIdx = ECCKEYASN_IDX_CURVEPARAMS;
  29151. #endif
  29152. pubIdx = ECCKEYASN_IDX_PUBKEY_VAL;
  29153. /* Clear dynamic data for ECC private key. */
  29154. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccKeyASN_Length);
  29155. /* Check named curve OID type. */
  29156. GetASN_OID(&dataASN[oidIdx], oidIgnoreType);
  29157. /* Try private key format .*/
  29158. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  29159. inOutIdx, inSz);
  29160. if (ret != 0) {
  29161. ret = ASN_PARSE_E;
  29162. }
  29163. }
  29164. }
  29165. if (ret == 0) {
  29166. if (dataASN[oidIdx].tag != 0) {
  29167. /* Named curve - check and get id. */
  29168. curve_id = CheckCurve(dataASN[oidIdx].data.oid.sum);
  29169. if (curve_id < 0) {
  29170. ret = ASN_OBJECT_ID_E;
  29171. }
  29172. }
  29173. else {
  29174. #ifdef WOLFSSL_CUSTOM_CURVES
  29175. /* Parse explicit parameters. */
  29176. ret = EccSpecifiedECDomainDecode(dataASN[specIdx].data.ref.data,
  29177. dataASN[specIdx].data.ref.length, key);
  29178. #else
  29179. /* Explicit parameters not supported in build configuration. */
  29180. ret = ASN_PARSE_E;
  29181. #endif
  29182. }
  29183. }
  29184. if (ret == 0) {
  29185. /* Import public point. */
  29186. ret = wc_ecc_import_x963_ex(dataASN[pubIdx].data.ref.data,
  29187. dataASN[pubIdx].data.ref.length, key, curve_id);
  29188. if (ret != 0) {
  29189. ret = ASN_ECC_KEY_E;
  29190. }
  29191. }
  29192. FREE_ASNGETDATA(dataASN, key->heap);
  29193. return ret;
  29194. #endif /* WOLFSSL_ASN_TEMPLATE */
  29195. }
  29196. #if defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  29197. /* build DER formatted ECC key, include optional public key if requested,
  29198. * return length on success, negative on error */
  29199. static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen,
  29200. int pubIn, int curveIn)
  29201. {
  29202. #ifndef WOLFSSL_ASN_TEMPLATE
  29203. byte curve[MAX_ALGO_SZ+2];
  29204. byte ver[MAX_VERSION_SZ];
  29205. byte seq[MAX_SEQ_SZ];
  29206. int ret, curveSz, verSz;
  29207. word32 totalSz;
  29208. int privHdrSz = ASN_ECC_HEADER_SZ;
  29209. int pubHdrSz = ASN_ECC_CONTEXT_SZ + ASN_ECC_HEADER_SZ;
  29210. #ifdef WOLFSSL_NO_MALLOC
  29211. byte prv[MAX_ECC_BYTES + ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  29212. byte pub[(MAX_ECC_BYTES * 2) + 1 + ASN_ECC_CONTEXT_SZ +
  29213. ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  29214. #else
  29215. byte *prv = NULL, *pub = NULL;
  29216. #endif
  29217. word32 idx = 0, prvidx = 0, pubidx = 0, curveidx = 0;
  29218. word32 seqSz, privSz, pubSz = ECC_BUFSIZE;
  29219. if (key == NULL || (output == NULL && inLen == NULL))
  29220. return BAD_FUNC_ARG;
  29221. if (curveIn) {
  29222. /* curve */
  29223. curve[curveidx++] = ECC_PREFIX_0;
  29224. curveidx++ /* to put the size after computation */;
  29225. curveSz = SetCurve(key, curve+curveidx, MAX_ALGO_SZ);
  29226. if (curveSz < 0)
  29227. return curveSz;
  29228. /* set computed size */
  29229. curve[1] = (byte)curveSz;
  29230. curveidx += (word32)curveSz;
  29231. }
  29232. /* private */
  29233. privSz = (word32)key->dp->size;
  29234. #ifdef WOLFSSL_QNX_CAAM
  29235. /* check if is a black key, and add MAC size if needed */
  29236. if (key->blackKey > 0 && key->blackKey != CAAM_BLACK_KEY_ECB) {
  29237. privSz = privSz + WC_CAAM_MAC_SZ;
  29238. }
  29239. #endif
  29240. #ifndef WOLFSSL_NO_MALLOC
  29241. prv = (byte*)XMALLOC(privSz + (word32)privHdrSz + MAX_SEQ_SZ,
  29242. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29243. if (prv == NULL) {
  29244. return MEMORY_E;
  29245. }
  29246. #else
  29247. if (sizeof(prv) < privSz + privHdrSz + MAX_SEQ_SZ) {
  29248. return BUFFER_E;
  29249. }
  29250. #endif
  29251. if (privSz < ASN_LONG_LENGTH) {
  29252. prvidx += SetOctetString8Bit(privSz, &prv[prvidx]);
  29253. }
  29254. else {
  29255. prvidx += SetOctetString(privSz, &prv[prvidx]);
  29256. }
  29257. ret = wc_ecc_export_private_only(key, prv + prvidx, &privSz);
  29258. if (ret < 0) {
  29259. #ifndef WOLFSSL_NO_MALLOC
  29260. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29261. #endif
  29262. return ret;
  29263. }
  29264. prvidx += privSz;
  29265. /* pubIn */
  29266. if (pubIn) {
  29267. PRIVATE_KEY_UNLOCK();
  29268. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  29269. PRIVATE_KEY_LOCK();
  29270. if (ret != LENGTH_ONLY_E) {
  29271. #ifndef WOLFSSL_NO_MALLOC
  29272. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29273. #endif
  29274. return ret;
  29275. }
  29276. #ifndef WOLFSSL_NO_MALLOC
  29277. pub = (byte*)XMALLOC(pubSz + (word32)pubHdrSz + MAX_SEQ_SZ,
  29278. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29279. if (pub == NULL) {
  29280. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29281. return MEMORY_E;
  29282. }
  29283. #else
  29284. if (sizeof(pub) < pubSz + pubHdrSz + MAX_SEQ_SZ) {
  29285. return BUFFER_E;
  29286. }
  29287. #endif
  29288. pub[pubidx++] = ECC_PREFIX_1;
  29289. if (pubSz > 128) /* leading zero + extra size byte */
  29290. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 2, pub+pubidx);
  29291. else /* leading zero */
  29292. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 1, pub+pubidx);
  29293. /* SetBitString adds leading zero */
  29294. pubidx += SetBitString(pubSz, 0, pub + pubidx);
  29295. PRIVATE_KEY_UNLOCK();
  29296. ret = wc_ecc_export_x963(key, pub + pubidx, &pubSz);
  29297. PRIVATE_KEY_LOCK();
  29298. if (ret != 0) {
  29299. #ifndef WOLFSSL_NO_MALLOC
  29300. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29301. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29302. #endif
  29303. return ret;
  29304. }
  29305. pubidx += pubSz;
  29306. }
  29307. /* make headers */
  29308. verSz = SetMyVersion(1, ver, FALSE);
  29309. seqSz = SetSequence((word32)verSz + prvidx + pubidx + curveidx, seq);
  29310. totalSz = prvidx + pubidx + curveidx + (word32)verSz + seqSz;
  29311. if (output == NULL) {
  29312. *inLen = totalSz;
  29313. #ifndef WOLFSSL_NO_MALLOC
  29314. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29315. if (pubIn) {
  29316. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29317. }
  29318. #endif
  29319. return LENGTH_ONLY_E;
  29320. }
  29321. if (inLen != NULL && totalSz > *inLen) {
  29322. #ifndef WOLFSSL_NO_MALLOC
  29323. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29324. if (pubIn) {
  29325. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29326. }
  29327. #endif
  29328. return BAD_FUNC_ARG;
  29329. }
  29330. /* write out */
  29331. /* seq */
  29332. XMEMCPY(output + idx, seq, seqSz);
  29333. idx = seqSz;
  29334. /* ver */
  29335. XMEMCPY(output + idx, ver, (size_t)verSz);
  29336. idx += (word32)verSz;
  29337. /* private */
  29338. XMEMCPY(output + idx, prv, prvidx);
  29339. idx += prvidx;
  29340. #ifndef WOLFSSL_NO_MALLOC
  29341. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29342. #endif
  29343. /* curve */
  29344. XMEMCPY(output + idx, curve, curveidx);
  29345. idx += curveidx;
  29346. /* pubIn */
  29347. if (pubIn) {
  29348. XMEMCPY(output + idx, pub, pubidx);
  29349. /* idx += pubidx; not used after write, if more data remove comment */
  29350. #ifndef WOLFSSL_NO_MALLOC
  29351. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29352. #endif
  29353. }
  29354. return (int)totalSz;
  29355. #else
  29356. DECL_ASNSETDATA(dataASN, eccKeyASN_Length);
  29357. word32 privSz, pubSz;
  29358. int sz = 0;
  29359. int ret = 0;
  29360. int curveIdSz = 0;
  29361. /* Check validity of parameters. */
  29362. if ((key == NULL) || ((output == NULL) && (inLen == NULL))) {
  29363. ret = BAD_FUNC_ARG;
  29364. }
  29365. /* Check key has parameters when encoding curve. */
  29366. if ((ret == 0) && curveIn && (key->dp == NULL)) {
  29367. ret = BAD_FUNC_ARG;
  29368. }
  29369. CALLOC_ASNSETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  29370. if (ret == 0) {
  29371. /* Private key size is the curve size. */
  29372. privSz = (word32)key->dp->size;
  29373. if (pubIn) {
  29374. /* Get the length of the public key. */
  29375. PRIVATE_KEY_UNLOCK();
  29376. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  29377. PRIVATE_KEY_LOCK();
  29378. if (ret == LENGTH_ONLY_E)
  29379. ret = 0;
  29380. }
  29381. }
  29382. if (ret == 0) {
  29383. /* Version: 1 */
  29384. SetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], 1);
  29385. /* Leave space for private key. */
  29386. SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PKEY], NULL, privSz);
  29387. if (curveIn) {
  29388. /* Get length of the named curve OID to put into the encoding. */
  29389. curveIdSz = SetCurve(key, NULL, 0);
  29390. if (curveIdSz < 0) {
  29391. ret = curveIdSz;
  29392. }
  29393. /* Curve OID */
  29394. SetASN_ReplaceBuffer(&dataASN[ECCKEYASN_IDX_CURVEID], NULL,
  29395. (word32)curveIdSz);
  29396. /* TODO: add support for SpecifiedECDomain curve. */
  29397. dataASN[ECCKEYASN_IDX_CURVEPARAMS].noOut = 1;
  29398. }
  29399. else {
  29400. SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PARAMS,
  29401. eccKeyASN_Length);
  29402. }
  29403. if (ret == 0) {
  29404. if (pubIn) {
  29405. /* Leave space for public key. */
  29406. SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PUBKEY_VAL], NULL, pubSz);
  29407. }
  29408. else {
  29409. /* Don't write out public key. */
  29410. SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PUBKEY,
  29411. eccKeyASN_Length);
  29412. }
  29413. /* Calculate size of the private key encoding. */
  29414. ret = SizeASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, &sz);
  29415. }
  29416. }
  29417. /* Return the size if no buffer. */
  29418. if ((ret == 0) && (output == NULL)) {
  29419. *inLen = (word32)sz;
  29420. ret = LENGTH_ONLY_E;
  29421. }
  29422. /* Check the buffer is big enough. */
  29423. if ((ret == 0) && (inLen != NULL) && (sz > (int)*inLen)) {
  29424. ret = BAD_FUNC_ARG;
  29425. }
  29426. if ((ret == 0) && (output != NULL)) {
  29427. /* Encode the private key. */
  29428. SetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, output);
  29429. if (curveIn) {
  29430. /* Put named curve OID data into encoding. */
  29431. curveIdSz = SetCurve(key,
  29432. (byte*)dataASN[ECCKEYASN_IDX_CURVEID].data.buffer.data,
  29433. (size_t)curveIdSz);
  29434. if (curveIdSz < 0) {
  29435. ret = curveIdSz;
  29436. }
  29437. }
  29438. if (ret == 0) {
  29439. /* Export the private value into the buffer. */
  29440. ret = wc_ecc_export_private_only(key,
  29441. (byte*)dataASN[ECCKEYASN_IDX_PKEY].data.buffer.data, &privSz);
  29442. }
  29443. if ((ret == 0) && pubIn) {
  29444. /* Export the public point into the buffer. */
  29445. PRIVATE_KEY_UNLOCK();
  29446. ret = wc_ecc_export_x963(key,
  29447. (byte*)dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.buffer.data,
  29448. &pubSz);
  29449. PRIVATE_KEY_LOCK();
  29450. }
  29451. }
  29452. if (ret == 0) {
  29453. /* Return the encoding size. */
  29454. ret = sz;
  29455. }
  29456. FREE_ASNSETDATA(dataASN, key->heap);
  29457. return ret;
  29458. #endif
  29459. }
  29460. /* Write a Private ecc key, including public to DER format,
  29461. * length on success else < 0 */
  29462. WOLFSSL_ABI
  29463. int wc_EccKeyToDer(ecc_key* key, byte* output, word32 inLen)
  29464. {
  29465. return wc_BuildEccKeyDer(key, output, &inLen, 1, 1);
  29466. }
  29467. /* Write only private ecc key to DER format,
  29468. * length on success else < 0 */
  29469. int wc_EccKeyDerSize(ecc_key* key, int pub)
  29470. {
  29471. word32 sz = 0;
  29472. int ret;
  29473. ret = wc_BuildEccKeyDer(key, NULL, &sz, pub, 1);
  29474. if (ret != LENGTH_ONLY_E) {
  29475. return ret;
  29476. }
  29477. return (int)sz;
  29478. }
  29479. /* Write only private ecc key to DER format,
  29480. * length on success else < 0 */
  29481. int wc_EccPrivateKeyToDer(ecc_key* key, byte* output, word32 inLen)
  29482. {
  29483. return wc_BuildEccKeyDer(key, output, &inLen, 0, 1);
  29484. }
  29485. #ifdef HAVE_PKCS8
  29486. /* Write only private ecc key or both private and public parts to unencrypted
  29487. * PKCS#8 format.
  29488. *
  29489. * If output is NULL, places required PKCS#8 buffer size in outLen and
  29490. * returns LENGTH_ONLY_E.
  29491. *
  29492. * return length on success else < 0 */
  29493. static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen,
  29494. int includePublic)
  29495. {
  29496. int ret;
  29497. word32 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 = (word32)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 = (word32)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 = (int)*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 += (word32)privSz;
  29663. }
  29664. else {
  29665. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  29666. return ASN_PARSE_E;
  29667. priv = input + *inOutIdx;
  29668. *inOutIdx += (word32)privSz;
  29669. endKeyIdx = (int)*inOutIdx;
  29670. }
  29671. if ((word32)privSz > *privKeyLen)
  29672. return BUFFER_E;
  29673. if (endKeyIdx == (int)*inOutIdx) {
  29674. *privKeyLen = (word32)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 += (word32)pubSz;
  29691. *privKeyLen = (word32)privSz;
  29692. XMEMCPY(privKey, priv, *privKeyLen);
  29693. *pubKeyLen = (word32)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((word32)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 = (word32)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((word32)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 = (int)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], (word32)keyType,
  29982. oidKeyType);
  29983. /* Leave space for private key. */
  29984. SetASN_Buffer(&dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], NULL, privKeyLen);
  29985. /* Don't write out attributes. */
  29986. dataASN[EDKEYASN_IDX_ATTRS].noOut = 1;
  29987. if (pubKey) {
  29988. /* Leave space for public key. */
  29989. SetASN_Buffer(&dataASN[EDKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
  29990. }
  29991. else {
  29992. /* Don't put out public part. */
  29993. SetASNItem_NoOutNode(dataASN, edKeyASN, EDKEYASN_IDX_PUBKEY,
  29994. edKeyASN_Length);
  29995. }
  29996. /* Calculate the size of encoding. */
  29997. ret = SizeASN_Items(edKeyASN, dataASN, edKeyASN_Length, &sz);
  29998. }
  29999. /* Check buffer is big enough. */
  30000. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  30001. ret = BAD_FUNC_ARG;
  30002. }
  30003. if ((ret == 0) && (output != NULL)) {
  30004. /* Encode private key. */
  30005. SetASN_Items(edKeyASN, dataASN, edKeyASN_Length, output);
  30006. /* Put private value into space provided. */
  30007. XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.buffer.data,
  30008. privKey, privKeyLen);
  30009. if (pubKey != NULL) {
  30010. /* Put public value into space provided. */
  30011. XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PUBKEY].data.buffer.data,
  30012. pubKey, pubKeyLen);
  30013. }
  30014. }
  30015. if (ret == 0) {
  30016. /* Return size of encoding. */
  30017. ret = sz;
  30018. }
  30019. FREE_ASNSETDATA(dataASN, NULL);
  30020. #endif
  30021. return ret;
  30022. }
  30023. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  30024. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  30025. /* Write a Private ED25519 key, including public to DER format,
  30026. * length on success else < 0 */
  30027. int wc_Ed25519KeyToDer(ed25519_key* key, byte* output, word32 inLen)
  30028. {
  30029. if (key == NULL) {
  30030. return BAD_FUNC_ARG;
  30031. }
  30032. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  30033. key->p, ED25519_PUB_KEY_SIZE, output, inLen, ED25519k);
  30034. }
  30035. /* Write only private ED25519 key to DER format,
  30036. * length on success else < 0 */
  30037. int wc_Ed25519PrivateKeyToDer(ed25519_key* key, byte* output, word32 inLen)
  30038. {
  30039. if (key == NULL) {
  30040. return BAD_FUNC_ARG;
  30041. }
  30042. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  30043. NULL, 0, output, inLen, ED25519k);
  30044. }
  30045. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  30046. #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_EXPORT)
  30047. /* Write only private Curve25519 key to DER format,
  30048. * length on success else < 0 */
  30049. int wc_Curve25519PrivateKeyToDer(curve25519_key* key, byte* output, word32 inLen)
  30050. {
  30051. int ret;
  30052. byte privKey[CURVE25519_KEYSIZE];
  30053. word32 privKeyLen = CURVE25519_KEYSIZE;
  30054. if (key == NULL) {
  30055. return BAD_FUNC_ARG;
  30056. }
  30057. ret = wc_curve25519_export_private_raw(key, privKey, &privKeyLen);
  30058. if (ret == 0) {
  30059. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  30060. X25519k);
  30061. }
  30062. return ret;
  30063. }
  30064. /* Write a public Curve25519 key to DER format,
  30065. * length on success else < 0 */
  30066. int wc_Curve25519PublicKeyToDer(curve25519_key* key, byte* output, word32 inLen,
  30067. int withAlg)
  30068. {
  30069. int ret;
  30070. byte pubKey[CURVE25519_PUB_KEY_SIZE];
  30071. word32 pubKeyLen = (word32)sizeof(pubKey);
  30072. if (key == NULL || output == NULL) {
  30073. return BAD_FUNC_ARG;
  30074. }
  30075. ret = wc_curve25519_export_public(key, pubKey, &pubKeyLen);
  30076. if (ret == 0) {
  30077. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  30078. X25519k, withAlg);
  30079. }
  30080. return ret;
  30081. }
  30082. #endif /* HAVE_CURVE25519 && HAVE_CURVE25519_KEY_EXPORT */
  30083. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  30084. int wc_Ed448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30085. ed448_key* key, word32 inSz)
  30086. {
  30087. int ret;
  30088. byte privKey[ED448_KEY_SIZE], pubKey[ED448_PUB_KEY_SIZE];
  30089. word32 privKeyLen = (word32)sizeof(privKey);
  30090. word32 pubKeyLen = (word32)sizeof(pubKey);
  30091. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30092. return BAD_FUNC_ARG;
  30093. }
  30094. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30095. pubKey, &pubKeyLen, ED448k);
  30096. if (ret == 0) {
  30097. if (pubKeyLen == 0) {
  30098. ret = wc_ed448_import_private_only(privKey, privKeyLen, key);
  30099. }
  30100. else {
  30101. ret = wc_ed448_import_private_key(privKey, privKeyLen,
  30102. pubKey, pubKeyLen, key);
  30103. }
  30104. }
  30105. return ret;
  30106. }
  30107. int wc_Ed448PublicKeyDecode(const byte* input, word32* inOutIdx,
  30108. ed448_key* key, word32 inSz)
  30109. {
  30110. int ret;
  30111. byte pubKey[ED448_PUB_KEY_SIZE];
  30112. word32 pubKeyLen = (word32)sizeof(pubKey);
  30113. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30114. return BAD_FUNC_ARG;
  30115. }
  30116. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30117. pubKey, &pubKeyLen, ED448k);
  30118. if (ret == 0) {
  30119. ret = wc_ed448_import_public(pubKey, pubKeyLen, key);
  30120. }
  30121. return ret;
  30122. }
  30123. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */
  30124. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)
  30125. int wc_Curve448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30126. curve448_key* key, word32 inSz)
  30127. {
  30128. int ret;
  30129. byte privKey[CURVE448_KEY_SIZE];
  30130. word32 privKeyLen = CURVE448_KEY_SIZE;
  30131. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30132. return BAD_FUNC_ARG;
  30133. }
  30134. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30135. NULL, NULL, X448k);
  30136. if (ret == 0) {
  30137. ret = wc_curve448_import_private(privKey, privKeyLen, key);
  30138. }
  30139. return ret;
  30140. }
  30141. int wc_Curve448PublicKeyDecode(const byte* input, word32* inOutIdx,
  30142. curve448_key* key, word32 inSz)
  30143. {
  30144. int ret;
  30145. byte pubKey[CURVE448_PUB_KEY_SIZE];
  30146. word32 pubKeyLen = (word32)sizeof(pubKey);
  30147. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30148. return BAD_FUNC_ARG;
  30149. }
  30150. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30151. pubKey, &pubKeyLen, X448k);
  30152. if (ret == 0) {
  30153. ret = wc_curve448_import_public(pubKey, pubKeyLen, key);
  30154. }
  30155. return ret;
  30156. }
  30157. #endif /* HAVE_CURVE448 && HAVE_ED448_KEY_IMPORT */
  30158. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  30159. /* Write a Private ecc key, including public to DER format,
  30160. * length on success else < 0 */
  30161. int wc_Ed448KeyToDer(ed448_key* key, byte* output, word32 inLen)
  30162. {
  30163. if (key == NULL) {
  30164. return BAD_FUNC_ARG;
  30165. }
  30166. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  30167. key->p, ED448_KEY_SIZE, output, inLen, ED448k);
  30168. }
  30169. /* Write only private ecc key to DER format,
  30170. * length on success else < 0 */
  30171. int wc_Ed448PrivateKeyToDer(ed448_key* key, byte* output, word32 inLen)
  30172. {
  30173. if (key == NULL) {
  30174. return BAD_FUNC_ARG;
  30175. }
  30176. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  30177. NULL, 0, output, inLen, ED448k);
  30178. }
  30179. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  30180. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_EXPORT)
  30181. /* Write private Curve448 key to DER format,
  30182. * length on success else < 0 */
  30183. int wc_Curve448PrivateKeyToDer(curve448_key* key, byte* output, word32 inLen)
  30184. {
  30185. int ret;
  30186. byte privKey[CURVE448_KEY_SIZE];
  30187. word32 privKeyLen = CURVE448_KEY_SIZE;
  30188. if (key == NULL) {
  30189. return BAD_FUNC_ARG;
  30190. }
  30191. ret = wc_curve448_export_private_raw(key, privKey, &privKeyLen);
  30192. if (ret == 0) {
  30193. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  30194. X448k);
  30195. }
  30196. return ret;
  30197. }
  30198. /* Write a public Curve448 key to DER format,
  30199. * length on success else < 0 */
  30200. int wc_Curve448PublicKeyToDer(curve448_key* key, byte* output, word32 inLen,
  30201. int withAlg)
  30202. {
  30203. int ret;
  30204. byte pubKey[CURVE448_PUB_KEY_SIZE];
  30205. word32 pubKeyLen = (word32)sizeof(pubKey);
  30206. if (key == NULL || output == NULL) {
  30207. return BAD_FUNC_ARG;
  30208. }
  30209. ret = wc_curve448_export_public(key, pubKey, &pubKeyLen);
  30210. if (ret == 0) {
  30211. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  30212. X448k, withAlg);
  30213. }
  30214. return ret;
  30215. }
  30216. #endif /* HAVE_CURVE448 && HAVE_CURVE448_KEY_EXPORT */
  30217. #ifndef WOLFSSL_ASN_TEMPLATE
  30218. #if (defined(HAVE_OCSP) || defined(HAVE_CRL)) && !defined(WOLFCRYPT_ONLY)
  30219. /* Get raw Date only, no processing, 0 on success */
  30220. static int GetBasicDate(const byte* source, word32* idx, byte* date,
  30221. byte* format, int maxIdx)
  30222. {
  30223. int ret, length;
  30224. const byte *datePtr = NULL;
  30225. WOLFSSL_ENTER("GetBasicDate");
  30226. ret = GetDateInfo(source, idx, &datePtr, format, &length, maxIdx);
  30227. if (ret < 0)
  30228. return ret;
  30229. XMEMCPY(date, datePtr, length);
  30230. return 0;
  30231. }
  30232. #endif /* HAVE_OCSP || HAVE_CRL */
  30233. #endif /* WOLFSSL_ASN_TEMPLATE */
  30234. #if defined(HAVE_OCSP) && !defined(WOLFCRYPT_ONLY)
  30235. #ifndef WOLFSSL_ASN_TEMPLATE
  30236. static int GetEnumerated(const byte* input, word32* inOutIdx, int *value,
  30237. int sz)
  30238. {
  30239. word32 idx = *inOutIdx;
  30240. word32 len;
  30241. byte tag;
  30242. WOLFSSL_ENTER("GetEnumerated");
  30243. *value = 0;
  30244. if (GetASNTag(input, &idx, &tag, sz) < 0)
  30245. return ASN_PARSE_E;
  30246. if (tag != ASN_ENUMERATED)
  30247. return ASN_PARSE_E;
  30248. if ((int)idx >= sz)
  30249. return BUFFER_E;
  30250. len = input[idx++];
  30251. if (len > 4 || (int)(len + idx) > sz)
  30252. return ASN_PARSE_E;
  30253. while (len--) {
  30254. *value = *value << 8 | input[idx++];
  30255. }
  30256. *inOutIdx = idx;
  30257. return *value;
  30258. }
  30259. #endif /* !WOLFSSL_ASN_TEMPLATE */
  30260. #ifdef WOLFSSL_ASN_TEMPLATE
  30261. /* ASN.1 template for OCSP single response.
  30262. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30263. */
  30264. static const ASNItem singleResponseASN[] = {
  30265. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30266. /* certId */
  30267. /* CID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  30268. /* hashAlgorithm */
  30269. /* CID_HASHALGO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  30270. /* CID_HASHALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  30271. /* CID_HASHALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  30272. /* issuerNameHash */
  30273. /* CID_ISSUERHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  30274. /* issuerKeyHash */
  30275. /* CID_ISSUERKEYHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  30276. /* serialNumber */
  30277. /* CID_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
  30278. /* certStatus - CHOICE */
  30279. /* good [0] IMPLICIT NULL */
  30280. /* CS_GOOD */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 2 },
  30281. /* revoked [1] IMPLICIT RevokedInfo */
  30282. /* CS_REVOKED */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 2 },
  30283. /* revocationTime */
  30284. /* CS_REVOKED_TIME */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30285. /* revocationReason [0] EXPLICIT CRLReason OPTIONAL */
  30286. /* CS_REVOKED_REASON */ { 2, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 1 },
  30287. /* crlReason */
  30288. /* CS_REVOKED_REASON_VAL */ { 3, ASN_ENUMERATED, 0, 0, 0 },
  30289. /* unknown [2] IMPLICIT UnknownInfo ::= NULL */
  30290. /* UNKNOWN */ { 1, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 2 },
  30291. /* thisUpdate */
  30292. /* THISUPDATE_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30293. /* nextUpdate */
  30294. /* NEXTUPDATE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  30295. /* NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30296. /* singleExtensions */
  30297. /* EXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  30298. };
  30299. enum {
  30300. SINGLERESPONSEASN_IDX_SEQ = 0,
  30301. SINGLERESPONSEASN_IDX_CID_SEQ,
  30302. SINGLERESPONSEASN_IDX_CID_HASHALGO_SEQ,
  30303. SINGLERESPONSEASN_IDX_CID_HASHALGO_OID,
  30304. SINGLERESPONSEASN_IDX_CID_HASHALGO_NULL,
  30305. SINGLERESPONSEASN_IDX_CID_ISSUERHASH,
  30306. SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH,
  30307. SINGLERESPONSEASN_IDX_CID_SERIAL,
  30308. SINGLERESPONSEASN_IDX_CS_GOOD,
  30309. SINGLERESPONSEASN_IDX_CS_REVOKED,
  30310. SINGLERESPONSEASN_IDX_CS_REVOKED_TIME,
  30311. SINGLERESPONSEASN_IDX_CS_REVOKED_REASON,
  30312. SINGLERESPONSEASN_IDX_CS_REVOKED_REASON_VAL,
  30313. SINGLERESPONSEASN_IDX_UNKNOWN,
  30314. SINGLERESPONSEASN_IDX_THISUPDATE_GT,
  30315. SINGLERESPONSEASN_IDX_NEXTUPDATE,
  30316. SINGLERESPONSEASN_IDX_NEXTUPDATE_GT,
  30317. SINGLERESPONSEASN_IDX_EXT,
  30318. };
  30319. /* Number of items in ASN.1 template for OCSP single response. */
  30320. #define singleResponseASN_Length (sizeof(singleResponseASN) / sizeof(ASNItem))
  30321. #endif
  30322. static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size,
  30323. int wrapperSz, OcspEntry* single)
  30324. {
  30325. #ifndef WOLFSSL_ASN_TEMPLATE
  30326. word32 idx = *ioIndex, prevIndex, oid, localIdx, certIdIdx;
  30327. int length;
  30328. int ret;
  30329. byte tag;
  30330. WOLFSSL_ENTER("DecodeSingleResponse");
  30331. prevIndex = idx;
  30332. /* Wrapper around the Single Response */
  30333. if (GetSequence(source, &idx, &length, size) < 0)
  30334. return ASN_PARSE_E;
  30335. /* Wrapper around the CertID */
  30336. certIdIdx = idx;
  30337. if (GetSequence(source, &idx, &length, size) < 0)
  30338. return ASN_PARSE_E;
  30339. single->rawCertId = source + certIdIdx;
  30340. /* Hash algorithm */
  30341. ret = GetAlgoId(source, &idx, &oid, oidIgnoreType, size);
  30342. if (ret < 0)
  30343. return ret;
  30344. single->hashAlgoOID = oid;
  30345. /* Save reference to the hash of CN */
  30346. ret = GetOctetString(source, &idx, &length, size);
  30347. if (ret < 0)
  30348. return ret;
  30349. if (length > (int)sizeof(single->issuerHash))
  30350. return BUFFER_E;
  30351. XMEMCPY(single->issuerHash, source + idx, length);
  30352. idx += length;
  30353. /* Save reference to the hash of the issuer public key */
  30354. ret = GetOctetString(source, &idx, &length, size);
  30355. if (ret < 0)
  30356. return ret;
  30357. if (length > (int)sizeof(single->issuerKeyHash))
  30358. return BUFFER_E;
  30359. XMEMCPY(single->issuerKeyHash, source + idx, length);
  30360. idx += length;
  30361. /* Get serial number */
  30362. if (wc_GetSerialNumber(source, &idx, single->status->serial,
  30363. &single->status->serialSz, size) < 0)
  30364. return ASN_PARSE_E;
  30365. single->rawCertIdSize = idx - certIdIdx;
  30366. if (idx >= size)
  30367. return BUFFER_E;
  30368. /* CertStatus */
  30369. switch (source[idx++])
  30370. {
  30371. case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
  30372. single->status->status = CERT_GOOD;
  30373. idx++;
  30374. break;
  30375. case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
  30376. single->status->status = CERT_REVOKED;
  30377. if (GetLength(source, &idx, &length, size) < 0)
  30378. return ASN_PARSE_E;
  30379. idx += length;
  30380. break;
  30381. case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
  30382. single->status->status = CERT_UNKNOWN;
  30383. idx++;
  30384. break;
  30385. default:
  30386. return ASN_PARSE_E;
  30387. }
  30388. if (idx >= size)
  30389. return BUFFER_E;
  30390. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  30391. single->status->thisDateAsn = source + idx;
  30392. localIdx = 0;
  30393. if (GetDateInfo(single->status->thisDateAsn, &localIdx, NULL,
  30394. (byte*)&single->status->thisDateParsed.type,
  30395. &single->status->thisDateParsed.length, size - idx) < 0)
  30396. return ASN_PARSE_E;
  30397. if (idx + localIdx >= size)
  30398. return BUFFER_E;
  30399. XMEMCPY(single->status->thisDateParsed.data,
  30400. single->status->thisDateAsn + localIdx - single->status->thisDateParsed.length,
  30401. single->status->thisDateParsed.length);
  30402. #endif
  30403. if (GetBasicDate(source, &idx, single->status->thisDate,
  30404. &single->status->thisDateFormat, size) < 0)
  30405. return ASN_PARSE_E;
  30406. #ifndef NO_ASN_TIME_CHECK
  30407. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  30408. if (!XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, BEFORE))
  30409. return ASN_BEFORE_DATE_E;
  30410. #endif
  30411. #endif
  30412. /* The following items are optional. Only check for them if there is more
  30413. * unprocessed data in the singleResponse wrapper. */
  30414. localIdx = idx;
  30415. if (((int)(idx - prevIndex) < wrapperSz) &&
  30416. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30417. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  30418. {
  30419. idx++;
  30420. if (GetLength(source, &idx, &length, size) < 0)
  30421. return ASN_PARSE_E;
  30422. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  30423. single->status->nextDateAsn = source + idx;
  30424. localIdx = 0;
  30425. if (GetDateInfo(single->status->nextDateAsn, &localIdx, NULL,
  30426. (byte*)&single->status->nextDateParsed.type,
  30427. &single->status->nextDateParsed.length, size - idx) < 0)
  30428. return ASN_PARSE_E;
  30429. if (idx + localIdx >= size)
  30430. return BUFFER_E;
  30431. XMEMCPY(single->status->nextDateParsed.data,
  30432. single->status->nextDateAsn + localIdx - single->status->nextDateParsed.length,
  30433. single->status->nextDateParsed.length);
  30434. #endif
  30435. if (GetBasicDate(source, &idx, single->status->nextDate,
  30436. &single->status->nextDateFormat, size) < 0)
  30437. return ASN_PARSE_E;
  30438. #ifndef NO_ASN_TIME_CHECK
  30439. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  30440. if (!XVALIDATE_DATE(single->status->nextDate, single->status->nextDateFormat, AFTER))
  30441. return ASN_AFTER_DATE_E;
  30442. #endif
  30443. #endif
  30444. }
  30445. /* Skip the optional extensions in singleResponse. */
  30446. localIdx = idx;
  30447. if (((int)(idx - prevIndex) < wrapperSz) &&
  30448. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30449. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  30450. {
  30451. idx++;
  30452. if (GetLength(source, &idx, &length, size) < 0)
  30453. return ASN_PARSE_E;
  30454. idx += length;
  30455. }
  30456. *ioIndex = idx;
  30457. return 0;
  30458. #else
  30459. DECL_ASNGETDATA(dataASN, singleResponseASN_Length);
  30460. int ret = 0;
  30461. CertStatus* cs = NULL;
  30462. word32 serialSz;
  30463. word32 issuerHashLen;
  30464. word32 issuerKeyHashLen;
  30465. word32 thisDateLen;
  30466. word32 nextDateLen;
  30467. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30468. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30469. WOLFSSL_ASN1_TIME *at;
  30470. #endif
  30471. (void)wrapperSz;
  30472. WOLFSSL_ENTER("DecodeSingleResponse");
  30473. CALLOC_ASNGETDATA(dataASN, singleResponseASN_Length, ret, NULL);
  30474. if (ret == 0) {
  30475. /* Certificate Status field. */
  30476. cs = single->status;
  30477. /* Set maximum lengths for data. */
  30478. issuerHashLen = OCSP_DIGEST_SIZE;
  30479. issuerKeyHashLen = OCSP_DIGEST_SIZE;
  30480. serialSz = EXTERNAL_SERIAL_SIZE;
  30481. thisDateLen = MAX_DATE_SIZE;
  30482. nextDateLen = MAX_DATE_SIZE;
  30483. /* Set OID type, buffers to hold data and variables to hold size. */
  30484. GetASN_OID(&dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID],
  30485. oidHashType);
  30486. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERHASH],
  30487. single->issuerHash, &issuerHashLen);
  30488. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH],
  30489. single->issuerKeyHash, &issuerKeyHashLen);
  30490. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_SERIAL], cs->serial,
  30491. &serialSz);
  30492. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT],
  30493. cs->thisDate, &thisDateLen);
  30494. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT],
  30495. cs->nextDate, &nextDateLen);
  30496. /* TODO: decode revoked time and reason. */
  30497. /* Decode OCSP single response. */
  30498. ret = GetASN_Items(singleResponseASN, dataASN, singleResponseASN_Length,
  30499. 1, source, ioIndex, size);
  30500. }
  30501. /* Validate the issuer hash length is the size required. */
  30502. if ((ret == 0) && (issuerHashLen != OCSP_DIGEST_SIZE)) {
  30503. ret = ASN_PARSE_E;
  30504. }
  30505. /* Validate the issuer key hash length is the size required. */
  30506. if ((ret == 0) && (issuerKeyHashLen != OCSP_DIGEST_SIZE)) {
  30507. ret = ASN_PARSE_E;
  30508. }
  30509. if (ret == 0) {
  30510. /* Store serial size. */
  30511. cs->serialSz = serialSz;
  30512. /* Determine status by which item was found. */
  30513. if (dataASN[SINGLERESPONSEASN_IDX_CS_GOOD].tag != 0) {
  30514. cs->status = CERT_GOOD;
  30515. }
  30516. if (dataASN[SINGLERESPONSEASN_IDX_CS_REVOKED].tag != 0) {
  30517. cs->status = CERT_REVOKED;
  30518. }
  30519. if (dataASN[SINGLERESPONSEASN_IDX_UNKNOWN].tag != 0) {
  30520. cs->status = CERT_UNKNOWN;
  30521. }
  30522. /* Store the thisDate format - only one possible. */
  30523. cs->thisDateFormat = ASN_GENERALIZED_TIME;
  30524. #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  30525. /* Check date is a valid string and BEFORE now. */
  30526. if (!XVALIDATE_DATE(cs->thisDate, ASN_GENERALIZED_TIME, BEFORE)) {
  30527. ret = ASN_BEFORE_DATE_E;
  30528. }
  30529. }
  30530. if (ret == 0) {
  30531. #endif
  30532. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30533. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30534. /* Store ASN.1 version of thisDate. */
  30535. cs->thisDateAsn = GetASNItem_Addr(
  30536. dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT], source);
  30537. at = &cs->thisDateParsed;
  30538. at->type = ASN_GENERALIZED_TIME;
  30539. XMEMCPY(at->data, cs->thisDate, thisDateLen);
  30540. at->length = thisDateLen;
  30541. #endif
  30542. }
  30543. if ((ret == 0) &&
  30544. (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
  30545. /* Store the nextDate format - only one possible. */
  30546. cs->nextDateFormat = ASN_GENERALIZED_TIME;
  30547. #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  30548. /* Check date is a valid string and AFTER now. */
  30549. if (!XVALIDATE_DATE(cs->nextDate, ASN_GENERALIZED_TIME, AFTER)) {
  30550. ret = ASN_AFTER_DATE_E;
  30551. }
  30552. }
  30553. if ((ret == 0) &&
  30554. (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
  30555. #endif
  30556. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30557. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30558. /* Store ASN.1 version of thisDate. */
  30559. cs->nextDateAsn = GetASNItem_Addr(
  30560. dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT], source);
  30561. at = &cs->nextDateParsed;
  30562. at->type = ASN_GENERALIZED_TIME;
  30563. XMEMCPY(at->data, cs->nextDate, nextDateLen);
  30564. at->length = nextDateLen;
  30565. #endif
  30566. }
  30567. if (ret == 0) {
  30568. /* OcspEntry now used. */
  30569. single->used = 1;
  30570. }
  30571. FREE_ASNGETDATA(dataASN, NULL);
  30572. return ret;
  30573. #endif
  30574. }
  30575. #ifdef WOLFSSL_ASN_TEMPLATE
  30576. /* ASN.1 template for OCSP response extension header.
  30577. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30578. */
  30579. static const ASNItem respExtHdrASN[] = {
  30580. /* responseExtensions */
  30581. /* EXT */ { 0, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 0 },
  30582. /* extensions */
  30583. /* EXT_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  30584. };
  30585. enum {
  30586. RESPEXTHDRASN_IDX_EXT = 0,
  30587. RESPEXTHDRASN_IDX_EXT_SEQ,
  30588. };
  30589. /* Number of items in ASN.1 template for OCSP response extension header. */
  30590. #define respExtHdrASN_Length (sizeof(respExtHdrASN) / sizeof(ASNItem))
  30591. #endif
  30592. static int DecodeOcspRespExtensions(byte* source, word32* ioIndex,
  30593. OcspResponse* resp, word32 sz)
  30594. {
  30595. #ifndef WOLFSSL_ASN_TEMPLATE
  30596. word32 idx = *ioIndex;
  30597. int length;
  30598. int ext_bound; /* boundary index for the sequence of extensions */
  30599. word32 oid;
  30600. int ret;
  30601. byte tag;
  30602. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  30603. if ((idx + 1) > sz)
  30604. return BUFFER_E;
  30605. if (GetASNTag(source, &idx, &tag, sz) < 0)
  30606. return ASN_PARSE_E;
  30607. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  30608. return ASN_PARSE_E;
  30609. if (GetLength(source, &idx, &length, sz) < 0)
  30610. return ASN_PARSE_E;
  30611. if (GetSequence(source, &idx, &length, sz) < 0)
  30612. return ASN_PARSE_E;
  30613. ext_bound = idx + length;
  30614. while (idx < (word32)ext_bound) {
  30615. word32 localIdx;
  30616. if (GetSequence(source, &idx, &length, sz) < 0) {
  30617. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  30618. return ASN_PARSE_E;
  30619. }
  30620. oid = 0;
  30621. if (GetObjectId(source, &idx, &oid, oidOcspType, sz) < 0) {
  30622. WOLFSSL_MSG("\tfail: OBJECT ID");
  30623. return ASN_PARSE_E;
  30624. }
  30625. /* check for critical flag */
  30626. if ((idx + 1) > (word32)sz) {
  30627. WOLFSSL_MSG("\tfail: malformed buffer");
  30628. return BUFFER_E;
  30629. }
  30630. localIdx = idx;
  30631. if (GetASNTag(source, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  30632. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  30633. ret = GetBoolean(source, &idx, sz);
  30634. if (ret < 0)
  30635. return ret;
  30636. }
  30637. ret = GetOctetString(source, &idx, &length, sz);
  30638. if (ret < 0)
  30639. return ret;
  30640. if (oid == OCSP_NONCE_OID) {
  30641. /* get data inside extra OCTET_STRING */
  30642. ret = GetOctetString(source, &idx, &length, sz);
  30643. if (ret < 0)
  30644. return ret;
  30645. resp->nonce = source + idx;
  30646. resp->nonceSz = length;
  30647. }
  30648. idx += length;
  30649. }
  30650. *ioIndex = idx;
  30651. return 0;
  30652. #else
  30653. /* certExtASN_Length is greater than respExtHdrASN_Length */
  30654. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  30655. int ret = 0;
  30656. word32 idx = *ioIndex;
  30657. word32 maxIdx = 0;
  30658. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  30659. CALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, resp->heap);
  30660. if (ret == 0) {
  30661. /* Check for header and move past. */
  30662. ret = GetASN_Items(respExtHdrASN, dataASN, respExtHdrASN_Length, 0,
  30663. source, &idx, sz);
  30664. }
  30665. if (ret == 0) {
  30666. /* Keep end extensions index for total length check. */
  30667. maxIdx = idx + dataASN[RESPEXTHDRASN_IDX_EXT_SEQ].length;
  30668. }
  30669. /* Step through all extensions. */
  30670. while ((ret == 0) && (idx < maxIdx)) {
  30671. /* Clear dynamic data, set OID type to expect. */
  30672. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  30673. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidOcspType);
  30674. /* TODO: check criticality. */
  30675. /* Decode OCSP response extension. */
  30676. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0,
  30677. source, &idx, sz);
  30678. if (ret == 0) {
  30679. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  30680. int length = dataASN[CERTEXTASN_IDX_VAL].length;
  30681. if (oid == OCSP_NONCE_OID) {
  30682. /* Extract nonce data. */
  30683. ret = GetOctetString(source, &idx, &length, sz);
  30684. if (ret >= 0) {
  30685. ret = 0;
  30686. /* get data inside extra OCTET_STRING */
  30687. resp->nonce = source + idx;
  30688. resp->nonceSz = length;
  30689. }
  30690. }
  30691. /* Ignore all other extension types. */
  30692. /* Skip over rest of extension. */
  30693. idx += length;
  30694. }
  30695. }
  30696. /* Return index after extensions. */
  30697. *ioIndex = idx;
  30698. FREE_ASNGETDATA(dataASN, resp->heap);
  30699. return ret;
  30700. #endif
  30701. }
  30702. #ifdef WOLFSSL_ASN_TEMPLATE
  30703. /* ASN.1 template for OCSP ResponseData.
  30704. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30705. */
  30706. static const ASNItem ocspRespDataASN[] = {
  30707. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30708. /* version DEFAULT v1 */
  30709. /* VER_PRESENT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  30710. /* VER */ { 2, ASN_INTEGER, 1, 0, 0 },
  30711. /* byName */
  30712. /* BYNAME */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  30713. /* byKey */
  30714. /* BYKEY */ { 1, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 2 },
  30715. /* producedAt */
  30716. /* PA */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0, },
  30717. /* responses */
  30718. /* RESP */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  30719. /* responseExtensions */
  30720. /* RESPEXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 }
  30721. };
  30722. enum {
  30723. OCSPRESPDATAASN_IDX_SEQ = 0,
  30724. OCSPRESPDATAASN_IDX_VER_PRESENT,
  30725. OCSPRESPDATAASN_IDX_VER,
  30726. OCSPRESPDATAASN_IDX_BYNAME,
  30727. OCSPRESPDATAASN_IDX_BYKEY,
  30728. OCSPRESPDATAASN_IDX_PA,
  30729. OCSPRESPDATAASN_IDX_RESP,
  30730. OCSPRESPDATAASN_IDX_RESPEXT,
  30731. };
  30732. /* Number of items in ASN.1 template for OCSP ResponseData. */
  30733. #define ocspRespDataASN_Length (sizeof(ocspRespDataASN) / sizeof(ASNItem))
  30734. #endif
  30735. static int DecodeResponseData(byte* source, word32* ioIndex,
  30736. OcspResponse* resp, word32 size)
  30737. {
  30738. #ifndef WOLFSSL_ASN_TEMPLATE
  30739. word32 idx = *ioIndex, prev_idx, localIdx;
  30740. int length;
  30741. int version;
  30742. int ret;
  30743. byte tag;
  30744. int wrapperSz;
  30745. OcspEntry* single;
  30746. WOLFSSL_ENTER("DecodeResponseData");
  30747. resp->response = source + idx;
  30748. prev_idx = idx;
  30749. if (GetSequence(source, &idx, &length, size) < 0)
  30750. return ASN_PARSE_E;
  30751. resp->responseSz = length + idx - prev_idx;
  30752. /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
  30753. * item isn't an EXPLICIT[0], then set version to zero and move
  30754. * onto the next item.
  30755. */
  30756. localIdx = idx;
  30757. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30758. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
  30759. {
  30760. idx += 2; /* Eat the value and length */
  30761. if (GetMyVersion(source, &idx, &version, size) < 0)
  30762. return ASN_PARSE_E;
  30763. } else
  30764. version = 0;
  30765. localIdx = idx;
  30766. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30767. ( tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1) ||
  30768. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2) ))
  30769. {
  30770. idx++; /* advance past ASN tag */
  30771. if (GetLength(source, &idx, &length, size) < 0)
  30772. return ASN_PARSE_E;
  30773. idx += length;
  30774. }
  30775. else
  30776. return ASN_PARSE_E;
  30777. /* save pointer to the producedAt time */
  30778. if (GetBasicDate(source, &idx, resp->producedDate,
  30779. &resp->producedDateFormat, size) < 0)
  30780. return ASN_PARSE_E;
  30781. /* Outer wrapper of the SEQUENCE OF Single Responses. */
  30782. if (GetSequence(source, &idx, &wrapperSz, size) < 0)
  30783. return ASN_PARSE_E;
  30784. localIdx = idx;
  30785. single = resp->single;
  30786. while (idx - localIdx < (word32)wrapperSz) {
  30787. ret = DecodeSingleResponse(source, &idx, size, wrapperSz, single);
  30788. if (ret < 0)
  30789. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  30790. if (idx - localIdx < (word32)wrapperSz) {
  30791. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  30792. DYNAMIC_TYPE_OCSP_ENTRY);
  30793. if (single->next == NULL) {
  30794. return MEMORY_E;
  30795. }
  30796. XMEMSET(single->next, 0, sizeof(OcspEntry));
  30797. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  30798. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  30799. if (single->next->status == NULL) {
  30800. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  30801. single->next = NULL;
  30802. return MEMORY_E;
  30803. }
  30804. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  30805. single->next->isDynamic = 1;
  30806. single = single->next;
  30807. }
  30808. }
  30809. /*
  30810. * Check the length of the ResponseData against the current index to
  30811. * see if there are extensions, they are optional.
  30812. */
  30813. if (idx - prev_idx < resp->responseSz)
  30814. if (DecodeOcspRespExtensions(source, &idx, resp, size) < 0)
  30815. return ASN_PARSE_E;
  30816. *ioIndex = idx;
  30817. return 0;
  30818. #else
  30819. DECL_ASNGETDATA(dataASN, ocspRespDataASN_Length);
  30820. int ret = 0;
  30821. byte version;
  30822. word32 dateSz, idx = *ioIndex;
  30823. OcspEntry* single = NULL;
  30824. WOLFSSL_ENTER("DecodeResponseData");
  30825. CALLOC_ASNGETDATA(dataASN, ocspRespDataASN_Length, ret, resp->heap);
  30826. if (ret == 0) {
  30827. resp->response = source + idx;
  30828. /* Default, not present, is v1 = 0. */
  30829. version = 0;
  30830. /* Max size of date supported. */
  30831. dateSz = MAX_DATE_SIZE;
  30832. /* Set the where to put version an produced date. */
  30833. GetASN_Int8Bit(&dataASN[OCSPRESPDATAASN_IDX_VER], &version);
  30834. GetASN_Buffer(&dataASN[OCSPRESPDATAASN_IDX_PA], resp->producedDate,
  30835. &dateSz);
  30836. /* Decode the ResponseData. */
  30837. ret = GetASN_Items(ocspRespDataASN, dataASN, ocspRespDataASN_Length,
  30838. 1, source, ioIndex, size);
  30839. }
  30840. /* Only support v1 == 0 */
  30841. if ((ret == 0) && (version != 0)) {
  30842. ret = ASN_PARSE_E;
  30843. }
  30844. /* Ensure date is a minimal size. */
  30845. if ((ret == 0) && (dateSz < MIN_DATE_SIZE)) {
  30846. ret = ASN_PARSE_E;
  30847. }
  30848. if (ret == 0) {
  30849. /* TODO: use byName/byKey fields. */
  30850. /* Store size of response. */
  30851. resp->responseSz = *ioIndex - idx;
  30852. /* Store date format/tag. */
  30853. resp->producedDateFormat = dataASN[OCSPRESPDATAASN_IDX_PA].tag;
  30854. /* Get the index of the responses SEQUENCE. */
  30855. idx = GetASNItem_DataIdx(dataASN[OCSPRESPDATAASN_IDX_RESP], source);
  30856. /* Start with the pre-existing OcspEntry. */
  30857. single = resp->single;
  30858. }
  30859. while ((ret == 0) && (idx < dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset)) {
  30860. /* Allocate and use a new OCSP entry if this is used. */
  30861. if (single->used) {
  30862. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  30863. DYNAMIC_TYPE_OCSP_ENTRY);
  30864. if (single->next == NULL) {
  30865. ret = MEMORY_E;
  30866. }
  30867. else {
  30868. XMEMSET(single->next, 0, sizeof(OcspEntry));
  30869. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  30870. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  30871. if (single->next->status == NULL) {
  30872. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  30873. single->next = NULL;
  30874. ret = MEMORY_E;
  30875. }
  30876. else {
  30877. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  30878. /* Entry to be freed. */
  30879. single->next->isDynamic = 1;
  30880. /* used will be 0 (false) */
  30881. single = single->next;
  30882. }
  30883. }
  30884. }
  30885. if (ret == 0) {
  30886. /* Decode SingleResponse into OcspEntry. */
  30887. ret = DecodeSingleResponse(source, &idx,
  30888. dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset,
  30889. dataASN[OCSPRESPDATAASN_IDX_RESP].length, single);
  30890. /* single->used set on successful decode. */
  30891. }
  30892. }
  30893. /* Check if there were extensions. */
  30894. if ((ret == 0) &&
  30895. (dataASN[OCSPRESPDATAASN_IDX_RESPEXT].data.buffer.data != NULL)) {
  30896. /* Get index of [1] */
  30897. idx = dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset;
  30898. /* Decode the response extensions. */
  30899. if (DecodeOcspRespExtensions(source, &idx, resp, *ioIndex) < 0) {
  30900. ret = ASN_PARSE_E;
  30901. }
  30902. }
  30903. FREE_ASNGETDATA(dataASN, resp->heap);
  30904. return ret;
  30905. #endif
  30906. }
  30907. #ifndef WOLFSSL_ASN_TEMPLATE
  30908. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  30909. static int DecodeCerts(byte* source,
  30910. word32* ioIndex, OcspResponse* resp, word32 size)
  30911. {
  30912. word32 idx = *ioIndex;
  30913. byte tag;
  30914. WOLFSSL_ENTER("DecodeCerts");
  30915. if (GetASNTag(source, &idx, &tag, size) < 0)
  30916. return ASN_PARSE_E;
  30917. if (tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
  30918. {
  30919. int length;
  30920. if (GetLength(source, &idx, &length, size) < 0)
  30921. return ASN_PARSE_E;
  30922. if (GetSequence(source, &idx, &length, size) < 0)
  30923. return ASN_PARSE_E;
  30924. resp->cert = source + idx;
  30925. resp->certSz = length;
  30926. idx += length;
  30927. }
  30928. *ioIndex = idx;
  30929. return 0;
  30930. }
  30931. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  30932. #endif /* !WOLFSSL_ASN_TEMPLATE */
  30933. #ifdef WOLFSSL_ASN_TEMPLATE
  30934. /* ASN.1 template for BasicOCSPResponse.
  30935. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30936. */
  30937. static const ASNItem ocspBasicRespASN[] = {
  30938. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30939. /* tbsResponseData */
  30940. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0, },
  30941. /* signatureAlgorithm */
  30942. /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0, },
  30943. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  30944. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  30945. /* parameters */
  30946. #ifdef WC_RSA_PSS
  30947. /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  30948. #endif
  30949. /* signature */
  30950. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  30951. /* certs */
  30952. /* CERTS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  30953. /* CERTS_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0, },
  30954. };
  30955. enum {
  30956. OCSPBASICRESPASN_IDX_SEQ = 0,
  30957. OCSPBASICRESPASN_IDX_TBS_SEQ,
  30958. OCSPBASICRESPASN_IDX_SIGALGO,
  30959. OCSPBASICRESPASN_IDX_SIGALGO_OID,
  30960. OCSPBASICRESPASN_IDX_SIGALGO_NULL,
  30961. #ifdef WC_RSA_PSS
  30962. OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS,
  30963. #endif
  30964. OCSPBASICRESPASN_IDX_SIGNATURE,
  30965. OCSPBASICRESPASN_IDX_CERTS,
  30966. OCSPBASICRESPASN_IDX_CERTS_SEQ,
  30967. };
  30968. /* Number of items in ASN.1 template for BasicOCSPResponse. */
  30969. #define ocspBasicRespASN_Length (sizeof(ocspBasicRespASN) / sizeof(ASNItem))
  30970. #endif /* WOLFSSL_ASN_TEMPLATE */
  30971. static int DecodeBasicOcspResponse(byte* source, word32* ioIndex,
  30972. OcspResponse* resp, word32 size, void* cm, void* heap, int noVerify)
  30973. {
  30974. #ifndef WOLFSSL_ASN_TEMPLATE
  30975. int length;
  30976. word32 idx = *ioIndex;
  30977. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  30978. word32 end_index;
  30979. #endif
  30980. int ret;
  30981. int sigLength;
  30982. const byte* sigParams = NULL;
  30983. word32 sigParamsSz = 0;
  30984. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  30985. (void)heap;
  30986. if (GetSequence(source, &idx, &length, size) < 0)
  30987. return ASN_PARSE_E;
  30988. if (idx + length > size)
  30989. return ASN_INPUT_E;
  30990. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  30991. end_index = idx + length;
  30992. #endif
  30993. if ((ret = DecodeResponseData(source, &idx, resp, size)) < 0)
  30994. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  30995. /* Get the signature algorithm */
  30996. if (GetAlgoId(source, &idx, &resp->sigOID, oidSigType, size) < 0) {
  30997. return ASN_PARSE_E;
  30998. }
  30999. #ifdef WC_RSA_PSS
  31000. else if (resp->sigOID == CTC_RSASSAPSS) {
  31001. word32 sz;
  31002. int len;
  31003. const byte* params;
  31004. sz = idx;
  31005. params = source + idx;
  31006. if (GetSequence(source, &idx, &len, size) < 0)
  31007. ret = ASN_PARSE_E;
  31008. if (ret == 0) {
  31009. idx += len;
  31010. sigParams = params;
  31011. sigParamsSz = idx - sz;
  31012. }
  31013. }
  31014. #endif
  31015. ret = CheckBitString(source, &idx, &sigLength, size, 1, NULL);
  31016. if (ret != 0)
  31017. return ret;
  31018. resp->sigSz = sigLength;
  31019. resp->sig = source + idx;
  31020. idx += sigLength;
  31021. /*
  31022. * Check the length of the BasicOcspResponse against the current index to
  31023. * see if there are certificates, they are optional.
  31024. */
  31025. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31026. if (idx < end_index)
  31027. {
  31028. int cert_inited = 0;
  31029. #ifdef WOLFSSL_SMALL_STACK
  31030. DecodedCert *cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  31031. DYNAMIC_TYPE_TMP_BUFFER);
  31032. if (cert == NULL)
  31033. return MEMORY_E;
  31034. #else
  31035. DecodedCert cert[1];
  31036. #endif
  31037. do {
  31038. if (DecodeCerts(source, &idx, resp, size) < 0) {
  31039. ret = ASN_PARSE_E;
  31040. break;
  31041. }
  31042. InitDecodedCert(cert, resp->cert, resp->certSz, heap);
  31043. cert_inited = 1;
  31044. /* Don't verify if we don't have access to Cert Manager. */
  31045. ret = ParseCertRelative(cert, CERT_TYPE,
  31046. noVerify ? NO_VERIFY : VERIFY_OCSP_CERT,
  31047. cm);
  31048. if (ret < 0) {
  31049. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  31050. break;
  31051. }
  31052. #ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK
  31053. if ((cert->extExtKeyUsage & EXTKEYUSE_OCSP_SIGN) == 0) {
  31054. if (XMEMCMP(cert->subjectHash,
  31055. resp->single->issuerHash, OCSP_DIGEST_SIZE) == 0) {
  31056. WOLFSSL_MSG("\tOCSP Response signed by issuer");
  31057. }
  31058. else {
  31059. WOLFSSL_MSG("\tOCSP Responder key usage check failed");
  31060. #ifdef OPENSSL_EXTRA
  31061. resp->verifyError = OCSP_BAD_ISSUER;
  31062. #else
  31063. ret = BAD_OCSP_RESPONDER;
  31064. break;
  31065. #endif
  31066. }
  31067. }
  31068. #endif
  31069. /* ConfirmSignature is blocking here */
  31070. ret = ConfirmSignature(
  31071. &cert->sigCtx,
  31072. resp->response, resp->responseSz,
  31073. cert->publicKey, cert->pubKeySize, cert->keyOID,
  31074. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31075. NULL);
  31076. if (ret != 0) {
  31077. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31078. ret = ASN_OCSP_CONFIRM_E;
  31079. break;
  31080. }
  31081. } while(0);
  31082. if (cert_inited)
  31083. FreeDecodedCert(cert);
  31084. #ifdef WOLFSSL_SMALL_STACK
  31085. XFREE(cert, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31086. #endif
  31087. if (ret != 0)
  31088. return ret;
  31089. }
  31090. else
  31091. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  31092. {
  31093. Signer* ca;
  31094. int sigValid = -1;
  31095. #ifndef NO_SKID
  31096. ca = GetCA(cm, resp->single->issuerKeyHash);
  31097. #else
  31098. ca = GetCA(cm, resp->single->issuerHash);
  31099. #endif
  31100. if (ca) {
  31101. SignatureCtx sigCtx;
  31102. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  31103. /* ConfirmSignature is blocking here */
  31104. sigValid = ConfirmSignature(&sigCtx, resp->response,
  31105. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  31106. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31107. NULL);
  31108. }
  31109. if (ca == NULL || sigValid != 0) {
  31110. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31111. return ASN_OCSP_CONFIRM_E;
  31112. }
  31113. (void)noVerify;
  31114. }
  31115. *ioIndex = idx;
  31116. return 0;
  31117. #else
  31118. DECL_ASNGETDATA(dataASN, ocspBasicRespASN_Length);
  31119. int ret = 0;
  31120. word32 idx = *ioIndex;
  31121. const byte* sigParams = NULL;
  31122. word32 sigParamsSz = 0;
  31123. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31124. #ifdef WOLFSSL_SMALL_STACK
  31125. DecodedCert* cert = NULL;
  31126. #else
  31127. DecodedCert cert[1];
  31128. #endif
  31129. int certInit = 0;
  31130. #endif
  31131. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  31132. (void)heap;
  31133. CALLOC_ASNGETDATA(dataASN, ocspBasicRespASN_Length, ret, heap);
  31134. if (ret == 0) {
  31135. /* Set expecting signature OID. */
  31136. GetASN_OID(&dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID], oidSigType);
  31137. /* Decode BasicOCSPResponse. */
  31138. ret = GetASN_Items(ocspBasicRespASN, dataASN, ocspBasicRespASN_Length,
  31139. 1, source, &idx, size);
  31140. }
  31141. if (ret == 0) {
  31142. word32 dataIdx = 0;
  31143. /* Decode the response data. */
  31144. if (DecodeResponseData(
  31145. GetASNItem_Addr(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source),
  31146. &dataIdx, resp,
  31147. GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source)
  31148. ) < 0) {
  31149. ret = ASN_PARSE_E;
  31150. }
  31151. }
  31152. #ifdef WC_RSA_PSS
  31153. if (ret == 0 && (dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS].tag != 0)) {
  31154. sigParams = GetASNItem_Addr(
  31155. dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
  31156. source);
  31157. sigParamsSz =
  31158. GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
  31159. source);
  31160. }
  31161. #endif
  31162. if (ret == 0) {
  31163. /* Get the signature OID and signature. */
  31164. resp->sigOID = dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID].data.oid.sum;
  31165. GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_SIGNATURE], &resp->sig,
  31166. &resp->sigSz);
  31167. }
  31168. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31169. if ((ret == 0) &&
  31170. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31171. /* TODO: support more than one certificate. */
  31172. /* Store reference to certificate BER data. */
  31173. GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ], &resp->cert,
  31174. &resp->certSz);
  31175. /* Allocate a certificate object to decode cert into. */
  31176. #ifdef WOLFSSL_SMALL_STACK
  31177. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), heap,
  31178. DYNAMIC_TYPE_TMP_BUFFER);
  31179. if (cert == NULL) {
  31180. ret = MEMORY_E;
  31181. }
  31182. }
  31183. if ((ret == 0) &&
  31184. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31185. #endif
  31186. /* Initialize the crtificate object. */
  31187. InitDecodedCert(cert, resp->cert, resp->certSz, heap);
  31188. certInit = 1;
  31189. /* Parse the certificate and don't verify if we don't have access to
  31190. * Cert Manager. */
  31191. ret = ParseCertRelative(cert, CERT_TYPE, noVerify ? NO_VERIFY : VERIFY,
  31192. cm);
  31193. if (ret < 0) {
  31194. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  31195. }
  31196. }
  31197. if ((ret == 0) &&
  31198. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31199. /* TODO: ConfirmSignature is blocking here */
  31200. /* Check the signature of the response. */
  31201. ret = ConfirmSignature(&cert->sigCtx, resp->response, resp->responseSz,
  31202. cert->publicKey, cert->pubKeySize, cert->keyOID, resp->sig,
  31203. resp->sigSz, resp->sigOID, NULL, 0, NULL);
  31204. if (ret != 0) {
  31205. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31206. ret = ASN_OCSP_CONFIRM_E;
  31207. }
  31208. }
  31209. if ((ret == 0) &&
  31210. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data == NULL))
  31211. #else
  31212. if (ret == 0)
  31213. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  31214. {
  31215. Signer* ca;
  31216. int sigValid = -1;
  31217. /* Resonse didn't have a certificate - lookup CA. */
  31218. #ifndef NO_SKID
  31219. ca = GetCA(cm, resp->single->issuerKeyHash);
  31220. #else
  31221. ca = GetCA(cm, resp->single->issuerHash);
  31222. #endif
  31223. if (ca) {
  31224. SignatureCtx sigCtx;
  31225. /* Initialize he signature context. */
  31226. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  31227. /* TODO: ConfirmSignature is blocking here */
  31228. /* Check the signature of the response CA public key. */
  31229. sigValid = ConfirmSignature(&sigCtx, resp->response,
  31230. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  31231. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31232. NULL);
  31233. }
  31234. if ((ca == NULL) || (sigValid != 0)) {
  31235. /* Didn't find certificate or signature verificate failed. */
  31236. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31237. ret = ASN_OCSP_CONFIRM_E;
  31238. }
  31239. }
  31240. if (ret == 0) {
  31241. /* Update the position to after response data. */
  31242. *ioIndex = idx;
  31243. }
  31244. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31245. if (certInit) {
  31246. FreeDecodedCert(cert);
  31247. }
  31248. #ifdef WOLFSSL_SMALL_STACK
  31249. if (cert != NULL) {
  31250. /* Dispose of certificate object. */
  31251. XFREE(cert, heap, DYNAMIC_TYPE_TMP_BUFFER);
  31252. }
  31253. #endif
  31254. #endif
  31255. FREE_ASNGETDATA(dataASN, heap);
  31256. return ret;
  31257. #endif /* WOLFSSL_ASN_TEMPLATE */
  31258. }
  31259. void InitOcspResponse(OcspResponse* resp, OcspEntry* single, CertStatus* status,
  31260. byte* source, word32 inSz, void* heap)
  31261. {
  31262. WOLFSSL_ENTER("InitOcspResponse");
  31263. XMEMSET(status, 0, sizeof(CertStatus));
  31264. XMEMSET(single, 0, sizeof(OcspEntry));
  31265. XMEMSET(resp, 0, sizeof(OcspResponse));
  31266. single->status = status;
  31267. resp->responseStatus = -1;
  31268. resp->single = single;
  31269. resp->source = source;
  31270. resp->maxIdx = inSz;
  31271. resp->heap = heap;
  31272. }
  31273. void FreeOcspResponse(OcspResponse* resp)
  31274. {
  31275. OcspEntry *single, *next;
  31276. if (resp != NULL) {
  31277. for (single = resp->single; single; single = next) {
  31278. next = single->next;
  31279. if (single->isDynamic) {
  31280. XFREE(single->status, resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  31281. XFREE(single, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  31282. }
  31283. }
  31284. }
  31285. }
  31286. #ifdef WOLFSSL_ASN_TEMPLATE
  31287. /* ASN.1 template for OCSPResponse.
  31288. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  31289. */
  31290. static const ASNItem ocspResponseASN[] = {
  31291. /* OCSPResponse ::= SEQUENCE */
  31292. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31293. /* responseStatus OCSPResponseStatus */
  31294. /* STATUS */ { 1, ASN_ENUMERATED, 0, 0, 0, },
  31295. /* responseBytes [0] EXPLICIT ResponseBytes OPTIONAL */
  31296. /* BYTES */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  31297. /* ResponseBytes ::= SEQUENCE */
  31298. /* BYTES_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  31299. /* responseType OBJECT IDENTIFIER */
  31300. /* BYTES_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  31301. /* response OCTET STRING */
  31302. /* BYTES_VAL */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  31303. };
  31304. enum {
  31305. OCSPRESPONSEASN_IDX_SEQ = 0,
  31306. OCSPRESPONSEASN_IDX_STATUS,
  31307. OCSPRESPONSEASN_IDX_BYTES,
  31308. OCSPRESPONSEASN_IDX_BYTES_SEQ,
  31309. OCSPRESPONSEASN_IDX_BYTES_TYPE,
  31310. OCSPRESPONSEASN_IDX_BYTES_VAL,
  31311. };
  31312. /* Number of items in ASN.1 template for OCSPResponse. */
  31313. #define ocspResponseASN_Length (sizeof(ocspResponseASN) / sizeof(ASNItem))
  31314. #endif /* WOLFSSL_ASN_TEMPLATE */
  31315. int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, int noVerify)
  31316. {
  31317. #ifndef WOLFSSL_ASN_TEMPLATE
  31318. int ret;
  31319. int length = 0;
  31320. word32 idx = 0;
  31321. byte* source = resp->source;
  31322. word32 size = resp->maxIdx;
  31323. word32 oid;
  31324. byte tag;
  31325. WOLFSSL_ENTER("OcspResponseDecode");
  31326. /* peel the outer SEQUENCE wrapper */
  31327. if (GetSequence(source, &idx, &length, size) < 0) {
  31328. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31329. return ASN_PARSE_E;
  31330. }
  31331. /* First get the responseStatus, an ENUMERATED */
  31332. if (GetEnumerated(source, &idx, &resp->responseStatus, size) < 0) {
  31333. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31334. return ASN_PARSE_E;
  31335. }
  31336. if (resp->responseStatus != OCSP_SUCCESSFUL) {
  31337. WOLFSSL_LEAVE("OcspResponseDecode", 0);
  31338. return 0;
  31339. }
  31340. /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
  31341. if (idx >= size) {
  31342. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31343. return ASN_PARSE_E;
  31344. }
  31345. if (GetASNTag(source, &idx, &tag, size) < 0) {
  31346. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31347. return ASN_PARSE_E;
  31348. }
  31349. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC)) {
  31350. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31351. return ASN_PARSE_E;
  31352. }
  31353. if (GetLength(source, &idx, &length, size) < 0) {
  31354. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31355. return ASN_PARSE_E;
  31356. }
  31357. /* Get the responseBytes SEQUENCE */
  31358. if (GetSequence(source, &idx, &length, size) < 0) {
  31359. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31360. return ASN_PARSE_E;
  31361. }
  31362. /* Check ObjectID for the resposeBytes */
  31363. if (GetObjectId(source, &idx, &oid, oidOcspType, size) < 0) {
  31364. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31365. return ASN_PARSE_E;
  31366. }
  31367. if (oid != OCSP_BASIC_OID) {
  31368. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31369. return ASN_PARSE_E;
  31370. }
  31371. ret = GetOctetString(source, &idx, &length, size);
  31372. if (ret < 0) {
  31373. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31374. return ret;
  31375. }
  31376. ret = DecodeBasicOcspResponse(source, &idx, resp, size, cm, heap, noVerify);
  31377. if (ret < 0) {
  31378. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31379. return ret;
  31380. }
  31381. WOLFSSL_LEAVE("OcspResponseDecode", 0);
  31382. return 0;
  31383. #else
  31384. DECL_ASNGETDATA(dataASN, ocspResponseASN_Length);
  31385. int ret = 0;
  31386. word32 idx = 0, size = resp->maxIdx;
  31387. byte* source = resp->source;
  31388. byte status;
  31389. byte* basic;
  31390. word32 basicSz;
  31391. WOLFSSL_ENTER("OcspResponseDecode");
  31392. CALLOC_ASNGETDATA(dataASN, ocspResponseASN_Length, ret, resp->heap);
  31393. if (ret == 0) {
  31394. /* Set variable to put status in and expect OCSP OID. */
  31395. GetASN_Int8Bit(&dataASN[OCSPRESPONSEASN_IDX_STATUS], &status);
  31396. GetASN_OID(&dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE], oidOcspType);
  31397. /* Decode OCSPResponse (and ResponseBytes). */
  31398. ret = GetASN_Items(ocspResponseASN, dataASN, ocspResponseASN_Length, 1,
  31399. source, &idx, size);
  31400. }
  31401. if (ret == 0) {
  31402. /* Get response. */
  31403. resp->responseStatus = status;
  31404. if (dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE].data.oid.sum
  31405. == OCSP_BASIC_OID) {
  31406. /* Get reference to BasicOCSPResponse. */
  31407. GetASN_GetRef(&dataASN[OCSPRESPONSEASN_IDX_BYTES_VAL], &basic,
  31408. &basicSz);
  31409. idx = 0;
  31410. /* Decode BasicOCSPResponse. */
  31411. ret = DecodeBasicOcspResponse(basic, &idx, resp, basicSz, cm, heap,
  31412. noVerify);
  31413. }
  31414. /* Only support BasicOCSPResponse. */
  31415. else {
  31416. ret = ASN_PARSE_E;
  31417. }
  31418. }
  31419. FREE_ASNGETDATA(dataASN, resp->heap);
  31420. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31421. return ret;
  31422. #endif /* WOLFSSL_ASN_TEMPLATE */
  31423. }
  31424. #ifdef WOLFSSL_ASN_TEMPLATE
  31425. /* ASN.1 template for OCSP nonce extension.
  31426. * RFC 6960, 4.4.1 - Nonce
  31427. * X.509: RFC 5280, 4.1 - Basic Certificate Fields. (Extension)
  31428. */
  31429. static const ASNItem ocspNonceExtASN[] = {
  31430. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31431. /* Extension */
  31432. /* EXT */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  31433. /* extnId */
  31434. /* EXT_OID */ {2, ASN_OBJECT_ID, 0, 0, 0 },
  31435. /* critcal not encoded. */
  31436. /* extnValue */
  31437. /* EXT_VAL */ {2, ASN_OCTET_STRING, 0, 1, 0 },
  31438. /* nonce */
  31439. /* EXT_NONCE */ {3, ASN_OCTET_STRING, 0, 0, 0 },
  31440. };
  31441. enum {
  31442. OCSPNONCEEXTASN_IDX_SEQ = 0,
  31443. OCSPNONCEEXTASN_IDX_EXT,
  31444. OCSPNONCEEXTASN_IDX_EXT_OID,
  31445. OCSPNONCEEXTASN_IDX_EXT_VAL,
  31446. OCSPNONCEEXTASN_IDX_EXT_NONCE,
  31447. };
  31448. /* Number of items in ASN.1 template for OCSP nonce extension. */
  31449. #define ocspNonceExtASN_Length (sizeof(ocspNonceExtASN) / sizeof(ASNItem))
  31450. #endif /* WOLFSSL_ASN_TEMPLATE */
  31451. word32 EncodeOcspRequestExtensions(OcspRequest* req, byte* output, word32 size)
  31452. {
  31453. const byte NonceObjId[] = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07,
  31454. 0x30, 0x01, 0x02 };
  31455. #ifndef WOLFSSL_ASN_TEMPLATE
  31456. byte seqArray[5][MAX_SEQ_SZ];
  31457. word32 seqSz[5], totalSz = (word32)sizeof(NonceObjId);
  31458. WOLFSSL_ENTER("SetOcspReqExtensions");
  31459. if (!req || !output || !req->nonceSz)
  31460. return 0;
  31461. totalSz += req->nonceSz;
  31462. totalSz += seqSz[0] = SetOctetString(req->nonceSz, seqArray[0]);
  31463. totalSz += seqSz[1] = SetOctetString(req->nonceSz + seqSz[0], seqArray[1]);
  31464. totalSz += seqSz[2] = SetObjectId(sizeof(NonceObjId), seqArray[2]);
  31465. totalSz += seqSz[3] = SetSequence(totalSz, seqArray[3]);
  31466. totalSz += seqSz[4] = SetSequence(totalSz, seqArray[4]);
  31467. if (totalSz > size)
  31468. return 0;
  31469. totalSz = 0;
  31470. XMEMCPY(output + totalSz, seqArray[4], seqSz[4]);
  31471. totalSz += seqSz[4];
  31472. XMEMCPY(output + totalSz, seqArray[3], seqSz[3]);
  31473. totalSz += seqSz[3];
  31474. XMEMCPY(output + totalSz, seqArray[2], seqSz[2]);
  31475. totalSz += seqSz[2];
  31476. XMEMCPY(output + totalSz, NonceObjId, sizeof(NonceObjId));
  31477. totalSz += (word32)sizeof(NonceObjId);
  31478. XMEMCPY(output + totalSz, seqArray[1], seqSz[1]);
  31479. totalSz += seqSz[1];
  31480. XMEMCPY(output + totalSz, seqArray[0], seqSz[0]);
  31481. totalSz += seqSz[0];
  31482. XMEMCPY(output + totalSz, req->nonce, req->nonceSz);
  31483. totalSz += req->nonceSz;
  31484. return totalSz;
  31485. #else
  31486. int ret = 0;
  31487. WOLFSSL_ENTER("SetOcspReqExtensions");
  31488. /* Check request has nonce to write in extension. */
  31489. if (req != NULL && req->nonceSz != 0) {
  31490. DECL_ASNSETDATA(dataASN, ocspNonceExtASN_Length);
  31491. int sz;
  31492. CALLOC_ASNSETDATA(dataASN, ocspNonceExtASN_Length, ret, req->heap);
  31493. /* Set nonce extension OID and nonce. */
  31494. SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_OID], NonceObjId,
  31495. sizeof(NonceObjId));
  31496. SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_NONCE], req->nonce,
  31497. req->nonceSz);
  31498. /* Calculate size of nonce extension. */
  31499. ret = SizeASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
  31500. &sz);
  31501. /* Check buffer big enough for encoding if supplied. */
  31502. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  31503. ret = BUFFER_E;
  31504. }
  31505. if ((ret == 0) && (output != NULL)) {
  31506. /* Encode nonce extension. */
  31507. SetASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
  31508. output);
  31509. }
  31510. if (ret == 0) {
  31511. /* Return size of encoding. */
  31512. ret = sz;
  31513. }
  31514. FREE_ASNSETDATA(dataASN, req->heap);
  31515. }
  31516. return ret;
  31517. #endif /* WOLFSSL_ASN_TEMPLATE */
  31518. }
  31519. #ifdef WOLFSSL_ASN_TEMPLATE
  31520. /* ASN.1 template for OCSPRequest.
  31521. * RFC 6960, 4.1.1 - ASN.1 Specification of the OCSP Request
  31522. */
  31523. static const ASNItem ocspRequestASN[] = {
  31524. /* OCSPRequest */
  31525. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31526. /* tbsRequest */
  31527. /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  31528. /* version not written - v1 */
  31529. /* requestorName not written */
  31530. /* requestList */
  31531. /* TBS_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  31532. /* Request */
  31533. /* TBS_LIST */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  31534. /* reqCert */
  31535. /* TBS_REQ_CID */ { 4, ASN_SEQUENCE, 1, 1, 0 },
  31536. /* hashAlgorithm */
  31537. /* TBS_REQ_HASH */ { 5, ASN_SEQUENCE, 1, 1, 0 },
  31538. /* TBS_REQ_HASH_OID */ { 6, ASN_OBJECT_ID, 0, 0, 0 },
  31539. /* issuerNameHash */
  31540. /* TBS_REQ_ISSUER */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  31541. /* issuerKeyHash */
  31542. /* TBS_REQ_ISSUERKEY */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  31543. /* serialNumber */
  31544. /* TBS_REQ_SERIAL */ { 5, ASN_INTEGER, 0, 0, 0 },
  31545. /* requestExtensions */
  31546. /* TBS_REQEXT */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 0 },
  31547. /* optionalSignature not written. */
  31548. };
  31549. enum {
  31550. OCSPREQUESTASN_IDX_SEQ = 0,
  31551. OCSPREQUESTASN_IDX_TBS,
  31552. OCSPREQUESTASN_IDX_TBS_SEQ,
  31553. OCSPREQUESTASN_IDX_TBS_LIST,
  31554. OCSPREQUESTASN_IDX_TBS_REQ_CID,
  31555. OCSPREQUESTASN_IDX_TBS_REQ_HASH,
  31556. OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID,
  31557. OCSPREQUESTASN_IDX_TBS_REQ_ISSUER,
  31558. OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY,
  31559. OCSPREQUESTASN_IDX_TBS_REQ_SERIAL,
  31560. OCSPREQUESTASN_IDX_TBS_REQEXT,
  31561. };
  31562. /* Number of items in ASN.1 template for OCSPRequest. */
  31563. #define ocspRequestASN_Length (sizeof(ocspRequestASN) / sizeof(ASNItem))
  31564. #endif
  31565. int EncodeOcspRequest(OcspRequest* req, byte* output, word32 size)
  31566. {
  31567. #ifndef WOLFSSL_ASN_TEMPLATE
  31568. byte seqArray[5][MAX_SEQ_SZ];
  31569. /* The ASN.1 of the OCSP Request is an onion of sequences */
  31570. byte algoArray[MAX_ALGO_SZ];
  31571. byte issuerArray[MAX_ENCODED_DIG_SZ];
  31572. byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
  31573. byte snArray[MAX_SN_SZ];
  31574. byte extArray[MAX_OCSP_EXT_SZ];
  31575. word32 seqSz[5], algoSz, issuerSz, issuerKeySz, extSz, totalSz;
  31576. int i, snSz;
  31577. WOLFSSL_ENTER("EncodeOcspRequest");
  31578. #ifdef NO_SHA
  31579. algoSz = SetAlgoID(SHA256h, algoArray, oidHashType, 0);
  31580. #else
  31581. algoSz = SetAlgoID(SHAh, algoArray, oidHashType, 0);
  31582. #endif
  31583. issuerSz = SetDigest(req->issuerHash, KEYID_SIZE, issuerArray);
  31584. issuerKeySz = SetDigest(req->issuerKeyHash, KEYID_SIZE, issuerKeyArray);
  31585. snSz = SetSerialNumber(req->serial, req->serialSz, snArray,
  31586. MAX_SN_SZ, MAX_SN_SZ);
  31587. extSz = 0;
  31588. if (snSz < 0)
  31589. return snSz;
  31590. if (req->nonceSz) {
  31591. /* TLS Extensions use this function too - put extensions after
  31592. * ASN.1: Context Specific [2].
  31593. */
  31594. extSz = EncodeOcspRequestExtensions(req, extArray + 2,
  31595. OCSP_NONCE_EXT_SZ);
  31596. extSz += SetExplicit(2, extSz, extArray);
  31597. }
  31598. totalSz = algoSz + issuerSz + issuerKeySz + snSz;
  31599. for (i = 4; i >= 0; i--) {
  31600. seqSz[i] = SetSequence(totalSz, seqArray[i]);
  31601. totalSz += seqSz[i];
  31602. if (i == 2) totalSz += extSz;
  31603. }
  31604. if (output == NULL)
  31605. return totalSz;
  31606. if (totalSz > size)
  31607. return BUFFER_E;
  31608. totalSz = 0;
  31609. for (i = 0; i < 5; i++) {
  31610. XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
  31611. totalSz += seqSz[i];
  31612. }
  31613. XMEMCPY(output + totalSz, algoArray, algoSz);
  31614. totalSz += algoSz;
  31615. XMEMCPY(output + totalSz, issuerArray, issuerSz);
  31616. totalSz += issuerSz;
  31617. XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
  31618. totalSz += issuerKeySz;
  31619. XMEMCPY(output + totalSz, snArray, snSz);
  31620. totalSz += snSz;
  31621. if (extSz != 0) {
  31622. XMEMCPY(output + totalSz, extArray, extSz);
  31623. totalSz += extSz;
  31624. }
  31625. return totalSz;
  31626. #else
  31627. DECL_ASNSETDATA(dataASN, ocspRequestASN_Length);
  31628. word32 extSz = 0;
  31629. int sz = 0;
  31630. int ret = 0;
  31631. WOLFSSL_ENTER("EncodeOcspRequest");
  31632. CALLOC_ASNSETDATA(dataASN, ocspRequestASN_Length, ret, req->heap);
  31633. if (ret == 0) {
  31634. /* Set OID of hash algorithm use on issuer and key. */
  31635. #ifdef NO_SHA
  31636. SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHA256h,
  31637. oidHashType);
  31638. #else
  31639. SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHAh,
  31640. oidHashType);
  31641. #endif
  31642. /* Set issuer, issuer key hash and serial number of certificate being
  31643. * checked. */
  31644. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUER],
  31645. req->issuerHash, KEYID_SIZE);
  31646. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY],
  31647. req->issuerKeyHash, KEYID_SIZE);
  31648. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_SERIAL],
  31649. req->serial, req->serialSz);
  31650. /* Only extension to write is nonce - check if one to encode. */
  31651. if (req->nonceSz) {
  31652. /* Get size of extensions and leave space for them in encoding. */
  31653. ret = extSz = EncodeOcspRequestExtensions(req, NULL, 0);
  31654. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT], NULL, extSz);
  31655. if (ret > 0) {
  31656. ret = 0;
  31657. }
  31658. }
  31659. else {
  31660. /* Don't write out extensions. */
  31661. dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].noOut = 1;
  31662. }
  31663. }
  31664. if (ret == 0) {
  31665. /* Calculate size of encoding. */
  31666. ret = SizeASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length,
  31667. &sz);
  31668. }
  31669. /* Check buffer big enough for encoding if supplied. */
  31670. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  31671. ret = BUFFER_E;
  31672. }
  31673. if ((ret == 0) && (output != NULL)) {
  31674. /* Encode OCSPRequest. */
  31675. SetASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length, output);
  31676. if (req->nonceSz) {
  31677. /* Encode extensions into space provided. */
  31678. ret = EncodeOcspRequestExtensions(req,
  31679. (byte*)dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].data.buffer.data,
  31680. extSz);
  31681. if (ret > 0) {
  31682. ret = 0;
  31683. }
  31684. }
  31685. }
  31686. if (ret == 0) {
  31687. /* Return size of encoding. */
  31688. ret = sz;
  31689. }
  31690. FREE_ASNSETDATA(dataASN, req->heap);
  31691. return ret;
  31692. #endif /* WOLFSSL_ASN_TEMPLATE */
  31693. }
  31694. int InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce,
  31695. void* heap)
  31696. {
  31697. int ret;
  31698. WOLFSSL_ENTER("InitOcspRequest");
  31699. if (req == NULL)
  31700. return BAD_FUNC_ARG;
  31701. XMEMSET(req, 0, sizeof(OcspRequest));
  31702. req->heap = heap;
  31703. if (cert) {
  31704. XMEMCPY(req->issuerHash, cert->issuerHash, KEYID_SIZE);
  31705. XMEMCPY(req->issuerKeyHash, cert->issuerKeyHash, KEYID_SIZE);
  31706. req->serial = (byte*)XMALLOC(cert->serialSz, req->heap,
  31707. DYNAMIC_TYPE_OCSP_REQUEST);
  31708. if (req->serial == NULL)
  31709. return MEMORY_E;
  31710. XMEMCPY(req->serial, cert->serial, cert->serialSz);
  31711. req->serialSz = cert->serialSz;
  31712. if (cert->extAuthInfoSz != 0 && cert->extAuthInfo != NULL) {
  31713. req->url = (byte*)XMALLOC(cert->extAuthInfoSz + 1, req->heap,
  31714. DYNAMIC_TYPE_OCSP_REQUEST);
  31715. if (req->url == NULL) {
  31716. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP);
  31717. return MEMORY_E;
  31718. }
  31719. XMEMCPY(req->url, cert->extAuthInfo, cert->extAuthInfoSz);
  31720. req->urlSz = cert->extAuthInfoSz;
  31721. req->url[req->urlSz] = 0;
  31722. }
  31723. }
  31724. if (useNonce) {
  31725. WC_RNG rng;
  31726. #ifndef HAVE_FIPS
  31727. ret = wc_InitRng_ex(&rng, req->heap, INVALID_DEVID);
  31728. #else
  31729. ret = wc_InitRng(&rng);
  31730. #endif
  31731. if (ret != 0) {
  31732. WOLFSSL_MSG("\tCannot initialize RNG. Skipping the OCSP Nonce.");
  31733. } else {
  31734. if (wc_RNG_GenerateBlock(&rng, req->nonce, MAX_OCSP_NONCE_SZ) != 0)
  31735. WOLFSSL_MSG("\tCannot run RNG. Skipping the OCSP Nonce.");
  31736. else
  31737. req->nonceSz = MAX_OCSP_NONCE_SZ;
  31738. wc_FreeRng(&rng);
  31739. }
  31740. }
  31741. return 0;
  31742. }
  31743. void FreeOcspRequest(OcspRequest* req)
  31744. {
  31745. WOLFSSL_ENTER("FreeOcspRequest");
  31746. if (req) {
  31747. if (req->serial)
  31748. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  31749. req->serial = NULL;
  31750. #ifdef OPENSSL_EXTRA
  31751. if (req->serialInt) {
  31752. if (req->serialInt->isDynamic) {
  31753. XFREE(req->serialInt->data, NULL, DYNAMIC_TYPE_OPENSSL);
  31754. }
  31755. XFREE(req->serialInt, NULL, DYNAMIC_TYPE_OPENSSL);
  31756. }
  31757. req->serialInt = NULL;
  31758. #endif
  31759. if (req->url)
  31760. XFREE(req->url, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  31761. req->url = NULL;
  31762. }
  31763. }
  31764. int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
  31765. {
  31766. int cmp = -1; /* default as not matching, cmp gets set on each check */
  31767. OcspEntry *single, *next, *prev = NULL, *top;
  31768. WOLFSSL_ENTER("CompareOcspReqResp");
  31769. if (req == NULL) {
  31770. WOLFSSL_MSG("\tReq missing");
  31771. return -1;
  31772. }
  31773. if (resp == NULL || resp->single == NULL) {
  31774. WOLFSSL_MSG("\tResp missing");
  31775. return 1;
  31776. }
  31777. /* Nonces are not critical. The responder may not necessarily add
  31778. * the nonce to the response. */
  31779. if (req->nonceSz && resp->nonce != NULL
  31780. #ifndef WOLFSSL_FORCE_OCSP_NONCE_CHECK
  31781. && resp->nonceSz != 0
  31782. #endif
  31783. ) {
  31784. cmp = req->nonceSz - resp->nonceSz;
  31785. if (cmp != 0) {
  31786. WOLFSSL_MSG("\tnonceSz mismatch");
  31787. return cmp;
  31788. }
  31789. cmp = XMEMCMP(req->nonce, resp->nonce, req->nonceSz);
  31790. if (cmp != 0) {
  31791. WOLFSSL_MSG("\tnonce mismatch");
  31792. return cmp;
  31793. }
  31794. }
  31795. /* match based on found status and return */
  31796. for (single = resp->single; single; single = next) {
  31797. cmp = req->serialSz - single->status->serialSz;
  31798. if (cmp == 0) {
  31799. cmp = XMEMCMP(req->serial, single->status->serial, req->serialSz)
  31800. || XMEMCMP(req->issuerHash, single->issuerHash, OCSP_DIGEST_SIZE)
  31801. || XMEMCMP(req->issuerKeyHash, single->issuerKeyHash, OCSP_DIGEST_SIZE);
  31802. if (cmp == 0) {
  31803. /* match found */
  31804. if (resp->single != single && prev) {
  31805. /* move to top of list */
  31806. top = resp->single;
  31807. resp->single = single;
  31808. prev->next = single->next;
  31809. single->next = top;
  31810. }
  31811. break;
  31812. }
  31813. }
  31814. next = single->next;
  31815. prev = single;
  31816. }
  31817. if (cmp != 0) {
  31818. WOLFSSL_MSG("\trequest and response mismatch");
  31819. return cmp;
  31820. }
  31821. return 0;
  31822. }
  31823. #endif /* HAVE_OCSP */
  31824. #ifdef WOLFSSL_ASN_TEMPLATE
  31825. /* ASN.1 template for certificate name hash. */
  31826. static const ASNItem nameHashASN[] = {
  31827. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  31828. /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  31829. };
  31830. enum {
  31831. NAMEHASHASN_IDX_OID = 0,
  31832. NAMEHASHASN_IDX_NAME
  31833. };
  31834. /* Number of items in ASN.1 template for certificate name hash. */
  31835. #define nameHashASN_Length (sizeof(nameHashASN) / sizeof(ASNItem))
  31836. #endif /* WOLFSSL_ASN_TEMPLATE */
  31837. /* store WC_SHA hash of NAME */
  31838. int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx)
  31839. {
  31840. #ifndef WOLFSSL_ASN_TEMPLATE
  31841. int length; /* length of all distinguished names */
  31842. int ret;
  31843. word32 dummy;
  31844. byte tag;
  31845. WOLFSSL_ENTER("GetNameHash");
  31846. dummy = *idx;
  31847. if (GetASNTag(source, &dummy, &tag, (word32)maxIdx) == 0 &&
  31848. tag == ASN_OBJECT_ID) {
  31849. WOLFSSL_MSG("Trying optional prefix...");
  31850. if (GetLength(source, idx, &length, (word32)maxIdx) < 0)
  31851. return ASN_PARSE_E;
  31852. *idx += (word32)length;
  31853. WOLFSSL_MSG("Got optional prefix");
  31854. }
  31855. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  31856. * calculated over the entire DER encoding of the Name field, including
  31857. * the tag and length. */
  31858. dummy = *idx;
  31859. if (GetSequence(source, idx, &length, (word32)maxIdx) < 0)
  31860. return ASN_PARSE_E;
  31861. ret = CalcHashId(source + dummy, (word32)length + *idx - dummy, hash);
  31862. *idx += (word32)length;
  31863. return ret;
  31864. #else
  31865. ASNGetData dataASN[nameHashASN_Length];
  31866. int ret;
  31867. XMEMSET(dataASN, 0, sizeof(dataASN));
  31868. /* Ignore the OID even when present. */
  31869. GetASN_OID(&dataASN[NAMEHASHASN_IDX_OID], oidIgnoreType);
  31870. /* Decode certificate name. */
  31871. ret = GetASN_Items(nameHashASN, dataASN, nameHashASN_Length, 0, source, idx,
  31872. (word32)maxIdx);
  31873. if (ret == 0) {
  31874. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  31875. * calculated over the entire DER encoding of the Name field, including
  31876. * the tag and length. */
  31877. /* Calculate hash of complete name including SEQUENCE. */
  31878. ret = CalcHashId(
  31879. GetASNItem_Addr(dataASN[NAMEHASHASN_IDX_NAME], source),
  31880. GetASNItem_Length(dataASN[NAMEHASHASN_IDX_NAME], source),
  31881. hash);
  31882. }
  31883. return ret;
  31884. #endif /* WOLFSSL_ASN_TEMPLATE */
  31885. }
  31886. #if defined(HAVE_CRL) && !defined(WOLFCRYPT_ONLY)
  31887. #ifdef OPENSSL_EXTRA
  31888. static char* GetNameFromDer(const byte* source, int sz)
  31889. {
  31890. char* out;
  31891. out = (char*)XMALLOC(sz, NULL, DYNAMIC_TYPE_OPENSSL);
  31892. if (out == NULL) {
  31893. WOLFSSL_MSG("Name malloc failed");
  31894. return NULL;
  31895. }
  31896. XMEMCPY(out, source, sz);
  31897. return out;
  31898. }
  31899. #endif
  31900. /* initialize decoded CRL */
  31901. void InitDecodedCRL(DecodedCRL* dcrl, void* heap)
  31902. {
  31903. WOLFSSL_MSG("InitDecodedCRL");
  31904. XMEMSET(dcrl, 0, sizeof(DecodedCRL));
  31905. dcrl->heap = heap;
  31906. #ifdef WOLFSSL_HEAP_TEST
  31907. dcrl->heap = (void*)WOLFSSL_HEAP_TEST;
  31908. #endif
  31909. }
  31910. /* free decoded CRL resources */
  31911. void FreeDecodedCRL(DecodedCRL* dcrl)
  31912. {
  31913. RevokedCert* tmp = dcrl->certs;
  31914. WOLFSSL_MSG("FreeDecodedCRL");
  31915. while(tmp) {
  31916. RevokedCert* next = tmp->next;
  31917. XFREE(tmp, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  31918. tmp = next;
  31919. }
  31920. #ifdef OPENSSL_EXTRA
  31921. if (dcrl->issuer != NULL)
  31922. XFREE(dcrl->issuer, NULL, DYNAMIC_TYPE_OPENSSL);
  31923. #endif
  31924. }
  31925. #ifdef WOLFSSL_ASN_TEMPLATE
  31926. /* ASN.1 template for revoked certificates.
  31927. * X.509: RFC 5280, 5.1 - CRL Fields
  31928. */
  31929. static const ASNItem revokedASN[] = {
  31930. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31931. /* userCertificate CertificateSerialNumber */
  31932. /* CERT */ { 1, ASN_INTEGER, 0, 0, 0 },
  31933. /* revocationDate Time */
  31934. /* TIME_UTC */ { 1, ASN_UTC_TIME, 0, 0, 2 },
  31935. /* TIME_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 2 },
  31936. /* crlEntryExensions Extensions */
  31937. /* TIME_EXT */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  31938. };
  31939. enum {
  31940. REVOKEDASN_IDX_SEQ = 0,
  31941. REVOKEDASN_IDX_CERT,
  31942. REVOKEDASN_IDX_TIME_UTC,
  31943. REVOKEDASN_IDX_TIME_GT,
  31944. REVOKEDASN_IDX_TIME_EXT,
  31945. };
  31946. /* Number of items in ASN.1 template for revoked certificates. */
  31947. #define revokedASN_Length (sizeof(revokedASN) / sizeof(ASNItem))
  31948. #endif
  31949. /* Get Revoked Cert list, 0 on success */
  31950. static int GetRevoked(RevokedCert* rcert, const byte* buff, word32* idx,
  31951. DecodedCRL* dcrl, int maxIdx)
  31952. {
  31953. #ifndef WOLFSSL_ASN_TEMPLATE
  31954. int ret;
  31955. int len;
  31956. word32 end;
  31957. RevokedCert* rc;
  31958. #ifdef CRL_STATIC_REVOKED_LIST
  31959. int totalCerts = 0;
  31960. #endif
  31961. WOLFSSL_ENTER("GetRevoked");
  31962. if (GetSequence(buff, idx, &len, maxIdx) < 0)
  31963. return ASN_PARSE_E;
  31964. end = *idx + len;
  31965. #ifdef CRL_STATIC_REVOKED_LIST
  31966. totalCerts = dcrl->totalCerts;
  31967. if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
  31968. return MEMORY_E;
  31969. }
  31970. rc = &rcert[totalCerts];
  31971. ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
  31972. if (ret < 0) {
  31973. WOLFSSL_MSG("wc_GetSerialNumber error");
  31974. return ret;
  31975. }
  31976. #else
  31977. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  31978. DYNAMIC_TYPE_REVOKED);
  31979. if (rc == NULL) {
  31980. WOLFSSL_MSG("Alloc Revoked Cert failed");
  31981. return MEMORY_E;
  31982. }
  31983. ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
  31984. if (ret < 0) {
  31985. WOLFSSL_MSG("wc_GetSerialNumber error");
  31986. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  31987. return ret;
  31988. }
  31989. /* add to list */
  31990. rc->next = dcrl->certs;
  31991. dcrl->certs = rc;
  31992. (void)rcert;
  31993. #endif /* CRL_STATIC_REVOKED_LIST */
  31994. dcrl->totalCerts++;
  31995. /* get date */
  31996. #ifndef NO_ASN_TIME
  31997. ret = GetBasicDate(buff, idx, rc->revDate, &rc->revDateFormat, maxIdx);
  31998. if (ret < 0) {
  31999. WOLFSSL_MSG("Expecting Date");
  32000. return ret;
  32001. }
  32002. #endif
  32003. /* skip extensions */
  32004. *idx = end;
  32005. return 0;
  32006. #else
  32007. DECL_ASNGETDATA(dataASN, revokedASN_Length);
  32008. int ret = 0;
  32009. word32 serialSz = EXTERNAL_SERIAL_SIZE;
  32010. word32 revDateSz = MAX_DATE_SIZE;
  32011. RevokedCert* rc;
  32012. #ifdef CRL_STATIC_REVOKED_LIST
  32013. int totalCerts = dcrl->totalCerts;
  32014. if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
  32015. return MEMORY_E;
  32016. }
  32017. rc = &rcert[totalCerts];
  32018. #else
  32019. /* Allocate a new revoked certificate object. */
  32020. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  32021. DYNAMIC_TYPE_CRL);
  32022. if (rc == NULL) {
  32023. ret = MEMORY_E;
  32024. }
  32025. #endif /* CRL_STATIC_REVOKED_LIST */
  32026. CALLOC_ASNGETDATA(dataASN, revokedASN_Length, ret, dcrl->heap);
  32027. if (ret == 0) {
  32028. /* Set buffer to place serial number into. */
  32029. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_CERT], rc->serialNumber,
  32030. &serialSz);
  32031. /* Set buffer to store revocation date. */
  32032. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_UTC], rc->revDate,
  32033. &revDateSz);
  32034. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_GT], rc->revDate,
  32035. &revDateSz);
  32036. /* Decode the Revoked */
  32037. ret = GetASN_Items(revokedASN, dataASN, revokedASN_Length, 1, buff, idx,
  32038. maxIdx);
  32039. }
  32040. if (ret == 0) {
  32041. /* Store size of serial number. */
  32042. rc->serialSz = serialSz;
  32043. rc->revDateFormat = (dataASN[REVOKEDASN_IDX_TIME_UTC].tag != 0)
  32044. ? dataASN[REVOKEDASN_IDX_TIME_UTC].tag
  32045. : dataASN[REVOKEDASN_IDX_TIME_GT].tag;
  32046. /* TODO: use extensions, only v2 */
  32047. /* Add revoked certificate to chain. */
  32048. #ifndef CRL_STATIC_REVOKED_LIST
  32049. rc->next = dcrl->certs;
  32050. dcrl->certs = rc;
  32051. #endif
  32052. dcrl->totalCerts++;
  32053. }
  32054. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32055. #ifndef CRL_STATIC_REVOKED_LIST
  32056. if ((ret != 0) && (rc != NULL)) {
  32057. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_CRL);
  32058. }
  32059. (void)rcert;
  32060. #endif
  32061. return ret;
  32062. #endif /* WOLFSSL_ASN_TEMPLATE */
  32063. }
  32064. #ifdef WOLFSSL_ASN_TEMPLATE
  32065. /* Parse the revoked certificates of a CRL.
  32066. *
  32067. * @param [in] dcrl Decoded CRL object.
  32068. * @param [in] buff Buffer holding CRL.
  32069. * @param [in] idx Index into buffer of revoked certificates.
  32070. * @param [in] maxIdx Maximum index of revoked cartificates data.
  32071. * @return 0 on success.
  32072. * @return ASN_PARSE_E on failure.
  32073. */
  32074. static int ParseCRL_RevokedCerts(RevokedCert* rcert, DecodedCRL* dcrl,
  32075. const byte* buff, word32 idx, word32 maxIdx)
  32076. {
  32077. int ret = 0;
  32078. /* Parse each revoked cerificate. */
  32079. while ((ret == 0) && (idx < maxIdx)) {
  32080. /* Parse a revoked certificate. */
  32081. if (GetRevoked(rcert, buff, &idx, dcrl, maxIdx) < 0) {
  32082. ret = ASN_PARSE_E;
  32083. }
  32084. }
  32085. return ret;
  32086. }
  32087. #endif /* WOLFSSL_ASN_TEMPLATE */
  32088. #ifndef WOLFSSL_ASN_TEMPLATE
  32089. /* Get CRL Signature, 0 on success */
  32090. static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
  32091. int maxIdx)
  32092. {
  32093. int length;
  32094. int ret;
  32095. WOLFSSL_ENTER("GetCRL_Signature");
  32096. ret = CheckBitString(source, idx, &length, maxIdx, 1, NULL);
  32097. if (ret != 0)
  32098. return ret;
  32099. dcrl->sigLength = length;
  32100. dcrl->signature = (byte*)&source[*idx];
  32101. *idx += dcrl->sigLength;
  32102. return 0;
  32103. }
  32104. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32105. int VerifyCRL_Signature(SignatureCtx* sigCtx, const byte* toBeSigned,
  32106. word32 tbsSz, const byte* signature, word32 sigSz,
  32107. word32 signatureOID, Signer *ca, void* heap)
  32108. {
  32109. /* try to confirm/verify signature */
  32110. #ifndef IGNORE_KEY_EXTENSIONS
  32111. if ((ca->keyUsage & KEYUSE_CRL_SIGN) == 0) {
  32112. WOLFSSL_MSG("CA cannot sign CRLs");
  32113. WOLFSSL_ERROR_VERBOSE(ASN_CRL_NO_SIGNER_E);
  32114. return ASN_CRL_NO_SIGNER_E;
  32115. }
  32116. #endif /* IGNORE_KEY_EXTENSIONS */
  32117. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  32118. if (ConfirmSignature(sigCtx, toBeSigned, tbsSz, ca->publicKey,
  32119. ca->pubKeySize, ca->keyOID, signature, sigSz,
  32120. signatureOID, NULL, 0, NULL) != 0) {
  32121. WOLFSSL_MSG("CRL Confirm signature failed");
  32122. WOLFSSL_ERROR_VERBOSE(ASN_CRL_CONFIRM_E);
  32123. return ASN_CRL_CONFIRM_E;
  32124. }
  32125. return 0;
  32126. }
  32127. #ifdef WOLFSSL_ASN_TEMPLATE
  32128. /* Find the signer for the CRL and verify the signature.
  32129. *
  32130. * @param [in] dcrl Decoded CRL object.
  32131. * @param [in] buff Buffer holding CRL.
  32132. * @param [in] cm Certificate manager object.
  32133. * @return 0 on success.
  32134. * @return ASN_CRL_NO_SIGNER_E when no signer found.
  32135. * @return ASN_CRL_CONFIRM_E when signature did not verify.
  32136. */
  32137. static int PaseCRL_CheckSignature(DecodedCRL* dcrl, const byte* buff, void* cm)
  32138. {
  32139. int ret = 0;
  32140. Signer* ca = NULL;
  32141. SignatureCtx sigCtx;
  32142. /* OpenSSL doesn't add skid by default for CRLs cause firefox chokes.
  32143. * If experiencing issues uncomment NO_SKID define in CRL section of
  32144. * wolfssl/wolfcrypt/settings.h */
  32145. #ifndef NO_SKID
  32146. if (dcrl->extAuthKeyIdSet) {
  32147. /* more unique than issuerHash */
  32148. ca = GetCA(cm, dcrl->extAuthKeyId);
  32149. }
  32150. /* Check issuerHash matched CA's subjectNameHash. */
  32151. if ((ca != NULL) && (XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  32152. KEYID_SIZE) != 0)) {
  32153. ca = NULL;
  32154. }
  32155. if (ca == NULL) {
  32156. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  32157. /* If AKID is available then this CA doesn't have the public
  32158. * key required */
  32159. if (ca && dcrl->extAuthKeyIdSet) {
  32160. WOLFSSL_MSG("CA SKID doesn't match AKID");
  32161. ca = NULL;
  32162. }
  32163. }
  32164. #else
  32165. ca = GetCA(cm, dcrl->issuerHash);
  32166. #endif /* !NO_SKID */
  32167. WOLFSSL_MSG("About to verify CRL signature");
  32168. if (ca == NULL) {
  32169. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  32170. ret = ASN_CRL_NO_SIGNER_E;
  32171. WOLFSSL_ERROR_VERBOSE(ret);
  32172. }
  32173. if (ret == 0) {
  32174. WOLFSSL_MSG("Found CRL issuer CA");
  32175. /* Verify CRL signature with CA. */
  32176. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  32177. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  32178. dcrl->signatureOID, ca, dcrl->heap);
  32179. }
  32180. return ret;
  32181. }
  32182. #endif
  32183. #ifndef WOLFSSL_ASN_TEMPLATE
  32184. static int ParseCRL_CertList(RevokedCert* rcert, DecodedCRL* dcrl,
  32185. const byte* buf,word32* inOutIdx, int sz, int verify)
  32186. {
  32187. word32 oid, dateIdx, idx, checkIdx;
  32188. int length;
  32189. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  32190. int doNextDate = 1;
  32191. #endif
  32192. byte tag;
  32193. if (dcrl == NULL || inOutIdx == NULL || buf == NULL) {
  32194. return BAD_FUNC_ARG;
  32195. }
  32196. /* may have version */
  32197. idx = *inOutIdx;
  32198. checkIdx = idx;
  32199. if (GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag == ASN_INTEGER) {
  32200. if (GetMyVersion(buf, &idx, &dcrl->version, sz) < 0)
  32201. return ASN_PARSE_E;
  32202. dcrl->version++;
  32203. }
  32204. if (GetAlgoId(buf, &idx, &oid, oidIgnoreType, sz) < 0)
  32205. return ASN_PARSE_E;
  32206. checkIdx = idx;
  32207. if (GetSequence(buf, &checkIdx, &length, sz) < 0) {
  32208. return ASN_PARSE_E;
  32209. }
  32210. #ifdef OPENSSL_EXTRA
  32211. dcrl->issuerSz = length + (checkIdx - idx);
  32212. dcrl->issuer = (byte*)GetNameFromDer(buf + idx, (int)dcrl->issuerSz);
  32213. #endif
  32214. if (GetNameHash(buf, &idx, dcrl->issuerHash, sz) < 0)
  32215. return ASN_PARSE_E;
  32216. if (GetBasicDate(buf, &idx, dcrl->lastDate, &dcrl->lastDateFormat, sz) < 0)
  32217. return ASN_PARSE_E;
  32218. dateIdx = idx;
  32219. if (GetBasicDate(buf, &idx, dcrl->nextDate, &dcrl->nextDateFormat, sz) < 0)
  32220. {
  32221. #ifndef WOLFSSL_NO_CRL_NEXT_DATE
  32222. (void)dateIdx;
  32223. return ASN_PARSE_E;
  32224. #else
  32225. dcrl->nextDateFormat = ASN_OTHER_TYPE; /* skip flag */
  32226. doNextDate = 0;
  32227. idx = dateIdx;
  32228. #endif
  32229. }
  32230. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  32231. if (doNextDate)
  32232. #endif
  32233. {
  32234. #ifndef NO_ASN_TIME
  32235. if (verify != NO_VERIFY &&
  32236. !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  32237. WOLFSSL_MSG("CRL after date is no longer valid");
  32238. WOLFSSL_ERROR_VERBOSE(CRL_CERT_DATE_ERR);
  32239. return CRL_CERT_DATE_ERR;
  32240. }
  32241. #else
  32242. (void)verify;
  32243. #endif
  32244. }
  32245. checkIdx = idx;
  32246. if (idx != dcrl->sigIndex &&
  32247. GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag != CRL_EXTENSIONS) {
  32248. int len;
  32249. if (GetSequence(buf, &idx, &len, sz) < 0)
  32250. return ASN_PARSE_E;
  32251. len += idx;
  32252. while (idx < (word32)len) {
  32253. if (GetRevoked(rcert, buf, &idx, dcrl, len) < 0)
  32254. return ASN_PARSE_E;
  32255. }
  32256. }
  32257. *inOutIdx = idx;
  32258. return 0;
  32259. }
  32260. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32261. #ifndef NO_SKID
  32262. static int ParseCRL_AuthKeyIdExt(const byte* input, int sz, DecodedCRL* dcrl)
  32263. {
  32264. #ifndef WOLFSSL_ASN_TEMPLATE
  32265. word32 idx = 0;
  32266. int length = 0, ret = 0;
  32267. byte tag;
  32268. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  32269. if (GetSequence(input, &idx, &length, sz) < 0) {
  32270. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  32271. return ASN_PARSE_E;
  32272. }
  32273. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  32274. return ASN_PARSE_E;
  32275. }
  32276. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  32277. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  32278. return 0;
  32279. }
  32280. if (GetLength(input, &idx, &length, sz) <= 0) {
  32281. WOLFSSL_MSG("\tfail: extension data length");
  32282. return ASN_PARSE_E;
  32283. }
  32284. dcrl->extAuthKeyIdSet = 1;
  32285. /* Get the hash or hash of the hash if wrong size. */
  32286. ret = GetHashId(input + idx, length, dcrl->extAuthKeyId);
  32287. return ret;
  32288. #else
  32289. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  32290. int ret = 0;
  32291. word32 idx = 0;
  32292. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  32293. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, dcrl->heap);
  32294. if (ret == 0) {
  32295. /* Parse an authority key identifier. */
  32296. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  32297. &idx, sz);
  32298. }
  32299. if (ret == 0) {
  32300. /* Key id is optional. */
  32301. if (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data == NULL) {
  32302. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  32303. }
  32304. else {
  32305. /* Get the hash or hash of the hash if wrong size. */
  32306. ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  32307. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  32308. dcrl->extAuthKeyId);
  32309. }
  32310. }
  32311. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32312. return ret;
  32313. #endif /* WOLFSSL_ASN_TEMPLATE */
  32314. }
  32315. #endif
  32316. #ifndef WOLFSSL_ASN_TEMPLATE
  32317. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf,
  32318. word32* inOutIdx, word32 sz)
  32319. {
  32320. int length;
  32321. word32 idx;
  32322. word32 ext_bound; /* boundary index for the sequence of extensions */
  32323. word32 oid;
  32324. byte tag;
  32325. WOLFSSL_ENTER("ParseCRL_Extensions");
  32326. (void)dcrl;
  32327. if (inOutIdx == NULL)
  32328. return BAD_FUNC_ARG;
  32329. idx = *inOutIdx;
  32330. /* CRL Extensions are optional */
  32331. if ((idx + 1) > sz)
  32332. return 0;
  32333. /* CRL Extensions are optional */
  32334. if (GetASNTag(buf, &idx, &tag, sz) < 0)
  32335. return 0;
  32336. /* CRL Extensions are optional */
  32337. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  32338. return 0;
  32339. if (GetLength(buf, &idx, &length, sz) < 0)
  32340. return ASN_PARSE_E;
  32341. if (GetSequence(buf, &idx, &length, sz) < 0)
  32342. return ASN_PARSE_E;
  32343. ext_bound = idx + length;
  32344. while (idx < (word32)ext_bound) {
  32345. word32 localIdx;
  32346. int ret;
  32347. if (GetSequence(buf, &idx, &length, sz) < 0) {
  32348. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  32349. return ASN_PARSE_E;
  32350. }
  32351. oid = 0;
  32352. if (GetObjectId(buf, &idx, &oid, oidCrlExtType, sz) < 0) {
  32353. WOLFSSL_MSG("\tfail: OBJECT ID");
  32354. return ASN_PARSE_E;
  32355. }
  32356. /* check for critical flag */
  32357. if ((idx + 1) > (word32)sz) {
  32358. WOLFSSL_MSG("\tfail: malformed buffer");
  32359. return BUFFER_E;
  32360. }
  32361. localIdx = idx;
  32362. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  32363. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  32364. ret = GetBoolean(buf, &idx, sz);
  32365. if (ret < 0)
  32366. return ret;
  32367. }
  32368. ret = GetOctetString(buf, &idx, &length, sz);
  32369. if (ret < 0)
  32370. return ret;
  32371. if (oid == AUTH_KEY_OID) {
  32372. #ifndef NO_SKID
  32373. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  32374. if (ret < 0) {
  32375. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  32376. return ret;
  32377. }
  32378. #endif
  32379. }
  32380. else if (oid == CRL_NUMBER_OID) {
  32381. localIdx = idx;
  32382. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 &&
  32383. tag == ASN_INTEGER) {
  32384. ret = GetASNInt(buf, &idx, &length, sz);
  32385. if (ret < 0) {
  32386. WOLFSSL_MSG("\tcouldn't parse CRL number extension");
  32387. return ret;
  32388. }
  32389. else {
  32390. if (length > 1) {
  32391. int i;
  32392. #ifdef WOLFSSL_SMALL_STACK
  32393. mp_int* m = (mp_int*)XMALLOC(sizeof(*m), NULL,
  32394. DYNAMIC_TYPE_BIGINT);
  32395. if (m == NULL) {
  32396. return MEMORY_E;
  32397. }
  32398. #else
  32399. mp_int m[1];
  32400. #endif
  32401. if (mp_init(m) != MP_OKAY) {
  32402. ret = MP_INIT_E;
  32403. }
  32404. if (ret == 0)
  32405. ret = mp_read_unsigned_bin(m, buf + idx, length);
  32406. if (ret != MP_OKAY)
  32407. ret = BUFFER_E;
  32408. if (ret == 0) {
  32409. dcrl->crlNumber = 0;
  32410. for (i = 0; i < (int)(*m).used; ++i) {
  32411. if (i > (CHAR_BIT *
  32412. (int)sizeof(word32) / DIGIT_BIT)) {
  32413. break;
  32414. }
  32415. dcrl->crlNumber |= ((word32)(*m).dp[i]) <<
  32416. (DIGIT_BIT * i);
  32417. }
  32418. }
  32419. mp_free(m);
  32420. #ifdef WOLFSSL_SMALL_STACK
  32421. XFREE(m, NULL, DYNAMIC_TYPE_BIGINT);
  32422. #endif
  32423. if (ret != 0)
  32424. return ret;
  32425. }
  32426. else if (length == 1) {
  32427. dcrl->crlNumber = buf[idx];
  32428. }
  32429. }
  32430. }
  32431. }
  32432. idx += length;
  32433. }
  32434. *inOutIdx = idx;
  32435. return 0;
  32436. }
  32437. #else
  32438. /* Parse the extensions of a CRL.
  32439. *
  32440. * @param [in] dcrl Decoded CRL object.
  32441. * @param [in] buff Buffer holding CRL.
  32442. * @param [in] idx Index into buffer of extensions.
  32443. * @param [in] maxIdx Maximum index of extension data.
  32444. * @return 0 on success.
  32445. * @return ASN_PARSE_E on failure.
  32446. */
  32447. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf, word32 idx,
  32448. word32 maxIdx)
  32449. {
  32450. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  32451. int ret = 0;
  32452. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, dcrl->heap);
  32453. while ((ret == 0) && (idx < maxIdx)) {
  32454. byte critical = 0;
  32455. /* Clear dynamic data. */
  32456. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  32457. /* Ensure OID is an extention type. */
  32458. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  32459. /* Set criticality variable. */
  32460. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  32461. /* Parse extension wrapper. */
  32462. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, buf, &idx,
  32463. maxIdx);
  32464. if (ret == 0) {
  32465. /* OID in extension. */
  32466. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  32467. /* Length of extension data. */
  32468. int length = dataASN[CERTEXTASN_IDX_VAL].length;
  32469. if (oid == AUTH_KEY_OID) {
  32470. #ifndef NO_SKID
  32471. /* Parse Authority Key Id extesion.
  32472. * idx is at start of OCTET_STRING data. */
  32473. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  32474. if (ret != 0) {
  32475. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  32476. }
  32477. #endif
  32478. }
  32479. /* TODO: Parse CRL Number extension */
  32480. /* TODO: check criticality */
  32481. /* Move index on to next extension. */
  32482. idx += length;
  32483. }
  32484. }
  32485. if (ret < 0) {
  32486. ret = ASN_PARSE_E;
  32487. }
  32488. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32489. return ret;
  32490. }
  32491. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32492. #ifdef WOLFSSL_ASN_TEMPLATE
  32493. /* ASN.1 template for a CRL- CertificateList.
  32494. * X.509: RFC 5280, 5.1 - CRL Fields
  32495. */
  32496. static const ASNItem crlASN[] = {
  32497. /* CertificateList */
  32498. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  32499. /* tbsCertList */
  32500. /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  32501. /* version Version OPTIONAL if present must be v2 */
  32502. /* TBS_VER */ { 2, ASN_INTEGER, 0, 0, 1 },
  32503. /* signature */
  32504. /* TBS_SIGALGO */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  32505. /* TBS_SIGALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  32506. /* TBS_SIGALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  32507. /* issuer */
  32508. /* TBS_ISSUER */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  32509. /* thisUpdate */
  32510. /* TBS_THISUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 2 },
  32511. /* TBS_THISUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 2 },
  32512. /* nextUpdate */
  32513. /* TBS_NEXTUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 3 },
  32514. /* TBS_NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 3 },
  32515. /* revokedCertificates */
  32516. /* TBS_REVOKEDCERTS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  32517. /* crlExtensions */
  32518. /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  32519. /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
  32520. /* signatureAlgorithm */
  32521. /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  32522. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  32523. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  32524. /* signatureValue */
  32525. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  32526. };
  32527. enum {
  32528. CRLASN_IDX_SEQ = 0,
  32529. CRLASN_IDX_TBS,
  32530. CRLASN_IDX_TBS_VER,
  32531. CRLASN_IDX_TBS_SIGALGO,
  32532. CRLASN_IDX_TBS_SIGALGO_OID,
  32533. CRLASN_IDX_TBS_SIGALGO_NULL,
  32534. CRLASN_IDX_TBS_ISSUER,
  32535. CRLASN_IDX_TBS_THISUPDATE_UTC,
  32536. CRLASN_IDX_TBS_THISUPDATE_GT,
  32537. CRLASN_IDX_TBS_NEXTUPDATE_UTC,
  32538. CRLASN_IDX_TBS_NEXTUPDATE_GT,
  32539. CRLASN_IDX_TBS_REVOKEDCERTS,
  32540. CRLASN_IDX_TBS_EXT,
  32541. CRLASN_IDX_TBS_EXT_SEQ,
  32542. CRLASN_IDX_SIGALGO,
  32543. CRLASN_IDX_SIGALGO_OID,
  32544. CRLASN_IDX_SIGALGO_NULL,
  32545. CRLASN_IDX_SIGNATURE,
  32546. };
  32547. /* Number of items in ASN.1 template for a CRL- CertificateList. */
  32548. #define crlASN_Length (sizeof(crlASN) / sizeof(ASNItem))
  32549. #endif
  32550. /* parse crl buffer into decoded state, 0 on success */
  32551. int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz,
  32552. int verify, void* cm)
  32553. {
  32554. #ifndef WOLFSSL_ASN_TEMPLATE
  32555. Signer* ca = NULL;
  32556. SignatureCtx sigCtx;
  32557. int ret = 0;
  32558. int len;
  32559. word32 idx = 0;
  32560. WOLFSSL_MSG("ParseCRL");
  32561. /* raw crl hash */
  32562. /* hash here if needed for optimized comparisons
  32563. * wc_Sha sha;
  32564. * wc_InitSha(&sha);
  32565. * wc_ShaUpdate(&sha, buff, sz);
  32566. * wc_ShaFinal(&sha, dcrl->crlHash); */
  32567. if (GetSequence(buff, &idx, &len, sz) < 0)
  32568. return ASN_PARSE_E;
  32569. dcrl->certBegin = idx;
  32570. /* Normalize sz for the length inside the outer sequence. */
  32571. sz = len + idx;
  32572. if (GetSequence(buff, &idx, &len, sz) < 0)
  32573. return ASN_PARSE_E;
  32574. dcrl->sigIndex = len + idx;
  32575. if (ParseCRL_CertList(rcert, dcrl, buff, &idx, dcrl->sigIndex, verify) < 0)
  32576. return ASN_PARSE_E;
  32577. if (ParseCRL_Extensions(dcrl, buff, &idx, dcrl->sigIndex) < 0)
  32578. return ASN_PARSE_E;
  32579. idx = dcrl->sigIndex;
  32580. if (GetAlgoId(buff, &idx, &dcrl->signatureOID, oidSigType, sz) < 0)
  32581. return ASN_PARSE_E;
  32582. if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
  32583. return ASN_PARSE_E;
  32584. /* openssl doesn't add skid by default for CRLs cause firefox chokes
  32585. if experiencing issues uncomment NO_SKID define in CRL section of
  32586. wolfssl/wolfcrypt/settings.h */
  32587. #ifndef NO_SKID
  32588. if (dcrl->extAuthKeyIdSet) {
  32589. ca = GetCA(cm, dcrl->extAuthKeyId); /* more unique than issuerHash */
  32590. }
  32591. if (ca != NULL && XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  32592. KEYID_SIZE) != 0) {
  32593. ca = NULL;
  32594. }
  32595. if (ca == NULL) {
  32596. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  32597. /* If AKID is available then this CA doesn't have the public
  32598. * key required */
  32599. if (ca && dcrl->extAuthKeyIdSet) {
  32600. WOLFSSL_MSG("CA SKID doesn't match AKID");
  32601. ca = NULL;
  32602. }
  32603. }
  32604. #else
  32605. ca = GetCA(cm, dcrl->issuerHash);
  32606. #endif /* !NO_SKID */
  32607. WOLFSSL_MSG("About to verify CRL signature");
  32608. if (ca == NULL) {
  32609. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  32610. ret = ASN_CRL_NO_SIGNER_E;
  32611. WOLFSSL_ERROR_VERBOSE(ret);
  32612. goto end;
  32613. }
  32614. WOLFSSL_MSG("Found CRL issuer CA");
  32615. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  32616. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  32617. dcrl->signatureOID, ca, dcrl->heap);
  32618. end:
  32619. return ret;
  32620. #else
  32621. DECL_ASNGETDATA(dataASN, crlASN_Length);
  32622. int ret = 0;
  32623. /* Default version - v1 = 0 */
  32624. byte version = 0;
  32625. word32 idx = 0;
  32626. /* Size of buffer for date. */
  32627. word32 lastDateSz = MAX_DATE_SIZE;
  32628. word32 nextDateSz = MAX_DATE_SIZE;
  32629. /* When NO_ASN_TIME is defined, verify not used. */
  32630. (void)verify;
  32631. WOLFSSL_MSG("ParseCRL");
  32632. CALLOC_ASNGETDATA(dataASN, crlASN_Length, ret, dcrl->heap);
  32633. if (ret == 0) {
  32634. /* Set variable to store version. */
  32635. GetASN_Int8Bit(&dataASN[CRLASN_IDX_TBS_VER], &version);
  32636. /* Set expecting signature OID. */
  32637. GetASN_OID(&dataASN[CRLASN_IDX_TBS_SIGALGO_OID], oidSigType);
  32638. /* Set buffer to put last and next date into. */
  32639. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC], dcrl->lastDate,
  32640. &lastDateSz);
  32641. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_GT], dcrl->lastDate,
  32642. &lastDateSz);
  32643. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC], dcrl->nextDate,
  32644. &nextDateSz);
  32645. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT], dcrl->nextDate,
  32646. &nextDateSz);
  32647. /* Set expecting signature OID. */
  32648. GetASN_OID(&dataASN[CRLASN_IDX_SIGALGO_OID], oidSigType);
  32649. /* Decode the CRL. */
  32650. ret = GetASN_Items(crlASN, dataASN, crlASN_Length, 1, buff, &idx, sz);
  32651. }
  32652. /* Version must be v2 = 1 if present. */
  32653. if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_VER].tag != 0) &&
  32654. (version != 1)) {
  32655. ret = ASN_PARSE_E;
  32656. }
  32657. /* Check minimum size of last date. */
  32658. if ((ret == 0) && (lastDateSz < MIN_DATE_SIZE)) {
  32659. ret = ASN_PARSE_E;
  32660. }
  32661. /* Check minimum size of next date. */
  32662. if ((ret == 0) && (nextDateSz < MIN_DATE_SIZE)) {
  32663. ret = ASN_PARSE_E;
  32664. }
  32665. /* 'signatureAlgorithm' OID must be the same as 'signature' OID. */
  32666. if ((ret == 0) && (dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum !=
  32667. dataASN[CRLASN_IDX_TBS_SIGALGO_OID].data.oid.sum)) {
  32668. ret = ASN_PARSE_E;
  32669. }
  32670. if (ret == 0) {
  32671. /* Store version */
  32672. dcrl->version = ++version;
  32673. /* Store offset of to be signed part. */
  32674. dcrl->certBegin = dataASN[CRLASN_IDX_TBS].offset;
  32675. /* Store index of signature. */
  32676. dcrl->sigIndex = dataASN[CRLASN_IDX_SIGALGO].offset;
  32677. /* Store address and length of signature data. */
  32678. GetASN_GetRef(&dataASN[CRLASN_IDX_SIGNATURE], &dcrl->signature,
  32679. &dcrl->sigLength);
  32680. /* Get the signature OID. */
  32681. dcrl->signatureOID = dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum;
  32682. /* Get the format/tag of the last and next date. */
  32683. dcrl->lastDateFormat = (dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag != 0)
  32684. ? dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag
  32685. : dataASN[CRLASN_IDX_TBS_THISUPDATE_GT].tag;
  32686. dcrl->nextDateFormat = (dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag != 0)
  32687. ? dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag
  32688. : dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT].tag;
  32689. #ifndef NO_ASN_TIME
  32690. if (dcrl->nextDateFormat != 0) {
  32691. /* Next date was set, so validate it. */
  32692. if (verify != NO_VERIFY &&
  32693. !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  32694. WOLFSSL_MSG("CRL after date is no longer valid");
  32695. ret = CRL_CERT_DATE_ERR;
  32696. WOLFSSL_ERROR_VERBOSE(ret);
  32697. }
  32698. }
  32699. }
  32700. if (ret == 0) {
  32701. #endif
  32702. #ifdef OPENSSL_EXTRA
  32703. /* Parse and store the issuer name. */
  32704. dcrl->issuerSz = GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER],
  32705. buff);
  32706. dcrl->issuer = (byte*)GetNameFromDer((byte*)GetASNItem_Addr(
  32707. dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  32708. (int)dcrl->issuerSz);
  32709. #endif
  32710. /* Calculate the Hash id from the issuer name. */
  32711. ret = CalcHashId(GetASNItem_Addr(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  32712. GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  32713. dcrl->issuerHash);
  32714. if (ret < 0) {
  32715. ret = ASN_PARSE_E;
  32716. }
  32717. }
  32718. if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_REVOKEDCERTS].tag != 0)) {
  32719. /* Parse revoked cerificates - starting after SEQUENCE OF. */
  32720. ret = ParseCRL_RevokedCerts(rcert, dcrl, buff,
  32721. GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff),
  32722. GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff));
  32723. }
  32724. if (ret == 0) {
  32725. /* Parse the extensions - starting after SEQUENCE OF. */
  32726. ret = ParseCRL_Extensions(dcrl, buff,
  32727. GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff),
  32728. GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff));
  32729. }
  32730. if (ret == 0) {
  32731. /* Find signer and verify signature. */
  32732. ret = PaseCRL_CheckSignature(dcrl, buff, cm);
  32733. }
  32734. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32735. return ret;
  32736. #endif /* WOLFSSL_ASN_TEMPLATE */
  32737. }
  32738. #endif /* HAVE_CRL */
  32739. #ifdef WOLFSSL_CERT_PIV
  32740. #ifdef WOLFSSL_ASN_TEMPLATE
  32741. /* Template for PIV. */
  32742. static const ASNItem pivASN[] = {
  32743. /* CERT */ { 0, ASN_PIV_CERT, 0, 0, 0 },
  32744. /* NONCE */ { 0, ASN_PIV_NONCE, 0, 0, 1 },
  32745. /* SIGNEDNONCE */ { 0, ASN_PIV_SIGNED_NONCE, 0, 0, 1 },
  32746. };
  32747. enum {
  32748. PIVASN_IDX_CERT = 0,
  32749. PIVASN_IDX_NONCE,
  32750. PIVASN_IDX_SIGNEDNONCE,
  32751. };
  32752. #define pivASN_Length (sizeof(pivASN) / sizeof(ASNItem))
  32753. static const ASNItem pivCertASN[] = {
  32754. /* 0x53 = 0x40 | 0x13 */
  32755. /* CERT */ { 1, ASN_APPLICATION | 0x13, 0, 1, 0 },
  32756. /* 0x70 = 0x40 | 0x10 + 0x20 (CONSTRUCTED) */
  32757. /* X509 */ { 2, ASN_APPLICATION | 0x10, 1, 0, 0 },
  32758. /* 0x71 = 0x40 | 0x11 + 0x20 (CONSTRUCTED) */
  32759. /* INFO */ { 2, ASN_APPLICATION | 0x11, 1, 0, 1 },
  32760. /* 0xFE = 0xC0 | 0x1E + 0x20 (CONSTRUCTED) */
  32761. /* ERR */ { 2, ASN_PRIVATE | 0x1e, 1, 0, 1 },
  32762. };
  32763. enum {
  32764. PIVCERTASN_IDX_CERT,
  32765. PIVCERTASN_IDX_X509,
  32766. PIVCERTASN_IDX_INFO,
  32767. PIVCERTASN_IDX_ERR,
  32768. };
  32769. #define pivCertASN_Length (sizeof(pivCertASN) / sizeof(ASNItem))
  32770. #endif
  32771. int wc_ParseCertPIV(wc_CertPIV* piv, const byte* buf, word32 totalSz)
  32772. {
  32773. #ifndef WOLFSSL_ASN_TEMPLATE
  32774. int length = 0;
  32775. word32 idx = 0;
  32776. WOLFSSL_ENTER("wc_ParseCertPIV");
  32777. if (piv == NULL || buf == NULL || totalSz == 0)
  32778. return BAD_FUNC_ARG;
  32779. XMEMSET(piv, 0, sizeof(wc_CertPIV));
  32780. /* Detect Identiv PIV (with 0x0A, 0x0B and 0x0C sections) */
  32781. /* Certificate (0A 82 05FA) */
  32782. if (GetASNHeader(buf, ASN_PIV_CERT, &idx, &length, totalSz) >= 0) {
  32783. /* Identiv Type PIV card */
  32784. piv->isIdentiv = 1;
  32785. piv->cert = &buf[idx];
  32786. piv->certSz = length;
  32787. idx += length;
  32788. /* Nonce (0B 14) */
  32789. if (GetASNHeader(buf, ASN_PIV_NONCE, &idx, &length, totalSz) >= 0) {
  32790. piv->nonce = &buf[idx];
  32791. piv->nonceSz = length;
  32792. idx += length;
  32793. }
  32794. /* Signed Nonce (0C 82 0100) */
  32795. if (GetASNHeader(buf, ASN_PIV_SIGNED_NONCE, &idx, &length, totalSz) >= 0) {
  32796. piv->signedNonce = &buf[idx];
  32797. piv->signedNonceSz = length;
  32798. }
  32799. idx = 0;
  32800. buf = piv->cert;
  32801. totalSz = piv->certSz;
  32802. }
  32803. /* Certificate Buffer Total Size (53 82 05F6) */
  32804. if (GetASNHeader(buf, ASN_APPLICATION | ASN_PRINTABLE_STRING, &idx,
  32805. &length, totalSz) < 0) {
  32806. return ASN_PARSE_E;
  32807. }
  32808. /* PIV Certificate (70 82 05ED) */
  32809. if (GetASNHeader(buf, ASN_PIV_TAG_CERT, &idx, &length,
  32810. totalSz) < 0) {
  32811. return ASN_PARSE_E;
  32812. }
  32813. /* Capture certificate buffer pointer and length */
  32814. piv->cert = &buf[idx];
  32815. piv->certSz = length;
  32816. idx += length;
  32817. /* PIV Certificate Info (71 01 00) */
  32818. if (GetASNHeader(buf, ASN_PIV_TAG_CERT_INFO, &idx, &length,
  32819. totalSz) >= 0) {
  32820. if (length >= 1) {
  32821. piv->compression = (buf[idx] & ASN_PIV_CERT_INFO_COMPRESSED);
  32822. piv->isX509 = ((buf[idx] & ASN_PIV_CERT_INFO_ISX509) != 0);
  32823. }
  32824. idx += length;
  32825. }
  32826. /* PIV Error Detection (FE 00) */
  32827. if (GetASNHeader(buf, ASN_PIV_TAG_ERR_DET, &idx, &length,
  32828. totalSz) >= 0) {
  32829. piv->certErrDet = &buf[idx];
  32830. piv->certErrDetSz = length;
  32831. idx += length;
  32832. }
  32833. return 0;
  32834. #else
  32835. /* pivCertASN_Length is longer than pivASN_Length */
  32836. DECL_ASNGETDATA(dataASN, pivCertASN_Length);
  32837. int ret = 0;
  32838. word32 idx;
  32839. byte info;
  32840. WOLFSSL_ENTER("wc_ParseCertPIV");
  32841. ALLOC_ASNGETDATA(dataASN, pivCertASN_Length, ret, NULL);
  32842. if (ret == 0) {
  32843. /* Clear dynamic data. */
  32844. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivASN_Length);
  32845. /* Start parsing from start of buffer. */
  32846. idx = 0;
  32847. /* Parse Identiv wrapper. */
  32848. ret = GetASN_Items(pivASN, dataASN, pivASN_Length, 1, buf, &idx,
  32849. totalSz);
  32850. if (ret == 0) {
  32851. /* Identiv wrapper found. */
  32852. piv->isIdentiv = 1;
  32853. /* Get nonce reference. */
  32854. if (dataASN[PIVASN_IDX_NONCE].tag != 0) {
  32855. GetASN_GetConstRef(&dataASN[PIVASN_IDX_NONCE], &piv->nonce,
  32856. &piv->nonceSz);
  32857. }
  32858. /* Get signedNonce reference. */
  32859. if (dataASN[PIVASN_IDX_SIGNEDNONCE].tag != 0) {
  32860. GetASN_GetConstRef(&dataASN[PIVASN_IDX_SIGNEDNONCE],
  32861. &piv->signedNonce, &piv->signedNonceSz);
  32862. }
  32863. /* Get the certificate data for parsing. */
  32864. GetASN_GetConstRef(&dataASN[PIVASN_IDX_CERT], &buf, &totalSz);
  32865. }
  32866. ret = 0;
  32867. }
  32868. if (ret == 0) {
  32869. /* Clear dynamic data and set variable to put cert info into. */
  32870. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivCertASN_Length);
  32871. GetASN_Int8Bit(&dataASN[PIVCERTASN_IDX_INFO], &info);
  32872. /* Start parsing from start of buffer. */
  32873. idx = 0;
  32874. /* Parse PIV cetificate data. */
  32875. ret = GetASN_Items(pivCertASN, dataASN, pivCertASN_Length, 1, buf, &idx,
  32876. totalSz);
  32877. if (ret == 0) {
  32878. /* Get X.509 certificate reference. */
  32879. GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_X509], &piv->cert,
  32880. &piv->certSz);
  32881. /* Set the certificate info if available. */
  32882. if (dataASN[PIVCERTASN_IDX_INFO].tag != 0) {
  32883. /* Bits 1 and 2 are compression. */
  32884. piv->compression = info & ASN_PIV_CERT_INFO_COMPRESSED;
  32885. /* Bits 3 is X509 flag. */
  32886. piv->isX509 = ((info & ASN_PIV_CERT_INFO_ISX509) != 0);
  32887. }
  32888. /* Get X.509 certificate error detection reference. */
  32889. GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_ERR], &piv->certErrDet,
  32890. &piv->certErrDetSz);
  32891. }
  32892. ret = 0;
  32893. }
  32894. FREE_ASNGETDATA(dataASN, NULL);
  32895. return ret;
  32896. #endif /* WOLFSSL_ASN_TEMPLATE */
  32897. }
  32898. #endif /* WOLFSSL_CERT_PIV */
  32899. #ifdef HAVE_SMIME
  32900. /*****************************************************************************
  32901. * wc_MIME_parse_headers - Reads the char array in and parses out MIME headers
  32902. * and parameters into headers. Will continue until in has no more content.
  32903. *
  32904. * RETURNS:
  32905. * returns zero on success, non-zero on error.
  32906. */
  32907. int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers)
  32908. {
  32909. MimeHdr* nextHdr = NULL;
  32910. MimeHdr* curHdr = NULL;
  32911. MimeParam* nextParam = NULL;
  32912. size_t start = 0;
  32913. size_t end = 0;
  32914. char* nameAttr = NULL;
  32915. char* bodyVal = NULL;
  32916. MimeTypes mimeType = MIME_HDR;
  32917. MimeStatus mimeStatus = MIME_NAMEATTR;
  32918. int ret = -1;
  32919. size_t pos = 0;
  32920. size_t lineLen = 0;
  32921. char* curLine = NULL;
  32922. char* ptr = NULL;
  32923. if (in == NULL || inLen <= 0 || in[inLen] != '\0' || headers == NULL) {
  32924. ret = BAD_FUNC_ARG;
  32925. goto error;
  32926. }
  32927. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL, DYNAMIC_TYPE_PKCS7);
  32928. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  32929. DYNAMIC_TYPE_PKCS7);
  32930. if (nextHdr == NULL || nextParam == NULL) {
  32931. ret = MEMORY_E;
  32932. goto error;
  32933. }
  32934. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  32935. XMEMSET(nextParam, 0, sizeof(MimeParam));
  32936. curLine = XSTRTOK(in, "\r\n", &ptr);
  32937. if (curLine == NULL) {
  32938. ret = ASN_PARSE_E;
  32939. goto error;
  32940. }
  32941. while (curLine != NULL) {
  32942. /* Leftover from previous line, add params to previous header. */
  32943. if (curLine[0] == ' ' && curHdr) {
  32944. mimeType = MIME_PARAM;
  32945. }
  32946. else {
  32947. mimeType = MIME_HDR;
  32948. }
  32949. start = 0;
  32950. lineLen = XSTRLEN(curLine);
  32951. if (lineLen == 0) {
  32952. ret = BAD_FUNC_ARG;
  32953. goto error;
  32954. }
  32955. for (pos = 0; pos < lineLen; pos++) {
  32956. char cur = curLine[pos];
  32957. if (mimeStatus == MIME_NAMEATTR && ((cur == ':' &&
  32958. mimeType == MIME_HDR) || (cur == '=' &&
  32959. mimeType == MIME_PARAM)) && pos >= 1) {
  32960. mimeStatus = MIME_BODYVAL;
  32961. end = pos-1;
  32962. if (nameAttr != NULL)
  32963. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  32964. ret = wc_MIME_header_strip(curLine, &nameAttr, start, end);
  32965. if (ret) {
  32966. goto error;
  32967. }
  32968. start = pos+1;
  32969. }
  32970. else if (mimeStatus == MIME_BODYVAL && cur == ';' && pos >= 1) {
  32971. end = pos-1;
  32972. if (bodyVal != NULL)
  32973. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  32974. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  32975. if (ret) {
  32976. goto error;
  32977. }
  32978. if (mimeType == MIME_HDR) {
  32979. nextHdr->name = nameAttr;
  32980. nameAttr = NULL;
  32981. nextHdr->body = bodyVal;
  32982. bodyVal = NULL;
  32983. nextHdr->next = curHdr;
  32984. curHdr = nextHdr;
  32985. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  32986. DYNAMIC_TYPE_PKCS7);
  32987. if (nextHdr == NULL) {
  32988. ret = MEMORY_E;
  32989. goto error;
  32990. }
  32991. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  32992. }
  32993. else {
  32994. nextParam->attribute = nameAttr;
  32995. nameAttr = NULL;
  32996. nextParam->value = bodyVal;
  32997. bodyVal = NULL;
  32998. nextParam->next = curHdr->params;
  32999. curHdr->params = nextParam;
  33000. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  33001. DYNAMIC_TYPE_PKCS7);
  33002. if (nextParam == NULL) {
  33003. ret = MEMORY_E;
  33004. goto error;
  33005. }
  33006. XMEMSET(nextParam, 0, sizeof(MimeParam));
  33007. }
  33008. mimeType = MIME_PARAM;
  33009. mimeStatus = MIME_NAMEATTR;
  33010. start = pos+1;
  33011. }
  33012. }
  33013. end = lineLen-1;
  33014. /* Omit newline characters. */
  33015. while ((curLine[end] == '\r' || curLine[end] == '\n') && end > 0) {
  33016. end--;
  33017. }
  33018. if (end >= start && mimeStatus == MIME_BODYVAL) {
  33019. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  33020. if (ret) {
  33021. goto error;
  33022. }
  33023. if (mimeType == MIME_HDR) {
  33024. nextHdr->name = nameAttr;
  33025. nameAttr = NULL;
  33026. nextHdr->body = bodyVal;
  33027. bodyVal = NULL;
  33028. nextHdr->next = curHdr;
  33029. curHdr = nextHdr;
  33030. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  33031. DYNAMIC_TYPE_PKCS7);
  33032. if (nextHdr == NULL) {
  33033. ret = MEMORY_E;
  33034. goto error;
  33035. }
  33036. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  33037. } else {
  33038. nextParam->attribute = nameAttr;
  33039. nameAttr = NULL;
  33040. nextParam->value = bodyVal;
  33041. bodyVal = NULL;
  33042. nextParam->next = curHdr->params;
  33043. curHdr->params = nextParam;
  33044. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  33045. DYNAMIC_TYPE_PKCS7);
  33046. if (nextParam == NULL) {
  33047. ret = MEMORY_E;
  33048. goto error;
  33049. }
  33050. XMEMSET(nextParam, 0, sizeof(MimeParam));
  33051. }
  33052. }
  33053. curLine = XSTRTOK(NULL, "\r\n", &ptr);
  33054. mimeStatus = MIME_NAMEATTR;
  33055. }
  33056. *headers = curHdr;
  33057. ret = 0; /* success if at this point */
  33058. error:
  33059. if (ret != 0)
  33060. wc_MIME_free_hdrs(curHdr);
  33061. wc_MIME_free_hdrs(nextHdr);
  33062. if (nameAttr != NULL)
  33063. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  33064. if (bodyVal != NULL)
  33065. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  33066. XFREE(nextParam, NULL, DYNAMIC_TYPE_PKCS7);
  33067. return ret;
  33068. }
  33069. /*****************************************************************************
  33070. * wc_MIME_header_strip - Reads the string in from indices start to end, strips
  33071. * out disallowed/separator characters and places the rest into *out.
  33072. *
  33073. * RETURNS:
  33074. * returns zero on success, non-zero on error.
  33075. */
  33076. int wc_MIME_header_strip(char* in, char** out, size_t start, size_t end)
  33077. {
  33078. size_t inPos = start;
  33079. size_t outPos = 0;
  33080. size_t inLen = 0;
  33081. if (end < start || in == NULL || out == NULL) {
  33082. return BAD_FUNC_ARG;
  33083. }
  33084. inLen = XSTRLEN(in);
  33085. if (start > inLen || end > inLen) {
  33086. return BAD_FUNC_ARG;
  33087. }
  33088. *out = (char*)XMALLOC(((end-start)+2)*sizeof(char), NULL,
  33089. DYNAMIC_TYPE_PKCS7);
  33090. if (*out == NULL) {
  33091. return MEMORY_E;
  33092. }
  33093. while (inPos <= end) {
  33094. if (in[inPos] >= MIME_HEADER_ASCII_MIN && in[inPos] <=
  33095. MIME_HEADER_ASCII_MAX && in[inPos] != ';' && in[inPos] != '\"') {
  33096. (*out)[outPos] = in[inPos];
  33097. outPos++;
  33098. }
  33099. inPos++;
  33100. }
  33101. (*out)[outPos] = '\0';
  33102. return 0;
  33103. }
  33104. /*****************************************************************************
  33105. * wc_MIME_find_header_name - Searches through all given headers until a header with
  33106. * a name matching the provided name is found.
  33107. *
  33108. * RETURNS:
  33109. * returns a pointer to the found header, if no match was found, returns NULL.
  33110. */
  33111. MimeHdr* wc_MIME_find_header_name(const char* name, MimeHdr* header)
  33112. {
  33113. while (header) {
  33114. if (!XSTRCMP(name, header->name)) {
  33115. return header;
  33116. }
  33117. header = header->next;
  33118. }
  33119. return header;
  33120. }
  33121. /*****************************************************************************
  33122. * wc_MIME_find_param_attr - Searches through all parameters until a parameter
  33123. * with a attribute matching the provided attribute is found.
  33124. *
  33125. * RETURNS:
  33126. * returns a pointer to the found parameter, if no match was found,
  33127. * returns NULL.
  33128. */
  33129. MimeParam* wc_MIME_find_param_attr(const char* attribute,
  33130. MimeParam* param)
  33131. {
  33132. while (param) {
  33133. if (!XSTRCMP(attribute, param->attribute)) {
  33134. return param;
  33135. }
  33136. param = param->next;
  33137. }
  33138. return param;
  33139. }
  33140. /*****************************************************************************
  33141. * wc_MIME_single_canonicalize - Canonicalize a line by converting the trailing
  33142. * line ending to CRLF.
  33143. *
  33144. * line - input line to canonicalize
  33145. * len - length of line in chars on input, length of output array on return
  33146. *
  33147. * RETURNS:
  33148. * returns a pointer to a canonicalized line on success, NULL on error.
  33149. */
  33150. char* wc_MIME_single_canonicalize(const char* line, word32* len)
  33151. {
  33152. size_t end = 0;
  33153. char* canonLine = NULL;
  33154. if (line == NULL || len == NULL || *len == 0) {
  33155. return NULL;
  33156. }
  33157. end = *len;
  33158. while (end >= 1 && ((line[end-1] == '\r') || (line[end-1] == '\n'))) {
  33159. end--;
  33160. }
  33161. /* Need 2 chars for \r\n and 1 for EOL */
  33162. canonLine = (char*)XMALLOC((end+3)*sizeof(char), NULL, DYNAMIC_TYPE_PKCS7);
  33163. if (canonLine == NULL) {
  33164. return NULL;
  33165. }
  33166. XMEMCPY(canonLine, line, end);
  33167. canonLine[end] = '\r';
  33168. canonLine[end+1] = '\n';
  33169. canonLine[end+2] = '\0';
  33170. *len = (word32)(end + 3);
  33171. return canonLine;
  33172. }
  33173. /*****************************************************************************
  33174. * wc_MIME_free_hdrs - Frees all MIME headers, parameters and strings starting from
  33175. * the provided header pointer.
  33176. *
  33177. * RETURNS:
  33178. * returns zero on success, non-zero on error.
  33179. */
  33180. int wc_MIME_free_hdrs(MimeHdr* head)
  33181. {
  33182. MimeHdr* curHdr = NULL;
  33183. MimeParam* curParam = NULL;
  33184. while (head) {
  33185. while (head->params) {
  33186. curParam = head->params;
  33187. head->params = head->params->next;
  33188. XFREE(curParam->attribute, NULL, DYNAMIC_TYPE_PKCS7);
  33189. XFREE(curParam->value, NULL, DYNAMIC_TYPE_PKCS7);
  33190. XFREE(curParam, NULL, DYNAMIC_TYPE_PKCS7);
  33191. }
  33192. curHdr = head;
  33193. head = head->next;
  33194. XFREE(curHdr->name, NULL, DYNAMIC_TYPE_PKCS7);
  33195. XFREE(curHdr->body, NULL, DYNAMIC_TYPE_PKCS7);
  33196. XFREE(curHdr, NULL, DYNAMIC_TYPE_PKCS7);
  33197. }
  33198. return 0;
  33199. }
  33200. #endif /* HAVE_SMIME */
  33201. #undef ERROR_OUT
  33202. #ifdef WOLFSSL_ASN_PRINT
  33203. /*******************************************************************************
  33204. * ASN.1 Parsing and Printing Implemenation
  33205. ******************************************************************************/
  33206. /* Initialize ASN.1 print options.
  33207. *
  33208. * @param [in, out] opts ASN.1 options for printing.
  33209. * @return 0 on success.
  33210. * @return BAD_FUNC_ARG when asn1 is NULL.
  33211. */
  33212. int wc_Asn1PrintOptions_Init(Asn1PrintOptions* opts)
  33213. {
  33214. int ret = 0;
  33215. if (opts == NULL) {
  33216. ret = BAD_FUNC_ARG;
  33217. }
  33218. else {
  33219. XMEMSET(opts, 0, sizeof(*opts));
  33220. }
  33221. return ret;
  33222. }
  33223. /* Set a print option into Asn1PrintOptions object.
  33224. *
  33225. * @param [in, out] opts ASN.1 options for printing.
  33226. * @param [in] opt Option to set value of.
  33227. * @param [in] val Value to set for option.
  33228. * @return 0 on success.
  33229. * @return BAD_FUNC_ARG when asn1 is NULL.
  33230. * @return BAD_FUNC_ARG when val is out of range for option.
  33231. */
  33232. int wc_Asn1PrintOptions_Set(Asn1PrintOptions* opts, enum Asn1PrintOpt opt,
  33233. word32 val)
  33234. {
  33235. int ret = 0;
  33236. /* Validate parameters. */
  33237. if (opts == NULL) {
  33238. ret = BAD_FUNC_ARG;
  33239. }
  33240. if (ret == 0) {
  33241. switch (opt) {
  33242. /* Offset into DER/BER data to start decoding from. */
  33243. case ASN1_PRINT_OPT_OFFSET:
  33244. opts->offset = val;
  33245. break;
  33246. /* Length of DER/BER encoding to parse. */
  33247. case ASN1_PRINT_OPT_LENGTH:
  33248. opts->length = val;
  33249. break;
  33250. /* Number of spaces to indent for each change in depth. */
  33251. case ASN1_PRINT_OPT_INDENT:
  33252. /* Only 4 bits allowed for value. */
  33253. if (val >= (1 << 4)) {
  33254. ret = BAD_FUNC_ARG;
  33255. }
  33256. else {
  33257. opts->indent = (word8)val;
  33258. }
  33259. break;
  33260. /* Draw branches instead of indenting. */
  33261. case ASN1_PRINT_OPT_DRAW_BRANCH:
  33262. /* Boolean value. */
  33263. opts->draw_branch = (val > 0);
  33264. break;
  33265. /* Show raw data of primitive types as octets. */
  33266. case ASN1_PRINT_OPT_SHOW_DATA:
  33267. /* Boolean value. */
  33268. opts->show_data = (val > 0);
  33269. break;
  33270. /* Show header data as octets. */
  33271. case ASN1_PRINT_OPT_SHOW_HEADER_DATA:
  33272. /* Boolean value. */
  33273. opts->show_header_data = (val > 0);
  33274. break;
  33275. /* Show the wolfSSL OID value for OBJECT_ID. */
  33276. case ASN1_PRINT_OPT_SHOW_OID:
  33277. /* Boolean value. */
  33278. opts->show_oid = (val > 0);
  33279. break;
  33280. /* Don't show text representations of primitive types. */
  33281. case ASN1_PRINT_OPT_SHOW_NO_TEXT:
  33282. /* Boolean value. */
  33283. opts->show_no_text = (val > 0);
  33284. break;
  33285. /* Don't show dump text representations of primitive types. */
  33286. case ASN1_PRINT_OPT_SHOW_NO_DUMP_TEXT:
  33287. /* Boolean value. */
  33288. opts->show_no_dump_text = (val > 0);
  33289. break;
  33290. }
  33291. }
  33292. return ret;
  33293. }
  33294. /* Initialize an ASN.1 parse object.
  33295. *
  33296. * @param [in, out] asn1 ASN.1 parse object.
  33297. * @return 0 on success.
  33298. * @return BAD_FUNC_ARG when asn1 is NULL.
  33299. */
  33300. int wc_Asn1_Init(Asn1* asn1)
  33301. {
  33302. int ret = 0;
  33303. if (asn1 == NULL) {
  33304. ret = BAD_FUNC_ARG;
  33305. }
  33306. else {
  33307. XMEMSET(asn1, 0, sizeof(*asn1));
  33308. asn1->file = XBADFILE;
  33309. }
  33310. return ret;
  33311. }
  33312. /* Set the file to use when printing.
  33313. *
  33314. * @param [in, out] asn1 ASN.1 parse object.
  33315. * @param [in] file File to print to.
  33316. * @return 0 on success.
  33317. * @return BAD_FUNC_ARG when asn1 is NULL.
  33318. * @return BAD_FUNC_ARG when file is XBADFILE.
  33319. */
  33320. int wc_Asn1_SetFile(Asn1* asn1, XFILE file)
  33321. {
  33322. int ret = 0;
  33323. if ((asn1 == NULL) || (file == XBADFILE)) {
  33324. ret = BAD_FUNC_ARG;
  33325. }
  33326. else {
  33327. asn1->file = file;
  33328. }
  33329. return ret;
  33330. }
  33331. /* Maximum OID dotted form size. */
  33332. #define ASN1_OID_DOTTED_MAX_SZ 16
  33333. /* Print OID in dotted form or as hex bytes.
  33334. *
  33335. * @param [in] file File pointer to write to.
  33336. * @param [in] oid OBJECT_ID data.
  33337. * @param [in] oid_len Length of OBJECT_ID data.
  33338. */
  33339. static void PrintObjectIdNum(XFILE file, unsigned char* oid, word32 len)
  33340. {
  33341. word16 dotted_nums[ASN1_OID_DOTTED_MAX_SZ];
  33342. word32 num = ASN1_OID_DOTTED_MAX_SZ;
  33343. word32 i;
  33344. /* Decode OBJECT_ID into dotted form array. */
  33345. if (DecodeObjectId(oid, len, dotted_nums, &num) == 0) {
  33346. /* Print out each number of dotted form. */
  33347. for (i = 0; i < num; i++) {
  33348. XFPRINTF(file, "%d", dotted_nums[i]);
  33349. /* Add separetor. */
  33350. if (i < num - 1) {
  33351. XFPRINTF(file, ".");
  33352. }
  33353. }
  33354. }
  33355. else {
  33356. /* Print out bytes as we couldn't decode. */
  33357. for (i = 0; i < len; i++) {
  33358. XFPRINTF(file, "%02x", oid[i]);
  33359. /* Add separetor. */
  33360. if (i < len - 1) {
  33361. XFPRINTF(file, ":");
  33362. }
  33363. }
  33364. }
  33365. }
  33366. /* OID value to name mapping. */
  33367. typedef struct OidName {
  33368. /* wolfSSL OID value. */
  33369. word32 oid;
  33370. /* Long name to print when OID seen. */
  33371. const char* name;
  33372. } OidName;
  33373. /* Extra OID to name mappings. */
  33374. static const OidName extraOids[] = {
  33375. { 0x005c, "commonName" },
  33376. { 0x005d, "surname" },
  33377. { 0x005e, "serialNumber" },
  33378. { 0x005f, "countryName" },
  33379. { 0x0060, "localityName" },
  33380. { 0x0061, "stateOrProvinceName" },
  33381. { 0x0062, "streetAddress" },
  33382. { 0x0063, "organizationName" },
  33383. { 0x0064, "organizationUnitName" },
  33384. { 0x0065, "title" },
  33385. { 0x0086, "certificateExtension" },
  33386. { 0x028d, "emailAddress" },
  33387. { 0x0293, "challengePassword" },
  33388. { 0x029a, "extensionReq" },
  33389. };
  33390. /* Length of table of extra OID to name mappings. */
  33391. #define EXTRA_OIDS_LEN ((int)(sizeof(extraOids) / sizeof(*extraOids)))
  33392. /* Convert OID value to long name.
  33393. *
  33394. * @param [in] oid OID value.
  33395. * @param [out] name Long name for OID when known.
  33396. * @return 1 when OID known.
  33397. * @return 0 when OID not known.
  33398. */
  33399. static int Oid2LongName(word32 oid, const char** name)
  33400. {
  33401. int ret = 0;
  33402. int i;
  33403. /* Step through each entry in table. */
  33404. for (i = 0; i < EXTRA_OIDS_LEN; i++) {
  33405. if (extraOids[i].oid == oid) {
  33406. /* Return the name associated with the OID value. */
  33407. *name = extraOids[i].name;
  33408. ret = 1;
  33409. break;
  33410. }
  33411. }
  33412. return ret;
  33413. }
  33414. /* Print the text version of the OBJECT_ID.
  33415. *
  33416. * @param [in] asn1 ASN.1 parse object.
  33417. * @param [in] opts ASN.1 options for printing.
  33418. */
  33419. static void PrintObjectIdText(Asn1* asn1, Asn1PrintOptions* opts)
  33420. {
  33421. word32 oid = (word32)-1;
  33422. #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
  33423. int nid;
  33424. #endif
  33425. const char* ln = NULL;
  33426. word32 i = 0;
  33427. int known = 1;
  33428. /* Get the OID value for the OBJECT_ID. */
  33429. GetObjectId(asn1->data + asn1->offset, &i, &oid, oidIgnoreType,
  33430. asn1->item.len + 2);
  33431. #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
  33432. /* Lookup NID for OID value. */
  33433. if ((nid = oid2nid(oid, oidIgnoreType)) != -1) {
  33434. /* Lookup long name for NID. */
  33435. ln = wolfSSL_OBJ_nid2ln(nid);
  33436. }
  33437. else
  33438. #endif
  33439. /* Lookup long name for extra known OID values. */
  33440. if (!Oid2LongName(oid, &ln)) {
  33441. /* Unknown OID value. */
  33442. ln = NULL;
  33443. known = 0;
  33444. }
  33445. XFPRINTF(asn1->file, ":");
  33446. /* Show OID value if not known or asked to. */
  33447. if ((!known) || opts->show_oid) {
  33448. XFPRINTF(asn1->file, "(0x%x) ", oid);
  33449. }
  33450. if (ln != NULL) {
  33451. /* Print long name. */
  33452. XFPRINTF(asn1->file, "%s", ln);
  33453. }
  33454. else {
  33455. /* Print out as numbers - either dotted or hex values. */
  33456. PrintObjectIdNum(asn1->file, asn1->data + asn1->item.data_idx,
  33457. asn1->item.len);
  33458. }
  33459. }
  33460. /* Print ASN.1 data as a character string.
  33461. *
  33462. * @param [in] asn1 ASN.1 parse object.
  33463. */
  33464. static void PrintText(Asn1* asn1)
  33465. {
  33466. word32 i;
  33467. XFPRINTF(asn1->file, ":");
  33468. /* Print all data bytes as characters. */
  33469. for (i = 0; i < asn1->item.len; i++) {
  33470. XFPRINTF(asn1->file, "%c", asn1->data[asn1->item.data_idx + i]);
  33471. }
  33472. }
  33473. /* Print data as a hex bytes.
  33474. *
  33475. * @param [in] file File pointer to write to.
  33476. * @param [in] data Data to print.
  33477. * @param [in] len Number of bytes to print.
  33478. */
  33479. static void PrintHex(XFILE file, unsigned char* data, word32 len)
  33480. {
  33481. word32 i;
  33482. /* Print data bytes as hex numbers. */
  33483. for (i = 0; i < len; i++) {
  33484. XFPRINTF(file, "%02x", data[i]);
  33485. }
  33486. }
  33487. /* Print ASN.1 data as a hex bytes.
  33488. *
  33489. * @param [in] asn1 ASN.1 parse object.
  33490. */
  33491. static void PrintHexText(Asn1* asn1)
  33492. {
  33493. XFPRINTF(asn1->file, ":");
  33494. PrintHex(asn1->file, asn1->data + asn1->item.data_idx, asn1->item.len);
  33495. }
  33496. /* Print ASN.1 BIT_STRING data as hex bytes noting special first byte.
  33497. *
  33498. * @param [in] asn1 ASN.1 parse object.
  33499. */
  33500. static void PrintBitStringText(Asn1* asn1)
  33501. {
  33502. if (asn1->item.len > 0) {
  33503. XFPRINTF(asn1->file, ":[%02x]", asn1->data[asn1->item.data_idx]);
  33504. PrintHex(asn1->file, asn1->data + asn1->item.data_idx + 1,
  33505. asn1->item.len - 1);
  33506. }
  33507. }
  33508. /* Print ASN.1 BOOLEAN data as text with value.
  33509. *
  33510. * @param [in] asn1 ASN.1 parse object.
  33511. */
  33512. static void PrintBooleanText(Asn1* asn1)
  33513. {
  33514. /* Booleans should be 1 byte of data. */
  33515. if (asn1->item.len == 1) {
  33516. XFPRINTF(asn1->file, ":%s (%d)",
  33517. (asn1->data[asn1->item.data_idx] == 0) ? "FALSE" : "TRUE",
  33518. asn1->data[asn1->item.data_idx]);
  33519. }
  33520. }
  33521. /* Print ASN.1 data as single byte +/- number.
  33522. *
  33523. * @param [in] asn1 ASN.1 parse object.
  33524. */
  33525. static void PrintNumberText(Asn1* asn1)
  33526. {
  33527. /* Only supporting 1 byte of data for now. */
  33528. if (asn1->item.len == 1) {
  33529. int num = asn1->data[asn1->item.data_idx];
  33530. XFPRINTF(asn1->file, ":%d", num >= 0x80 ? num - 0x100 : num);
  33531. }
  33532. }
  33533. /* Print ASN.1 data as a text based on the tag.
  33534. *
  33535. * TODO: handle more tags.
  33536. *
  33537. * @param [in] asn1 ASN.1 parse object.
  33538. * @param [in] opts ASN.1 options for printing.
  33539. */
  33540. static void PrintAsn1Text(Asn1* asn1, Asn1PrintOptions* opts)
  33541. {
  33542. /* Get the long name for OBJECT_ID where possible. */
  33543. if (asn1->item.tag == ASN_OBJECT_ID) {
  33544. PrintObjectIdText(asn1, opts);
  33545. }
  33546. /* Data is an array of printable characters. */
  33547. else if ((asn1->item.tag == ASN_UTF8STRING) ||
  33548. (asn1->item.tag == ASN_IA5_STRING) ||
  33549. (asn1->item.tag == ASN_PRINTABLE_STRING) ||
  33550. (asn1->item.tag == ASN_T61STRING) ||
  33551. (asn1->item.tag == ASN_BMPSTRING) ||
  33552. (asn1->item.tag == ASN_UTC_TIME) ||
  33553. (asn1->item.tag == ASN_GENERALIZED_TIME) ||
  33554. (asn1->item.tag == ASN_UNIVERSALSTRING) ||
  33555. (asn1->item.tag == ASN_OBJECT_DESC) ||
  33556. (asn1->item.tag == ASN_CHARACTER_STRING)) {
  33557. PrintText(asn1);
  33558. }
  33559. /* Show TRUE and FALSE with number. */
  33560. else if (asn1->item.tag == ASN_BOOLEAN) {
  33561. PrintBooleanText(asn1);
  33562. }
  33563. /* Show number. */
  33564. else if (asn1->item.tag == ASN_ENUMERATED) {
  33565. PrintNumberText(asn1);
  33566. }
  33567. /* Dumping potentially long string of hex digites. */
  33568. else if (!opts->show_no_dump_text) {
  33569. /* Dump all bytes. */
  33570. if ((asn1->item.tag == ASN_INTEGER) ||
  33571. (asn1->item.tag == ASN_OCTET_STRING) ||
  33572. ((asn1->item.tag > ASN_APPLICATION) && (asn1->item.cons))) {
  33573. PrintHexText(asn1);
  33574. }
  33575. /* First byte is number of unused bits in last byte.
  33576. * Print first specially and dump rest of the bytes. */
  33577. else if (asn1->item.tag == ASN_BIT_STRING) {
  33578. PrintBitStringText(asn1);
  33579. }
  33580. }
  33581. }
  33582. #define HexToChar(n) ((((n) >= 32) && ((n) < 127)) ? (n) : '.')
  33583. /* Dump data as hex bytes.
  33584. *
  33585. * @param [in] file File pointer to write to.
  33586. * @param [in] data Data to print.
  33587. * @param [in] len Number of bytes to print.
  33588. */
  33589. static void DumpData(XFILE file, unsigned char* data, word32 len)
  33590. {
  33591. word32 i;
  33592. word32 j;
  33593. for (i = 0; i < len; i += j) {
  33594. /* Print offset. */
  33595. XFPRINTF(file, " %04x:", i);
  33596. for (j = 0; (j < 16) && (i + j < len); j++) {
  33597. /* Print byte as hex number. */
  33598. XFPRINTF(file, "%s%02x", (j == 8) ? " " : " ", data[i + j]);
  33599. }
  33600. /* Print spaces between hex and characters. */
  33601. XFPRINTF(file, " %*s", (16 - j) * 3 + ((j < 8) ? 1 : 0), "");
  33602. for (j = 0; (j < 16) && (i + j < len); j++) {
  33603. /* Print byte as hex number. */
  33604. XFPRINTF(file, "%c", HexToChar(data[i + j]));
  33605. }
  33606. XFPRINTF(file, "\n");
  33607. }
  33608. }
  33609. /* Update current depth based on the current position.
  33610. *
  33611. * @param [in, out] asn1 ASN.1 parse object.
  33612. */
  33613. static void UpdateDepth(Asn1* asn1)
  33614. {
  33615. /* If current index is greater than or equal end index then it is done. */
  33616. while ((asn1->depth > 0) &&
  33617. (asn1->end_idx[asn1->depth-1] <= asn1->curr)) {
  33618. /* Move up a depth. */
  33619. asn1->depth--;
  33620. }
  33621. }
  33622. /* Check validity of end index of constructed ASN.1 items.
  33623. *
  33624. * @param [in, out] asn1 ASN.1 parse object.
  33625. * @return 0 on success.
  33626. * @return ASN_DEPTH_E when end offset invalid.
  33627. */
  33628. static int CheckDepth(Asn1* asn1)
  33629. {
  33630. int ret = 0;
  33631. int i;
  33632. word32 curr_end = asn1->curr + asn1->item.len;
  33633. for (i = 0; (ret == 0) && (i < asn1->depth); i++) {
  33634. /* Each end index must be at least as large as the current one. */
  33635. if (asn1->end_idx[i] < asn1->end_idx[asn1->depth]) {
  33636. ret = ASN_DEPTH_E;
  33637. }
  33638. /* Each end index must be at least as large as current index. */
  33639. if (asn1->end_idx[i] < curr_end) {
  33640. ret = ASN_DEPTH_E;
  33641. }
  33642. }
  33643. return ret;
  33644. }
  33645. /* Draw branching based on depth for an ASN.1 item.
  33646. *
  33647. * @param [in] asn1 ASN.1 parse object.
  33648. */
  33649. static void DrawBranch(Asn1* asn1)
  33650. {
  33651. int i;
  33652. word32 end = asn1->curr + asn1->item.len;
  33653. /* Write out the character for all depths but current. */
  33654. for (i = 0; i < asn1->depth; i++) {
  33655. if (asn1->item.cons || (end < asn1->end_idx[i])) {
  33656. if (i < asn1->depth - 1) {
  33657. /* Constructed or not end index and not current depth: | */
  33658. XFPRINTF(asn1->file, "\xe2\x94\x82");
  33659. }
  33660. else {
  33661. /* Constructed or not end index and current depth: |- */
  33662. XFPRINTF(asn1->file, "\xe2\x94\x9c");
  33663. }
  33664. }
  33665. else if ((i > 1) && (end >= asn1->end_idx[i-1])) {
  33666. /* End index for previous: _|_ (in top half) */
  33667. XFPRINTF(asn1->file, "\xe2\x94\xb4");
  33668. }
  33669. else {
  33670. /* End index but not for previous: L (in top half) */
  33671. XFPRINTF(asn1->file, "\xe2\x94\x94");
  33672. }
  33673. }
  33674. /* Prefix to tag name. */
  33675. if (asn1->item.cons) {
  33676. if (asn1->depth > 0) {
  33677. /* Have other line to connect to: T (in bottom half) */
  33678. XFPRINTF(asn1->file, "\xe2\x94\xac");
  33679. }
  33680. else {
  33681. /* Have no other line to connect to: r */
  33682. XFPRINTF(asn1->file, "\xe2\x94\x8c");
  33683. }
  33684. }
  33685. else {
  33686. /* In a sequence: - */
  33687. XFPRINTF(asn1->file, "\xe2\x94\x80");
  33688. }
  33689. }
  33690. /* Print data as hex bytes separated by space.
  33691. *
  33692. * @param [in] file File pointer to write to.
  33693. * @param [in] data Data to print.
  33694. * @param [in] len Number of bytes to print.
  33695. */
  33696. static void PrintHexBytes(XFILE file, unsigned char* data, word32 len)
  33697. {
  33698. word32 i;
  33699. for (i = 0; i < len; i++) {
  33700. XFPRINTF(file, " %02x", data[i]);
  33701. }
  33702. }
  33703. /* Dump header data.
  33704. *
  33705. * @param [in] asn1 ASN.1 parse object.
  33706. * @param [in] opts ASN.1 options for printing.
  33707. */
  33708. static void DumpHeader(Asn1* asn1, Asn1PrintOptions* opts)
  33709. {
  33710. /* Put on same line when not showing data too and not showing text data. */
  33711. if ((!opts->show_data) && opts->show_no_text) {
  33712. XFPRINTF(asn1->file, "%10s", "");
  33713. }
  33714. else {
  33715. /* Align with start of data. */
  33716. XFPRINTF(asn1->file, "\n%12s", "");
  33717. }
  33718. XFPRINTF(asn1->file, " %02x", asn1->item.tag);
  33719. if (asn1->curr >= asn1->offset + 1) {
  33720. /* Print the header bytes as hex bytes separated by a space. */
  33721. PrintHexBytes(asn1->file, asn1->data + asn1->offset + 1,
  33722. asn1->curr - (asn1->offset + 1));
  33723. }
  33724. }
  33725. /* Print ASN.1 item info based on header and indeces.
  33726. *
  33727. * @param [in] asn1 ASN.1 parse object.
  33728. * @param [in] opts ASN.1 options for printing.
  33729. */
  33730. static void PrintInfo(Asn1* asn1, Asn1PrintOptions* opts)
  33731. {
  33732. /* Print offset of this ASN.1 item. */
  33733. XFPRINTF(asn1->file, "%4d: ", asn1->offset);
  33734. /* Print length of header. */
  33735. XFPRINTF(asn1->file, "%1d ", asn1->curr - asn1->offset);
  33736. /* Print data length. */
  33737. XFPRINTF(asn1->file, "%c%4d%c", asn1->item.cons ? '[' : '+', asn1->item.len,
  33738. asn1->item.cons ? ']' : ' ');
  33739. /* Print depth. */
  33740. XFPRINTF(asn1->file, " %s(%d)", (asn1->depth < 10) ? " " : "", asn1->depth);
  33741. if (!opts->draw_branch) {
  33742. /* Indent to depth as required. */
  33743. XFPRINTF(asn1->file, "%*s ", asn1->depth * opts->indent, "");
  33744. if (!opts->indent) {
  33745. /* Indicate constructed if no indent. */
  33746. XFPRINTF(asn1->file, "%c", asn1->item.cons ? '+' : ' ');
  33747. }
  33748. }
  33749. else {
  33750. /* Draw branch structure for ASN.1 item. */
  33751. XFPRINTF(asn1->file, " ");
  33752. DrawBranch(asn1);
  33753. }
  33754. /* Print tag name. */
  33755. XFPRINTF(asn1->file, "%-16s", TagString(asn1->item.tag));
  33756. }
  33757. /* Expecting tag part of ASN.1 item. */
  33758. #define ASN_PART_TAG 0
  33759. /* Expecting length part of ASN.1 item. */
  33760. #define ASN_PART_LENGTH 1
  33761. /* Expecting data part of ASN.1 item. */
  33762. #define ASN_PART_DATA 2
  33763. /* Print next ASN.1 item.
  33764. *
  33765. * @param [in, out] asn1 ASN.1 parse object.
  33766. * @param [in] opts ASN.1 print options.
  33767. * @return 0 on success.
  33768. * @return BAD_FUNC_ARG when asn1 or opts is NULL.
  33769. * @return ASN_LEN_E when ASN.1 item's length too long.
  33770. * @return ASN_DEPTH_E when end offset invalid.
  33771. */
  33772. static int wc_Asn1_Print(Asn1* asn1, Asn1PrintOptions* opts)
  33773. {
  33774. int ret = 0;
  33775. /* Process tag. */
  33776. if (asn1->part == ASN_PART_TAG) {
  33777. /* Recalculate which depth we are at. */
  33778. UpdateDepth(asn1);
  33779. /* Get tag. */
  33780. asn1->item.tag = asn1->data[asn1->curr] & (byte)~ASN_CONSTRUCTED;
  33781. /* Store whether tag indicates constructed. */
  33782. asn1->item.cons = (asn1->data[asn1->curr] & ASN_CONSTRUCTED) ==
  33783. ASN_CONSTRUCTED;
  33784. /* Start of ASN.1 item is current index. */
  33785. asn1->offset = asn1->curr;
  33786. /* Step over tag. */
  33787. asn1->curr++;
  33788. /* Next part is length. */
  33789. asn1->part = ASN_PART_LENGTH;
  33790. }
  33791. /* Process length. */
  33792. if (asn1->part == ASN_PART_LENGTH) {
  33793. int len;
  33794. /* Decode length and step over it. */
  33795. if (GetLength(asn1->data, &asn1->curr, &len, asn1->max) < 0) {
  33796. ret = ASN_LEN_E;
  33797. }
  33798. else {
  33799. /* Store ASN.1 item data offset. */
  33800. asn1->item.data_idx = asn1->curr;
  33801. /* Store ASN.1 item data length. */
  33802. asn1->item.len = (word32)len;
  33803. /* Print info about ASN.1 item. */
  33804. PrintInfo(asn1, opts);
  33805. if (!asn1->item.cons) {
  33806. /* Move on to print data. */
  33807. asn1->part = ASN_PART_DATA;
  33808. }
  33809. else {
  33810. /* Print header now if not printing data. */
  33811. if (opts->show_header_data) {
  33812. DumpHeader(asn1, opts);
  33813. }
  33814. XFPRINTF(asn1->file, "\n");
  33815. /* Record end offset for this depth. */
  33816. asn1->end_idx[asn1->depth++] = asn1->curr + asn1->item.len;
  33817. /* Done with this ASN.1 item. */
  33818. asn1->part = ASN_PART_TAG;
  33819. }
  33820. /* Check end indeces are valid. */
  33821. ret = CheckDepth(asn1);
  33822. }
  33823. }
  33824. /* Process data. */
  33825. if ((ret == 0) && (asn1->part == ASN_PART_DATA)) {
  33826. if (!opts->show_no_text) {
  33827. /* Print text representation of data. */
  33828. PrintAsn1Text(asn1, opts);
  33829. }
  33830. if (opts->show_header_data) {
  33831. /* Dump header bytes. */
  33832. DumpHeader(asn1, opts);
  33833. }
  33834. XFPRINTF(asn1->file, "\n");
  33835. if (opts->show_data) {
  33836. /* Dump data bytes. */
  33837. DumpData(asn1->file, asn1->data + asn1->item.data_idx,
  33838. asn1->item.len);
  33839. }
  33840. /* Step past data to next ASN.1 item. */
  33841. asn1->curr += asn1->item.len;
  33842. /* Update the depth based on end indeces. */
  33843. UpdateDepth(asn1);
  33844. /* Done with this ASN.1 item. */
  33845. asn1->part = ASN_PART_TAG;
  33846. }
  33847. /* Make ASN.1 item printing go out. */
  33848. fflush(asn1->file);
  33849. return ret;
  33850. }
  33851. /* Print all ASN.1 items.
  33852. *
  33853. * @param [in, out] asn1 ASN.1 parse object.
  33854. * @param [in] opts ASN.1 print options.
  33855. * @param [in] data BER/DER data to print.
  33856. * @param [in] len Length of data to print in bytes.
  33857. * @return 0 on success.
  33858. * @return BAD_FUNC_ARG when asn1, opts or data is NULL.
  33859. * @return ASN_LEN_E when ASN.1 item's length too long.
  33860. * @return ASN_DEPTH_E when end offset invalid.
  33861. * @return ASN_PARSE_E when not all of an ASN.1 item parsed.
  33862. */
  33863. int wc_Asn1_PrintAll(Asn1* asn1, Asn1PrintOptions* opts, unsigned char* data,
  33864. word32 len)
  33865. {
  33866. int ret = 0;
  33867. if ((asn1 == NULL) || (opts == NULL) || (data == NULL)) {
  33868. ret = BAD_FUNC_ARG;
  33869. }
  33870. if (ret == 0) {
  33871. /* Initialize start position. */
  33872. asn1->curr = 0;
  33873. /* Start parsing at tag. */
  33874. asn1->part = ASN_PART_TAG;
  33875. /* Start depth at 0. */
  33876. asn1->depth = 0;
  33877. /* Store the starting point of the data to parse. */
  33878. asn1->data = data + opts->offset;
  33879. if (opts->length > 0) {
  33880. /* Use user specified maximum length. */
  33881. asn1->max = opts->length;
  33882. }
  33883. else {
  33884. /* Maximum length is up to end from offset. */
  33885. asn1->max = len - opts->offset;
  33886. }
  33887. /* Keep going while no error and have data to parse. */
  33888. while ((ret == 0) && (asn1->curr < asn1->max)) {
  33889. /* Print an ASN.1 item. */
  33890. ret = wc_Asn1_Print(asn1, opts);
  33891. }
  33892. }
  33893. if ((ret == 0) && (asn1->part != ASN_PART_TAG)) {
  33894. /* Stopped before finishing ASN.1 item. */
  33895. ret = ASN_PARSE_E;
  33896. }
  33897. if ((ret == 0) && (asn1->depth != 0)) {
  33898. /* Stopped without seeing all items in a constructed item. */
  33899. ret = ASN_DEPTH_E;
  33900. }
  33901. return ret;
  33902. }
  33903. #endif /* WOLFSSL_ASN_PRINT */
  33904. #endif /* !NO_ASN */
  33905. /* Functions that parse, but are not using ASN.1 */
  33906. #if !defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
  33907. (!defined(NO_BIG_INT) || defined(WOLFSSL_SP_MATH))
  33908. /* import RSA public key elements (n, e) into RsaKey structure (key) */
  33909. /* this function does not use any ASN.1 parsing */
  33910. int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e,
  33911. word32 eSz, RsaKey* key)
  33912. {
  33913. if (n == NULL || e == NULL || key == NULL)
  33914. return BAD_FUNC_ARG;
  33915. key->type = RSA_PUBLIC;
  33916. if (mp_init(&key->n) != MP_OKAY)
  33917. return MP_INIT_E;
  33918. if (mp_read_unsigned_bin(&key->n, n, nSz) != 0) {
  33919. mp_clear(&key->n);
  33920. return ASN_GETINT_E;
  33921. }
  33922. #ifdef HAVE_WOLF_BIGINT
  33923. if ((int)nSz > 0 && wc_bigint_from_unsigned_bin(&key->n.raw, n, nSz) != 0) {
  33924. mp_clear(&key->n);
  33925. return ASN_GETINT_E;
  33926. }
  33927. #endif /* HAVE_WOLF_BIGINT */
  33928. if (mp_init(&key->e) != MP_OKAY) {
  33929. mp_clear(&key->n);
  33930. return MP_INIT_E;
  33931. }
  33932. if (mp_read_unsigned_bin(&key->e, e, eSz) != 0) {
  33933. mp_clear(&key->n);
  33934. mp_clear(&key->e);
  33935. return ASN_GETINT_E;
  33936. }
  33937. #ifdef HAVE_WOLF_BIGINT
  33938. if ((int)eSz > 0 && wc_bigint_from_unsigned_bin(&key->e.raw, e, eSz) != 0) {
  33939. mp_clear(&key->n);
  33940. mp_clear(&key->e);
  33941. return ASN_GETINT_E;
  33942. }
  33943. #endif /* HAVE_WOLF_BIGINT */
  33944. #ifdef WOLFSSL_XILINX_CRYPT
  33945. if (wc_InitRsaHw(key) != 0) {
  33946. return BAD_STATE_E;
  33947. }
  33948. #endif
  33949. return 0;
  33950. }
  33951. #endif /* !NO_RSA && !HAVE_USER_RSA && (!NO_BIG_INT || WOLFSSL_SP_MATH) */
  33952. #ifdef WOLFSSL_SEP
  33953. #endif /* WOLFSSL_SEP */